query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Replaces u'celsius' with 'fahrenheit' in the provided string.
def replace_celcius(string): return string.replace(u'celsius', u'fahrenheit')
[ "def fahrenheit_to_celsius():\n fahrenheit = entry_temp.get()\n # If entry field is empty, convert temp\n if fahrenheit != \"\":\n celsius = (5 / 9) * (float(fahrenheit) - 32)\n # Rounds celsius to 2 decimal places and converts\n # to text\n label_result[\"text\"] = f\"{round(ce...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
scale is an integer index that refers to an exponent applied to entSensorValue. The sensor_exponent comes from the cisco definitions, and I want to move those out of the plugin at some point.
def _entity_sensor_scale_to_exponent(sensor_scale): sensor_exponent = [u'-24', u'-21', u'-18', u'-15', u'-12', u'-9', u'-6', u'-3', u'0', u'3', u'6', u'9', u'12', u'15', u'18', u'21', u'24'] return int(sensor_exponent[sensor_scale - 1])
[ "def math_scale(self, c, channel, scale = None):\n dev = self.selectedDevice(c)\n if scale is None:\n resp = yield dev.query('MATH%d:VERT:SCA?' %channel)\n else:\n scale = format(scale,'E')\n yield dev.write(('MATH%d:VERT:SCA '+scale) %channel)\n resp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pulls the entPhysicalClass items tree. We're interested in '6' (Power Supply Units). note that this could be expanded out if there's a need.
def _power_supplies(self): power_supplies = {} varbinds = self._snmp_connection.bulk_walk(entPhysicalClass) for varbind in varbinds: if varbind.value == u'6': psu_id = int(varbind.index) power_supplies[psu_id] = {u'psu_id': psu_id, u'psu_name': self._e...
[ "def _get_entity_table(self):\n\n result_dict = QualiMibTable('entPhysicalTable')\n\n entity_table_critical_port_attr = {'entPhysicalContainedIn': 'str',\n 'entPhysicalVendorType': 'str'}\n entity_table_optional_port_attr = {'entPhysicalDescr': 'str', '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps indices used in the Cisco Entity Mib to the module number
def _module_numbers(self): module_numbers = {} varbinds = self._snmp_connection.bulk_walk(entPhysicalParentRelPos) for varbind in varbinds: module_numbers[int(varbind.index)] = varbind.value return module_numbers
[ "def update_module_indexes(self, generation):\n self.species_module_index_map = {}\n\n if Config.blueprint_nodes_use_representatives:\n # For representatives species_module_index_map becomes: representative -> (species index, member index)\n for rep, module in self.species_module...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all the profiles available in the carbonblack.credentials files.
def _find_cb_profiles(): dir_locations = [".carbonblack", os.path.join(os.path.expanduser("~"), ".carbonblack")] cred_file = "credentials.response" profiles = [] for dir in dir_locations: cred_file_path = os.path.join(dir, cred_file) _MOD_LOGGER.debug("Searching CB profiles on '%s'", cr...
[ "def list_profiles(cls, base_directory):\n pc = config_file(os.path.join(base_directory, 'profiles', 'profile.config'))\n return pc[:]", "def available_profiles(cls) -> List[str]:\n return list(cfg.get(\"profiles\"))", "def list(self):\n # List is to be extended (directories should n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
machines host1,host2,host3... Set the machines where the job will be executed. A list of machines where the job will run, separated by commas or space.
def do_machines(self, args): lex_parser = shlex.shlex(args) lex_parser.whitespace += "," lex_parser.wordchars += "-" machine_list = [m for m in lex_parser] #TODO check if the hostname has space in it, if yes, invalid. if not machine_list: print("Invalid. See ...
[ "def get_machines():\r\n return listMachinesFomFile", "def _GetMachineList(self):\n machines = self._experiment.remote\n # All Label.remote is a sublist of experiment.remote.\n for l in self._experiment.labels:\n for r in l.remote:\n assert r in machines\n return machines", "def check...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a summary of the status of the jobs.
def do_status(self, args): status = self._leet.job_status for job in self.finished_jobs: status.append({"id" : job.id, "hostname" : job.machine.hostname, "plugin": job.plugin_instance.LEET_PG_NAME, "status" : j...
[ "def _get_job_status(self):\n total_hits = session.query(BoxHit).filter_by(training_job_id=self.id).count()\n num_hits_left = session.query(BoxHit).filter_by(training_job_id=self.id, outstanding=True).count()\n total_urls = self.num_urls\n num_urls_left = session.query(VideoTrainingURL)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancel all pending jobs
def do_cancel_all_jobs(self, args): self._leet.cancel_all_jobs()
[ "def cancel(self) -> None:\n for mjob in self._managed_jobs:\n mjob.cancel()", "def _cancel_all_jobs(self):\n status = self._get_status_obj()\n s = SLURM()\n for job_id in status.job_ids:\n s.scancel(job_id)\n logger.info('Pipeline job \"{}\" cancelled.'.fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get The future form of a verb. for example the future form of qal with Damma as a Haraka of future verb, we get yqolu. الحصول على صيغة الفعل في المضارع، فالفعل قال، وحركة عينه في المضارع صمة، نحصل على يقول.
def get_future_form(verb_vocalised, haraka=FATHA): word=verb_vocalised transitive=True; future_type=haraka if future_type not in (FATHA,DAMMA,KASRA): future_type=get_future_type_by_name(future_type); vb=verbclass(word,transitive,future_type); #vb.verb_class(); return vb.conjugate_tense_pronoun(TenseFuture,Pron...
[ "def morph_verb(word, ending, number, person, tense):\n\n if ending == 'root':\n return word\n if ending == 'infinitive': \n return \"to %s\" % word\n if word == 'be':\n # what 'internal' does no one knows... \n if ending == \"internal\":\n return morph_be(number, per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using Mapzen Search API to attempt to geocode a location string
def geocode(location): GeoDict = parse_mapzen_response(fetch_mapzen_response(location)) GeoDict['query_text'] = location return GeoDict
[ "def geocode(location):\n\n\ttxt = fetch_mapzen_response(location)\n\tmydict = parse_mapzen_response(txt)\n\tmydict['query_text'] = location\n\treturn mydict", "def geocode(addr_str):\n\n\tbase_url = 'http://gis.oregonmetro.gov/rlisapi2/locate/'\n\turl_template = '{0}?token={1}&input={2}&form=json'\n\turl = url_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests predictable success & failure of different values for a specified parameter when passed to a specified function
def test_parameter_values(func, var_name=None, fail_list=[], success_list=[], **kwargs): # If variable name is specified, test each value in fail_list # and success_list if var_name is not None: ...
[ "def _check_value(self, value, name, check_function):\n if check_function is not None:\n is_good = check_function(value) #May raise an exception\n assert is_good in [0,1,True,False]\n if not is_good:\n raise ValueError(\"Invalid parameter value %r for parameter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the NSR from openbaton based on user_info and the nsr
def release_resources(self, user_info, payload=None): ob_client = OBClient(user_info.name) logger.info('Deleting resources for user: {}'.format(user_info.name)) logger.debug('Received this payload: {}'.format(payload)) nsr = None try: nsr = json.loads(payload) ...
[ "def delete_user():", "def run(self):\n tenant_id = self.context[\"tenant\"][\"id\"]\n users = self.context[\"tenants\"][tenant_id][\"users\"]\n number = users.index(self.context[\"user\"])\n for network in self.context[\"tenants\"][tenant_id][\"networks\"]:\n # delete one o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears the fingerprint, making the object reusable
def clear(self): self._fingerprint = 0
[ "def fingerprint(self):\n self._fingerprint = None", "def identity(self):\n del(self.fingerprint)", "def clear(self):\n self._map = {}", "def clear (self):\n\n\t\tself.meta = {}\n\t\tself.data = {}", "def clear(self) -> None:\n del self._details\n del self._circuit\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a byte, returns the fingerprint
def update(self, m): if not six.PY3: m = ord(m) if ++self._buffpos >= self._size: self._bufpos = 0 om = self._buff[self._buffpos] self._buff[self._buffpos] = m self._fingerprint = self._add_byte(self._fingerprint & self._u[om], m) return self._fing...
[ "def add_byte(self, newbyte):\n self._data.append(newbyte)", "def _add_additional_byte(record):\n return record[:8] + '00' + record[8:]", "def pushBytesToIPFS(bytes):\n global IPFS_API\n\n res = IPFS_API.add_bytes(bytes)\n # TODO: verify that the add was successful\n\n # Receiving weir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates one task for each ingest chunk present in the build folder. It is required that the info file is already placed in order for this task to run succesfully.
def create_ingest_task(storage, task_queue): for filename in storage.list_files(prefix='build/'): t = IngestTask( chunk_path=storage.get_path_to_file('build/'+filename), chunk_encoding='npz', layer_path=storage.layer_path, ) task_queue.insert(t)
[ "def task_generate_tasks():\n \n yield {\n 'basename': 'generate_tasks',\n 'name': None,\n # 'doc': 'docs for X',\n 'watch': ['trains/'],\n 'task_dep': ['create_folders'],\n }\n \n for root, dirs, files in os.walk('trains/',topdown=False):\n for f in file...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
you can use this to fix black spots from when downsample tasks fail by specifying a point inside each black spot.
def create_fixup_downsample_tasks(task_queue, layer_path, points, shape=Vec(2048, 2048, 64), mip=0, axis='z'): vol = CloudVolume(layer_path, mip) offsets = compute_fixup_offsets(vol, points, shape) for offset in tqdm(offsets, desc="Inserting Corrective Downsample Tasks"): task = DownsampleTask( layer_p...
[ "def test_bad_start_point_recovers(self):\n self.star.analyze(start_point=(1000, 1000))\n self.test_passed()\n self.test_wobble_center()\n self.test_wobble_diameter()", "def CleanBadPixels(spectraUp,spectraDown):\n \n Clean_Up= []\n Clean_Do = []\n Clean_Av = []\n eps=25...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transfer an Eyewire consensus into neuroglancer. This first requires importing the raw segmentation via a hypersquare ingest task. However, this can probably be streamlined at some point. The volume map file should be JSON encoded and
def create_hypersquare_consensus_tasks(task_queue, src_path, dest_path, volume_map_file, consensus_map_path): with open(volume_map_file, 'r') as f: volume_map = json.loads(f.read()) vol = CloudVolume(dest_path) for boundstr, volume_id in tqdm(volume_map.items(), desc="Inserting HyperSquare Consensus Remap ...
[ "def process(source_transcript_json):\r\n # pdb.set_trace() # test\r\n output_json = infer(bucket_name, source_transcript_json, models_dir) \r\n success = upload_json_to_train(bucket_name, output_json, output_json['transcript_name'])\r\n return output_json", "def make_consensus(model_path, reference_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
affinity map masking block by block. The block coordinates should be aligned with cloud storage.
def create_mask_affinity_map_tasks(task_queue, aff_input_layer_path, aff_output_layer_path, aff_mip, mask_layer_path, mask_mip, output_block_start, output_block_size, grid_size ): for z in tqdm(range(grid_size[0]), desc='z loop'): for y in range(grid_size[1]): for x in range(grid_size[2...
[ "def GenerateMapAffinity(img,nb_vertex,pointsInterest,objects_centroid,scale):\n\n # Apply the downscale right now, so the vectors are correct. \n img_affinity = Image.new(img.mode, (int(img.size[0]/scale),int(img.size[1]/scale)), \"black\")\n # Create the empty tensors\n totensor = transforms.Compose([...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for card_info_lookup
def test_card_info_lookup(self): pass
[ "def test_cards_get(self):\n pass", "def _get_card(self, name: str) -> Dict:", "def test_get_info(self):\n pass", "def test_cards_get():\n card = mango.Cards.get(mango.Cards.list()[0].get(\"uid\"))\n ok_(card)", "def test_lookup(self):\n self.assertEqual(lookupCat('test'),'N')", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for lookup_account
def test_lookup_account(self): pass
[ "def test_get_account(self):\n pass", "def test_account_get(self):\n pass", "def test_retrieve_account(self):\n pass", "def test_get_account_using_get(self):\n pass", "def test_duo_account_get(self):\n pass", "def test_get_account_details_account_info_get(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the Brownian motion process
def bm_update(self,dt,delta): curr_coord = self.Coord self.History.append(curr_coord) change = self.bm_change(dt,delta) self.Coord = curr_coord + change
[ "def _sample_brownian_bridge_at(self, times, b=None):\n if b is None:\n b = self.b\n bm = self._sample_brownian_motion_at(times)\n return bm + np.array(times) * (b - bm[-1]) / times[-1]", "def update_bpm(self, new_bpm):\n self.bpm = new_bpm\n self.seconds2tick = 60. /...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup the events defined in the settings.
def _setup_events(conf): events = {} for name in conf.keys(): events[name] = Event(name=name) for listener in conf[name]: action = 'run' if ':' in listener: listener, action = listener.rsplit(':') events[name].add_listener(listener, action) ...
[ "def InitOtherEvents(self):\n\n pass", "def setup_helper(self, ext, events, errors):\n for num, type in events.iteritems():\n opcode = ext.first_event + num\n self.events[opcode] = type\n # register all events to their target!\n type.event_target_class.reg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download a remote dataset into path Fetch a dataset pointed by remote's url, save into path using remote's filename and ensure its integrity based on the MD5 Checksum of the downloaded file. Adapted from scikitlearn's sklearn.datasets.base._fetch_remote.
def download_from_remote(remote, save_dir, force_overwrite=False): if remote.destination_dir is None: download_dir = save_dir else: download_dir = os.path.join(save_dir, remote.destination_dir) if not os.path.exists(download_dir): os.makedirs(download_dir) download_path = os.pa...
[ "def _fetch_remote_data(remote, download_dir, data_home):\n\n file_path = '{}.zip'.format(download_dir)\n if not Path(file_path).exists():\n urllib.request.urlretrieve(remote.url, file_path)\n _unzip_dataset( file_path, data_home)", "def download_dataset_from_url(dataset_url_md5, name, to_path):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unzip a zip file inside it's current directory.
def unzip(zip_path, cleanup=False): zfile = zipfile.ZipFile(zip_path, 'r') zfile.extractall(os.path.dirname(zip_path)) zfile.close() if cleanup: os.remove(zip_path)
[ "def UnzipFile(self, zip_file, dest):\n command = ('Add-Type -A System.IO.Compression.FileSystem; '\n '[IO.Compression.ZipFile]::ExtractToDirectory(\\'{zip_file}\\', '\n '\\'{dest}\\')').format(zip_file=zip_file, dest=dest)\n self.RemoteCommand(command)", "def unzip(filename, is_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and untar a tar file.
def download_tar_file(tar_remote, save_dir, force_overwrite, cleanup=False): tar_download_path = download_from_remote(tar_remote, save_dir, force_overwrite) untar(tar_download_path, cleanup=cleanup)
[ "def _download(self):\n self._system.download_file(\"http://curl.haxx.se/download/\" + self._tar_name)", "def untar(conn, tarball, path):\n conn.run(f\"tar xf {tarball} -C {path}\")", "def download_untar(url, download_path, extract_path=None):\n file_name = url.split('/')[-1]\n if extract_path is ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Untar a tar file inside it's current directory.
def untar(tar_path, cleanup=False): tfile = tarfile.open(tar_path, 'r') tfile.extractall(os.path.dirname(tar_path)) tfile.close() if cleanup: os.remove(tar_path)
[ "def untar(path, fname, deleteTar=True):\n print(\"unpacking \" + fname)\n fullpath = os.path.join(path, fname)\n shutil.unpack_archive(fullpath, path)\n if deleteTar:\n os.remove(fullpath)", "def untar(conn, tarball, path):\n conn.run(f\"tar xf {tarball} -C {path}\")", "def untar(tarfile, o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Are a[0] and a[1] the same length?
def same_len(count, a:tuple): if len(a[0]) == len(a[1]): return count + 1 return count
[ "def size(A):\n\treturn (len(A[0]),len(A))", "def one_dim(a: cython.double[:]):\n a[0] *= 2\n return a[0], a.ndim", "def test_empty(self):\n a = np.ones((3, 4, 5))\n ai = np.ones((3, 0, 5), dtype=np.intp)\n\n actual = take_along_axis(a, ai, axis=1)\n assert_equal(actual.shape,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of tuples (spacy tokens, bpe_tokens) to compare tokens
def compare_joined_tokens(sp_tokens, bpe_tokens): out = [] for s, b in zip(sp_tokens, bpe_tokens): joined_bpe = functools.reduce(join_bpe, b, []) if s != joined_bpe: out.append((s, joined_bpe)) return out
[ "def compare_tokens(self, tokens1, tokens2):\n _tokens1 = [word for word in tokens1 if word in self.model.vocab]\n _tokens2 = [word for word in tokens2 if word in self.model.vocab]\n return self.model.n_similarity(_tokens1, _tokens2)", "def get_2grams(tokens):\n if len(tokens) < 2:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
is a[0] shorter than a[1]?
def count_less(count, a): if len(a[0]) < len(a[1]): return count + 1 return count
[ "def is_sorted(a):\n\tfor i in range(1,len(a)):\n\t\tif _less(a[i], a[i-1]):\n\t\t\treturn False\n\treturn True", "def is_longer(L1, L2):\n\n return len(L1) > len(L2)", "def check_array(a):\n print_array(\"FINAL\", a)\n i = 0\n while i < (len(a) - 1):\n if a[i + 1] < a[i]:\n print(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Take obj_a and obj_b and combines them under a boolean union object. returns the boolean object. Make sure that these objects aren't attached to a scene as this function does not clone them
def make_boole_union(obj_a, obj_b): # If we're missing any objects, return if obj_a is None or obj_b is None: return # Create a union type boolean object boole = c4d.BaseObject(c4d.Oboole) boole[c4d.BOOLEOBJECT_TYPE] = 0 # A Union B # Put them inside the boole obj_a.InsertUnder(b...
[ "def __and__(self, obj):\n return self._boolean_operation(obj, operator.__and__)", "def __or__(self, obj):\n return self._boolean_operation(obj, operator.__or__)", "def union_filters(a: Filter, b: Filter) -> Filter:\n if a is True or b is True:\n return True\n if isinstance(a, DenyList) and i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the coordinates of the origin bounding box that are intersected by the intersect bounding box. >>> bounding_box = 10, 100, 30, 110 >>> other_bbox = 20, 100, 40, 105 >>> bounding_box_intersection(bounding_box, other_bbox) (10, 0, 20, 5) >>> bounding_box_intersection(other_bbox, bounding_box) (0, 0, 10, 5) >>> co...
def bounding_box_intersection(origin: Tuple[int, int, int, int], intersect: Tuple[int, int, int, int]) \ -> Optional[Tuple[int, int, int, int]]: o_t, o_l, o_b, o_r = origin t, l, b, r = intersect out_top = max(t, o_t) out_left = max(l, o_l) out_bottom = min(b, o_b) out_right = min(r, o_...
[ "def intersection(box0, box1):\n if isinstance(box0, bounding_box_pb2.BoundingBox):\n box0 = BoundingBox(box0.start, box0.size)\n if isinstance(box1, bounding_box_pb2.BoundingBox):\n box1 = BoundingBox(box1.start, box1.size)\n if not isinstance(box0, BoundingBox):\n raise ValueError('box0 must be a Boun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aligns prediction Nodes to truth.
def align_nodes(truth: List[Node], prediction: List[Node], fscore=None) -> List[Tuple[int, int]]: if fscore is None: _, _, fscore = compute_recall_precision_fscore(truth, prediction) # For each prediction (column), pick the highest-scoring # True symbol. closest_truths = list(fscore.argmax(axis...
[ "def _setup_prediction(self):\n\n def dedup_output(sparse_tensor):\n sol_values = sparse_tensor.values - 4 * tf.to_int32(\n sparse_tensor.values >= 4\n )\n sol = tf.SparseTensor(\n sparse_tensor.indices,\n sol_values, # tf.Print(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
writes a pixel of varying size depending on the size of the overall image
def write_pixel(color, img_size, location, image, scale_factor): x_location = scale(location.item(0), scale_factor) y_location = scale(location.item(1), scale_factor) img_cont = int(img_size/100) if img_cont == 0: image.putpixel((x_location, y_location), color) else: write_to_range(...
[ "def add_pixel(img, index, size, pixel):\n img.putpixel((index % size, index // size), pixel)", "def exportImg(self):\n if self.superSampling:\n print(\"Exporting with size adjusted\")\n self.img = self.img.resize((int(self.width/2),int(self.height/2)),Image.NEAREST)\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loops through the given range coloring the pixels
def write_to_range(start_x, end_x, start_y, end_y, color, image, img_size): for curr_x in range(start_x, end_x, 1): for curr_y in range(start_y, end_y, 1): if curr_x > 0 and curr_y > 0: if curr_x < img_size and curr_y < img_size: image.putpixel((curr_x, curr_...
[ "def setColorBarRange(start=1,end=254):\n dislin.colran(start,end)", "def color(iteration_):\n global offset\n clr = iteration_ * offset\n return clr, 0, 255 - clr", "def compute(self):\n for y in range(self.size[1]):\n for x in range(self.size[0]):\n i = self.pixel_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge two sorted iterators, return a list
def merge_two_iterators(itr1: Iterator, itr2: Iterator) -> List: result = [] elem1, elem2 = next(itr1), next(itr2) def rest_elems(itr): for _, el in enumerate(itr): result.append(el) while True: if elem1 < elem2: result.append(elem1) try: ...
[ "def merge(iterators):\n streams = [iterator_to_stream(g) for g in [iter(y) for y in iterators]]\n heapq.heapify(streams)\n while streams:\n stream = heapq.heappop(streams)\n if stream is not None:\n val, stream = stream_next(stream)\n heapq.heappush(streams, stream)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a legacy XML project and raise a UserException if there was an error.
def load_xml(project, file_path): tree = ElementTree() try: root = tree.parse(file_path) except Exception as e: raise UserException( "there was an error reading the project file", str(e)) _assert(root.tag == 'Project', "Unexpected root tag '{0}', 'Project' ...
[ "def _importOld(oldFilePath):\r\n \r\n xml_obj = objectify.XML_Objectify(oldFilePath)\r\n return xml_obj.make_instance()", "def test_recover_from_bad_xml(self):\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n jp2 = Jp2k(self._bad_xml_file)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate an assertion and raise a UserException if it failed.
def _assert(ok, detail): if not ok: raise UserException("the project file is invalid", detail)
[ "def assert_that(self, assertion):\n if isinstance(assertion, Assertion):\n if not assertion.assertion_value:\n raise AssertionError(assertion.assertion_error_message)\n else:\n raise RuntimeError(\"The assertThat method expects an Assertion instance\")", "def as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a populated QrcPackage instance.
def _load_package(package_element): package = QrcPackage() package.name = package_element.get('name') _assert(package.name is not None, "Missing 'Package.name' attribute.") package.contents = _load_mfs_contents(package_element) package.exclusions = [] for exclude_element in package_element.i...
[ "def package_obj(self, *args, **kwargs):\n if self.package_path is None or not wc_is_package(self.package_path):\n return None\n return Package(self.package_path, *args, **kwargs)", "def _package(self):\n if self._package_obj is None:\n self._package_obj = self._import_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace any qmake scopes in a value.
def _replace_scopes(value): value = value.replace('linux-*', 'linux') value = value.replace('macx', 'macos') value = value.replace('win32', 'win') return value
[ "def scope(self, value):\n self._scope = json.dumps(value, indent=4)", "def set_scope_element(scope, key, value):\n scope=scope.copy()\n scope[key] = value\n return scope", "def set(self, scope, name, value):\n if not scope in self.vars:\n self.vars[scope] = {}\n self.va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift the mean value of `x_mod` such that it equals the mean of `x_org`.
def shift_mean(x_mod, x_org): @_decorate_validation def validate_input(): _numeric('x_mod', ('integer', 'floating', 'complex'), shape=(-1, -1)) _numeric('x_org', ('integer', 'floating', 'complex'), shape=x_mod.shape) validate_input() return x_mod + (x_org.mean() - x_m...
[ "def mean_shift_update(x, data, kernel):\n # first, calculate the interpoint distance\n d_squared = np.sum((data - x)**2, axis=1)\n\n # eqvaluate the kernel at each distance\n weights = kernel(d_squared)\n\n # now reweight each point\n shift = (data.T.dot(weights))/np.sum(weights)\n\n # return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stretch image such that pixels values are in the range [0, `max_val`].
def stretch_image(img, max_val): @_decorate_validation def validate_input(): _numeric('img', 'floating', shape=(-1, -1)) _numeric('max_val', ('integer', 'floating'), range_='(0;inf)') validate_input() min_ = img.min() max_ = img.max() if max_ > min_: val = max_val / (...
[ "def _scale(X, vmax=100, make_round=True, verbose=3):\n if verbose>=3: print('[d3heatmap] >Scaling image between [min-100]')\n try:\n # Normalizing between 0-100\n # X = X - X.min()\n X = X / X.max().max()\n X = X * vmax\n if make_round:\n X = np.round(X)\n exc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the user and term in the form.
def get_form_kwargs(self, **kwargs): kwargs = super(ChallengeVerifyView, self).get_form_kwargs(**kwargs) kwargs['display_term'] = self.display_term kwargs['user'] = self.request.user return kwargs
[ "def setUser(user):", "def set_term(browser, term):\n\n term_set = 'bwlkostm.P_FacStoreTerm2'\n\n browser.log.debug('Setting term to %s @ %s' % (term, term_set))\n result = browser.post(browser.banner_url(term_set), {'term': term})\n\n if not result.ok:\n raise ValueError(result)\n\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize each form in the formset with a challenge.
def get_form(self, form_class): formset = super(ChallengeVerifyView, self).get_form(form_class) challenges = Challenge.objects.select_related( 'candidate__user__userprofile', 'challenge_type').filter( verifying_user=self.request.user, candidate__term=self.display_term) fo...
[ "def initial_formset_data(self, request, step, formset):\n return None", "def initial_form_data(self, request, step, form):\n return None", "def _construct_form(self, i, **kwargs):\n form = super(BaseCodepointVariantFormSet, self)._construct_form(i, **kwargs)\n form.fields['when'].ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper method that returns a dictionary containing a requirement name and a form, to be used for each requirement in the template.
def get_entry(name, req, form): entry = {'requirement': name, 'form': form} form.initial['credits_needed'] = 0 if req: form.instance = req form.initial['credits_needed'] = req.credits_needed return entry
[ "def render_requirements(self):\n con = {}\n con[\"requirements\"] = self._get_requirements_list()\n return render_to_string(\"requirements_template.jinja\", con)", "def get_form_data(req):\n # read form data\n form_data = dict()\n print(type(req.form))\n for key, value in req.for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the candidate of the challenge to the requester.
def form_valid(self, form): form.instance.candidate = self.candidate messages.success(self.request, 'Challenge requested!') return super(CandidatePortalView, self).form_valid(form)
[ "def candidate(self, candidate):\n self._candidate = candidate", "def challenge(self, challenge):\n\n self._challenge = challenge", "def candidate_party(self, candidate_party):\n\n self._candidate_party = candidate_party", "def candidate_id(self, candidate_id):\n\n self._candidate_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Endpoint for updating a candidate's initiation status. The post parameters "candidate" and "initiated" specify the candidate (by Candidate pk) and their new initiation status, respectively.
def update_candidate_initiation_status(request): candidate_pk = request.POST.get('candidate') if not candidate_pk: return json_response(status=404) candidate = get_object_or_none(Candidate, pk=candidate_pk) initiated = json.loads(request.POST.get('initiated')) if not candidate or initiated i...
[ "def test_candidate_update(self):\r\n self.register_user()\r\n result = self.login_user()\r\n access_token = json.loads(result.data.decode())['access_token']\r\n\r\n # first, we create a candidate by making a POST request\r\n rv = self.client().post('/candidate',headers=dict(Autho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the division of this Game.
def division(self, division): self._division = division
[ "def division(self, division):\n \n self._division = division", "def set_divide(self, a_divide):\n self.set_parameter('divide', a_divide)\n return self", "def division(self):\n return self._division", "def set_divisions(self, nx=1, ny=1):\n\n self.nx = nx\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the round of this Game.
def round(self, round): self._round = round
[ "def round_num(self, round_num: int):\n\n self._round_num = round_num", "def setRounds(self, rounds):\n self.roundsToGo = rounds", "def setrounds(self, number):\n self._rounds = number", "def rounds(self, rounds):\n\n self._rounds = rounds", "def setRoundingRadius( self, radius )...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_name of this Game.
def player_a_name(self, player_a_name): self._player_a_name = player_a_name
[ "def player_name(self, player_name: str) -> None:\n assert_type(player_name, of_type=(str, NoStrClass), func_name=\"player_name\")\n self._player_name = player_name", "def set_name(self, input_name):\n self.playerName = input_name", "def player_b_name(self, player_b_name):\n\n self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_name of this Game.
def player_b_name(self, player_b_name): self._player_b_name = player_b_name
[ "def player_a_name(self, player_a_name):\n\n self._player_a_name = player_a_name", "def player_b_games(self, player_b_games):\n\n self._player_b_games = player_b_games", "def player_b_id(self, player_b_id):\n\n self._player_b_id = player_b_id", "def player_name(self, player_name: str) -> ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_id of this Game.
def player_a_id(self, player_a_id): self._player_a_id = player_a_id
[ "def player_a_games(self, player_a_games):\n\n self._player_a_games = player_a_games", "def set_id(self, player_id):\n pass", "def player_id(self, player_id):\n\n self._player_id = player_id", "def player_a_name(self, player_a_name):\n\n self._player_a_name = player_a_name", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_id of this Game.
def player_b_id(self, player_b_id): self._player_b_id = player_b_id
[ "def player_b_games(self, player_b_games):\n\n self._player_b_games = player_b_games", "def player_b_name(self, player_b_name):\n\n self._player_b_name = player_b_name", "def player_a_id(self, player_a_id):\n\n self._player_a_id = player_a_id", "def set_id(self, player_id):\n pass"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_points of this Game.
def player_a_points(self, player_a_points): self._player_a_points = player_a_points
[ "def give_points(id_player: str, id_tournament: str, points: float):\n player = Player.get(id_player)\n if player:\n player.set_points(id_tournament, points)", "def player_a_games(self, player_a_games):\n\n self._player_a_games = player_a_games", "def player_b_points(self, player...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_points of this Game.
def player_b_points(self, player_b_points): self._player_b_points = player_b_points
[ "def player_b_games(self, player_b_games):\n\n self._player_b_games = player_b_games", "def player_a_points(self, player_a_points):\n\n self._player_a_points = player_a_points", "def player_b_id(self, player_b_id):\n\n self._player_b_id = player_b_id", "def set_points(self):\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_games of this Game.
def player_a_games(self, player_a_games): self._player_a_games = player_a_games
[ "def player_b_games(self, player_b_games):\n\n self._player_b_games = player_b_games", "def games(self, games):\n\n self._games = games", "def games_played(self, games_played):\n\n self._games_played = games_played", "def player_a_points(self, player_a_points):\n\n self._player_a_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_games of this Game.
def player_b_games(self, player_b_games): self._player_b_games = player_b_games
[ "def player_a_games(self, player_a_games):\n\n self._player_a_games = player_a_games", "def games(self, games):\n\n self._games = games", "def player_b_points(self, player_b_points):\n\n self._player_b_points = player_b_points", "def player_b_id(self, player_b_id):\n\n self._player...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_rating of this Game.
def player_a_rating(self, player_a_rating): self._player_a_rating = player_a_rating
[ "def player_a_rating_adjustment(self, player_a_rating_adjustment):\n\n self._player_a_rating_adjustment = player_a_rating_adjustment", "def player_b_rating(self, player_b_rating):\n\n self._player_b_rating = player_b_rating", "def rating(self, rating):\n\n self._rating = rating", "def pla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_rating of this Game.
def player_b_rating(self, player_b_rating): self._player_b_rating = player_b_rating
[ "def player_b_rating_adjustment(self, player_b_rating_adjustment):\n\n self._player_b_rating_adjustment = player_b_rating_adjustment", "def player_a_rating(self, player_a_rating):\n\n self._player_a_rating = player_a_rating", "def setB(self, b):\n self.b = b", "def player_b_id(self, playe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_a_rating_adjustment of this Game.
def player_a_rating_adjustment(self, player_a_rating_adjustment): self._player_a_rating_adjustment = player_a_rating_adjustment
[ "def player_a_rating(self, player_a_rating):\n\n self._player_a_rating = player_a_rating", "def player_b_rating_adjustment(self, player_b_rating_adjustment):\n\n self._player_b_rating_adjustment = player_b_rating_adjustment", "def player_efficiency_rating(self, player_efficiency_rating):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the player_b_rating_adjustment of this Game.
def player_b_rating_adjustment(self, player_b_rating_adjustment): self._player_b_rating_adjustment = player_b_rating_adjustment
[ "def player_b_rating(self, player_b_rating):\n\n self._player_b_rating = player_b_rating", "def player_a_rating_adjustment(self, player_a_rating_adjustment):\n\n self._player_a_rating_adjustment = player_a_rating_adjustment", "def player_a_rating(self, player_a_rating):\n\n self._player_a_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the match_id of this Game.
def match_id(self, match_id): self._match_id = match_id
[ "def set_id(self, player_id):\n pass", "def set_match_id(match_id):\n conn = get_connect()\n conn.execute(\"UPDATE match SET isSearched = 1 WHERE matchId = \" + str(match_id))\n conn.commit()\n conn.close()\n print(\"matchId \" + str(match_id) + \" has been searched\")\n return", "def p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a list of cytoband objects to database
def add_cytobands(self, cytobands): LOG.debug(f"Inserting {len(cytobands)} cytoband intervals into database") result = self.cytoband_collection.insert_many(cytobands) LOG.debug(f"Number of inserted documents:{len(result.inserted_ids)}")
[ "def add_bangumis(bangumi_list):\n db = opendb()\n db.insert_multiple(bangumi_list)\n print(\n '{0} bangumi/s has been inserted into database.'.format(\n len(bangumi_list)\n )\n )\n db.close()", "def insert_object_list(session, object_list):\n session.add_all(object_list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary of cytobands with chromosomes as keys
def cytoband_by_chrom(self, build="37"): if "38" in str(build): build = "38" else: build = "37" match = {"$match": {"build": build}} group = { "$group": { "_id": "$chrom", "cytobands": { "$push": { ...
[ "def make_chrom_to_contigs(tabix_file: pysam.TabixFile) -> dict:\n return {\n # Eg '1': 'NC_000001.10',\n VERSIONLESS_CHROMS[c.split('.', 1)[0]]: c\n for c in tabix_file.contigs if c.startswith('NC')\n }", "def get_band_map(self) -> dict:\n raise NotImplementedError()", "def ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns `imgaug BoundingBoxesOnImage` object which can be used to boxes on the image
def get_bounding_boxes_on_image(self, image_shape): return BoundingBoxesOnImage(self.bboxes, image_shape)
[ "def bounding_boxes_math(image):\n image = (image>mean([amax(image),amin(image)]))\n image,ncomponents = measurements.label(image)\n objects = measurements.find_objects(image)\n result = []\n h,w = image.shape\n for o in objects:\n y1 = h-o[0].start\n y0 = h-o[0].stop\n x0 = o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of values, return the number of times high is broken >>> arr = np.array([11,12,9,8,13]) >>> list(high_count(arr)) [0, 1, 1, 1, 2]
def high_count(values): length = len(values) arr = np.zeros(length, dtype=np.int16) count = 0 max_val = values[0] for i in np.arange(1, length): if values[i] > max_val: max_val = values[i] count += 1 arr[i] = count return arr
[ "def low_count(values):\n length = len(values)\n arr = np.zeros(length, dtype=np.int16)\n count = 0\n min_val = values[0]\n for i in np.arange(1, length):\n if values[i] < min_val:\n min_val = values[i]\n count += 1\n arr[i] = count\n return arr", "def last_hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of values, return the number of times low is broken >>> arr = np.array([13,14,12,11,9,10]) >>> list(low_count(arr)) [0, 0, 1, 2, 3, 3]
def low_count(values): length = len(values) arr = np.zeros(length, dtype=np.int16) count = 0 min_val = values[0] for i in np.arange(1, length): if values[i] < min_val: min_val = values[i] count += 1 arr[i] = count return arr
[ "def high_count(values):\n length = len(values)\n arr = np.zeros(length, dtype=np.int16)\n count = 0\n max_val = values[0]\n for i in np.arange(1, length):\n if values[i] > max_val:\n max_val = values[i]\n count += 1\n arr[i] = count\n return arr", "def lower_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of values, return an array with the index of the corresponding last highs Note index starts at zero >>> arr = np.array([12,14,11,12,13,18]) >>> list(last_high(arr)) [0, 1, 1, 1, 1, 5]
def last_high(values): length = len(values) arr = np.zeros(length, dtype=np.int32) max_val = values[0] counter = 0 for i in np.arange(1, length): if values[i] > max_val: max_val = values[i] counter = i arr[i] = counter return arr
[ "def last_high(self):\n return self.data.last('1D').high.iat[0]", "def last_index( list, value ):\n return len( list ) - list[::-1].index( value ) - 1", "def last_occurance (arr, key):\r\n low_index = 0\r\n high_index = len(arr) - 1\r\n while low_index <= high_index:\r\n mid_index = lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Internal implementation of the image downloading. Opens the URLs file and iterates over each URL.
def _download_images(self, url_file, destination_dir, log_file): logger = self.setup_log(log_file) logger.info(config.LOG_INITIAL_MESSAGE % (url_file, destination_dir)) with open(url_file) as urls: for i, l in enumerate(urls): pass bar = progressbar.ProgressB...
[ "def load_images(self):\n\n # verify if self.urls is empty. in case it is not, we download the images from the urls list\n if self.urls == '':\n print('The scraping object doesn\\'t have a dictionary of urls to scrape.'\n + '\\n Please use .get_urls() to load the urls.')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads images from URLs given by the url_file, stores them into the directory destination_dir, and logs the progress in the log_file.
def download_images(self, url_file, destination_dir, log_file): try: self._download_images(url_file, destination_dir, log_file) except IOError as error: sys.stderr.write(str(error)) sys.exit(error.errno) except Exception as error: sys.stderr.write(...
[ "def _download_images(self, url_file, destination_dir, log_file):\n logger = self.setup_log(log_file)\n logger.info(config.LOG_INITIAL_MESSAGE % (url_file, destination_dir))\n\n with open(url_file) as urls:\n for i, l in enumerate(urls):\n pass\n bar = progressb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a psmeca Sm format string to a SymMT object
def psmeca2SymMT( string ): # convert first 12 columns into array mtline = NP.fromstring( string, count=12, sep =' ', dtype=float ) # get the location part c = mtline[0:3] # assume lon/lat/depth are centroid h = NP.array( [mtline[10], mtline[11], mtline[2]] ) # assume second lon/lat are hypoc...
[ "def psmeca2EigMT( string ): \n \n # convert first 12 columns into array\n mtline = NP.fromstring( string, count=12, sep =' ', dtype=float )\n \n # get the location part\n c = mtline[0:3] # assume lon/lat/depth are centroid\n h = NP.array( [mtline[10], mtline[11], mtline[2]] ) # assume second l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a psmeca Sm format string to a EigMT object
def psmeca2EigMT( string ): # convert first 12 columns into array mtline = NP.fromstring( string, count=12, sep =' ', dtype=float ) # get the location part c = mtline[0:3] # assume lon/lat/depth are centroid h = NP.array( [mtline[10], mtline[11], mtline[2]] ) # assume second lon/lat are h...
[ "def psmeca2SymMT( string ): \n\n # convert first 12 columns into array\n mtline = NP.fromstring( string, count=12, sep =' ', dtype=float )\n \n # get the location part\n c = mtline[0:3] # assume lon/lat/depth are centroid\n h = NP.array( [mtline[10], mtline[11], mtline[2]] ) # assume second lon/l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From an input file or stdin, read a list of moment tensors in psmeca form Expected format lon/lat/z/mrr/mtt/mpp/mrt/mrp/mtp/exp/lon0/lat0/str/anything else if isEig is false, return list of SymMT objects, otherwise get a list of EigMT objects
def read_psmecalist( istream , isEig=False ): mtlist=[] # this will be the output list # read everything alltxt = NP.genfromtxt( istream, delimiter='\n' , dtype=str) try: istream.close() except: tmp=1 # loop through all tensors n = len(alltxt) # check for desired out...
[ "def psmeca2EigMT( string ): \n \n # convert first 12 columns into array\n mtline = NP.fromstring( string, count=12, sep =' ', dtype=float )\n \n # get the location part\n c = mtline[0:3] # assume lon/lat/depth are centroid\n h = NP.array( [mtline[10], mtline[11], mtline[2]] ) # assume second l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert from a lon/lat/depth/strike/dip/rake/mag string to a double couple type
def sdr2dc( string ): # convert first 7 columns into array try: data = NP.fromstring( string, count=7, sep =' ', dtype=float ) except IndexError: print >> sys.stderr, "Error: Require 7 columns: lon/lat/depth/strike/dip/rake/mag" return None # get variables hypo = data[0:3 ] ...
[ "def fix_lon(l):\n l = l.replace(\"?\", \"\")\n if l[-1:] == \"E\":\n return float(l[:-1])\n if l[-1:] == \"W\":\n return -1 * float(l[:-1])\n return l", "def parse_geo(string, regex=None):\r\n string = string.strip()\r\n if regex is None:\r\n sep = r\"(\\s*[;,\\s]\\s*)\"\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a full update of the orderbook, asks and bids are expected to be in ascending and descending order respectively
def updateOrderbookFull(self, asks, bids): self.asks = asks self.bids = bids
[ "def update(self, update):\n try:\n price = float(update[0])\n count = int(update[1])\n amount = float(update[2])\n if count > 0:\n if amount > 0:\n self.bids[price] = amount\n else:\n self.asks[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Voice Shuffle the playing queue. Accepts no arguments.
def on_shuffle(self, event): self.pre_check(event) shuffle(self.get_player(event.guild.id).queue) api_loop(event.channel.send_message, "Queue shuffled.")
[ "def shuffle_button_pressed(self) -> None:\n value = self.shufflevar.get()\n current_song = self.songbox.get(tk.ACTIVE)\n if value == 1:\n random_song = random.randint(0,len(self.song_list)-1)\n pygame.mixer.music.queue(self.song_list[random_song])\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Voice Get the information of a certain song in the queue or the amount of songs in the queue. If an integer argument is input, then this will return the relevant queue entry. If a string is input, then the string will be used to search for queue entry titles. Otherwise, if no arguments are passed, this will return the ...
def on_queued_command(self, event, index=None): self.pre_check(event) if not self.get_player(event.guild.id).queue: api_loop( event.channel.send_message, "There aren't any songs queued right now.", ) elif index is None: api_loop...
[ "def _queue_text(self, queue):\n if len(queue) > 0:\n message = [f\"{len(queue)} songs in queue:\"]\n message += [\n f\" {index+1}. **{song.title}** (requested by **{song.requested_by.name}**)\"\n for (index, song) in enumerate(queue)\n ] # add...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Voice Move an item that's already queued to the front of the queue by index. Only accepts a single integer argument (the index of the target queue item).
def on_queue_next_command(self, event, index): self.pre_check(event) self.same_channel_check(event) if 1 < index <= len(self.get_player(event.guild.id).queue): index -= 1 self.get_player(event.guild.id).queue.insert( 0, self.get_player(even...
[ "async def moveTo(self, index):\n\n await self.VoiceClient.http.setQueueSource(self.tag, {\"index\": index})\n\n return self", "def moveSong(self, puid, index) :\n current = self.currentSong()\n songindex = [i for i in range(0, len(self.list)) if self.list[i][\"puid\"] == puid][0]\n# ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View the timeline of a transaction
def get_transaction_history(self, txn_id_or_ref): response = self.get(f"{self.gateway_path}/timeline/{txn_id_or_ref}") return response
[ "def history():\n\n #Query transactions by user id\n trans = Transactions.query.filter_by(owner=session['user_id']).all()\n\n #Convert Price to US Dollars and format transaction time\n for t in trans:\n t.price = usd(t.price)\n t.transacted = t.transacted.strftime('%Y-%m-%d %H:%M:%S')\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the index corresponding at the first occurence of value in list
def index(liste, value): for ii in range(len(liste)): if liste[ii] == value: return ii return None
[ "def find_index_of_val(mylist,value):\n l = [i[0] for i in mylist]\n return l.index(value)", "def linear_search_v2(lst, value):\n\n # The first index is included, the second is not, and the third is the\n # increment.\n for i in range(len(lst) - 1, -1, -1):\n if lst[i] == value:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates job_params dict for api call to launch a Plexus job. Some parameters required to launch a job are not available to the user in the Plexus UI. For example, an app id is required, but only the app name is provided in the UI. This function acts as a backend lookup of the required param value using the userprovided...
def construct_job_params(self, hook: Any) -> dict[Any, Any | None]: missing_params = self.required_params - set(self.job_params) if missing_params: raise AirflowException(f"Missing the following required job_params: {', '.join(missing_params)}") params = {} for prm in self.jo...
[ "def _create_job_spec(\n self,\n job_id: Text,\n training_input: Dict[Text, Any],\n job_labels: Optional[Dict[Text, Text]] = None) -> Dict[Text, Any]:\n\n job_spec = {\n 'display_name': job_id,\n 'job_spec': training_input,\n 'labels': job_labels,\n }\n return job_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to set the name of the render_database
def set_render_database_name(self, file_name): try: self.render_database=file_name self.filepath_render_database = os.path.join(self.filepath, self.render_database) print("set render_database filename to", file_name) except: print("setting render database ...
[ "def SetDatabaseName(self, name):\n self.database_name = name", "def db_name(self, db_name):\n self._db_name = db_name", "def db_name(self, db_name):\n\n self._db_name = db_name", "def database_name(self, database_name):\n self._database_name = database_name", "def set_database_name(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to set the name of the object_database
def set_object_database (self, file_name): try: self.object_database=file_name self.filepath_object_database = os.path.join(self.filepath, self.object_database) print("set object_database filename to", file_name) except: print("setting object database fail...
[ "def SetDatabaseName(self, name):\n self.database_name = name", "def db_name(self, db_name):\n self._db_name = db_name", "def database_name(self, database_name):\n self._database_name = database_name", "def db_name(self, db_name):\n\n self._db_name = db_name", "def set_DatabaseName(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to set the name of the output_database
def set_output_database (self, file_name): try: self.object_database=file_name self.filepath_output_database = os.path.join(self.filepath, self.output_database) print("set output_database filename to", file_name) except: print("setting object database fail...
[ "def SetDatabaseName(self, name):\n self.database_name = name", "def set_DatabaseName(self, value):\n InputSet._set_input(self, 'DatabaseName', value)", "def database_name(self, database_name):\n self._database_name = database_name", "def db_name(self, db_name):\n self._db_name = db_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method to import excel data to the correct database
def import_excel(self, filepath_excel,database_type): if database_type == "render": try: connection = sqlite3.connect(self.filepath_render_database) pointer = connection.cursor() sql_anweisung = """ INSERT INTO render_information ( ...
[ "def importXlsxIntoDb(input):\n #import global variable\n global UPLOAD_ID\n global PATIENT_NUM\n global DATABASE\n\n connection = db.create_connection(DATABASE)\n\n xlsx = pd.read_excel(input)\n\n #looping on each row\n print(\" - Importing data in DB\", end = '')\n for index, row in xls...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
establish connection to frontend notebook
def connect(): if not is_notebook(): print('Python session is not running in a Notebook Kernel') return global _comm kernel = get_ipython().kernel kernel.comm_manager.register_target('tdb', handle_comm_opened) # initiate connection to frontend. _comm = Comm(target_name='tdb', d...
[ "def init_notebook():\n \n # Note: not using IPython Comm objects yet, since they seem rather\n # undocumented and I could not get them to work when I tried for a bit.\n # This means though, that flexx in the notebook only works on localhost.\n \n from IPython.display import display, clear_output,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sends figure to frontend
def send_fig(fig, name): imgdata = BytesIO() fig.savefig(imgdata, format='png') imgdata.seek(0) # rewind the data uri = 'data:image/png;base64,' + urllib.parse.quote( base64.encodebytes(imgdata.getbuffer())) send_action("update_plot", params={"src": uri, "name": name})
[ "def send_figure(\n self, fig: go.Figure, export_image: Optional[Union[Path, str]] = \"\"\n ):\n self.loop.run_until_complete(self.check_backend())\n # pylint: disable=C0415\n from openbb_terminal.helper_funcs import command_location\n\n title = \"Interactive Chart\"\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Qt's MIME data object for data in valid QmxGraph's drag&drop format.
def create_qt_mime_data(data): from PyQt5.QtCore import QByteArray, QDataStream, QIODevice, QMimeData item_data = QByteArray() data_stream = QDataStream(item_data, QIODevice.WriteOnly) qgraph_mime = { 'version': qmxgraph.constants.QGRAPH_DD_MIME_VERSION, } qgraph_mime.update(data) ...
[ "def test_drag_drop_invalid_mime_type(loaded_graph, drag_drop_events) -> None:\n item_data = QByteArray()\n data_stream = QDataStream(item_data, QIODevice.WriteOnly)\n data_stream.writeString(\n json.dumps('<?xml version=\"1.0\"?><message>Hello World!</message>').encode('utf8')\n )\n\n mime_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
execute the NFS call If an error code is specified in the exceptions it means that the caller wants to handle the error himself
def execute(self, ops, exceptions=[], delay=5, maxretries=3): retry_errors = [NFS4ERR_DELAY, NFS4ERR_GRACE] state_errors = [NFS4ERR_STALE_CLIENTID, NFS4ERR_BADSESSION, NFS4ERR_BADSLOT, NFS4ERR_DEADSESSION] while True: res = self.sess.compound(ops) ...
[ "def gvfs_wrapper(self, func, *args):\n try:\n func(*args)\n except exceptions.BashException as exc:\n exc_msg = str(exc).strip()\n\n if exc_msg.endswith(\"Connection reset by peer\"):\n # re-mount and try again\n gvfs.mount(self.mtp_url)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates a postgres DB with a `test_df` table in the `connection_test` schema to test DataConnectors against
def test_connectable_postgresql_db(sa, test_backends, test_df): if "postgresql" not in test_backends: pytest.skip("skipping fixture because postgresql not selected") url = get_sqlalchemy_url( drivername="postgresql", username="postgres", password="", host=os.getenv("GE_...
[ "def setup_postgres_retriever_db():\n for test_data in all_script_names:\n install_dataset_postgres(test_data)", "def setUp(self):\n self.addTypeEqualityFunc(pandas.DataFrame, self.assertDataframeEqual)\n self.database_connection.connect()", "def dburl(\n tmp_path_factory: pytest....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the golden path for setting up a StreamlinedSQLDatasource using test_yaml_config
def test_golden_path_sql_datasource_configuration( mock_emit, caplog, empty_data_context_stats_enabled, sa, test_connectable_postgresql_db, ): context: DataContext = empty_data_context_stats_enabled with set_directory(context.root_directory): # Everything below this line (except for...
[ "def pytest_configure():\n exec(open(\"script/generate_sql\").read())", "def pytest_configure():\n with open(\"script/generate_sql\") as fp:\n exec(fp.read())", "def test_one_datasource_allowed(testdir: Testdir) -> None:\n schema = (\n testdir.SCHEMA_HEADER\n + '''\n datasou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the golden path for InferredAssetFilesystemDataConnector with PandasExecutionEngine using test_yaml_config
def test_golden_path_inferred_asset_pandas_datasource_configuration( mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory ): base_directory = str( tmp_path_factory.mktemp("test_golden_path_pandas_datasource_configuration") ) create_files_in_directory( directory...
[ "def test_golden_path_runtime_data_connector_pandas_datasource_configuration(\n mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory\n):\n base_directory = str(\n tmp_path_factory.mktemp(\"test_golden_path_pandas_datasource_configuration\")\n )\n\n create_files_in_direct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests output of test_yaml_config() for a Datacontext configured with a Datasource with RuntimeDataConnector. Even though the test directory contains multiple files that can be readin by GX, the RuntimeDataConnector will output 0 data_assets, and return a "note" to the user. This is because the RuntimeDataConnector is n...
def test_golden_path_runtime_data_connector_pandas_datasource_configuration( mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory ): base_directory = str( tmp_path_factory.mktemp("test_golden_path_pandas_datasource_configuration") ) create_files_in_directory( d...
[ "def test_golden_path_runtime_data_connector_and_inferred_data_connector_pandas_datasource_configuration(\n mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory\n):\n base_directory = str(\n tmp_path_factory.mktemp(\"test_golden_path_pandas_datasource_configuration\")\n )\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests output of test_yaml_config() for a Datacontext configured with a Datasource with InferredAssetDataConnector and RuntimeDataConnector. 1. The InferredAssetDataConnector will output 4 data_assets, which correspond to the files in the test_dir_charlie folder 2. RuntimeDataConnector will output 0 data_assets, and ret...
def test_golden_path_runtime_data_connector_and_inferred_data_connector_pandas_datasource_configuration( mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory ): base_directory = str( tmp_path_factory.mktemp("test_golden_path_pandas_datasource_configuration") ) create_f...
[ "def test_golden_path_runtime_data_connector_pandas_datasource_configuration(\n mock_emit, caplog, empty_data_context_stats_enabled, test_df, tmp_path_factory\n):\n base_directory = str(\n tmp_path_factory.mktemp(\"test_golden_path_pandas_datasource_configuration\")\n )\n\n create_files_in_direct...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used by flask to initialize a user
def init_user( app ): login_manager.init_app(app) app.register_blueprint(user)
[ "def InitUser():\n result = AppUser.query(AppUser.user == users.get_current_user()).fetch()\n\n if result:\n app_user = result[0]\n else:\n app_user = AppUser(user=users.get_current_user(),\n email=users.get_current_user().email())\n app_user.put()\n\n return app_user", "def use...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splits X in time if it is chronologically sorted.
def time_split(X, test_size=0.1): split_index = int(len(X)*(1 - test_size)) return X[:split_index], X[split_index:]
[ "def split_by_timegap(X, timename='time', hours=1):\n \n time = X[timename].values\n dt = np.diff(time)\n\n # print(len(time))\n \n i = [int(ii) for ii in np.where(dt>np.timedelta64(hours, 'h'))[0]] + [len(time)-1]\n i = [-1] + list(set(i))\n i.sort()\n \n # print('Split index'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_Implement this method_ Write a function that takes as input an input file and and output file name. Read the input file and write to the output file the courses listed with the semester that they occur in. For example 'cs 121' in the input file would be 'cs 121 fall' in the output file.
def addSemester(inputFile, outputFile): fall_classes = ['cs 121', 'cs 223', 'cs 260', 'cs 215'] spring_classes = ['cs 122', 'cs 166', 'cs 224', 'cs 251', 'cs 261'] with open(inputFile, 'r') as f: newlist = f.readlines() for i in range(len(newlist)): newlist[i] = new...
[ "def write_inputfile():", "def write_to_file(self):\n with open('Students/'+ self.student_id, 'w+', encoding = 'utf-8') as f:\n class_list = ','.join(self.classes_taken)\n new_file = self.student_name + ',' + self.grad_year + ',' + class_list\n f.write(new_file)", "def export_courses(c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
_Implement this method_ Write a function that takes as input an input file and stores the contents in a matrix. Each row in the matrix should be a line in the input file. Each element in a row should be an element from the line, delimited by a tab.
def storeTabDelimitedFile(inputFile): list0 = [] with open(inputFile, 'r') as f: newlist = f.readlines() #print(newlist) for i in range(len(newlist)): #newlist[i] = newlist[i].strip('\t') newlist[i] = newlist[i].strip('\n') # this makes the matrix easier to read...
[ "def read_matrix(file_name,delimiter=\"\\t\"):\n\n input_file=open(file_name)\n lines=input_file.readlines()\n i=0\n temp=lines[0]\n temp=temp.split(delimiter)\n matrix=np.zeros((len(lines),len(temp)),dtype=np.float128)\n \n for line in lines:\n s=line.split(\"\\t\")\n j=0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints and flushes the things passes as arguments.
def printnflush(*args): if pyscheduler.verbose: print args sys.stdout.flush()
[ "def print_flush(*args):\r\n\tprint(*args, end=\"\")\r\n\tsys.stdout.flush()", "def print_flush(*args):\n print(*args, end=\"\")\n sys.stdout.flush()", "def flushoutput(self):\n pass", "def printAndFlush(string):\n\tprint string\n\tsys.stdout.flush()", "def utool_print(*args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to run tasks inside a process. It implements an infinite loop controlled by the messages received from 'pipe_end'.
def run_task(process_name, tasks, pipe_end): task_ended = False try: while not task_ended: # Blocks until it receives a message message_type, value = pipe_end.recv() if message_type == "EXECUTE": result = tasks[value].run() pipe_end.se...
[ "def go(self):\n self.logger.info(\".go() starting\")\n for p in self.pipes:\n self.logger.debug(\".go() calling once on %s\" % p)\n while p.once():\n self.loop()\n self.loop()\n assert len(self.queue) == 0\n self.logger.debug(\".go() finished\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the process that will be in charge of executing the tasks and a pipe to communicate with the main process.
def __init__(self, process_name, target_function, tasks): self.pipe_start, self.pipe_end = multiprocessing.Pipe() printnflush ("Process started: %s"%process_name) self.process = multiprocessing.Process(group=None, target=target_function, ...
[ "def new_process() -> Process:\n return multiprocessing.Process()", "def start_new_processes(self):\n # initialize cache to mutualize calls to Variable.get in DAGs\n # needs to be done before this process is forked to create the DAG parsing processes.\n SecretCache.init()\n\n while ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }