query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Search for a webelement, get its text, compare with expected_text
def verify_text(self, expected_text: str, *locator): e = self.driver.find_element(*locator) actual_text = e.text assert expected_text == actual_text, f"Expected {expected_text} does not match actual {actual_text}"
[ "def get_text_in_element():\n nonlocal text_\n if text_ is None:\n text_ = element.text\n element_text = element.text\n if element_text == text:\n return element\n if text.lower() == element_text.lower():\n return el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
发送信息 ss_q 用于放置当前usv的状态信息,此信息需要发送给其他usv和监控端,实现集群协同 sp_q 用于放置当前usv的BPSO决策结果,并发送出去
def send_msg(ss_q, sp_q): print("开启发送信息线程") while True: if not ss_q.empty(): # 发送当前usv状态信息 client.send(b'\n') string_to_send = str(ss_q.get()) client.send(string_to_send.encode()) print("sending state message %s...\n" % string_to_send) ...
[ "def send_msg(ss_q, sp_q):\n while True:\n if not ss_q.empty(): # 发送当前usv状态信息\n ser.write(str.encode('\\n'))\n string_to_send = str(ss_q.get())\n ser.write(str.encode(string_to_send))\n print(\"sending state message %s...\\n\" % string_to_send...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the input history
def show_input_history(self): # copy with user multifilter pass
[ "def print_history(self) :\n\n self.history.display()", "def history():", "def do_history(self, args):\n print(self._hist)", "def show_history_log(self):\n self.visual.print_enum(self.visual.history_log)", "def show_history():\n\trecords = histcache.get_all_records()\n\t\n\tif (len(reco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display raw bibtex of the selection
def show_raw_bibtex(self, entry_idx=None): if entry_idx is None: entry_idx = self.selector.get_selection() else: entry_idx = self.selector.select_by_index(entry_idx) if not entry_idx: self.visual.error("Need a selection to show raw bibtex of") retu...
[ "def bibtex(self) -> str:\n a = BibDatabase()\n a.entries = [self.bib]\n return bibtexparser.dumps(a)", "def copy_raw_bibtex(self, entry_idx=None):\n if entry_idx is None:\n entry_idx = self.selector.get_selection()\n else:\n entry_idx = self.selector.selec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy the raw bibtex of the selection
def copy_raw_bibtex(self, entry_idx=None): if entry_idx is None: entry_idx = self.selector.get_selection() else: entry_idx = self.selector.select_by_index(entry_idx) if not entry_idx: self.visual.error("Need a selection to show raw bibtex of") retu...
[ "def copy_selection( self, ):\n try:\n data = self.msg_text.get( \"sel.first\", \"sel.last\" )\n pyperclip.copy( data )\n except Exception as exception: # if no selection\n pass", "def bibtex(self) -> str:\n a = BibDatabase()\n a.entries = [self.bib]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open the pdf of an entry
def pdf_open(self, arg=None): nums = self.selector.select_by_index(arg) if not nums or nums is None: self.visual.print("Need a selection to open.") # arg has to be a single string if utils.has_none(nums): self.visual.print("Need a valid entry index.") for ...
[ "def open_pdf(self, root):\n\t\tpdf_name = root + os.path.extsep + 'pdf'\n\t\tself.logger.info('Opening \"{0}\"...'.format(pdf_name))\n\t\tos.system('/usr/bin/open \"{0}\"'.format(pdf_name))", "def openPdf(self, file):\n\n #import subprocess\n #from subprocess import CalledProcessError\n\n # make sure th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Jump to a specific history step
def jump_history(self, index): if type(index) is str: index = utils.str_to_int(index) if self.reference_history_index == index: self.visual.error("Already on starting history.") return if index >= 0 and index < len(self.reference_history): self.ste...
[ "def _(event):\n event.current_buffer.go_to_history(event.arg - 1)", "def brws_go_forward(driver, _):\n brws_history_go(driver, 1)", "def ea_viewer_history_push_and_jump(*args):\n return _ida_kernwin.ea_viewer_history_push_and_jump(*args)", "def jumpto(*args):\n return _ida_kernwin.jumpto(*args)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to step +/ n steps to history
def step_history(self, n_steps=-1): n_steps = utils.get_single_index(n_steps) self.visual.debug("Stepping through a {}-long history, current index: {}, current length: {}, step is {}".format(len(self.reference_history), self.reference_history_index, len(self.reference_entry_id_list), n_steps)) i...
[ "def increment_steps(self):\n self.num_steps += 1", "def increment_step(self):\n self.steps = self.steps + 1", "def backtrack_steps():\n\n # Initialize position and number of steps\n x = 0\n n_steps = 0\n\n # Walk until we get to positive 1\n while x < 1:\n x += 2 * np.random...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display the history of past logs
def show_history_log(self): self.visual.print_enum(self.visual.history_log)
[ "def history():", "def show_history():\n\trecords = histcache.get_all_records()\n\t\n\tif (len(records) > 0):\n\t\tfor record in records:\n\t\t\tprint record[\"URL\"].ljust(ptcl.COLUMN_WIDTH) +\\\n\t\t\t\tptcl.TABLE_SEP + record[\"Time\"].ljust(ptcl.COLUMN_WIDTH)\n\telse:\n\t\tprint \"Empty History!\"", "def pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the reference list to its latest modificdation Calling the function after a search will set the reference list to the resulting entry set.
def change_history(self, new_reflist, modification_msg): self.visual.log("New reference list wrt: [{}], yielded {} items.".format(modification_msg, len(new_reflist))) self.push_reference_list(new_reflist, modification_msg) # unselect stuff -- it's meaningless now self.unselect()
[ "def setListModified(self):\r\n\r\n currentList = self.pdef.getCurrentListObject()\r\n #also set pdef.Modified for saving file\\\r\n self.pdef.Modified = True\r\n #print(\"setListModified - ListModified=%s\" % (currentList.ListModified)) # DBGDBG\r\n if(currentList.ListModified == False):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to attach a local pdf path to an entry
def set_local_pdf_path(self, str_selection=None): nums = self.selector.select_by_index(str_selection) if nums is None or not nums or len(nums) > 1: self.visual.error("Need a single selection to set pdf to.") return entry = self.entry_collection.entries[self.reference_entr...
[ "def pdfloc(entry, pdf_dir):\n pdfout = entry['ID'].replace(':', '_') + '.pdf'\n out_dir = pdf_dir\n if 'dir' in entry:\n out_dir = out_dir + entry['dir'] + '/'\n return out_dir + pdfout", "def put_attach_document(filename: str, entry_hash: str) -> str:\n g.ledger.file.insert_metadata(entry_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to cite an entry
def cite(self, arg=None): nums = self.selector.select_by_index(arg) if nums is None or not nums: self.visual.error("Need a selection to cite.") return citation_id = ", ".join([self.reference_entry_id_list[n] for n in nums]) citation = "\\cite{{{}}}".format(citatio...
[ "def cite(silent=False):\n if silent is False:\n print(__cite__)\n else:\n return __bibtex__", "def make_citation(meta):\n pass", "def how_to_cite(self):\n super().how_to_cite(cancer_type='colorectal cancer', pmid=31031003)", "def how_to_cite():\n print(\"For instructions on how...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search the web for a pdf pertaining to the current entry selection
def search_web_pdf(self, str_selection=None): nums = self.selector.select_by_index(str_selection) if nums is None or not nums or len(nums) > 1: self.visual.error("Need a single selection to download pdf to.") return entry_id = self.reference_entry_id_list[nums[0]] ...
[ "def pdf_open(self, arg=None):\n nums = self.selector.select_by_index(arg)\n if not nums or nums is None:\n self.visual.print(\"Need a selection to open.\")\n # arg has to be a single string\n if utils.has_none(nums):\n self.visual.print(\"Need a valid entry index.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the command line arguments and write the corresponding XDMF file.
def main(): parser = ArgumentParser( description="Write an XDMF file for post-processing results in HDF5.") parser.add_argument(dest="file_name", metavar="<filename>", help="path to an HDF5 file for which XDMF metadata should be written") parser.add_argument("-t", "--type", d...
[ "def exportBulletFile(*argv):", "def main():\r\n parser = argparse.ArgumentParser()\r\n\r\n parser.add_argument('-data', type=str, dest='data', default=None, help='xyz file')\r\n parser.add_argument('-output', type=str, dest='output', default=None, help='File name for output files')\r\n parser.add_arg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In this function, we read a csv file to separate the dataset into two parts called "nudity" and "normal". We, then, copy the nude images into the "nudity" folder and the other into the "normal" folder.
def process_raw_dataset(path_csv, processed_data): labels = defaultdict(list) with open(path_csv, 'rb') as csvfile: stream_data = csv.DictReader(csvfile, delimiter=',') for row in stream_data: for (k, v) in row.items(): labels[k].append(v) ...
[ "def preprocess_data(csv_file):\n\n # Load data\n x_train, x_val, x_test, y_train, y_val, y_test = load_train_data(csv_file)\n\n # Add mirror flip augmentation\n x_train, x_val, x_test, y_train, y_val, y_test = add_flipped_images(x_train, x_val, x_test, y_train, y_val, y_test)\n\n # Save as .npy\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert vector to one hot form.
def to_one_hot(v): n = len(v) m = max(v) + 1 out = np.zeros((n, m)) out[np.arange(n), v] = 1 return out
[ "def one_hot_encoding_vector(self, vector):\n enc = OneHotEncoder(sparse=False, n_values=self.number_of_unique_targets)\n matrix = enc.fit_transform([vector]).reshape((len(vector), enc.n_values))\n return matrix", "def _one_hot_encode(label_vector, total_num_labels):\n out = np.zeros(shape...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return best saved model from basename.
def best_model_from_dir(basename): models = glob.glob(basename + '*.index') best_model = None # get best model, if exists models_out = [] for m in models: match = re.match(re.escape(basename) + '(1?[0-9]{4}).index', m) if match: models_out.append(int(match.groups()[0])) ...
[ "def _get_best_single_model(self, pattern='_SN_', i='all'):\n tested_models = {}\n for model_file in os.listdir(self.models_path):\n if pattern in model_file:\n model = keras.models.load_model(os.path.join(self.models_path, model_file))\n if i=='all':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run predictions w/ test time rotation augmentation by angs
def predict_testaug(model, X, batchsize=None, angs=None): preds = [] for a in angs: print('rotating test set by angle: {:.2f}...'.format(a)) rotX = np.stack(Parallel(n_jobs=-1)(delayed(rotate) (im, a, preserve_range=True) ...
[ "def test():\n\n for data_path in tqdm(opt.DATA_PATH_LIST):\n \n # make save folder for each test dataset\n SAVE_PATH = os.path.join(opt.SAVE_PATH,os.path.basename(data_path))\n os.makedirs(SAVE_PATH,exist_ok=True)\n\n # get image data \n Img_paths = sorted(glob.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate a mass using the Torres calibration
def massTorres(teff, erteff, logg, erlogg, feh, erfeh): ntrials = 100 randomteff = teff + erteff * np.random.randn(ntrials) randomlogg = logg + erlogg * np.random.randn(ntrials) randomfeh = feh + erfeh * np.random.randn(ntrials) # Parameters for the Torres calibration: a1, a2, a3 = 1.5689, 1.37...
[ "def cal_mass(self):\n\n if not self.check_def(['E','px','py','pz']):\n sys.exit('Particle error: Quadri impulsion not define (error for mass routine)')\n\n\n \n if self.E**2-self.px**2-self.py**2-self.pz**2>1e-7: #precision problem\n self.mass=math.sqrt(self.E**2-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform the add ToDo request and return the data in case of success
def post_add_todo_request(self): response = requests.post( url=self.url, headers=self.default_headers, json=self.habitica_todo.to_json_dict() ) return get_data_or_exit(response)
[ "def add_todo():\n task = flask.request.form[\"task\"]\n todos.append(ToDo(task))\n return \"success\"", "def add_task(request):\n data = {\"success\": False}\n try:\n title = request.POST.get(\"title\")\n status = request.POST.get(\"status\")\n desc = request.POST.get(\"desc\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to get collection names of the current dataset
def get_current_collection_names(account, dataset): token = get_access_token() selected_dataset_id = get_dataset_id(token, dataset) r = requests.get(f"{PENNSIEVE_URL}/datasets/{selected_dataset_id}/collections", headers=create_request_headers(token)) r.raise_for_status() return r.json()
[ "def collections(self):\r\n\t\tself.fetch_collections()\r\n\t\treturn self._collection_names", "def get_collection_names(self):\n return self._collection_classes_by_name.keys()", "def get_collection():\n label1=subprocess.Popen(['mongo', 'pxe', '--eval', 'db.getCollectionNames()'], stdout=subprocess.P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to upload the collection tags of a dataset to Pennsieve
def upload_collection_names(account, dataset, tags): token = get_access_token() selected_dataset_id = get_dataset_id(token, dataset) if not has_edit_permissions(token, selected_dataset_id): abort(403, "You do not have permission to edit this dataset.") store = [] for tag in tags: ...
[ "def uploadData(self):", "def _upload_datastore():\n raise NotImplementedError", "def put_tags(self, tags_field, tags):\n self.document[tags_field] = tags", "def upload_data(self):\n labeled_ids = self.get_labeled_ids()\n\n users = []\n users_ids = []\n\n activities = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to reserve a DOI after dataset has been published
def reserve_dataset_doi(dataset): # sourcery skip: extract-method token = get_access_token() dataset_id = get_dataset_id(token, dataset) try: doi_request = requests.post(f"{PENNSIEVE_URL}/datasets/{dataset_id}/doi", headers=create_request_headers(token)) doi_request.raise_for_status() ...
[ "def reserve(data, username=None, password=None):\n if ('title' not in data):\n data['title'] = \"Placeholder Dataset Title\"\n \n data['set_reserved'] = \"true\"\n\n return post(data, username, password);", "def validate_reserve_request(self, doi: Doi):\n # For reserve requests, need to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to get the DOI of a dataset
def get_dataset_doi(dataset): token = get_access_token() dataset_id = get_dataset_id(token, dataset) try: doi_request = requests.get(f"{PENNSIEVE_URL}/datasets/{dataset_id}/doi", headers=create_request_headers(token)) if doi_request.status_code == 404: return {"doi": "No DOI fou...
[ "def doi(self):\n return LiteratureReader(self.record).doi", "def get_doi(ref):\n doi = None\n # if the DOI field is present\n if 'CB_DOI' in add_params.keys():\n for dd in ref.find_all('dd'):\n if len(dd.contents[0]) > 3:\n if dd.contents[0][:3] == 'DOI':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to get the package type counts of a dataset (package type counts are the amount of files in a dataset)
def get_package_type_counts(dataset_name): token = get_access_token() dataset_id = get_dataset_id(token, dataset_name) r = requests.get(f"https://api.pennsieve.io/datasets/{dataset_id}/packageTypeCounts", headers=create_request_headers(token)) r.raise_for_status() return r.json()
[ "def type_count():\n types = []\n for typ in Statistics.all_type():\n types.append({'label': typ.lower(), 'y': Statistics.type_count(typ)})\n fix_types = []\n for i in sorted(types, key=lambda k: k['y']):\n if i['y'] != 0:\n fix_types.append(i)\n return jsonify(result=fix_typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function used to get the total amount of items in a local dataset
def get_total_items_in_local_dataset(dataset_path): # count the amount of items in folder create_soda_json_total_items = 0 for _, dirs, filenames in walk(dataset_path): # walk through all folders and it's subfolders for Dir in dirs: if Dir[:1] != ".": create_soda_...
[ "def get_amount_of_items(self):\n amount = 0\n for item in self.get_items():\n amount += item.amount\n return amount", "def _get_total_records(self):\n return json.loads(requests.get(self.url).content)['meta']['results']['total']", "def total_items(collection):\n result...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function plots the average pdr for all links that have been made between mprs and their selectors in comparison to the average mpr achieved by all links.
def plot_mpr_pdr(options, tags=None, cursor=None): options['prefix'] = "mpr" if options['grayscale']: colors = options['graycm'](range(1, 10, 1)) else: colors = options['color'](range(1, 10, 1)) fig_1 = MyFig(options, xlabel='MPR vs NOMPR', ylabel='Fraction of MPRs', ...
[ "def plot_relativePowerToAverage(self):\n\n #fluct_avg = []\n fluct_PtP = []\n rem_PtP = []\n #rem_avg = []\n RPA = []\n\n for d in range(self.endDay-self.startDay):\n # calc avg powers in fluct and remainder for day d\n fluct_avg = (sum(self.fluctuati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare games using condorcet method with an IRV tiebreaker as described in
def main(): # Ask for games to compare. games = {} more_games = True while more_games: search = input("Enter board game to search (leave empty if finished):") if search: matches = bgg_compare.find_game(search) print("Games found:") for game_id, nam...
[ "def play_games(self, num, verbose=False, exit_threshold=(float('inf'), float('inf'))):\n player1_won = 0\n player2_won = 0\n draws = 0\n start_time = time.time()\n for _ in range(num):\n result = self.play_game(verbose=verbose)\n if result == self.game.Winne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test attitude number of terms.
def test_do_check_number_of_terms(self): self.assertTrue(self.a.do_check_number_of_terms(self.b)) self.assertFalse(self.a.do_check_number_of_terms(self.c))
[ "def do_check_number_of_terms(self, uAnotherAttitude):\n self_terms = self._terms\n other_terms = uAnotherAttitude.get_terms()\n if len(self_terms) != len(other_terms):\n return False\n return True", "def test_all_terms_accessor(self):\n all_terms = self.graph.getAllT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
kafka_setup func to setup up message broker for receives data
def kafka_setup(self): # To consume latest messages and auto-commit offsets consumer = KafkaConsumer('test-topic', group_id='test-consumer', bootstrap_servers=['kafka:9092']) filename = "/home/debianml/idsFinal/modelo_ultimo_newf...
[ "def __init__(self):\n self.producer = KafkaProducer(bootstrap_servers=os.getenv(\"BOOTSTRAP_SERVERS\"),client_id=\"test\",acks='all')", "def kafka_consumer_start():\n zkconnect = os.environ.get('zkconnect')\n if zkconnect == None: zkconnect = \"localhost\"\n FuseKafkaLog(zkconnect).start()", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
to get disabled layers
def disabled(self): return QgsProject.instance().readListEntry("Identify", "disabledLayers", "None")[0]
[ "def disableLayers(self):\n for df in arcpy.mapping.ListDataFrames(self.mxd):\n for lyr in arcpy.mapping.ListLayers(self.mxd, \"\", df):\n lyr.visible = False", "def select_layers(m, enable, disable):\n for l in m.layers:\n if l.name in enable:\n l.active = Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
To select objects in multiples layers inside a selection rectangle
def __select(self): searchRect = QgsRectangle(self.first, self.last) for layer in self.canvas().layers(): if not self.identified or layer.id() not in self.disabled(): if layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() in self.types: render...
[ "def findLayerSelection():\n \n curGeo = mari.geo.current()\n curChannel = curGeo.currentChannel()\n channels = curGeo.channelList()\n curLayer = mari.current.layer()\n layers = ()\n layerSelList = []\n chn_layerList = ()\n \n layerSelect = False\n \n if curLayer.isSelected():\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PAM pulse p(t) = p(nTB/sps) generation >>>>> pt = pampt(sps, ptype, pparms) <<<<<
def pampt(sps, ptype, pparms=[], plot='', duty=1): if ptype is 'rect': pt = np.ones(sps) elif ptype is 'tri': triarray = np.arange(0,1,(1/float(sps)))[1:] pt = np.concatenate([triarray,[1],triarray[::-1]]) elif ptype is 'sinc': k = pparms[0] beta = pparms[1] n...
[ "def pamhRt(sps, ptype, pparms=[]):\n pt = pampt(int(sps), ptype, pparms)\n hrt = multiply(pt,1/float(np.sum(np.power(pt,2))))\n hrt = hrt[::-1]\n return hrt", "def pampt(sps, ptype, pparms=[]):\n if ptype.lower() == 'rect':\n nn = np.arange(sps)\n pt = np.ones(nn.size)\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PAM normalized matched filter (MF) receiver filter h_R(t) = h_R(nTB/sps) generation >>>>> hRt = pamhRt(sps, ptype, pparms) <<<<<
def pamhRt(sps, ptype, pparms=[]): pt = pampt(int(sps), ptype, pparms) hrt = multiply(pt,1/float(np.sum(np.power(pt,2)))) hrt = hrt[::-1] return hrt
[ "def pam_pt(FB, Fs, ptype, pparms=[]):\n ptyp = ptype.lower()\n if (ptyp=='rect' or ptyp=='man' or ptyp=='msin'):\n kR = 0.5; kL = -kR\n elif ptyp=='tri':\n kR = 1.0; kL = -kR\n elif (ptyp=='rcf' or ptyp=='rrcf' or ptyp=='sinc'):\n kR = pparms[0]; kL = -kR\n else:\n kR = 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Review the state of the current main spreadsheet, create it if required (by merging the previous main + checklist) or by copying the previous main spreadsheet if the previous checklist is missing. This will determine which initial window will be shown
def spreadsheet_file_setup(self, current_date: MyDate, previous_date: MyDate) -> Tuple[str, str, str]: if not os.path.exists(self.spreadsheet_directory): os.makedirs(self.spreadsheet_directory) current_date_str = current_date.strdate previous_date_str = previous_date.strdate ...
[ "def sync_spreadsheet(self):\n\n\t\t# Open up the main sheet\n\n\t\t# Glob in columns to let us figure out which row each parent is in\n\n\t\t# For each parent\n\n\t\t\t# If any of the 'I fill out' entries are None (besides 'notes')\n\n\t\t\t\t# Get the row values and see if I updated any of them\n\n\t\t\t\t# If I ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solve the people selection for every natural budget B in the range [Bmin, Bmax] Gather a solution to each such B under self.solution_dictionary[B].
def solve(self, Bmin=2, Bmax=6, integer_programming=False, normalized_coverage=True, secondary_objective_coefficient=0.01, risk_manager=None) -> Tuple[bool, str]: if self.state == "Initial_main_spreadsheet_loaded": self.solutions_dictionary = {} self.fig_output_dir = os.pat...
[ "def random_choose_candidate_solve (x_v, C, A, S, budgets, start_time, verbose=True):\n A = A.copy()\n edges_removed = []\n budget = np.max(budgets)\n results_info = []\n for i in range(budget):\n if (len(C) == 0):\n # Maximum balance achieved -> budget high.\n results_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Analyse the AST built from `str_definition`.
def _analyse_ast(str_code: str) -> Tuple[bool, Set[str]]: node = ast.parse(str_code) visitor = VarCounterVisitor() visitor.visit(node) return visitor.has_return, visitor.get_vars()
[ "def compile(self, expr_str, code):\n\n # Evaluation proceeds in two steps. First parse the string into\n # an AST, represented by a ValueTree.\n # Then traverse the AST converting it into one or more lines of\n # Python3 code.\n\n # The parser normally should not raise any exece...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method for compiling subroutines
def compile_subroutine(self): xml = '<subroutineDec>\n' if self.tokenizer.get_token() == 'constructor': xml += self.tokenizer.keyword() + self.tokenizer.identifier() else: xml += self.tokenizer.keyword() + self.tokenizer.keyword() xml += self.tokenizer.identifier() + self.tokenizer.symbol() self....
[ "def __compile_subroutine_body(self):\r\n self.compile_statements()", "def _compile_subroutine_call(self):\n\n nme = self.tokens[self._cur_ind][\"value\"]\n self._process_token(\"type\", \"identifier\")\n\n if self.tokens[self._cur_ind][\"value\"] == \"(\":\n self._process_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for distinguishing among statements and executing appropriate compilation methods
def compile_statements(self): if self.tokenizer.get_token() == 'do': self.compile_do() elif self.tokenizer.get_token() == 'let': self.compile_let() elif self.tokenizer.get_token() == 'while': self.compile_while() elif self.tokenizer.get_token() == 'return': self.compile_return() elif self.tokeni...
[ "def compile_statements(self) -> None:\n while self._get_current_token() != '}':\n if self._get_current_token() in self.STATEMENT_TOKENS:\n getattr(self, 'compile_' + self._get_current_token())()\n else:\n raise CompilationEngineError(f\"{self._get_current_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for compiling return statements
def compile_return(self): xml = '<returnStatement>\n' + self.tokenizer.keyword() self.outfile.write(xml) if self.tokenizer.get_token() != ';': self.compile_expression() xml = self.tokenizer.symbol() + '</returnStatement>\n' self.outfile.write(xml)
[ "def _compile_return(self):\n self._xmltranslator.open_section(\"returnStatement\")\n self._process_token(\"value\", \"return\")\n is_void = True\n while is_term(self.tokens[self._cur_ind]):\n is_void = False\n self._compile_expression()\n self._vmtranslator....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for compiling if statements
def compile_if(self): xml = '<ifStatement>\n' + self.tokenizer.keyword() + self.tokenizer.symbol() self.outfile.write(xml) self.compile_expression() xml = self.tokenizer.symbol() + self.tokenizer.symbol() + '<statements>\n' self.outfile.write(xml) while self.tokenizer.get_token() != '}': self.compile...
[ "def compile_if(self):\r\n lab1 = self.class_name + \".L\" + str(self.label_index)\r\n self.label_index += 1\r\n lab2 = self.class_name + \".L\" + str(self.label_index)\r\n self.label_index += 1\r\n self.tokenizer.advance() # ignore 'if' keyword\r\n self.tokenizer.advance(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for compiling terms.
def compile_term(self): self.outfile.write('<term>\n') count = 0 while(self.tokenizer.get_token() not in [')',']',';',',', '/', '|', '<', '>', '=', '*', '+', '&']): if self.tokenizer.get_token().isdigit(): self.outfile.write(self.tokenizer.int_value()) elif '"' in self.tokenizer.get_token(): self...
[ "def compileTerm(self):\n firstType = self.tokenizer.tokenType # The first token type\n firstVal = self.tokenizer.tokenVal # The first token value\n self.tokenizer.advance() # Advances to the second token of the term, or to the first token after the term.\n secondType = self.tokenizer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for compiling expression list
def compile_expression_list(self): self.compile_expression() while(self.tokenizer.get_token() == ','): self.outfile.write(self.tokenizer.symbol()) self.compile_expression()
[ "def __compile_expression_list(self, xml_tree):\n tk = self.__tokenizer\n # check is list is empty, meaning next token is )\n if tk.get_token_type() == SYMBOL and tk.get_next_token() == ')':\n xml_tree.text = '\\n'\n return\n\n # expression\n self.__compile_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get ref_dict and original xml. Return modified xml.
def changeXML(request): if request.is_ajax(): mod_xml = change_XML(request.POST.get("origXML", None), request.POST.get("refDict", None)) return HttpResponse(mod_xml)
[ "def get_document_xml():", "def translate_xml(self):\n self._from_origin_to_dict()\n self._from_dict_to_destination()\n return self", "def xml_obj(self):\n return self._xml_obj", "def test_xml_to_dict_and_back(self):\n # etree_to_dict(e) and dict_to_etree(d)\n e = ope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot the boundary of the decision function of a classifier.
def plot_decision_function(fitted_classifier, range_features, ax=None): from sklearn.preprocessing import LabelEncoder feature_names = list(range_features.keys()) # create a grid to evaluate all possible samples plot_step = 0.02 xx, yy = np.meshgrid( np.arange(*range_features[feature_names[...
[ "def plot_decision_boundary(model, X, y, title=\"\"):\n # Set min and max values and give it some padding\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n h = 0.01\n # Generate a grid of points with distance h between them\n xx, yy = np....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
No args, returns public IP as string.
def get_public_ip(): public_ip = get('https://api.ipify.org').text return public_ip
[ "def getPublicIP():\r\n\t\r\n\treturn request.urlopen('http://ip.42.pl/raw').read().decode()", "def get_public_ip() -> str:\n try:\n return json.loads(urlopen(\"https://api.myip.com\").read())[\"ip\"]\n except Exception as e:\n return \"\"", "def get_public_ip(self):\n ip_addr = reque...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an Observable, return the hexdigest of the MD5 computation used for hal9000.
def _compute_hal9000_md5(observable: Observable) -> str: md5_hasher = md5() md5_hasher.update(observable.type.encode('utf-8', errors='ignore')) md5_hasher.update(observable.value.encode('utf-8', errors='ignore')) return md5_hasher.hexdigest()
[ "def MD5(self) -> _n_0_t_3[_n_0_t_9]:", "def md5hash(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"md5hash\")", "def ComputeMD5Hex(byte_str):\r\n hasher = hashlib.md5()\r\n hasher.update(byte_str)\r\n return hasher.hexdigest()", "def _md5(input):\n m = hashlib.md5()\n m.upda...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an observable sequence that stays connected to the source indefinitely to the observable sequence. Providing a subscriber_count will cause it to connect() after that many subscriptions occur. A subscriber_count of 0 will result in emissions firing immediately without waiting for subscribers.
def auto_connect(self, subscriber_count: int = 1) -> Observable[_T]: connectable_subscription: List[Optional[abc.DisposableBase]] = [None] count = [0] source = self is_connected = [False] if subscriber_count == 0: connectable_subscription[0] = source.connect() ...
[ "def rx_publish(\n an_observable: Observable,\n subject_handler: Optional[SubjectHandler] = None,\n connection_handler: Optional[ConnectableObservableHandler] = None,\n subject_factory: SubjectFactory = rx_subject,\n) -> ConnectableObservable:\n _ref_count_activated = False # Flag to enable auto-con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return page title and description from the global variable pages if a match with current node page.src_pathname is found.
def get_page_contents(node): try: return (SITE_NAME + ' | ' + PAGES[node.page.src_pathname][0], \ PAGES[node.page.src_pathname][1]) except KeyError: return ('%%%TITLE%%%', '')
[ "def pages(self):\n if getattr(self, '_pages', False):\n return self.home.joinpath('%s-pages' % self.name)", "def available_pages(app='sample'):\n j = lambda a, s, t: ('.'.join([a, s]), t)\n return [\n j(app, 'home', 'Home'),\n j(app, 'contactus', 'Contact Us'),\n j(ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if `df` is already loaded in, if not, load from file.
def _check_df_load(df): if isinstance(df, str): if df.lower().endswith('json'): return _check_gdf_load(df) else: return pd.read_csv(df) elif isinstance(df, pd.DataFrame): return df else: raise ValueError(f"{df} is not an accepted DataFrame format.")
[ "def load_database():\n try:\n db = pd.read_pickle(config.get_full_db_path())\n print('Loading saved key dataframe')\n print(db)\n except FileNotFoundError:\n print('No saved key dataframe')\n db = pd.DataFrame() #Initialize empty db\n db.to_pickle(config.get_full_db_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether or not a transformation should be performed.
def _check_do_transform(df, reference_im, affine_obj): try: crs = getattr(df, 'crs') except AttributeError: return False # if it doesn't have a CRS attribute if not crs: return False # return False for do_transform if crs is falsey elif crs and (reference_im is not None or aff...
[ "def can_retransform(self):\r\n return self._can_retransform", "def _is_transformable(self):\n if not self._app.get_paths():\n raise NotTransformable(\"No image to\")\n elif not edit_supported(self._app.get_path()):\n raise NotTransformable(\"Filetype not supported for\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a geometry is loaded in. Returns the geometry if it's a shapely geometry object. If it's a wkt string or a list of coordinates, convert to a shapely geometry.
def _check_geom(geom): if isinstance(geom, BaseGeometry): return geom elif isinstance(geom, str): # assume it's a wkt return loads(geom) elif isinstance(geom, list) and len(geom) == 2: # coordinates return Point(geom)
[ "def convert_geometry(geometry: Optional[GeometryLike]) -> Optional[shapely.geometry.base.BaseGeometry]:\n\n if isinstance(geometry, shapely.geometry.base.BaseGeometry):\n return geometry\n\n if isinstance(geometry, dict):\n if GeoJSON.is_geometry(geometry):\n return shapely.geometry....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if `im` is already loaded in; if not, load it in.
def _check_skimage_im_load(im): if isinstance(im, str): return skimage.io.imread(im) elif isinstance(im, np.ndarray): return im else: raise ValueError( "{} is not an accepted image format for scikit-image.".format(im))
[ "def load_image(self, path):\n if path:\n self.original_image = cv2.imread(path, 1)\n self.prepare_images()", "def is_image_loaded(self):\n return self.loaded", "def load_image(filename):\n rgb = imread(filename)\n return UncertainImage(rgb)", "def load_image(self, im...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts data to a numpy array of dtype ``theano.config.floatX``.
def floatX(arr): return np.asarray(arr, dtype=theano.config.floatX)
[ "def _to_numpy_ndarray(cls, data):\n if isinstance(data, np.ndarray):\n return data\n arr = np.array(data, dtype=np.float)\n if len(arr.shape) == 1:\n arr = np.reshape(arr, newshape=(1, arr.shape[0]))\n return arr", "def as_floatX(variable):\n\n if isinstance(v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
> Exibe a ajuda interativa de um "comando" do Python.
def ajuda(com): título(f'Acessando o manual do comando \'{com}\'', cor='azul') print(cores['branco']) help(com) print(end=cores['sem']) sleep(2)
[ "def ejecutar_comando(comando):\n comando = comando.decode('UTF-8')\n proc = subprocess.Popen(comando, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n salida, error = proc.communicate() # ! Si la variable 'error', está vacía no hay error\n if error: \n return False\n return salid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This tries to complete lcdict column keys.
def completer_func_cols(text, state): return [x for x in lc_keys if x.startswith(text)][state]
[ "def test_columnsAsDictKeys(self):\n values = {self.schema.FOO.BAR: 1}\n self.assertEquals(values, {self.schema.FOO.BAR: 1})\n values.pop(self.schema.FOO.BAR)\n self.assertEquals(values, {})", "def get_lang1_keys(self):\n return self.get_columns() #alias for get_columns", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the 'exp_by_states' function
def test_exp_by_states(self): api = my_mock.api_mock({"items": [{'state': 'Waiting', 'id': 10134}, {'state': 'Waiting', 'id': 10135}, {'state': 'Running', 'id': 10130}]}) states_d = helpers.exps_by_states_dict(api, helpe...
[ "def eval_exp_table(self):\n\n maximum = max(self.exp_states, key=self.exp_states.get)\n minimum = min(self.exp_states, key=self.exp_states.get)\n print(maximum, self.exp_states[maximum])\n print(minimum, self.exp_states[minimum])", "def generate_states(esncell, xs, h0):\n (map_ih, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a response with a template depending if the request is ajax or not and it renders with the given context.
def render_to_response(self, context, **response_kwargs): if self.request.is_ajax(): template = self.page_template else: template = self.get_template_names() return self.response_class( request=self.request, template=template, context=c...
[ "def on_template_response(self, context, **kwargs):\r\n request = kwargs.setdefault(\"request\", RequestFactory().get(\"/\"))\r\n\r\n res = TemplateResponse(request, \"some/template.html\", context)\r\n\r\n return self.on_response(res, **kwargs)", "def render_to_response(self, context):\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs an ASA calculation. This function takes a selection of atoms (in the most common case all atoms in a structure) and lattice coordinates (in the most common a 3x3 box of unitcells). This function should be considered lowlevel and not part of the interface.
def _run_asa(atoms, lattice_coords, spoints, probe=1.4, bucket_size=5, \ MAXSYM=200000): # get array of radii inflated by probe size of the selection of atoms. atom_radii = array(atoms.getData('radius', forgiving=False)) + probe # get array of coordinates atom_coords = array(atoms.getData('...
[ "def calcASA(atoms, probe=1.4, n_sphere_point=960):\r\n atoms.setRadii(getAtomRadii(atoms))\r\n\r\n sphere_points = generate_sphere_points(n_sphere_point)\r\n const = 4.0 * math.pi / len(sphere_points)\r\n\r\n test_point = [0.0, 0.0, 0.0]\r\n areas = []\r\n\r\n coords_all = atoms.getCoords()\r\n\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepares input entities for ASA calculation, which includes masking water molecules and water chains.
def _prepare_entities(entities): # First we mask all water residues and chains with all residues masked # (water chains). lattice_residues = einput(entities, 'R') lattice_residues.maskChildren('H_HOH', 'eq', 'name') lattice_chains = einput(entities, 'C') lattice_chains.maskChildren([], 'eq', 'v...
[ "def prepare(self, adinputs=None, **params):\n log = self.log\n log.debug(gt.log_message(\"primitive\", \"prepare\", \"starting\"))\n\n filenames = [ad.filename for ad in adinputs]\n paths = [ad.path for ad in adinputs]\n\n timestamp_key = self.timestamp_keys[\"prepare\"]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Escapes all the elements of the array
def escaped(array): return list(map(re.escape, array))
[ "def _escape(strings):\n ret = []\n for string in strings:\n if string == '[' or string == ']' or string == \"\\\"\":\n string = '\\\\' + string\n ret.append(string)\n return \"\".join(ret)", "def encode(array):\n return ''.join(map(unichr, array))", "def _escape_squarebrack...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates if the type is from a source file
def _validate_source(self, tipo): self.source_type = True self._get_source(tipo) return self.source_type
[ "def is_source(filename):\n\n accepted = {\n '.c', '.cc', '.cp', '.cpp', '.cxx', '.c++', '.m', '.mm', '.i', '.ii',\n '.mii'\n }\n __, ext = os.path.splitext(filename)\n return ext.lower() in accepted", "def _source_check(self):\n\n _extension = self.source[-3:]\n if _extens...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates if the type is a built in type
def _validate_built_in(self, tipo): self.source_type = False self.source_file = "builtin" return tipo in self.c_built_ins or self._match_array(tipo, self.c_built_in_array_types)
[ "def is_builtin_type(s):\n cls, flags = parse_type(s)\n if cls in _type_default_values:\n return True\n return False", "def CheckType(self, *args, **kwargs):\n pass", "def is_builtin_type(tp):\n return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the source file of the type received
def _get_source(self, tipo): if self._match_array(tipo, self.c_array_types): tipo = tipo.strip()[:-4] db = Database() query = "SELECT type_source FROM types WHERE type_name = '" + tipo + "' ORDER BY type_id" self.source_file = list(db.execute_query(query)) if self.so...
[ "def _read_source(self):\n \n if self.fileType == FTPythonCompiled or \\\n self.fileType == FTCompiledModule:\n return None\n \n filename = Filename(self.filename)\n filename.setExtension('py')\n try:\n file = open(filename, 'rU')\n ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all types from the database and adds their arrays types for regex
def _get_types(self): db = Database() self.c_built_ins = list(map(lambda tup: tup[0], db.select_built_types())) self.c_built_in_array_types = r'^(' + '|'.join(self.escaped(self.c_built_ins)) + ')\[[0-9]*\]' self.c_types = list(map(lambda tup: tup[0], db.select_types())) self.c_a...
[ "def data_types():\n\n return ...", "def initTypes(self):\n self.types = [ty.NoneType]*self.numcols()\n for k,row in enumerate(self.data):\n for i in range(self.numcols()):\n val = row[i]\n typ = self.types[i]\n if not val is None:\n if typ in [ty.NoneType,ty.IntType]:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total number of twitter shares for the given URL
def twitter_shares_for_url(url): score = 0 response = requests.get(TWITTER_URL % url) response_dict = json.loads(response.text) try: score = int(response_dict['count']) except KeyError: pass return score
[ "def getSharedCount(articleURL):\n try:\n response = requests.get(articleURL)\n if(response.status_code != 200):\n return\n \n parser = bs4.BeautifulSoup(response.content, 'html.parser')\n sharedcount = parser.find(\"span\", attrs={\"class\": \"c-sharebox__stats-number c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the total number of facebook shares/likes/comments for the given URL
def facebook_shares_for_url(url): score = 0 response = requests.get(FB_URL % url) response_dict = json.loads(response.text) try: if type(response_dict) == dict: score = int(response_dict['shares']) except KeyError: pass return score
[ "def twitter_shares_for_url(url):\n score = 0\n response = requests.get(TWITTER_URL % url)\n response_dict = json.loads(response.text)\n try: \n score = int(response_dict['count'])\n except KeyError:\n pass\n return score", "def get_fb_score(url):\n\n try:\n fb_url = 'htt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request User RDR API token and return as a header
def get_token(): token = getpass.getpass('Paste in your RDR API token and press Enter:') return {'Authorization': 'token ' + token}
[ "def auth_header(token):\n return {'Authorization': f'Bearer {token}'}", "def UserToken(self) -> object:", "def __call__(self, r):\n r.headers[\"Authorization\"] = \"Bearer \" + self.token\n return r", "def get_token():\n print(\"entrou no busca token safra\")\n queryset = ReqBuilder.ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that documentation exists for all classes and methods in the BaseModel
def check_documentation(self): self.assertIsNotNone(BaseModel.__doc__) self.assertIsNotNone(__init__.__doc__) self.assertIsNotNone(__str__.__doc__) self.assertIsNotNone(save.__doc__) self.assertIsNotNone(to_dict.__doc__)
[ "def test_method_docs(self):\n for func in dir(BaseModel):\n self.assertTrue(len(func.__doc__) > 0)", "def test_method_docs(self):\n for func in dir(Amenity):\n self.assertTrue(len(func.__doc__) > 0)", "def test_method_docs(self):\n for func in dir(Rectangle):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that instance and attributs created.
def test_instance_created(self): base_model = BaseModel() self.assertIsInstance(base_model, BaseModel) self.assertTrue(hasattr(base_model, "created_at")) self.assertTrue(hasattr(base_model, "updated_at"))
[ "def test_InstancesAttributes(self):\n self.assertTrue(hasattr(self.new_user, \"email\"))\n self.assertTrue(hasattr(self.new_user, \"password\"))\n self.assertTrue(hasattr(self.new_user, \"first_name\"))\n self.assertTrue(hasattr(self.new_user, \"last_name\"))", "def test_get_attribute...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that id attribute is a string type.
def test_id_type(self): base_model = BaseModel() self.assertTrue(base_model.id, str)
[ "def test_id_string(self):\n b6 = Base(\"test\")\n self.assertEqual(b6.id, \"test\")", "def test_id_attribute_is_not_a_string(self):\n c = Clip(id='shot1')\n with self.assertRaises(TypeError) as cm:\n c.id = 123\n\n self.assertEqual(\n cm.exception.message,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a positive samples dataset.
def load_positive_dataset( filenames, positive_batch_size, walk_length ): positive_example_parser = PositiveExampleParser(walk_length) ds = tf.data.Dataset.from_tensor_slices(filenames) ds = ds.shuffle(len(filenames)) ds = ds.interleave( tf.data.TFRecordDataset, cycle_length=tf.data.AUTOTUNE, ...
[ "def init_positive_examples(self, data_path):\n self.pos_features = glob.glob(os.path.join(data_path, \"*_pos-features_*\"), recursive=True)\n # Now collect the corresponding labels!\n self.pos_labels = []\n for feature_path in self.pos_features:\n feature_parts = feature_path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inject random uniform negative sampling into the tf.data.Data pipeline. This function assumes the input node id space has been compressed on [0, num_nodes1].
def add_uniform_random_negatives( ds, num_nodes, num_negs_per_pos, ): negative_sampler = RandomUniformNegativeSampler(num_nodes, num_negs_per_pos) return ds.map( negative_sampler, deterministic=False, num_parallel_calls=tf.data.AUTOTUNE )
[ "def global_uniform_negative_sampling(\n self, num_samples, exclude_self_loops=True, replace=False, etype=None\n ):\n raise NotImplementedError(\n \"global_uniform_negative_sampling not implemented yet\"\n )", "def neg_sampling_transform(data):\n train_neg_edge_index = negati...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize expected edge score callable.
def __init__( self, weights, edge_score_norm ): self.weights = weights self.edge_score_norm = edge_score_norm
[ "def add_expected_edge_score(\n ds,\n weights = None,\n edge_score_norm = None,\n):\n expected_edge_score_fn = ComputeExpectedEdgeScore(\n weights=weights, edge_score_norm=edge_score_norm\n )\n return ds.map(\n expected_edge_score_fn,\n deterministic=False,\n num_parallel_calls=tf.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the expected edge score in a tf.data.Dataset pipeline.
def add_expected_edge_score( ds, weights = None, edge_score_norm = None, ): expected_edge_score_fn = ComputeExpectedEdgeScore( weights=weights, edge_score_norm=edge_score_norm ) return ds.map( expected_edge_score_fn, deterministic=False, num_parallel_calls=tf.data.AUTOTUNE, )
[ "def evaluate(predicted_edges, graph):\n count = 0\n for edge in predicted_edges:\n if graph.has_edge(*edge):\n count+=1\n return count/len(predicted_edges)", "def evaluate(self, dataset):\n success = 0\n for sample, labelVector, label in dataset.tests:\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that creates a layer of a neural network using dropout
def dropout_create_layer(prev, n, activation, keep_prob): dropout = tf.keras.layers.Dropout(keep_prob) initializer = tf.keras.initializers.VarianceScaling(scale=2.0, mode=("fan_avg")) tensor = tf.layers.Dense(units=n, activation=activation, ...
[ "def dropout_create_layer(prev, n, activation, keep_prob):\n init = tf.contrib.layers.variance_scaling_initializer(mode=\"FAN_AVG\")\n regularizer = tf.layers.Dropout(keep_prob)\n layer = tf.layers.Dense(n, activation, name='layer',\n kernel_initializer=init,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for perturb_light_post
def test_perturb_light_post(self): Parameters = Parameters() response = self.client.open('/perturb/light', method='POST', data=json.dumps(Parameters), content_type='application/json') self...
[ "def test_post_party(self):\n pass", "def test_crouch_posture(self):\n self.assertTrue(\n PepperPostureTest.pepper_virtual.goToPosture(\"Crouch\", 0.5))\n self.assertTrue(\n PepperPostureTest.pepper_virtual.goToPosture(\"crouch\", 0.5))", "def test_v2_recognize_post(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for perturb_nodefail_post
def test_perturb_nodefail_post(self): Parameters = Parameters2() response = self.client.open('/perturb/nodefail', method='POST', data=json.dumps(Parameters), content_type='application/json') ...
[ "def test_post_party(self):\n pass", "def test_null_author(self, client):\n assert len(post.posts) == 0\n response = client.post('/post/submit', data=dict(\n topic='neg_test'\n ), follow_redirects=True)\n assert response.status_code == 200\n assert len(post.pos...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for perturb_sensor_post
def test_perturb_sensor_post(self): Parameters = Parameters1() response = self.client.open('/perturb/sensor', method='POST', data=json.dumps(Parameters), content_type='application/json') s...
[ "def test_v2_recognize_post(self):\n pass", "def test_post_nveto_pmts(self):\n pass", "def test_perturb_light_post(self):\n Parameters = Parameters()\n response = self.client.open('/perturb/light',\n method='POST',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for start_post
def test_start_post(self): response = self.client.open('/start', method='POST') self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
[ "def test_mark_post_process_complete_create(self):\n pass", "def test_create_stage_using_post(self):\n pass", "def test_post_foods(self):\n pass", "def test_post_transaction_pattern(self):\n pass", "def test_post_chain(self):\n pass", "def _on_test_begin(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decompress a version 2 |isphx| |objects.inv| bytestring. The ``prefixed comment lines are left unchanged, whereas the
def decompress(bstr): from sphobjinv.error import VersionError def decompress_chunks(bstrm): """Handle chunk-wise zlib decompression. Internal function pulled from intersphinx.py@v1.4.1: https://github.com/sphinx-doc/sphinx/blob/1.4.1/sphinx/ ext/intersphinx.py#L79-L124. ...
[ "def decompression_inversion():\n dna_seq, bin_seq, comp_seq, file_comp = binary_to_seq()\n \n #bwt reconstruction\n table = [\"\"] * len(dna_seq)\n\n for i in range(0,len(dna_seq),1):\n table = [dna_seq[i] + table[i] for i in range(0,len(dna_seq))]\n table = sorted(table)\n \n or...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle chunkwise zlib decompression.
def decompress_chunks(bstrm): decompressor = zlib.decompressobj() for chunk in iter(lambda: bstrm.read(BUFSIZE), b""): yield decompressor.decompress(chunk) yield decompressor.flush()
[ "def __handle_decompression(self, x):\n if self.__compress:\n return zlib.decompress(x)\n return x", "def decompress(self, data):\n decompressor = zlib.decompressobj(zlib.MAX_WBITS | 16)\n data = decompressor.decompress(data) + decompressor.flush()\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compress a version 2 |isphx| |objects.inv| bytestring. The ``prefixed comment lines are left unchanged, whereas the
def compress(bstr): from sphobjinv.re import pb_comments, pb_data # Preconvert any DOS newlines to Unix s = bstr.replace(b"\r\n", b"\n") # Pull all of the lines m_comments = pb_comments.findall(s) m_data = pb_data.finditer(s) # Assemble the binary header comments and data # Comments a...
[ "def _compress(self, stream: BinaryIO, body: str):\n\n def writestr(s):\n stream.write(s.encode())\n\n body = body.encode()\n comp_body = zlib.compress(body)\n adler_chksum = zlib.adler32(comp_body)\n writestr('PIAFILEVERSION_2.0,CTBVER1,compress\\r\\npmzlibcodec')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize Random Aisle Turn Planning Environment
def __init__(self, params=None, draw_new_turn_on_reset=True, seed=None, rng=None): if rng is None: self._rng = np.random.RandomState() else: self._rng = rng self.seed(seed) self._draw_new_turn_on_reset = draw_new_turn_on_reset turn_params = self._draw_ra...
[ "def initialize(config_data):\r\n\tglobal ENVIRONMENT\r\n\tENVIRONMENT = environment.Environment(config_data)\r\n\tglobal RANDOMIZER\r\n\tRANDOMIZER = random.Random(ENVIRONMENT.RANDOM_SEED)", "def test_random_init_test():\n env = ML10(env_type='test')\n assert len(env._task_envs) == 5\n for task_env in e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render humanfriendly representation of the environment on the screen.
def render(self, mode='human'): return self._env.render(mode)
[ "def render(self, mode='human'):\n\n if self.RENDER_ENV_ONLY:\n SCREEN_W = 600\n SCREEN_H = 600\n \n if self.viewer is None:\n from gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(SCREEN_W, SCREEN_H)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the state of the environment
def set_state(self, state): self._env.set_state(state)
[ "def set_env(**kwargs):\n _env.set(**kwargs)", "def set_state(self, state):\n self.set_last_state(state)\n self.root.set_state(state)\n self.stage = AppStage(state[\"app_state\"][\"stage\"])", "def set_state(self,state):\n self.__state = state", "def set_state(self, state):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draw random turn params
def _draw_random_turn_params(self): return TurnParams( main_corridor_length=self._rng.uniform(10, 16), turn_corridor_length=self._rng.uniform(4, 12), turn_corridor_angle=self._rng.uniform(-3./8. * np.pi, 3./8.*np.pi), main_corridor_width=self._rng.uniform(0.5, 1.5...
[ "def draw(watts):", "def set_random_parameters(self):\n self.a = randint(1, self.p - 1)\n self.b = randint(0, self.p)\n # print(self.a, self.b)", "def go():\n startX = random.randint(-200, -100)\n startY = random.randint(100, 150)\n widtha = random.randint(30, 70)\n heighta = ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract egocentric map and path from rich observation
def _extract_egocentric_observation(self, rich_observation): costmap = rich_observation.costmap robot_pose = self._env.get_robot().get_pose() ego_costmap = extract_egocentric_costmap( costmap, robot_pose, resulting_origin=(self._egomap_x_bounds[0], self._egom...
[ "def normalized_ache():\n return {\n \"id\": \"normalize.gene:ACHE\",\n \"type\": \"GeneDescriptor\",\n \"value\": {\n \"id\": \"hgnc:108\",\n \"type\": \"Gene\"\n },\n \"label\": \"ACHE\",\n \"xrefs\": {\n \"ensembl:ENSG00000087085\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lazy parsing for tags.
def _parse_tags(self): tokens = self.tags_str[1:].split(";") self._tags = { k.strip(): v for token in tokens for k, v in [token.split("=")] }
[ "def parse_tags(self):\n tags = []\n try:\n for tag in self._tag_group_dict[\"tags\"]:\n tags.append(Tag(tag))\n except:\n return tags\n return tags", "def _parse_tags(tags):\n tag_dict = {}\n for tag in tags:\n tag_name = \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main listen loop. First ensures the client is connected. Following that it will receive messages every second and call the handler function.
def _listen(self): if not self.is_connected: self.connect() while True: data = self.recv() ping = PING_RE.match(data) if ping: self.handle_ping(ping.group(1)) else: result = self.handle_message(data) ...
[ "def listen(self):\n # first create the server socket\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server.bind((self.host, self.port))\n while True:\n client_socket, client_addr = server.ac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts an event and function and registers that function as an event handler to be called. If unique is set to true then all other handlers will be removed.
def register_handler(self, event, fn, unique=False): if event not in self._registry or unique: self._registry[event] = [fn] else: self._registry[event].append(fn) return fn
[ "def register(self, event, fn):\n\n # TODO: Can we check the method signature?\n self._handler_dict.setdefault(event, [])\n if fn not in self._handler_dict[event]:\n self._handler_dict[event].append(fn)", "def add_handler(handler_list, handler_function):\n if not handler_functio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Square distance between two points
def getSquareDistance(p1, p2): dx = p1[0] - p2[0] dy = p1[1] - p2[1] return dx * dx + dy * dy
[ "def square_distance(a, b):\n return np.sum((a-b)**2)", "def distance(a: Point, b: Point) -> float:\n return math.sqrt(math.pow(b.x - a.x, 2) + math.pow(b.y - a.y, 2))", "def distance(x1: float, y1: float, x2: float, y2:float) -> float:\n return round(math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) , 2)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Square distance between point and a segment
def getSquareSegmentDistance(p, p1, p2): x = p1[0] y = p1[1] dx = p2[0] - x dy = p2[1] - y if dx != 0 or dy != 0: t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy) if t > 1: x = p2[0] y = p2[1] elif t > 0: x += dx * t ...
[ "def get_distance_point_to_segment(p, s):\r\n area = triangle_area([p, s.p1, s.p2])\r\n d = get_distance_point_to_point(s.p1, s.p2)\r\n h = 2. * area / d\r\n\r\n return h", "def segment_point_distance_sq(x1, y1, x2, y2, px, py):\n pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)\n if pd2 == 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the tuple of terms for the expression.
def terms(self) -> Tuple[Term, ...]: ...
[ "def ast_getterms(n):\n if type(n) is ast.Name:\n return [[n.id]]\n elif type(n) is ast.Constant or type(n) is ast.Num:\n return [[n.n]]\n elif type(n) is ast.Expression:\n return ast_getterms(n.body)\n elif type(n) is ast.UnaryOp:\n assert type(n.op) is ast.USub\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the strength for the constraint.
def strength(self) -> float: ...
[ "def strength(self):\n return self._strength", "def strength(self):\n # type: () -> NexGuardWatermarkingStrength\n return self._strength", "def GetStrength(self) -> float:\n ...", "def strength(self):\n # The limiting factor in strength is how much the Materials can stretch\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Indicate if the constraint is violated in teh current state of the solver.
def violated(self) -> bool: ...
[ "def did_solve(self) -> bool:\n return self._solution.info.status == \"solved\"", "def is_solved(self):\n return not self.grid", "def _is_violated(self, rel: Tuple[NAryMatrixRelation, float, float], val) -> bool:\n m, min_val, max_val = rel\n # Keep only the assignment of variables p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a constraint to the solver.
def addConstraint(self, constraint: Constraint, /) -> None: ...
[ "def add_constraint(self, constraint):\n self.constraints.append(constraint)", "def add_constraint(self, constraint):", "def add_constraint(self, constraint):\n\n constraint.index = len(self.constraints)\n self.constraints[constraint.name] = constraint", "def add_constraint(self, constrai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a constraint from the solver.
def removeConstraint(self, constraint: Constraint, /) -> None: ...
[ "def removeConstraint(self, *args):\n return _libsbml.Model_removeConstraint(self, *args)", "def del_constraint(self, node, name):\r\n return self._send({'name': 'delConstraint', 'args': [node, name]})", "def remove_constraint(self, label: Hashable, *, cascade: bool = False):\n if cascade:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether the solver contains a constraint.
def hasConstraint(self, constraint: Constraint, /) -> bool: ...
[ "def ok(self, solution):\n if self.constraints is not None:\n for constraint in self.constraints:\n if not constraint(solution):\n return False\n return True", "def _param_in_constr(constraints):\n for constr in constraints:\n if len(lu....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an edit variable to the solver.
def addEditVariable( self, variable: Variable, strength: float | Literal["weak"] | Literal["medium"] | Literal["strong"] | Literal["required"], /, ) -> None: ...
[ "def add_variable(self, var_id, lb=None, ub=None, vartype=VarType.CONTINUOUS, persistent=True, update_problem=True):", "def doEdit(var, value, target):\n currentValue = target.get(var, \"\")\n newValue = Simplifier.simplify(str(value).replace(f\"{{{var}}}\", str(currentValue)))\n target[var] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }