query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
This builds your guide. Use Keyword to update any options at build time. | def build_guide(self, **kwargs):
# This builds your guide master and updates your options
self.create_guide_master(**kwargs)
prefix = self.prefix # Naming prefix. Use this for every new node you create and there should be no name clashes.
options = self.options ... | [
"def build_guide(self, **kwargs):\n\n # This builds your guide master and updates your options\n prefix, options = self.create_guide_master(**kwargs)\n\n prefix = self.prefix\n options = self.options\n mirror_value = self.mirror_value\n\n\n noxform_grp = self.gui... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add fu code to list. | def add_fu(self, state):
self._fu_set.add(state) | [
"def add_code(self, code):\n self.code += code",
"def add_code(self, code):\n self.custom_code.append(code)",
"def addFriend(self, f):\n\t\tself.friends.append(f)",
"def set_function_list(self, L):\n\t\tself.function_list = L",
"def list_add(self,data):\r\n self.list.append(data)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allow to scroll through the raw data of the csv file selected | def see_raw_data(city):
while True:
try:
see_raw_data_input = input('\nIn addition of the stats above, would you like to scroll through the raw data? (y/n)\n')
if see_raw_data_input not in ('y', 'n'):
raise Exception ('Invalid answer')
if see_raw_data_inp... | [
"def process_loading_file(self):\n column_headers = []\n column_headers_all = []\n\n # Open the file once to get idea of the total rowcount to display progress\n with open(self.csv_file_path[0], newline='') as csv_file:\n self.progress_max.emit(len(csv_file.readlines()) - 2)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialization function. Sets the model name and function, path to input data, and the output filename. | def __init__(self, sfs, model, popnames, output):
self.sfs = self.load_sfs(sfs)
self.modelname = model
# Make an extrapolating version of the function
self.modelfunc = dadi.Numerics.make_extrap_log_func(
self.set_model_func(model))
self.params = self.set_parameters()
... | [
"def __init__(self, model_paths, raw_data, real_label, output_folder):\n self._model_paths = model_paths\n self.raw_data = raw_data\n self.real_label = real_label\n self.output_folder = output_folder",
"def __init__(self, model_name=\"\", model=\"\", snapshot=\"\", module_names=[]):\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the dadi SFS file and return it as a Spectrum object. Dadi will do basic checking of the spectrum, but we will be more thorough. | def load_sfs(self, sfs):
try:
fs = dadi.Spectrum.from_file(sfs)
except:
print 'The spectrum file you provided is not valid!'
exit(1)
return fs | [
"def stis_spectrum_loader(file_obj, **kwargs):\n\n with read_fileobj_or_hdulist(file_obj, **kwargs) as hdulist:\n header = hdulist[0].header\n meta = {'header': header}\n\n unit = Unit(\"erg/cm**2 Angstrom s\")\n disp_unit = Unit('Angstrom')\n data = hdulist[1].data['FLUX'].fla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a model name, set the function that has to be called to run that model. This should be safe because we restrict the user input for the models at the argument parsing stage. | def set_model_func(self, model):
if model == 'SI':
import cavefish_dadi.Models.si
return cavefish_dadi.Models.si.si
elif model == 'SC':
import cavefish_dadi.Models.sc
return cavefish_dadi.Models.sc.sc
elif model == 'IM':
import cavefish... | [
"def get_model(model: str) -> Any:\n try:\n model_function = eval(model)\n except (NameError, AttributeError) as err:\n sys.exit(f'{err}. Accepted models from {tf}, {sm}, {tfa}, {tfc}')\n return model_function",
"def get_function(model_or_function, preprocess_function=None):\n from diann... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Summarize the replicate runs and convert the parameters estimates into meaningful numbers. | def summarize(self, locuslen):
# First, calculate the mean of the parameter estimates from each
# of the replicates
hot_means = []
for r_t in zip(*self.hot_params):
v = [x for x in r_t if not math.isnan(x)]
hot_means.append(sum(v)/len(v))
cold_means = []
... | [
"def get_runs(self) -> int:",
"def representation_size_experiments(\n experimental_run,\n n_samples=100, \n min_features=50,\n max_features=100, \n increment=50,\n loss=LOG_LOSS,\n test_metric=accuracy_score,\n random_state=None): \n all_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Drive the UV plane combination. Functionally, this means Performing concatenation Cleaning the concatenated MS in the UV plane Imaging the concatenated MS | def _drive_uv(param_dict, clargs, output_basename, casa_instance):
script = []
if glob.glob('{}.concat.ms'.format(output_basename)) and clargs.overwrite:
os.system('rm -rf {}.concat.ms'.format(output_basename))
# casa_instance.run_script(script)
# todo
# write an extension of the drivecas... | [
"def computeUV(mdl,xx,yy,uu,vv):\n dshape=uu.shape\n uu=uu.flatten()\n vv=vv.flatten()\n corr=np.zeros(uu.shape,dtype=complex)\n for ind in range(uu.shape[0]):\n corr[ind]=idft2d(mdl,xx,yy,uu[ind],vv[ind],norm=mdl.size)\n return np.reshape(corr,dshape)",
"def plane_unwrapping():\r\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Drive the feather combination. Functionally, this means Cleaning the individual ms separately. Imaging the individual ms. Feathering the two together. | def _drive_feather(param_dict, clargs, output_basename, casa_instance):
# todo later -> the imstat stuff
script = []
thresh, seven_meter_clean_args = utils.param_dict_to_clean_input(
param_dict, seven_meter=True)
_, twelve_meter_clean_args = utils.param_dict_to_clean_input(
param_dic... | [
"def formationFlying(): ### PENDING\n\tpass",
"def feather_clean(in_directory):\n # in_directory = UpdateSP500Data.TOP_LEVEL_PATH / 'feather'\n Path.is_dir(in_directory)\n all_files = os.listdir(in_directory)\n for item in all_files:\n if item.endswith('.feather'):\n # Remove options... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate weightings to use for the feather task | def _calc_feather_weighting(param_dict):
weightings = param_dict['weightings']
if not isinstance(weightings, (list, tuple)):
return 1.0
return float(weightings[1]) / float(weightings[0]) | [
"def weight(self):",
"def calc_weight(self):\n self.weight = (self.Profile.Atot*1e-6 * self.lStiff*1e-3\n * self.Material.density\n )\n pass",
"def get_weights(self):",
"def get_weight(self):\n pass",
"def CalculateWeightedSum( self ):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Automatically generate a basename or else use the one provided. | def _gen_basename(param_dict, clargs):
if param_dict['output_basename'] in ['', 'auto']:
return clargs.input_fname.lower().split('.json')[0]
else:
return param_dict['output_basename'] | [
"def make_fullname(basename, _type=None):\n return '{}.{}'.format(basename, extensions.get(_type, None))",
"def basename(arg):\n if not isinstance(arg, str):\n return arg\n try:\n name = os.path.basename(arg)\n except:\n name = arg\n\n fileExtensions = ['el', 'txt', 'dat', 'csv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! Create ssh client. Create ssh client to run commands in host machine from inside container. | def create_client():
hostname = "localhost"
username = "she393"
password = os.getenv("PASSWORD")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=hostname, username=username, password=password)
return client | [
"def ssh_client():\n return paramiko.SSHClient()",
"def ssh(self):\n logger.debug('Creating SSH connection to bastion')\n cmd = self._container_run_command() + [\n 'python3',\n os.path.join('/app', 'deploy', 'ssh.py'),\n '--vars-file', self._container_file_realpat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
! Wrapper for HTTP responses. message The content of the successful (200) HTTP response. Flask HTTP response object with content of message from the argument and status code 200. | def response(message):
res = Response(json.dumps(message))
res.status_code = 200
res.content_type = "application/json"
return res | [
"def success_response( message, code = 200 ):\n return jsonify( { 'success_message' : message } ), code",
"def simpleResponse(code, message):\n return response({'code':code, 'message':message})",
"def build_response(http_status, message):\n return Response(data={'detail': message},\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One to one identification of the snapshots. | def snapshot_identification(snapshot):
return {
'user_id': snapshot['user_id'],
'timestamp': snapshot['timestamp'],
'snapshot_id': snapshot['snapshot_id']} | [
"def snapshot_id(self) -> Optional[str]:\n return pulumi.get(self, \"snapshot_id\")",
"def ensure_identity_match(self, inventory):\n if 'identity' in self.meta:\n if self.meta['identity'] != inventory.identity:\n raise SnapshotMismatchError(\n expected=in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The AccountBroker initialze() function before we added the policy stat table. Used by test_policy_table_creation() to make sure that the AccountBroker will correctly add the table for cases where the DB existed before the policy support was added. | def prespi_AccountBroker_initialize(self, conn, put_timestamp, **kwargs):
if not self.account:
raise ValueError(
'Attempting to create a new database with no account set')
self.create_container_table(conn)
self.create_account_stat_table(conn, put_timestamp) | [
"def init_tables():\n # drop_table_m_candidates()\n # drop_table_m_qiita_users()\n create_table_m_candidates()\n create_table_m_qiita_users()",
"def _InitTables(self):\n \n self.config_table = sa.Table('config', self.metadata,\n sa.Column('name', sa.String(50), primary_key=True),\n sa.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied from AccountBroker before the metadata column was added; used for testing with TestAccountBrokerBeforeMetadata. Create account_stat table which is specific to the account DB. | def premetadata_create_account_stat_table(self, conn, put_timestamp):
conn.executescript('''
CREATE TABLE account_stat (
account TEXT,
created_at TEXT,
put_timestamp TEXT DEFAULT '0',
delete_timestamp TEXT DEFAULT '0',
container_count INTEGER,
... | [
"def pre_track_containers_create_policy_stat(self, conn):\n conn.executescript(\"\"\"\n CREATE TABLE policy_stat (\n storage_policy_index INTEGER PRIMARY KEY,\n object_count INTEGER DEFAULT 0,\n bytes_used INTEGER DEFAULT 0\n );\n INSERT OR IGNORE INTO policy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied from AccountBroker before the sstoage_policy_index column was added; used for testing with TestAccountBrokerBeforeSPI. Create container table which is specific to the account DB. | def prespi_create_container_table(self, conn):
conn.executescript("""
CREATE TABLE container (
ROWID INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
put_timestamp TEXT,
delete_timestamp TEXT,
object_count INTEGER,
bytes_used INTEGER,
... | [
"def pre_track_containers_create_container_table(self, conn):\n # revert to old trigger script to support one of the tests\n OLD_POLICY_STAT_TRIGGER_SCRIPT = \"\"\"\n CREATE TRIGGER container_insert_ps AFTER INSERT ON container\n BEGIN\n INSERT OR IGNORE INTO policy_stat\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied from AccountBroker before the container_count column was added. Create policy_stat table which is specific to the account DB. Not a part of Pluggable Backends, internal to the baseline code. | def pre_track_containers_create_policy_stat(self, conn):
conn.executescript("""
CREATE TABLE policy_stat (
storage_policy_index INTEGER PRIMARY KEY,
object_count INTEGER DEFAULT 0,
bytes_used INTEGER DEFAULT 0
);
INSERT OR IGNORE INTO policy_stat (
... | [
"def pre_track_containers_create_container_table(self, conn):\n # revert to old trigger script to support one of the tests\n OLD_POLICY_STAT_TRIGGER_SCRIPT = \"\"\"\n CREATE TRIGGER container_insert_ps AFTER INSERT ON container\n BEGIN\n INSERT OR IGNORE INTO policy_stat\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copied from AccountBroker before the container_count column was added (using old stat trigger script) Create container table which is specific to the account DB. | def pre_track_containers_create_container_table(self, conn):
# revert to old trigger script to support one of the tests
OLD_POLICY_STAT_TRIGGER_SCRIPT = """
CREATE TRIGGER container_insert_ps AFTER INSERT ON container
BEGIN
INSERT OR IGNORE INTO policy_stat
(storage_p... | [
"def prespi_create_container_table(self, conn):\n conn.executescript(\"\"\"\n CREATE TABLE container (\n ROWID INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT,\n put_timestamp TEXT,\n delete_timestamp TEXT,\n object_count INTEGER,\n bytes_us... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the class count of ROIs for each sample. | def count_classes(self, index=None):
if index is None:
index = np.arange(self.Samples.shape[0])
elif isinstance(index, int):
index = [index]
count = np.zeros((len(index), len(self._classes)), dtype=np.int)
for _ind in range(len(index)):
... | [
"def class_counts(self) -> (List[int], None):\n if self.isclassifier():\n if self.shadow_tree.get_class_weight() is None:\n return np.array(np.round(self.shadow_tree.get_node_nsamples_by_class(self.id)), dtype=int)\n else:\n return np.round(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the maximum number of ROIs per batch sample in the dataset | def get_max_rois(self):
maxsize = 0
for index in self.SampleID:
rois = self.__getrois__(index);
maxsize = max(maxsize, rois.shape[0])
return maxsize | [
"def max_batch_size(self):\n\n return int(np.min([self.max_rows, self.N]))",
"def _maxNofdataset(self, selpex_results_object):\r\n maxNofdataset = 0\r\n line2write_list = []\r\n for aaseq in selpex_results_object.selpex_results: \r\n pepres = selpex_results_object.selpex_res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes dictionary of the station and their amount of connections. | def make_station_dict(self):
self.station_dict = {}
# interates over stations and puts the amount of connections in the dict
for station in self.stations:
length = len(self.stations[station].connections)
self.station_dict[station] = length
return self.st... | [
"def connection_count(self):\n connlist = qnetwork.connections(self.connection, self.credentials)\n per_node = {}\n for node_data in connlist.data:\n per_node[node_data['id']] = 0\n for _ in node_data['connections']:\n per_node[node_data['id']] += 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts the station dict based on the amount of connections (value). | def create_station_list(self):
sorted_station_list = sorted(self.station_dict, key=self.station_dict.get)
return sorted_station_list | [
"def sort_by_station(channels):\n stations = collections.defaultdict(list)\n for trace_id, coords in channels.items():\n network, station, location, channel = trace_id.split('.')\n stations[(network, station)] += [(location, channel,) + coords]\n return stations.items()",
"def sort(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries all possible configurations starting at the first station and only adds the configuration with the best score. | def visit_all_possibilities(self, first_station, track, grid):
# loops over connections of station
for connection in first_station.connections:
# keeps adding untill the max length of a track is reached
if track.add_station(grid, self.stations[connection].name):
#... | [
"def pick_next_station(self, station):\n self.best_score = 0\n\n stations = self.grid.stations\n # all connections of the last added added station \n lookahead_1 = self.grid.get_station(self.best_connection[1]).connections\n\n for la1 in lookahead_1.values():\n next_sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a species identified by taxid and containing empty dictionnary of orthologs | def __init__(self, taxid, species_name = None, lineage=None):
self.genes = dict()
self.taxid = taxid
self.species = species_name
self.lineage = lineage | [
"def init_taxon():\n if not exists('./data/taxdmp.zip'):\n ftp = FTP('ftp.ncbi.nih.gov')\n ftp.login()\n ftp.cwd('pub/taxonomy')\n ftp.retrbinary('RETR taxdmp.zip', open('./data/taxdmp.zip', 'wb').write)\n ftp.quit\n with ZipFile('./data/taxdmp.zip', 'r') as dumpfile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add an entry in the dic with key "human gene ID" and value "ortholog gene ID" | def add_gene(self, human_gene, ortholog):
if human_gene not in self.genes:
self.genes[human_gene] = list()
self.genes[human_gene].append(ortholog) | [
"def addGeneToGeneDict(self, gene, gene_ens):\n self.genes.update({gene_ens : gene})",
"def AddGeneHomology(elem1, elem2, DicoHomologyLevel, homologyType):\n\tif elem1 not in DicoHomologyLevel: # if the gene from the specie 1 is not\n\t\t# in the dictionary, we add it and we create the list of homologs gen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute default analysis with baySeq | def run_bayseq(self):
try:
res = robjects.r('library("parallel")')
res = robjects.r('library("stats4")')
res = robjects.r('library("BiocGenerics")')
res = robjects.r('library("S4Vectors")')
res = robjects.r('library("IRanges")')
res = robje... | [
"def run_analysis(self, argv):\n self._run_argparser(argv)\n self.run()",
"def run_analysis(self):\n exe = where.__executable__\n cmd = \"{exe} {rundate:%Y %m %d} --{pipeline}\".format(exe=exe, **self.vars).split()\n if self.vars[\"id\"]:\n cmd.append(f\"--id={self.va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the requested income range view in full detail. | def GetIncomeRangeView(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def getRange(self):\n \n pass",
"def GetAgeRangeView(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def get_range(self, start, end):",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a single byte through the packet parsing state amchine. Returns NOT_DONE if the packet is incomplete. Returns SUCCESS is the packet was received successfully. Returns CHECKSUM if a checksum error is detected. | def process_byte(self, byte):
if self.index == -1:
if byte == 0xff:
self.index = 0
self.checksum = 0
elif self.index == 0:
if byte != 0xff:
self.checksum += byte
self.pkt_bytes[0] = byte
self... | [
"def process(self, next_byte) -> bool:\r\n\r\n # Received Message Structures:\r\n # '#B25500' + payload bytes + '\\r\\n'\r\n # '#U00' + payload bytes + '\\r\\n'\r\n # Or for some NM3 firmware versions:\r\n # '#B25500' + payload bytes + 'T' + timestamp + '\\r\\n'\r\n # '#U00... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers a function to run before each request. | def before_request(self, f):
self.before_request_funcs.append(f)
return f | [
"def before_request(self, f):\n self.before_request_funcs.setdefault(None, []).append(f)\n return f",
"def before_request(self, func: typing.Callable):\n return self.add_hook(type_=\"pre\", hook=func)",
"def before_request(self, f):\n self.before_request_funcs[None].append(f)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register a function to be run after each request. | def after_request(self, f):
self.after_request_funcs.append(f)
return f | [
"def after_request(self, f):\n self.after_request_funcs.setdefault(None, []).insert(0, f)\n return f",
"def after_request_handle(self, func):\n self.after_request.append(func)\n return func",
"def after_request(self, f):\n self.after_request_handlers.append(f)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers a template context processor function. | def context_processor(self, f):
self.template_context_processors.append(f)
return f | [
"def _register(fn):\n context.context().add_function(fn)",
"def context_processor(self, f):\n self.template_context_processors[None].append(f)\n return f",
"def context_processor(self, fn=None):\n if fn is None:\n return self.context_processor\n\n self._defer(lambda app: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enroll a new profile to Azure Speaker ID. | def enroll_profile(region, subscription_key, wav_path):
fs, audio_data = _check_and_load_wav_file_length(wav_path)
profile_id = _add_profile(region, subscription_key)
url = "%s/speaker/identification/v2.0/text-independent/profiles/%s/enrollments" % (
_get_azure_endpoint(region), profile_id)
headers = {
... | [
"def attach_security_profile(securityProfileName=None, securityProfileTargetArn=None):\n pass",
"def _createSpeakerByName(self, name):\n data = DEFAULT_SPEAKER\n data['name'] = name\n return Speaker(**data).put()",
"def test_speaker(self):\n self.course.speakers.create(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the number of suicides for a type of agent given game mode, observability, and game seed. If game seed passed is 1, then all game seeds are aggregated. | def suicide_query(game_mode=0, observability=-1, game_seed=-1, agent=-1):
event_id = "death"
# Keep only those games within given configuration
if game_seed != -1:
selection = data.loc[(data['game_mode'] == game_mode) & (data['observability'] == observability) &
(data[... | [
"def get_agent_number_of_players(players):\n return sum([count_players(player) for player in players\n if player.startswith('agent')])",
"def get_num_coop_agents(model):\n\n agent_cooperations = [a.number_of_c for a in model.schedule.agents]\n # print(\"hey\", agent_cooperations)\n agent_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a module item. | def create_module_item(self, module_item, **kwargs):
unrequired_types = ["ExternalUrl", "Page", "SubHeader"]
if isinstance(module_item, dict) and "type" in module_item:
# content_id is not required for unrequired_types
if module_item["type"] in unrequired_types or "content_id" ... | [
"def create_module(self, information):\n self.module = self.get_module(activate=True, information=information)\n self.module.create()\n self.change_status(color=\"yellow\")",
"def load_new_item(self, item_name, item_type):\n\n new_item = item_type(item_name, self.IDgen.new_id())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete this module item. | def delete(self, **kwargs):
response = self._requester.request(
"DELETE",
"courses/{}/modules/{}/items/{}".format(
self.course_id, self.module_id, self.id
),
_kwargs=combine_kwargs(**kwargs),
)
module_item_json = response.json()
... | [
"def delete_item(self, item_id):\n pass",
"def module_delete(self):\n self.test_runner.run_module_delete_auto_by_non_admin()",
"def delete_item(self, item):\r\n item.delete_item_from_room(self)",
"def module_delete_existing(self):\n self.test_runner.run_module_delete_existing()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One sample/paired sample permutation test based on a tstatistic. This function can perform the test on one variable or simultaneously on multiple variables. When applying the test to multiple variables, the "tmax" method is used for adjusting the pvalues of each variable for multiple comparisons. Like Bonferroni correc... | def permutation_t_test(
X, n_permutations=10000, tail=0, n_jobs=None, seed=None, verbose=None
):
from .cluster_level import _get_1samp_orders
n_samples, n_tests = X.shape
X2 = np.mean(X**2, axis=0) # precompute moments
mu0 = np.mean(X, axis=0)
dof_scaling = sqrt(n_samples / (n_samples - 1.0))
... | [
"def PermutationTest(self):\n # U = union of B and T\n union_sample = np.concatenate((self.x_benchmark, self.x_trial), axis=0)\n n_samples = self.NB + self.NT\n \n # Initialize array of test statistic values\n self.TS_tilde = np.zeros(self.n_perm, dtype=np.float)\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get confidence intervals from nonparametric bootstrap. | def bootstrap_confidence_interval(
arr, ci=0.95, n_bootstraps=2000, stat_fun="mean", random_state=None
):
if stat_fun == "mean":
def stat_fun(x):
return x.mean(axis=0)
elif stat_fun == "median":
def stat_fun(x):
return np.median(x, axis=0)
elif not callable(st... | [
"def get_bootstrap_ci(cons: np.ndarray, n_trials: int = 100):\n cons_trials = np.zeros((n_trials, cons.shape[0]))\n\n for t in range(n_trials):\n\n shuff_scores = np.random.choice(cons, cons.shape[0], replace=True)\n cons_trials[t, :] = shuff_scores\n\n conf_ints = np.zeros((2, n_trials - 1))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if word is provided in slot values. Send word to URLbuilder and return JSON data. Give user definition information. | def my_word_definition_handler(handler_input):
# type: (HandlerInput) -> Response
slots = handler_input.request_envelope.request.intent.slots
if word_slot in slots:
curr_word = slots[word_slot].value
handler_input.attributes_manager.session_attributes[
word_slot_key] = curr_word... | [
"def my_word_example_handler(handler_input):\n # type: (HandlerInput) -> Response\n slots = handler_input.request_envelope.request.intent.slots\n\n if example_slot in slots:\n curr_word = slots[example_slot].value\n handler_input.attributes_manager.session_attributes[\n example_slo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function handles the example sentence intent | def my_word_example_handler(handler_input):
# type: (HandlerInput) -> Response
slots = handler_input.request_envelope.request.intent.slots
if example_slot in slots:
curr_word = slots[example_slot].value
handler_input.attributes_manager.session_attributes[
example_slot_key] = cur... | [
"def get_sentence(self):",
"def get_suggested_text(): \n # for now, just print the sentences\n pass",
"def motivation_letter(mistake_word, true_word):",
"def hook(self, sentence, words):\n pass",
"def sentence():\r\n return nounPhrase() + \" \" + verbPhrase()",
"def test_make_sentences():\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
AMAZON.FallbackIntent is only available in enUS locale. This handler will not be triggered except in that locale, so it is safe to deploy on any locale. | def fallback_handler(handler_input):
# type: (HandlerInput) -> Response
speech = (
"The {} skill can't help you with that. "
"I can look up a word in the dictionary for you").format(skill_name)
reprompt = ("I can look up a word in the dictionary, "
"Just say any word in Engli... | [
"def _fallback_range(self, utterances, lang, message, fb_range):\n msg = message.reply(\n 'mycroft.skills.fallback',\n data={'utterance': utterances[0][0],\n 'lang': lang,\n 'fallback_range': (fb_range.start, fb_range.stop)}\n )\n response... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of snapshot_ids associated with the given image | def getSnapshotsOf(image):
snapshotIds = []
deviceMapping = image.block_device_mapping # dict of devices
devices = deviceMapping.keys()
for d in devices:
snapshotId = deviceMapping[d].snapshot_id
if snapshotId is not None:
snapshotIds.append(snapshotId.encode())
return s... | [
"def get_snapshots_of(image):\n snapshot_ids = []\n device_mapping = image.block_device_mapping # dict of devices\n devices = device_mapping.keys()\n for device in devices:\n if device_mapping[device].snapshot_id is not None:\n snapshot_ids.append(device_mappin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use dictionaries 'cos we'll have to crossreference to get snapshots that go with the AMIs returns list of dictionaries representing images from one region | def getImagesD(region):
images = getImages(region)
imageDicts = []
for im in images:
imageDict = {"name": im.name,
"id": im.id,
"region": im.region.name,
"state": im.state,
"created": im.creationDate,
... | [
"def getSnapshotsD(region):\n # Can a snapshot belong to more than one AMI? Dunno, keep list just in case (so it never breaks due to it)\n snapshots = getSnapshots(region)\n snapshotsDicts = []\n ims = getImages(region)\n for s in snapshots:\n amis = getAmisOf(s, ims)\n amiIds = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list of dictionaries representing snapshots from one region | def getSnapshotsD(region):
# Can a snapshot belong to more than one AMI? Dunno, keep list just in case (so it never breaks due to it)
snapshots = getSnapshots(region)
snapshotsDicts = []
ims = getImages(region)
for s in snapshots:
amis = getAmisOf(s, ims)
amiIds = []
amiKeeps... | [
"def get_snapshots():\n #client = boto_ec2_client(region)\n paginator = ec2.get_paginator('describe_snapshots')\n response_iterator = paginator.paginate(OwnerIds=[accountId])\n snapshots = list()\n for page in response_iterator:\n for obj in page['Snapshots']:\n snapshots.append(obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list of dictionaries representing volumes from one region | def getVolumesD(region):
volumes = getVolumes(region)
instances = getInstancesD(region)
volumesDicts = []
for v in volumesDicts:
volumesDict = {"id": v.id,
"KEEP-tag": getKeepTag(v),
"instance_KEEP-tag": getKeepTag(getInstanceOf(v)),
... | [
"def get_volumes(self, region):\n try:\n conn = ec2.connect_to_region(region, **self.credentials)\n region_volumes = conn.get_all_volumes()\n except boto.exception.EC2ResponseError:\n return [] # This better not fail silently or I'll cut a person.\n return regi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list of dictionaries representing instances for one region, will help with volumeinstanceKEEPtag lookup. Maybe. | def getInstancesD(region):
instances = getInstances(region)
instancesDicts = {"id": i.id,
"KEEP-tag": getKeepTag(i),
"instance_type": i.instance_type,
"state": i.state,
"launch_time": i.launch_time,
"se... | [
"def get_instances(self, region):\n try:\n conn = ec2.connect_to_region(region, **self.credentials)\n region_instances = []\n reservations = conn.get_all_reservations()\n for reservation in reservations:\n for instance in reservation.instances:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retrieve list of AMIs that refer to a given snapshot | def getAmisOf(snapshot, images):
amis = []
for im in images:
snapshotsOfThisIm = getSnapshotsOf(im)
for soti in snapshotsOfThisIm:
if soti == snapshot.id:
amis.append(im)
return amis | [
"def getSnapshotsOf(image):\n snapshotIds = []\n deviceMapping = image.block_device_mapping # dict of devices\n devices = deviceMapping.keys()\n for d in devices:\n snapshotId = deviceMapping[d].snapshot_id\n if snapshotId is not None:\n snapshotIds.append(snapshotId.encode())\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If tag with key='KEEP' exists, return its value (can be an empty string), else it's 'notag' | def getKeepTag(obj):
if 'KEEP' in obj.tags:
return obj.tags['KEEP']
else:
return "-------no-tag"
# try:
# tag = obj.tags['KEEP']
# except:
# # Note: some with empty KEEP-tags, through web console they look the same as those untagged
# return "-----"
# return ... | [
"def get_keep_tag(obj):\n if 'KEEP' in obj.tags and len(obj.tags['KEEP'].strip()) != 0:\n return obj.tags['KEEP']\n else:\n return \"-------no-tag\"",
"def get_tag(key: str) -> Optional[str]:\n _check_active_model_version()\n return _active_model_version.get_tag(key) # t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the object (instance, volume, snapshot, AMI) has a tag with 'PROD' for key | def isProduction(obj):
return 'PROD' in obj.tags # This is deprecated? obj.tags.has_key('PROD') | [
"def tag_key_exists(self, key):\n return key in self.map",
"def hasKey(self, key):\n for t in self.getTags():\n if t.getKey().getName() == key:\n return True\n return False",
"def is_object_metadata(data):\n for key in ['app_commit', 'app_release']:\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write volumes to file | def generateInfoVolumes(regions):
print "\nWriting volumes info to output file %s" % volumes_data_output_file
with open(volumes_data_output_file, 'w') as f1:
f1.write("VOLUMES\n")
f1.write(
"Name\tvolume_ID\tKEEP-tag_of_volume\tKEEP-tag_of_instance\tproduction?\tvolume_attachment_sta... | [
"def write_volume(self):\n volfile = open(self.basedir + \"/volume\", 'w')\n volume = self.get_volume()\n volfile.write(volume + \"\\n\")\n volfile.close()",
"def write_inventory_file(inventory_item):\n try:\n with open('inventory', 'w') as file:\n file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the application directory. | def get_appdir():
return APP_PATH | [
"def app_dir(self):\n return os.path.dirname(self.config_file)",
"def app_dir(self):\n return self._app_dir",
"def get_global_app_dir(self):\n globalapps = self.choose_path(Installer.global_app_dirs)\n if globalapps:\n return globalapps\n self.report_error('Unable to de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the TSV file corresponding to the current annotation level. | def tsv_name():
if PAR['level'] == 1:
return 'col.tsv'
else:
return 'myc.tsv' | [
"def _get_traj_file(self):\n return self._traj_file",
"def saveTSV(self, filename=None, **kargs):\n self.saveCSV(filename, tsv=True, **kargs)",
"def open_tsv(tsv_name):\n\t\n\ttsv_file = pd.read_csv(tsv_name, sep = '\\t')\n\n\treturn tsv_file",
"def to_tsv_files(self, enclosing_folder):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicate whether the current level is level 1 (colonization). | def colonization():
return get('level') == 1 | [
"def is_single_level(self):\n return self.fragments_tree.height <= 2",
"def is_top_level(self) -> bool:\n return self._indent == ''",
"def is_mainline(self) -> bool:\n node = self\n\n while node.parent:\n parent = node.parent\n\n if not parent.variations or pare... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicate whether the current level is level 2 (AM fungal structures). | def intra_struct():
return get('level') == 2 | [
"def support_level2_data(self) -> bool:\n return self._support_level2_data",
"def is_subgroup(self, right):\n if right.level() == 1:\n return True\n if is_Gamma0(right):\n return self.level() % right.level() == 0\n if is_Gamma1(right):\n if right.level(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds AMFinder commandline parser. | def build_arg_parser():
main = ArgumentParser(description='AMFinder command-line arguments.',
allow_abbrev=False,
formatter_class=RawTextHelpFormatter)
subparsers = main.add_subparsers(dest='run_mode', required=True,
help... | [
"def build_parser(self, parser: ArgumentParser) -> None:",
"def build_parser(self):\n parser = argparse.ArgumentParser(\n description=\"Run Crystal Matching algorithm attempting to translate co-ordinates \"\n \"on an input image to the coordinate-space of an output image w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns absolute paths to input files. | def abspath(files):
files = sum([glob.glob(x) for x in files], [])
return [os.path.abspath(x) for x in files] | [
"def input_files(self) -> List[str]:\n raise NotImplementedError # P0",
"def input_file_paths(base_path):\n\tpaths = []\n\tfor dirpath, dirnames, filenames in os.walk(base_path):\n\t\tfor onefile in filenames:\n\t\t\t# the following if statement is due to OS X .DsStore bullshit...\n\t\t\tif not (onefile.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creating a custom time entry, minimum must is hour duration and project param | def createTimeEntry(self, hourduration, description=None, projectid=None, projectname=None,
taskid=None, clientname=None, year=None, month=None, day=None, hour=None,
billable=False, hourdiff=-2):
data = {
"time_entry": {}
}
if not proj... | [
"def _create_time_entry(duration, description, projectid, start):\n data = {\n \"time_entry\": {\n \"description\": description,\n \"start\": start.astimezone().isoformat(),\n \"duration\": duration, # duration in seconds\n \"pid\": projectid,\n \"cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fast query given the Client's name and Project's name | def getClientProject(self, clientName, projectName):
for client in self.getClients():
if client['name'] == clientName:
cid = client['id']
if not cid:
print('Could not find such client name')
return None
for projct in self.getClientProjects(ci... | [
"def _project_search(self, cr, uid, obj, name, args, context=None):\n cr.execute(\"\"\"\n SELECT pp.id,*\n FROM (\n Select\n node.id, node.name AS short_name,\n --cast ((count(parent.name)) as int) as nivel\n replac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update data for an existing client. If the name or notes parameter is not supplied, the existing data on the Toggl server will not be changed. | def updateClient(self, id, name=None, notes=None):
data = {}
data['client'] = {}
data['client']['name'] = name
data['client']['notes'] = notes
response = self.postRequest(Endpoints.CLIENTS + '/{0}'.format(id), parameters=data, method='PUT')
return self.decodeJSON(respon... | [
"def update_client(client_name, updated_client_name): # Operacion modificar\n global clients\n\n if client_name in clients:\n index = clients.index(client_name)\n clients[index] = updated_client_name\n else:\n print(\"Client isn\\'t in the client list\")",
"def client_notes(self, cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method will run all the episodes with epsilon greedy strategy | def run_epsilon(env, num_of_bandits, iterations, episodes):
# Initialize total mean rewards array per episode by zero
epsilon_rewards = np.zeros(iterations)
for i in range(episodes):
print(f"Running Epsilon episode:{i}")
n = 1
action_count_per_bandit = np.ones(num_of_bandits)
... | [
"def run(self) -> None:\n for episode in range(1, self.episodes + 1):\n print('Episode:', episode)\n steps, state_action_history = self.run_one_episode()\n self.steps_per_episode.append(steps)\n if episode % parameters.CACHING_INTERVAL == 0 or steps < 1000:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Train agent over given number of iterations. Each iteration consists of self play over n_episodes and then a learn step where agent updates network based on random sample from replay buffer | def train(self, iters, n_episodes):
for i in range(iters):
self.self_play(n_episodes)
self.learn() | [
"def train(self, num_episodes: int) -> List:\n reward_per_episode: List[float] = []\n num_steps_sampled: int = 0\n\n for episode_idx in range(1, num_episodes + 1):\n # Log progress\n if episode_idx % self.config.LOG_EVERY == 0:\n window_rewards = reward_per_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate pair message between node Hv and Hw. since the cat operation, msgs from hv > hw and hw > hv are different | def __init__(self, dim_hv, dim_hw, msg_dim):
super(PairMessageGenerator, self).__init__()
self.dim_hv, self.dim_hw, self.msg_dim = dim_hv, dim_hw, msg_dim
self.in_dim = dim_hv + dim_hw # row * feature_dim, 2048
self.mlp = nn.Sequential(
nn.LayerNorm(self.in_dim), # this lay... | [
"def __mk_output_msg(filter):\n msg = Sonar()\n msg.header.stamp = rospy.Time.now()\n best = filter.get_best_particle()\n cov = filter.get_covariance()\n msg.x = best[0]\n msg.y = best[1]\n msg.covariance = cov.flatten().tolist()\n return msg",
"def generate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Import all model data using the loader. | def import_data(self):
self.models = []
for o in self.loader.load():
klass = self.type_for(o)
if hasattr(klass, "from_api"):
self.models.append(klass.from_api(o))
else:
self.models.append(klass(o))
return self.models | [
"def import_all():\n\n # count the number of files loaded\n count = 0\n\n # get model name\n model_name_list = [model for data_models in settings.OBJECT_DATA_MODELS\n for model in data_models]\n\n model_name_list += [model for model in settings.OTHER_DATA_MODELS]\n\n # import... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test GenBank parsing invalid product line raises ValueError | def test_invalid_product_line_raises_value_error(self):
def parse_invalid_product_line():
rec = SeqIO.read(path.join('GenBank', 'invalid_product.gb'),
'genbank')
self.assertRaises(ValueError, parse_invalid_product_line) | [
"def test_malformed_line():\n \n header_parser = get_header()\n # Missing position\n variant_line = \"1\\t.\\tA\\tT\\t100\\tPASS\\tMQ=1\\tGT:GQ\\t0/1:60\\t\"\\\n \"0/1:60\\t1/1:60\"\n \n with pytest.raises(SyntaxError):\n variant = format_variant(\n line = vari... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\b Lists all your published apps. $ 21 publish list Results from the list command are paginated. Use 'n' to move to the next page and 'p' to move to the previous page. You can view detailed admin information about an app by specifying it's id at the prompt. | def list(ctx):
# pylint: disable=redefined-builtin
_list_apps(ctx.obj['config'], ctx.obj['client']) | [
"def cli_list(ctx):\n try:\n r = api.apps_get()\n pprint(r)\n except ApiException as e:\n print(\"Exception when calling AppsApi->apps_get: %s\\n\", e)",
"async def app_list(self) -> List[interface.App]:\n return await self.relay(\"app_list\")()",
"def list_app():\n response = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\b Removes a published app from the Marketplace. $ 21 publish remove [yes] {app_id} \b Removes all published apps from the Marketplace. $ 21 publish remove [yes] all \b | def remove(ctx, app_id, all, assume_yes):
if all and not app_id:
for _app_id in _get_all_app_ids(ctx.obj['config'], ctx.obj['client']):
_delete_app(ctx.obj['config'], ctx.obj['client'], _app_id, assume_yes)
elif app_id and not all:
_delete_app(ctx.obj['config'], ctx.obj['client'], ap... | [
"def remove():\n run('pew rm {0}'.format(package_name()))",
"def app_delete(self, name):\n self.core.api.os.shell.cmd('{0} delete app /app.name:\"{1}\"'.format(self.APP_CMD, name))",
"def remove_app(self):\n \n pass",
"def delete_app(AppId=None):\n pass",
"def del_editable_app(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
\b Publishes an app to 21 Marketplace. $ 21 publish submit path_to_manifest/manifest.yaml The contents of the manifest file should follow the guidelines specified at | def submit(ctx, manifest_path, marketplace, skip, parameters):
if parameters is not None:
try:
parameters = _parse_parameters(parameters)
except:
logger.error(
"Manifest parameter overrides should be in the form 'key1=\"value1\" "
"key2=\"value... | [
"def _publish(client, manifest_path, marketplace, skip, overrides):\n try:\n manifest_json = check_app_manifest(manifest_path, overrides, marketplace)\n app_url = \"{}://{}\".format(manifest_json[\"schemes\"][0], manifest_json[\"host\"])\n app_ip = urlparse(app_url).hostname\n\n if no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses parameters string and returns a dict of overrides. This function assumes that parameters string is in the form of '"key1="value1" key2="value2"'. Use of single quotes is optional but is helpful for strings that contain spaces. | def _parse_parameters(parameters):
if not re.match(r'^(\w+)="([^=]+)"(\s{1}(\w+)="([^=]+)")*$', parameters):
raise ValueError
# first we add tokens that separate key/value pairs.
# in case of key='ss sss ss', we skip tokenizing when we se the first single quote
# and resume when we see the s... | [
"def parse_input_args(input_str: str):\n output_dict = {}\n if not input_str:\n raise ValueError(\"Empty input string: {}\".format(input_str))\n\n key_pairs: list = input_str.split(\",\")\n\n key_pairs = [x.strip() for x in key_pairs]\n\n if not key_pairs:\n raise ValueError(\"Incorrect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publishes application by uploading the manifest to the given marketplace | def _publish(client, manifest_path, marketplace, skip, overrides):
try:
manifest_json = check_app_manifest(manifest_path, overrides, marketplace)
app_url = "{}://{}".format(manifest_json["schemes"][0], manifest_json["host"])
app_ip = urlparse(app_url).hostname
if not skip:
... | [
"def submit(ctx, manifest_path, marketplace, skip, parameters):\n if parameters is not None:\n try:\n parameters = _parse_parameters(parameters)\n except:\n logger.error(\n \"Manifest parameter overrides should be in the form 'key1=\\\"value1\\\" \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries the marketplace for published apps | def get_search_results(config, client, page):
resp = client.get_published_apps(config.username, page)
resp_json = resp.json()
search_results = resp_json["results"]
if search_results is None or len(search_results) == 0:
logger.info(
click.style("You haven't published any apps to the m... | [
"def _get_apps(self):\n return self.api.get('/v2/apps')",
"def get_apps(provider, query):\n\n workdir = os.path.dirname(os.path.realpath(__file__))\n with open(os.path.join(workdir, '..', 'config.yml')) as f:\n config = yaml.load(f)\n ex = Explorer()\n logging.info('Read bucket: %s', con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace "AUTO" in the host and quickbuy with the ZeroTier IP. The server subsequently replaces, in the displayed quickbuy, instances of the manifest host value with a mkt.21.co address. | def replace_auto(manifest_dict, marketplace):
manifest_dict = copy.deepcopy(manifest_dict)
def get_formatted_zerotier_address(marketplace):
host = get_zerotier_address(marketplace)
if "." not in host:
return "[{}]".format(host)
else:
return host
if 'AUTO' in ... | [
"def set_host_addr(self):\n \n # if using on same computer use random loopback address\n # because IP server stores as key value pairs and overwrites if same address (only for testing)\n if self.scope == \"localhost\":\n num1 = random.randint(0,199)\n num2 = random.rand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the manifest file Ensures that the required fields in the manifest are present and valid | def validate_manifest(manifest_json):
manifest_json = copy.deepcopy(manifest_json)
for field in ["schemes", "host", "basePath", "info"]:
if field not in manifest_json:
raise exceptions.ValidationError(
click.style("Field '{}' is missing from the manifest file.", fg="red").for... | [
"def validate_manifest(parser, options):\n if not options.manifest:\n return\n\n template = \"When specifying --manifest, {0} is also required\"\n\n if not options.manifest_id:\n parser.error(template.format(\"--manifest-id\"))\n \n if not options.manifest_service:\n parser.error(template.format(\"--m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the zerotier IP address from the given marketplace name | def get_zerotier_address(marketplace):
logger.info("You might need to enter your superuser password.")
address = zerotier.get_address(marketplace)
if not address:
join_cmd = click.style("21 join", bold=True, reset=False)
no_zt_network = click.style(
"You are not part of the {}. U... | [
"def get_ip():\n return '219.45.143.143'",
"def get_vip_address(self, vip_name):\n networks = self.nailgun_client.get_networks(self.cluster_id)\n vip = networks.get('vips').get(vip_name, {}).get('ipaddr', None)\n asserts.assert_is_not_none(\n vip, \"Failed to get the IP of {} se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set mode wireframe only | def setDisplayMode(self, mode):
return "Wireframe" | [
"def toggle_wireframe(self):\n self.view['wireframe'] = not self.view['wireframe']\n self.update_flags()",
"def toggle_wireframe():\n model_editor = viewport.get_model_panel()\n if model_editor:\n viewport.toggle_wireframe(model_editor)",
"def setSurfaceShadingMode(mode='flat'):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register an asset required by a dashboard module. Some modules require special scripts or stylesheets, like the | def register_module_asset(self, asset):
self._module_assets.append(asset) | [
"def process_xmodule_assets():\r\n sh('xmodule_assets common/static/xmodule')",
"def assets():\n pass",
"def register(app):\n app.register_blueprint(bp)\n\n assets = app.jinja_env.assets_environment\n\n assets.register('site_css', Bundle(\n 'scss/site.scss', filters='libsass', output='site... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare this dashboard instance to run. | def _prepare(self):
# Set configuration defaults and save to the project document
self.config.setdefault('PAGINATION', True)
self.config.setdefault('PER_PAGE', 25)
# Create and configure the Flask application
self.app = self._create_app(self.config)
# Add assets and ro... | [
"def prepare(self):\n scenario = self.get_scenario()\n self.kpi_file = self.engine.create_artifact(\"selenium_tests_report\", \".txt\")\n script_type, script_is_folder = self.detect_script_type(scenario.get(\"script\"))\n runner_config = BetterDict()\n\n if script_type == \".py\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this method for custom job titles. This method generates job titles. By default, the title is a pretty (but verbose) form of the job state point, based on the project schema. | def job_title(self, job):
def _format_num(num):
if isinstance(num, bool):
return str(num)
elif isinstance(num, Real):
return str(round(num, 2))
return str(num)
try:
s = []
for keys in sorted(self._schema_variabl... | [
"def get_job_title(self, job_name):\n return ''",
"def _postage_title(self, cube, label_mems, label_ref_dates):\n title = ''\n if label_mems:\n try:\n title += '%s: %s' % (self.realization.title(),\n cube.coord(self.realization).po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this method for custom job subtitles. This method generates job subtitles. By default, the subtitle is a minimal unique substring of the job id. | def job_subtitle(self, job):
return str(job)[:max(8, self._project_min_len_unique_id())] | [
"def subtitle(self, txt):\n num = len(txt)\n ticks = \"-\" * num\n print(txt)\n print(ticks)",
"def get_subtitle_print(subs: List[Track]) -> List[str]:\n data = []\n if not subs:\n data.append(\"--\")\n for sub in subs:\n line_items = []\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override this method for custom job sorting. This method returns a key that can be compared to sort jobs. By | def job_sorter(self, job):
key = natsort.natsort_keygen(key=self.job_title, alg=natsort.REAL)
return key(job) | [
"def sort_key(self):\n ...",
"def sort_key(self) -> SortKeyCallable:\n return self.__sort_key",
"def sort_key(self):\n return self._sort_key",
"def job_priority_key(self, job):\n camp, user = job.camp, job.user\n end = camp.time_left / user.shares # lower value -> higher pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers routes with the Flask application. This method configures context processors, templates, and sets up routes for a basic Dashboard instance. Additionally, routes declared by modules are registered by this method. | def _register_routes(self):
dashboard = self
@dashboard.app.after_request
def prevent_caching(response):
if 'Cache-Control' not in response.headers:
response.headers['Cache-Control'] = 'no-store'
return response
@dashboard.app.context_processor
... | [
"def _install_routes(self):\n @self.app.route('/', defaults = { 'page': 1 })\n @self.app.route('/<int:page>/')\n def index(page = 1):\n return self.render_template('index.html', page = page)\n\n @self.app.route('/archive/')\n @self.app.route('/archive/<tag>/')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear project and dashboard server caches. The dashboard relies on caching for performance. If the data space is altered, this method may need to be called before the dashboard reflects those changes. | def update_cache(self):
# Try to update signac project cache. Requires signac 0.9.2 or later.
with warnings.catch_warnings():
warnings.simplefilter(action='ignore', category=FutureWarning)
try:
self.project.update_cache()
except Exception:
... | [
"def clear_cache(self):\n template = 'https://ci.appveyor.com/api/projects/{0.username}/{0.project}/buildcache'\n url = template.format(self)\n headers = {'Authorization': 'Bearer {0.api_token}'.format(self)}\n response = requests.delete(url, headers=headers)\n print('Status code:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the command line interface. Call this function to use signacdashboard from its command line | def main(self):
def _run(args):
kwargs = vars(args)
if kwargs.get('host', None) is not None:
self.config['HOST'] = kwargs.pop('host')
if kwargs.get('port', None) is not None:
self.config['PORT'] = kwargs.pop('port')
self.config['PR... | [
"def cli():\n config, auth, execute_now = read_command_line_arguments()\n main(config, auth, execute_now)",
"def main(args):\n cli = CLI()\n # Check arguments\n cli.parse_arguments(args)",
"def main():\n # Get the path to the settings file.\n if len(sys.argv) == 1:\n settings_path = '/etc/ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl simple addition example | def test_documentation_popxl_addition(self):
filename = "simple_addition.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_and_numbers(self):\n self.assertEqual(add(3,8), 11)",
"def test_calculator_add():\n assert calculator.calculator_add(4, 4) == 8\n assert calculator.calculator_add(0, 0) == 0\n assert calculator.calculator_add(0, 1) == 1\n assert calculator.calculator_add(0, -5) == -5",
"def test_add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl basic subgraph example | def test_documentation_popxl_basic_subgraph(self):
filename = "basic_graph.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_create_multi_subgraph(self):\n filename = \"create_multi_graphs_from_same_func.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_get_subgraph(self):\n query_string = [('seedNodes', 'seedNodes_example')]\n response ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl replication example | def test_documentation_popxl_replication(self):
filename = "replication.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_mnist_replication_train(self):\n filename = \"mnist_rts.py --replication-factor 2\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_replicate_pg_to_pg(self):\n # TODO - Real and more complex e2e tests will be added here\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl create multiple subgraph example | def test_documentation_popxl_create_multi_subgraph(self):
filename = "create_multi_graphs_from_same_func.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_basic_subgraph(self):\n filename = \"basic_graph.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_get_subgraph(self):\n query_string = [('seedNodes', 'seedNodes_example')]\n response = self.client.open(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the code loading example | def test_documentation_popxl_code_loading(self):
filename = "code_loading.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_examples():\n import airconics\n # pytest runs test files in ./__pycache__: need to go up two levels\n example_dir = os.path.abspath(\n os.path.join(__file__, '..', '..', 'examples', 'core'))\n example_scripts = os.listdir(example_dir)\n for script in example_scripts:\n if scr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the nested code loading example | def test_documentation_popxl_nested_code_loading(self):
filename = "code_loading_nested.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_load_data(self):\n pass",
"def test_documentation_popxl_code_loading(self):\n filename = \"code_loading.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_yaml_loader(self):\n self.loader_test('obo_sample.yaml', Package, yaml_loader)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the nested Session contexts example | def test_documentation_popxl_nested_session_contexts(self):
filename = "nested_session_contexts.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_to_session(self):\n pass",
"def test_session(self):\n try:\n self.client.connect()\n session = self.client.session()\n if self.client.admin_party:\n self.assertIsNone(session)\n else:\n self.assertEqual(session['user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl call_with_info example | def test_documentation_popxl_call_with_info(self):
filename = "call_with_info.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_main_info(info):\n info.return_value.infotype = \"list\"\n argv = [\"info\", \"levels\"]\n args = cli._parse_args(argv)\n cli._execute(args)\n\n info.return_value.infotype = \"total_precipitation\"\n argv = [\"info\", \"total_precipitation\"]\n args = cli._parse_args(argv)\n cli._e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl basic repeat example | def test_documentation_popxl_repeat_0(self):
filename = "repeat_graph_0.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_simple_repeat(self):\n r = mi.repeatfunc(lambda: 5)\n self.assertEqual([5, 5, 5, 5, 5], [next(r) for _ in range(5)])",
"def test_documentation_popxl_in_sequence(self):\n filename = \"in_sequence.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl getting / setting tensor data example | def test_documentation_popxl_get_set_tensors(self):
filename = "tensor_get_write.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_predictor():",
"def test_add_get_tensor(mock_data):\n dataset = Dataset(\"test-dataset\")\n\n # 1D tensors of all data types\n data = mock_data.create_data(10)\n add_get_arrays(dataset, data)",
"def test_pauli_rep(self):\n X = qml.PauliX(0)\n Y = qml.PauliY(2)\n t = Te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl autodiff op | def test_documentation_popxl_autodiff(self):
filename = "autodiff.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_57o_correct_preflop_odds(self):\n self.assertEqual(self.hand.preFlopOdds10, 7.9)",
"def test_99_correct_preflop_odds(self):\n self.assertEqual(self.hand.preFlopOdds10, 15.6)",
"def test_pressure_increasing_check_some_decreasing(mocker, pressure_values, expected):\n profile = mocker.pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl in sequence context manager | def test_documentation_popxl_in_sequence(self):
filename = "in_sequence.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_pop(self):\n self.stack.pop()",
"def test_pop_methods(self):\n\n batch = Batch(Mock())\n\n # mock BatchRequests\n mock_obj = Mock()\n mock_ref = Mock()\n batch._objects_batch = mock_obj\n batch._reference_batch = mock_ref\n\n mock_obj.pop.assert_no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl remote variable | def test_documentation_popxl_remote_var(self):
filename = "remote_variable.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_remote_rts_var(self):\n filename = \"remote_rts_var.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_documentation_popxl_rts_var(self):\n filename = \"rts_var.py\"\n self.run_python(filename, file_dir=working_dir,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl remote rts variable | def test_documentation_popxl_remote_rts_var(self):
filename = "remote_rts_var.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_remote_var(self):\n filename = \"remote_variable.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_documentation_popxl_rts_var(self):\n filename = \"rts_var.py\"\n self.run_python(filename, file_dir=working_dir, wo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl rts variable | def test_documentation_popxl_rts_var(self):
filename = "rts_var.py"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_remote_rts_var(self):\n filename = \"remote_rts_var.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_get_state_tostring_incorrect(self):\n got_var, const_number = rapid_datatypes.get_rapid_data(self.controller, 'T_ROB1',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl mnist with replication example | def test_documentation_popxl_mnist_replication_train(self):
filename = "mnist_rts.py --replication-factor 2"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_mnist_rts_train(self):\n filename = \"mnist_rts.py --replication-factor 2 --rts\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def test_documentation_popxl_mnist_rts_train_test(self):\n filename = \"mnist_rts.py --replication-fact... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl mnist with RTS example | def test_documentation_popxl_mnist_rts_train(self):
filename = "mnist_rts.py --replication-factor 2 --rts"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_mnist_rts_train_test(self):\n filename = \"mnist_rts.py --replication-factor 2 --rts --test\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def mnist_testing(shuffled = True):\n mndata = MNIST(MNIST_PATH)\n test_ims, test_labels = m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the popxl mnist with RTS example | def test_documentation_popxl_mnist_rts_train_test(self):
filename = "mnist_rts.py --replication-factor 2 --rts --test"
self.run_python(filename, file_dir=working_dir, working_dir=working_dir) | [
"def test_documentation_popxl_mnist_rts_train(self):\n filename = \"mnist_rts.py --replication-factor 2 --rts\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_dir)",
"def mnist_testing(shuffled = True):\n mndata = MNIST(MNIST_PATH)\n test_ims, test_labels = mndata.load_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |