query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Convert (list of )+ tokens to a padded LongTensor.
def get_long_tensor(tokens_list, batch_size, pad_id=PAD_ID): sizes = [] x = tokens_list while isinstance(x[0], list): sizes.append(max(len(y) for y in x)) x = [z for y in x for z in y] tokens = torch.LongTensor(batch_size, *sizes).fill_(pad_id) for i, s in enumerate(tokens_lis...
[ "def get_long_tensor(tokens_list, batch_size, pad_id=constant.PAD_ID):\n sizes = []\n x = tokens_list\n while isinstance(x[0], list):\n sizes.append(max(len(y) for y in x))\n x = [z for y in x for z in y]\n tokens = torch.LongTensor(batch_size, *sizes).fill_(pad_id)\n for i, s in enumer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit a word, given edit and seq2seq predictions.
def edit_word(word, pred, edit_id): if edit_id == 1: return word elif edit_id == 2: return word.lower() elif edit_id == 0: return pred else: raise Exception("Unrecognized edit ID: {}".format(edit_id))
[ "def edit(self, data: str) -> None:\n original_words = []\n content = []\n for word in self.db.query(data):\n entry = self.dict2entry(word)\n original_words.append(entry.word)\n content.append(entry.get_str())\n\n # Launch editor with the matched entries\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup the name of the word vectors file, given a directory and the language shorthand.
def get_wordvec_file(w2v_name, wordvec_dir, shorthand, wordvec_type=None): lcode, tcode = shorthand.split('_', 1) # locate language folder word2vec_dir = os.path.join('../..', wordvec_dir, 'word2vec', w2v_name) fasttext_dir = os.path.join('../..', wordvec_dir, 'fasttext', w2v_name) lang_dir =...
[ "def vocabulary_file_by_name(working_dir, key):\n return os.path.join(\n working_dir,\n transform_fn_io.TRANSFORM_FN_DIR,\n 'assets',\n key)", "def language_label(fn):\n bn = path.basename(fn)\n n = path.splitext(bn)[0]\n n = n.replace('_vocab', '')\n return n", "def filename(la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adjust the evaluation interval adaptively. If cur_dev_size <= thres_dev_size, return base_interval; else, linearly increase the interval (round to integer times of base interval).
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval): if cur_dev_size <= thres_dev_size: return base_interval else: alpha = round(cur_dev_size / thres_dev_size) return base_interval * alpha
[ "def get_base_step(scale):\n return EPS ** (1. / scale)", "def linear_warmup(base_value, max_warmup_iter, cur_step):\n if max_warmup_iter <= cur_step:\n return base_value\n return base_value * cur_step / max_warmup_iter", "def exp_warmup(base_value, max_warmup_iter, cur_step):\n if max_warmup...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unmap a list of list of indices, by optionally copying from src_tokens.
def unmap_with_copy(indices, src_tokens, vocab): result = [] for ind, tokens in zip(indices, src_tokens): words = [] for idx in ind: if idx >= 0: words.append(vocab.id2word[idx]) else: idx = -idx - 1 # flip and minus 1 ...
[ "def unmap_with_copy(indices, src_tokens, vocab):\n result = []\n for ind, tokens in zip(indices, src_tokens):\n words = []\n for idx in ind:\n if idx >= 0:\n words.append(vocab.id2word[idx])\n else:\n idx = -idx - 1 # flip and minus 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prune decoded sequences after EOS token.
def prune_decoded_seqs(seqs): out = [] for s in seqs: if EOS in s: idx = s.index(EOS) out += [s[:idx]] else: out += [s] return out
[ "def prune_decoded_seqs(seqs):\n out = []\n for s in seqs:\n if constant.EOS in s:\n idx = s.index(constant.EOS_TOKEN)\n out += [s[:idx]]\n else:\n out += [s]\n return out", "def remove_EOS_PAD(long_phrase):\n i=0\n phrase= []\n\n while len(long_phr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prune a decoded hypothesis
def prune_hyp(hyp): if EOS_ID in hyp: idx = hyp.index(EOS_ID) return hyp[:idx] else: return hyp
[ "def prune_hyp(hyp):\n if constant.EOS_ID in hyp:\n idx = hyp.index(constant.EOS_ID)\n return hyp[:idx]\n else:\n return hyp", "def test_prune(self, tensor_observable, expected):\n O = tensor_observable\n\n O_pruned = O.prune()\n assert isinstance(O_pruned, type(exp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort a series of packed list, according to a ref list. Also return the original index before the sort.
def sort(packed, ref, reverse=True): assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list) packed = [ref] + [range(len(ref))] + list(packed) sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))] return tuple(sorted_packed[1:])
[ "def sort(packed, ref, reverse=True):\n assert (isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list)\n packed = [ref] + [range(len(ref))] + list(packed)\n sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]\n return tuple(sorted_packed[1:])", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unsort a sorted list, based on the original idx.
def unsort(sorted_list, oidx): assert len(sorted_list) == len(oidx), "Number of list elements must match with original indices." _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
[ "def unsort(sorted_list, oidx):\n assert len(sorted_list) == len(oidx), \"Number of list elements must match with original indices.\"\n _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))]\n return unsorted", "def unsort_dim(seq, sort_inds, dim=0):\n inv_inds = np.zeros_like(sort_inds...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unsort a sorted tensor on its 0th dimension, based on the original idx.
def tensor_unsort(sorted_tensor, oidx): assert sorted_tensor.size(0) == len(oidx), "Number of list elements must match with original indices." backidx = [x[0] for x in sorted(enumerate(oidx), key=lambda x: x[1])] return sorted_tensor[backidx]
[ "def unsort_dim(seq, sort_inds, dim=0):\n inv_inds = np.zeros_like(sort_inds)\n for i, ind in enumerate(sort_inds):\n inv_inds[ind] = i\n seq = torch.index_select(seq, dim, to_tensor(inv_inds))\n return seq", "def unsort_sequence(tensor, indices, batch_first=False):\n if batch_first:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return element effective area and system temperauture at given frequency. Effective area and temperature values for SKA1LOW provided by Eloy de Lera Acedo (eloy at mrao dot cam dot ac dot uk).
def element_area_and_temperature(freq_hz): # Element noise data. noise_data = { 'freqs': [0.05e9, 0.07e9, 0.11e9, 0.17e9, 0.25e9, 0.35e9, 0.45e9, 0.55e9, 0.65e9], 'a_eff': [1.8791, 1.8791, 1.8694, 1.3193, 0.6080, 0.2956, 0.2046, 0.1384, 0.0792], 't_sys...
[ "def element_effective_area(freq_hz):\n freqs = np.array([0.05e9, 0.07e9, 0.11e9, 0.17e9, 0.25e9, 0.35e9, 0.45e9,\n 0.55e9, 0.65e9])\n a_eff = np.array([1.8791, 1.8791, 1.8694, 1.3193, 0.6080, 0.2956, 0.2046,\n 0.1384, 0.0792])\n f_cut = 2\n f1 = interp1d(np.log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate the station StokesI noise RMS, in Jy, for the given observation length sampled with the specified number of times.
def evaluate_scaled_noise_rms(freq_hz, num_times, bandwidth_hz=100e3, eta=1.0, obs_length_h=1000.0, num_antennas=256): k_B = 1.38064852e-23 t_acc = (obs_length_h * 3600.0) / num_times a_eff, t_sys = element_area_and_temperature(freq_hz) # Single receiver polarisation SEFD....
[ "def evaluate_noise_rms_Jy(freqHz, bw, obs_length):\n\n\n c0 = 299792458. #cw m/s\n kB = 1.3806488e-23 #cw m^2 kg s^{-2} K^{-1}\n lambda_ = c0 / freqHz\n\n # Values from Peter Dewdney's spreadsheet.\n A_sparse = lambda_**2 / 3.0 #cw made 3 -> 3.0 out of paranoia\n A_physical = rv.user_interferome...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run with atomic (synchronous) I/O.
def atomic_io(cmd, in_file, out_file, err_file, prog=None): with open(in_file, 'r') as inp, open(out_file, 'w') as out, open(err_file, 'w') as err: p = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=err) while True: line = inp.readline() ...
[ "def test_stream_readonly(self):\n stream = io.IOBase()\n with progress(time=10, stream=stream) as prg:\n for _ in range(100):\n prg.tick()\n time.sleep(0.1)", "def import_sync(cls, fileformat, filename, dataset, run, lumi):\n # This must be a top-leve...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write lines to gzipped file.
def write_gzfile(lines, f): out = gzip.open(f, 'wb') for line in lines: out.write('{}\n'.format(line)) out.close()
[ "def write_body_in_gz_file(self):\r\n if self.arguments['--out']:\r\n self.file = gzip.open(self.arguments['--out'] + '.gz', \"a+b\")\r\n for list_item in self.list_of_body_objects:\r\n self.file.write(list_item.line.encode('utf-8'))\r\n self.file.close()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets original base image from GCP disk labels
def get_base_image_from_labels(user_disk): labels = ['cf_version', 'branch', 'target', 'build_id'] disk_labels = user_disk.extra['labels'] if all(label in disk_labels for label in labels): cf_version = disk_labels['cf_version'] branch = disk_labels['branch'] target = disk_labels['t...
[ "def get_label(client, label):\n image_name = get_image_name()\n image = client.images.get(image_name)\n try:\n return image.labels[label]\n except KeyError:\n raise Exception(f\"Image should have a label '{label}'\")", "def set_base_image_labels(driver, user_disk, img_name, branch, targ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets disk labels with base image version data
def set_base_image_labels(driver, user_disk, img_name, branch, target): dashes = [i for i, c in enumerate(img_name) if c=='-'] cf_version = img_name[dashes[0]+1:dashes[3]] build_id = img_name[dashes[-1]+1:] driver.ex_set_volume_labels(user_disk, {'cf_version': cf_version, 'branch': branch, ...
[ "def set_disk_labels(layout, layout_config):\n # TODO: Trace disk generator and inject this\n partition_tables = layout_config.get('partition_tables')\n for partition_table in partition_tables:\n label = partition_table.get('label')\n if label:\n LOG.info('Table: %s is set as %s in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restores instance with existing user disk and original base image. Creates a new instance with latest image if user disk doesn't exist. Stores runtime data in external GCP disk. Launches Cuttlefish if creation is successful.
def create_or_restore_instance(driver, user_id, sig_server_addr, sig_server_port, zone='us-central1-b', tags=[], branch='aosp-master', target='aosp_cf_x86_phone-userdebug'): # SETUP target = target.replace('_','-') instance_name = f'halyard-{user_id}' disk_name = f'halyard-user-{user_id...
[ "def restore(project, zone, instance, snapshot):\n disks = []\n description = 'Created from %s by %s' % (snapshot, getpass.getuser())\n for disk, size in get_disks(instance).items():\n gcloud(\n project,\n 'compute',\n 'disks',\n 'create',\n '--...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Launch cvd on given instance and connect to operator on given address. If use_user_disk is True it uses existing user data disk.
def launch_cvd(instance_name, zone, sig_server_addr, sig_server_port, use_user_disk=True): cuttlefish_dir = '/usr/local/share/cuttlefish' user_data_dir = '/mnt/user_data' launch_command = f'gcloud compute ssh --zone={zone} {instance_name} -- ' if use_user_disk: launch_command += f'HOME={user_...
[ "def cmd(user_cmd):\n\n instances = u.lookup_instances(limit_to_current_user=True)\n assert instances, f\"{u.get_username()} doesn't have an instances to connect to. Use 'ncluster nano'\" \\\n f\" to bring up a small instance.\"\n instance = instances[0]\n user_cmd = f\"ssh -t -i {u.get_keypa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outputs a pass message.
def success(): sys.stdout.write('%s[ pass ]%s\n' % (colors.GREEN, colors.RESET))
[ "def pass_cmd(self, password):\n print_debug(\"Executing PASS\")\n command = \"PASS %s\\r\\n\" % password\n msg_rec = self.send_and_log(self.s, command)\n return msg_rec", "def test_pass(self, grades):\n grades.add_message('PASS: %s' % (self.path,))\n for line in self.mes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outputs an fail message.
def fail(): sys.stdout.write('%s[ fail ]%s\n' % (colors.RED, colors.RESET))
[ "def print_failure(msg):\n\n tf.print(BColors.FAIL + msg + BColors.ENDC, output_stream=sys.stderr)\n sys.exit(1)", "def fail(msg):\n print(f'::error::{msg}')\n sys.exit(1)", "def report_failure(self, out, test, example, got):\n out(self._failure_header(test, example) +\n self._chec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays a pinwheel animation.
def pin_wheel(self): spinner = '|/-\\' sys.stdout.write('%s \r' % spinner[self.last_spin]) sys.stdout.flush() self.last_spin += 1 if self.last_spin > len(spinner) - 1: self.last_spin = 0 time.sleep(.2)
[ "def wheel(ticks):\n m = PyMouse()\n m.scroll(ticks)", "def draw_wheel():\r\n\touter_radius = 1\r\n\tthickness = .4\r\n\tif wireframe:\r\n\t\tglutWireTorus(thickness,outer_radius - thickness,8,8)\r\n\telse:\r\n\t\tglutSolidTorus(thickness,outer_radius - thickness,8,8)\r\n\t\tglPushAttrib(GL_CURRENT_BIT)\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays a moving bar animation.
def moving_bar(self, color='reset'): progress_pill = ('%s%s%s' % (colors.GREEN, '==', colors.RESET)) sys.stdout.write(' [ %-*s%s%*s ]\r' % (self.left_pad,'', progress_pill, self.right_pad, '')) sys.stdout.flush() if self.left_pad == 10: self.direction = 'left' elif self.right_pad == 1...
[ "def animator(progbar, count, tot_string = False, linenum = False, terminal = False, \n init = False, length = False):\n if init:\n from textprogressbar import TextProgressBar\n return TextProgressBar(length, dirname = tot_string)\n if type(linenum) == int:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extractsms extract SMS messages from BeautifulSoup tree of Google Voice SMS HTML. Output is a list of dictionaries, one per message.
def extractsms(htmlsms) : msgitems = [] # accum message items here # Extract all conversations by searching for a DIV with an ID at top level. tree = BeautifulSoup.BeautifulSoup(htmlsms) # parse HTML into tree conversations = tree.findAll("div",attrs={"id" : True},recursive=False) for con...
[ "def extractsms(htmlsms) :\r\n msgitems = []\t\t\t\t\t\t\t\t\t\t# accum message items here\r\n #\tExtract all conversations by searching for a DIV with an ID at top level.\r\n tree = BeautifulSoup.BeautifulSoup(htmlsms)\t\t\t# parse HTML into tree\r\n conversations = tree.findAll(\"div\",attrs={\"id\" :...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get mysql connection from connection pool.
def __get_connection(): # 根据配置文件创建连接池 if not Mysql.__mysql_pool: Mysql.__mysql_pool = PooledDB( creator=MySQLdb, use_unicode=False, cursorclass=DictCursor, db=sqlconf.MysqlConfig['db'], host=sqlconf.MysqlConfig['...
[ "def _get_conn_pool(*args, **kwargs):\n from .connection import MySQLConnectionPool\n pool_name = kwargs.setdefault(\"pool_name\", \"mysql_pool\")\n\n if pool_name not in _instances:\n _instances[pool_name] = MySQLConnectionPool(*args, **kwargs)\n pool = _instances[pool_name]\n assert isinstan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all sql command execute result.
def get_all(self, sql_command, cmd_param=None): if cmd_param: count = self._mysql_cursor.execute(sql_command, cmd_param) else: count = self._mysql_cursor.execute(sql_command) if count: sql_result = self._mysql_cursor.fetchall() else: sql_r...
[ "def ExecQuery(self, sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n resList = cur.fetchall()\n\n # 查询完毕后必须关闭连接\n self.conn.close()\n return resList", "def execQuery(self,sql):\n cur = self.__GetConnect()\n cur.execute(sql)\n resList = cur.fetc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens the csv file containing GitHub issue data and loads it into a row based table where the keys are the date of the data.
def load_issues(issues_path): issues_dict = {} with open(issues_path) as issues: issue_rdr = csv.DictReader(issues) for row in issue_rdr: issues_dict[row["Date"]] = row return issues_dict
[ "def import_from_csv(self) -> None:\n logging.info('import_from_csv')\n if self.target_table and str(self.target_table).lower() in [\"issue\", \"version\"]:\n if self.file_path and exists(self.file_path):\n # Read CSV file\n csv_data = pd.read_csv(self.file_pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Primary function of the script. Loads both the entropy data and the issues data. Next, using keys from the Date field of the entropy file, pulls out the fields of interest from the issues table and merges the new data into the row data from the entropy file. Finally, the merged row is written to the specified output cs...
def github_merge(config_data): issues = load_issues(config_data.issues_path) with open(config_data.entropy_path) as entropy: entropy_rdr = csv.reader(entropy) with open(config_data.merged_path, 'w', newline='') as merge: merge_wrtr = csv.writer(merge) entropy_hdrs = next(...
[ "def combine_data_main(data1,data2,lookup,foutput):\n\n # Get the maximum number of ortholog probesets we'll have to append\n max_orthologs = 0\n for probe_set_id in data1.keys():\n max_orthologs = max(max_orthologs,len(lookup(probe_set_id)))\n logging.debug(\"Max_orthologs = %d\" % max_orthologs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a copy of the expression, but with a new name.
def with_name(self, name): return self.func(name, self.expr)
[ "def substitute(self, var_name, expression):\n if self.getName() == var_name:\n return expression\n else:\n return self", "def keep_name(self) -> Self:\n return self._from_pyexpr(self._pyexpr.keep_name())", "def Alias(newname, oldname):\n return Value(newname, lambd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NamedMatrix(name, n, m) NamedMatrix(name, n, m, expr) NamedMatrix(name) if name is already a matrix NamedMatrix(name, expr) if name or expr is already a matrix
def __new__(cls, *args, **kwargs): self = object.__new__(cls) if not (1 <= len(args) <= 4): TypeError('1 to 4 positional arguments are required') args = list(args) name = args.pop(0) if isinstance(name, (sp.MatrixBase, sp.MatrixExpr)): if len(args) >= 2: ...
[ "def set_matrix(self, name, mat):\n self._matrices[name] = mat", "def isMatrix(M):\r\n if type(M) == matrix:\r\n return M\r\n elif type(M) == np.ndarray:\r\n return matrix(M)\r\n else:\r\n raise Exception('Unknown input format. Should be matrix or numpy array')", "def make_m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes the last slice from a input wav file
def getlastslice(inputtaken): output = inputtaken.split('.')[0] + 'last.wav' with contextlib.closing(wave.open(inputtaken, 'r')) as framesget: frames = framesget.getnframes() rate = framesget.getframerate() duration = frames / float(rate)#duration of the input file duration1 = durati...
[ "def get_last_sample(self) -> InternalSample:", "def _get_recording(self, index):\n assert index >= 0\n recs = np.nonzero((index - self.offsets[:-1]) >= 0)[0]\n if len(recs) == 0: # pragma: no cover\n # If the index is greater than the total size,\n # return the last re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function checks for the endsilence of an input wav file
def checkendsilence(inputgiven): output = getlastslice(inputgiven) wave_file = wave.open(output, "r") for i in range(wave_file.getnframes()): current_frame = wave_file.readframes(1) unpacked_signed_value = struct.unpack("<h", current_frame) if abs(unpacked_signed_value[0]) > 500: ...
[ "def wavend_exists(output_hdul):\n result = \"WAVEND\" in output_hdul\n return result", "def _remove_silence(self):\n\n # Gets the last bit of silence that's at least one sec\n start, stop = silence.detect_silence(self.audio_segment,\n min_silence_le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the maximum frequency of a wav file
def checkfrequency(inputgiven): data_size = 40000 wav_file = wave.open(inputgiven, 'r') data = wav_file.readframes(data_size) wav_file.close() data = struct.unpack('{n}h'.format(n=data_size), data) print max(data)
[ "def get_max_sample(snd):\n\n return snd.get_max()", "def max_frequency(document):\n max_f = 1\n for w in set(document):\n max_f = max(max_f, augmented_term_frequency(w, document))\n return max_f", "def get_max_frequency(self, device):\n sysfile = '/sys/class/devfreq/{}/max_freq'.forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the Voigt line shape at x with Lorentzian component FWHM l_fwhm and Gaussian component FWHM g_fwhm.
def _Voigt(self, x, g_fwhm, l_fwhm, semi_amp=1, center=0.0): sigma = g_fwhm / np.sqrt(2.0 * np.log(2.0)) return semi_amp * np.real(wofz(((x-center) + 1j*l_fwhm)/(sigma*np.sqrt(2.0)))) / (sigma * np.sqrt(2.0*np.pi))
[ "def gaussian_line(w, w0, sigma):\n return 2/sigma*(np.log(2)/np.pi)**0.5*np.exp(\n -4*np.log(2)*((w-w0)/sigma)**2)", "def pseudovoigt_fit(x,x0,I,HWHM_l,HWHM_r,sigma):\n psv = sigma*lorentzian(x,x0,I,HWHM_l, HWHM_r) + (1-sigma)*gaussian(x,x0,I,HWHM_l,HWHM_r)\n return psv", "def gaussian(x, x0, I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets for a flow identified by an 5tuple (IP header) the transmit power to be used.
def set_per_flow_tx_power(flowId, txPower): return
[ "def set_power(self, power):\n print('Setting santec power to %.4f mW' % power)\n self.santec1.write(\"LP %.2f\" % power)\n self.santec2.write(\"LP %.2f\" % power)\n self.santec3.write(\"LP %.2f\" % power)\n self.santec4.write(\"LP %.2f\" % power)", "def get5vPower(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove any entries in the transmit power table.
def clean_per_flow_tx_power_table(): return
[ "def drop_table(self):\n for ss in self.spectrae:\n ss.tau[('H',1,1215)] = np.array([0])", "def purgeTable(self):\n todelete = set()\n for implicant in self.implicant_list:\n todelete.add(implicant)\n for f in self.functions_to_simplify:\n if (i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the transmit power level used for the given flow.
def get_per_flow_tx_power(flowId): return
[ "def tx_power(self) -> int:\n # Follow table 10 truth table from the datasheet for determining power\n # level from the individual PA level bits and output power register.\n pa0 = self.pa_0_on\n pa1 = self.pa_1_on\n pa2 = self.pa_2_on\n current_output_power = self.output_po...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the whole transmit power table.
def get_per_flow_tx_power_table(): return
[ "def eval_tx_power():\n sender_probes = {'A':[], 'B':[]}\n\n # Start sending\n s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)\n s.setblocking(False)\n\n while True:\n p = s.recv(32)\n node_id = str(p[:5], 'utf-8')\n if len(p) < 32:\n sleep(0.05)\n contin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Install new WiFi MAC Processor
def install_mac_processor(interface, mac_profile): return
[ "def update_mac_processor(interface, mac_profile):\n pass", "def install_teensy_core_mac(unused_install_prefix, install_dir, cache_dir):\n teensy_artifacts = _ARDUINO_CORE_ARTIFACTS[\"teensy\"][platform.system()]\n\n teensyduino_artifact = teensy_artifacts[\"teensyduino\"]\n teensyduino_zip = file_ope...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update WiFi MAC Processor
def update_mac_processor(interface, mac_profile): pass
[ "def update_firmware(self) -> str:", "def command_update_hw(self, cmd):\n # TODO\n pass", "def change_mac(interface: Interface, mac: str, processor: User) -> Interface:\n old_mac = interface.mac\n interface.mac = mac\n message = deferred_gettext(\"Changed MAC address from {} to {}.\").for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uninstall WiFi MAC Processor
def uninstall_mac_processor(interface, mac_profile): pass
[ "def uninstall(self):\n os.system(uninstallSoftware)", "def uninstall():\n\n pyblish.api.deregister_host(\"tvpaint\")", "def Uninstall(vm):\n vm.RemoteCommand('rm -rf tpu')", "def remove_device(hass: HomeAssistant, mac: str):\n registry = dr.async_get(hass)\n device = registry.async_get_devic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`data_consumer(queue, interval)` This is an EXAMPLE of the multiprocessing data consumer. You may write your own one and replace `data_consumer` in the following "main function".
def data_consumer(queue, interval, space): while True: data = queue.get() logging.info("Data consumer: get data with timestamp {}.") # print("get data: ")#,end='' # print(data) # print("LeftMost:",space._leftMost) timeStamp = list(data.keys()) timeStamp = timeStamp[0] planes = list(data.values()) pla...
[ "def data_consumer(self):\r\n while True:\r\n try:\r\n data = self.data_queue.get()\r\n # print('DEBUG: %s\\n' % data)\r\n self.analyzer.classify_data(data)\r\n self.data_queue.task_done()\r\n if data == 'quit':\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize the sedov problem
def init_data(my_data, rp): msg.bold("initializing the sedov problem...") # make sure that we are passed a valid patch object if not isinstance(my_data, patch.CellCenterData2d): print("ERROR: patch invalid in sedov.py") print(my_data.__class__) sys.exit() # get the density, mo...
[ "def __init__(self,initial_v,v_select=0,max_dev_semitones=1):\n self.v=initial_v\n self.v_select=v_select\n self.max_dev_semitones=max_dev_semitones", "def _init_V(self, V):\n if V < 0: raise Exception(\"Number of vertices must be nonnegative\")\n self._V = V\n self._E = 0\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
examples of how to get basic data from bbg
def examples(): # get some data for a single name x = blp.bdp('BDEV LN Equity', 'px_last') print(x) print('the type of x', type(x)) print('the value of x:', x.iloc[0]['px_last']) # get multiple data for a single name y = blp.bdp('BDEV LN Equity', flds=['px_bid', 'px_ask']) ...
[ "def NCBIreadGBK(accession):\r\n net_handle = Entrez.efetch(db=\"nuccore\",id=str(accession),\r\n rettype='gbwithparts', retmode=\"txt\")\r\n gnome_record=SeqIO.read(net_handle, \"genbank\")\r\n net_handle.close()\r\n return gnome_record", "def get_GBA_BP(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function to get bond data from bloomberg using tickers in an excel sheet.
def get_bonds(): print('getting bond data...') # securtiyList = ['US29265WAA62 Corp', 'XS1713463559 Corp', 'XS2000719992 Corp', 'XS0954675129 Corp', 'XS0954675129 Corp'] fieldList = ['ticker', 'coupon', 'nxt_call_dt', 'final_maturity', 'mty_typ', 'px_mid', 'z_sprd_mid', 'yas_ispread',...
[ "def get_prices_IB(self):\n try:\n # Connection\n ib = IB_API()\n \n # Input data and call \n contract_values = {\n 'm_symbol': self.symbol,\n 'm_exchange': 'SMART',\n 'm_secType': 'STK',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tableau des fréquences d'un texte
def tableau_frequences_fic(nom_de_fichier): with open(nom_de_fichier,'r') as f : texte = f.read().split() L = [0]*26 for mot in texte : for lettre in mot : L[alphabet_dico[lettre]] += 1 return L
[ "def tableau_frequences(texte):\n t = texte.split()\n L = [0]*26\n nb = 0\n for mot in t :\n for lettre in mot :\n L[alphabet_dico[lettre]] += 1\n nb += 1\n for i in range(26) :\n L[i] = L[i] / nb\n return L", "def frequence(text):\n crackCode = \"\"\n n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tableau des fréquences d'un texte
def tableau_frequences(texte): t = texte.split() L = [0]*26 nb = 0 for mot in t : for lettre in mot : L[alphabet_dico[lettre]] += 1 nb += 1 for i in range(26) : L[i] = L[i] / nb return L
[ "def tableau_frequences_fic(nom_de_fichier):\n with open(nom_de_fichier,'r') as f :\n texte = f.read().split()\n L = [0]*26\n for mot in texte :\n for lettre in mot :\n L[alphabet_dico[lettre]] += 1\n return L", "def frequence(text):\n crackCode = \"\"\n nbrOccurence = c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Distance entre deux tableaux de fréquences t1 et t2
def distance(t1,t2): S = 0 for i in range(len(t1)): S = S + (t1[i]-t2[i])**2 return S
[ "def trame_distance(t1, t2):\n return np.linalg.norm(t1 - t2)", "def distance(t1,t2):\n\n if len(t1) != len(t2):\n raise ValueError(\"distance: tuples must be the same length\")\n\n r = [0,] * len(t1)\n for i in range(0,len(t1)):\n r[i] = (t1[i] - t2[i]) ** 2\n r = tuple(r)\n\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scores snippets given a scorer.
def score_snippets(snippets, scorer): snippet_expressions = [snippet.embedding for snippet in snippets] all_snippet_embeddings = torch.stack(snippet_expressions, dim=1) scores = torch.t(torch.mm(torch.t(scorer), all_snippet_embeddings)) if scores.size()[0] != len(snippets): raise ValueError("G...
[ "def compute_scores(self, *scorers):\n if self.nodes[0]:\n list_ = self.nodes\n else:\n list_ = self.reaction_trees\n\n for idx, item in enumerate(list_):\n scores = {repr(scorer): scorer(item) for scorer in scorers}\n self.all_scores[idx].update(scor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a token predictor given the parameters.
def construct_token_predictor(params, vocabulary, utterance_attention_key_size, schema_attention_key_size, snippet_size, anonymizer=None): if not anonymizer and not...
[ "def predict_tokens(self, tokens):\n return", "def __init__(self, tokens):\n self.mdl = self.train(tokens)", "def __init__(self, tokens):\n\n self.mdl = self.train(tokens)", "def generate_token(self, prev_tokens=None):\n\n # calcular cual de todas las palabras del vocabulario es la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load building data into the database from the processed shapefile.
def from_shapefile(strict=False, progress=True, verbose=False, **kwargs): building_shp = get_processed_data_file(os.path.join('buildings', 'buildings.shp')) mapping = LayerMapping(Building, building_shp, building_mapping, transfo...
[ "def dbLoad():\n conn = sqlite3.connect(SQLFILE)\n with conn:\n r = shapefile.Reader(ZIPCODES).shapeRecords()\n print(\"shapes to process %s\" % len(r))\n for d in r:\n print(\"shape record length %s\" % len(d.record))\n [print(\"%s %s\" % (x, y)) for x, y in enumera...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all usage details of the subscription
def cli_consumption_list_usage(client, invoice_name=None, billing_period_name=None, top=None, include_additional_properties=False, include_meter_details=False, start_date=None, end_date=None): if include_additional_properties and include_meter_details: expand = 'additionalProperties,meterDetails' elif i...
[ "def test_get_usage_by_subscription_id(self):\n pass", "def list(self):\n return self._engine.exec(\"subscription-manager list\")", "def test_get_usage_by_subscription_id_uo_m_period_and_usage_type(self):\n pass", "def get_subscriptions(self):\n \n r = self.fitbit_service.get('http:/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the date of last SACPI entry day + 5 months
def _get_first_end_date(self): ins = acm.FInstrument['SACPI'] market = "internal" start_year = acm.Time.DateAddDelta(acm.Time.FirstDayOfYear(self.start_date), 0, 0, -1) this_year_prices = acm.FPrice.Select("instrument='%s' and market='%s' and day>'%s' and day<'%s'" % (in...
[ "def last_month():\n return datetime.now() + relativedelta(months=-1)", "def default_end_date() -> str:\n last = now - relativedelta(months=1)\n return f\"{last.year}-{last.month:02}\"", "def _get_monthEnd(self):\n return self - self.day + self.monthDays", "def max_drawdown_date(self) -> dt.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cppstd must be a number
def test_check_cppstd_type(): conanfile = ConanFileMock(MockSettings({})) with pytest.raises(ConanException) as exc: check_min_cppstd(conanfile, "gnu17", False) assert "cppstd parameter must be a number", str(exc)
[ "def stdnum_validator(type):\n\n def validator(value):\n stdmod = getattr(__import__('stdnum', fromlist=[type]), type)\n try:\n if not stdmod.is_valid(value):\n raise\n except:\n raise InvalidStandardNumber(value)\n return True\n \n return va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check_min_cppstd must accept cppstd less/equal than cppstd in settings
def test_check_min_cppstd_from_settings(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", "17", "libstdc++") check_min_cppstd(conanfile, cppstd, False)
[ "def test_valid_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"libstdc++\")\n assert valid_min_cppstd(conanfile, cppstd, False)", "def test_valid_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check_min_cppstd must raise when cppstd is greater when supported on settings
def test_check_min_cppstd_from_outdated_settings(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", cppstd, "libstdc++") with pytest.raises(ConanInvalidConfiguration) as exc: check_min_cppstd(conanfile, "17", False) assert "Current cppstd ({}) is lower than the required C++ standard (17)." ...
[ "def test_check_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"libstdc++\")\n check_min_cppstd(conanfile, cppstd, False)", "def test_valid_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", cppstd, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
current cppstd in settings must has GNU extension when extensions is enabled
def test_check_min_cppstd_from_settings_with_extension(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", "gnu17", "libstdc++") check_min_cppstd(conanfile, cppstd, True) conanfile.settings.values["compiler.cppstd"] = "17" with pytest.raises(ConanException) as raises: check_min_cppstd(c...
[ "def test_valid_min_cppstd_from_settings_with_extension(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"gnu17\", \"libstdc++\")\n assert valid_min_cppstd(conanfile, cppstd, True)\n\n conanfile.settings.values[\"compiler.cppstd\"] = \"17\"\n assert not valid_min_cppstd(conanfile, cp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
valid_min_cppstd must accept cppstd less/equal than cppstd in settings
def test_valid_min_cppstd_from_settings(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", "17", "libstdc++") assert valid_min_cppstd(conanfile, cppstd, False)
[ "def test_check_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"libstdc++\")\n check_min_cppstd(conanfile, cppstd, False)", "def test_valid_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", cppstd, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
valid_min_cppstd returns False when cppstd is greater when supported on settings
def test_valid_min_cppstd_from_outdated_settings(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", cppstd, "libstdc++") assert not valid_min_cppstd(conanfile, "17", False)
[ "def test_valid_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"libstdc++\")\n assert valid_min_cppstd(conanfile, cppstd, False)", "def test_check_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
valid_min_cppstd must returns True when current cppstd in settings has GNU extension and extensions is enabled
def test_valid_min_cppstd_from_settings_with_extension(cppstd): conanfile = _create_conanfile("gcc", "9", "Linux", "gnu17", "libstdc++") assert valid_min_cppstd(conanfile, cppstd, True) conanfile.settings.values["compiler.cppstd"] = "17" assert not valid_min_cppstd(conanfile, cppstd, True)
[ "def test_valid_min_cppstd_from_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", \"17\", \"libstdc++\")\n assert valid_min_cppstd(conanfile, cppstd, False)", "def test_valid_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
valid_min_cppstd must returns False when the compiler does not support a standard
def test_valid_min_cppstd_unsupported_standard(): conanfile = _create_conanfile("gcc", "9", "Linux", None, "libstdc++") assert not valid_min_cppstd(conanfile, "42", False)
[ "def test_valid_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\", \"Linux\", cppstd, \"libstdc++\")\n assert not valid_min_cppstd(conanfile, \"17\", False)", "def test_check_min_cppstd_from_outdated_settings(cppstd):\n conanfile = _create_conanfile(\"gcc\", \"9\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the output directory (if needed) for a given test filename.
def _make_output_directory(self): fs = self._filesystem output_filename = fs.join(self._root_output_dir, self._test_name) fs.maybe_make_directory(fs.dirname(output_filename))
[ "def make_output_dir(self):\n base = self.output_path()\n if not os.path.exists(base):\n os.makedirs(base)", "def make_test_dir(path, test_name):\n LOG.info('In make_test_dir')\n OutputWrite.change_to_script_directory(__file__)\n path_with_test_name = os.path.join(pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a filename inside the output dir that contains modifier. For example, if test name is "fast/dom/foo.html" and modifier is "expected.txt", the return value is "//fast/dom/fooexpected.txt".
def output_filename(self, modifier): fs = self._filesystem output_filename = fs.join(self._root_output_dir, self._test_name) return fs.splitext(output_filename)[0] + modifier
[ "def results_dir( pat=None ):\n for f in os.listdir('.'):\n if f[:12] == 'TestResults.':\n if pat == None or f.find( pat ) >= 0:\n return f\n return ''", "def modifier(self) -> str:\n match = RE_MODIFIER.match(self.string.split(\".\")[-1])\n return match.group(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This loop method can be run periodically to read messages out of the incoming message buffer. It also deals with replying to ping requests from other devices. Note that it is not necessary to handle reconnection to the broker in this function; that task is done by the pahomqtt loop function.
def loop(self): # dump all incoming messages into a list and empty the string incoming_messages = self.receiver.getDataFromCallback() # empty the buffer self.receiver.emptyDataFromCallback() parsed_messages = [] pingacks = [] for message in incoming_messages: ...
[ "def _reader(self):\n while True:\n self._callbacks.log(logging.DEBUG, 'Reading from_printer queue')\n msg_from_printer = self._get_message_from_printer()\n if msg_from_printer:\n self._process_message_from_printer(msg_from_printer)\n time.sleep(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when a message that was to be sent using the publish() call has completed transmission to the broker. For messages with QoS levels 1 and 2, this means that the appropriate handshakes have completed. For QoS 0, this simply means that the message has left the client. The mid variable matches the mid variable retur...
def on_publish(self, mqtt_client, userdata, mid): logging.debug("DEBUG - publish ack received")
[ "def on_publish(self, unused_client, unused_userdata, unused_mid):\n logger.debug('Published message acked.')", "def on_publish(self, unused_client, unused_userdata, unused_mid):\n\t\tprint 'Published message acked.'", "def on_publish(self, unused_client, unused_userdata, unused_mid):\n print('Pub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the broker responds to a subscribe request. The mid variable matches the mid variable returned from the corresponding subscribe() call. The granted_qos variable is a list of integers that give the QoS level the broker has granted for each of the different subscription requests.
def on_subscribe(self, mqtt_client, userdata, mid, granted_qos): logging.debug("DEBUG - subscribe ack received")
[ "def on_subscribe( client, userdata, mid, granted_qos ):\n logging.info( \"Topic successfully subcribed with QoS: %s\" %granted_qos )", "def __setitem__(self, callback_id, subscription_request):", "def handle_subscription(client, userdata, message):\n payload = message.payload\n payload = payload.decod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the broker responds to an unsubscribe request. The mid variable matches the mid variable returned from the corresponding unsubscribe() call.
def on_unsubscribe(self, mqtt_client, userdata, mid ): logging.debug("DEBUG - unsubscribe ack received")
[ "def _onUnsubscribe(self, client:mqtt.Client, userdata:Any, mid:int) -> None:\n\t\t# TODO doc, error check when not connected, not subscribed\n\t\tfor t in self.subscribedTopics.values():\n\t\t\tif t.mid == mid:\n\t\t\t\tdel self.subscribedTopics[t.topic]\n\t\t\t\tself.messageHandler and self.messageHandler.onUnsub...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Called when the client has log information. Define to allow debugging. The level variable gives the severity of the message and will be one of MQTT_LOG_INFO, MQTT_LOG_NOTICE, MQTT_LOG_WARNING, MQTT_LOG_ERR, and MQTT_LOG_DEBUG. The message itself is in buf. This may be used at the same time as the standard Python loggin...
def on_log(self, mqtt_client, userdata, level, buf): logging.debug("DEBUG - on_log received")
[ "def on_log(client, userdata, level, buf):\n _LOG.log(LOG_LEVEL_MAP[level], \"MQTT client: %s\" % buf)", "def log (self, level, msg, log_mqtt=False):\n msg = self.logger.log(level, msg)\n if log_mqtt and level >= self.logger.level:\n msgs = msg.split(':')\n self.publish(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks to make sure that the OSG_APP directory exists and the VO directories have the proper permissions. Returns True if everything is okay, False otherwise. APP_DIR must exist and have a etc directory with 1777 permissions for success. If APP_DIR begins with /cvmfs/oasis.opensciencegrid.org, skip tests If APP_DIR is ...
def _check_app_dir(self, app_dir): try: if self._app_dir_in_oasis(app_dir): self.log('OSG_APP is an OASIS repository, skipping tests', level=logging.DEBUG) return True # Added for SOFTWARE-1567 if utilities.blank(app_d...
[ "def _check_app_dir():\n if not os.path.exists(os.path.expanduser('~/.config/scheduler')):\n os.mkdir(os.path.expanduser('~/.config/scheduler'))", "def _is_fluxcd_app_compliant(path):\n mandatory_components = (\"base\", constants.APP_ROOT_KUSTOMIZE_FILE)\n check_mandatory = all(comp in os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the checkpoint directory exists.
def checkpoint_directory(checkpoint): if os.path.isdir(checkpoint): pass else: os.mkdir(checkpoint)
[ "def has_checkpoint(checkpoint_path, rb_path):\n if not (os.path.exists(checkpoint_path) and os.path.exists(rb_path)):\n return False\n if \"model.pyth\" not in os.listdir(checkpoint_path):\n return False\n if len(os.listdir(rb_path)) == 0:\n return False\n return True", "def has_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the history directory exists. Save the training history using pickle
def save_training_history(hist): if os.path.exists("history/history") != True: os.mknod("history/history") with open("history/history", "wb") as file_pi: pickle.dump(hist.history, file_pi) print("Training History saved")
[ "def history_path(base_path: Path, training_run):\n return base_path / _TRAINING_RUNS_DIR / training_run / _HISTORY_FILE_NAME", "def get_history_filepath(config: configs.Config) -> str:\n return os.path.join(config.model_training.dir_out, histories.DEFAULT_FILENAME_HISTORY)", "def save_history():\n\n m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract flag from "memory dump."
def extractFlag(str): flag = "" lines = str.split("\n") for line in lines: m = r2.search(line) if m: #print "DEBUG: matched %s %s %s %s" % \ # (m.group(4), m.group(3), m.group(2), m.group(1)) byte0 = int("0x" + m.group(4), 16) byte1 = int("0x" + m.group(3), 16) byte2 = int("0x" + m.gro...
[ "def read_debug_flag(self):\n flag_end = self.code.find('}', self.instruction_pointer)\n flag = self.code[self.instruction_pointer + 1: flag_end]\n self.instruction_pointer = flag_end + 1\n return flag", "def get_page_flags(self,pte):\n self.kpflags.seek(Pte.pte_to_pfn(pte)*8,os.SEE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new DXF drawing.
def new(dxfversion='AC1009'): dwg = Drawing.new(dxfversion) if dwg.dxfversion > 'AC1009': dwg.reset_fingerprintguid() dwg.reset_versionguid() return dwg
[ "def draw_design(self, dxfversion=None):\n\n if self.file == None:\n raise Exception(\"No file name given. Use design.file to set name.\")\n \n if dxfversion is None:\n self.drawing = ezdxf.new()\n else:\n self.drawing = ezdxf.new(dxfversion=dxfversio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read DXF drawing from a text stream, which only needs a readline() method.
def read(stream, legacy_mode=True, dxfversion=None): return Drawing.read(stream, legacy_mode=legacy_mode, dxfversion=dxfversion)
[ "def load_draw(instream):\n fonts = [_load_font(instream, fore='#', back='-', key_format=draw_input_key)]\n return Typeface(fonts)", "def import_dxf(self):\n self.init_import()\n\n with open(self.filename) as fin:\n lines = 0\n for code, data in self.dxf_entry(fin):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read DXF drawing specified by filename from file system.
def readfile(filename, encoding=None, legacy_mode=False): if not is_dxf_file(filename): raise IOError("File '{}' is not a DXF file.".format(filename)) info = dxf_file_info(filename) with io.open(filename, mode='rt', encoding=info.encoding, errors='ignore') as fp: dwg = read(fp, legacy_mode=...
[ "def import_dxf(self):\n self.init_import()\n\n with open(self.filename) as fin:\n lines = 0\n for code, data in self.dxf_entry(fin):\n function = self.state_switcher.get(self.state, lambda self,\n code, data: \"not...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read DXF drawing specified by filename from a zip archive, or if filename is None the first DXF file in the zip archive.
def readzip(zipfile, filename=None): with ctxZipReader(zipfile, filename) as zipstream: dwg = read(zipstream, dxfversion=zipstream.dxfversion) dwg.filename = zipstream.dxf_file_name return dwg
[ "def read_gdf_from_zip(zip_fp):\r\n with ZipFile(zip_fp) as z:\r\n # Lists all files inside the ZipFile, here assumes that there is only a single file inside\r\n layer = z.namelist()[0]\r\n data = gpd.read_file(io.BytesIO(z.read(layer)))\r\n return data", "def load_shapes_from_zip(filen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the provided email/username is allowed to register.
def check_registration_allowed(self, email, username, password): message = '' status = 'done' for provider, options in self.active_authenticators(email, username, password): allow_reg = _get_tri_state(options, 'allow-register', True) if allow_reg is None: # i.e. challeng...
[ "def test_registeration_invalid_email(self):\n response = self.signup_a_user(self.user_invalid_email)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n self.assertEqual(response.data[\"errors\"][\"email\"],\n [\"Enter a valid email address.\"]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the username/email & password using auth providers in order. If a match is found, returns the 'autoregister' option for that provider.
def check_auto_registration(self, trans, login, password): if '@' in login: email = login username = None else: email = None username = login for provider, options in self.active_authenticators(email, username, password): if provider is...
[ "def get_provider_credentials(provider):\n logging.info('Getting provider credentials for {}'.format(provider))\n uppercase_provider = provider.upper()\n username_variable = '{}_USERNAME'.format(uppercase_provider)\n authentication_variable = '{}_AUTHENTICATION'.format(uppercase_provider)\n username ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that auth provider allows password changes and current_password matches.
def check_change_password(self, user, current_password): for provider, options in self.active_authenticators(user.email, user.username, current_password): if provider is None: log.debug( "Unable to find module: %s" % options ) else: auth_result = provider....
[ "def test_checkPasswordMatches(self):\n return self.compareCheckPassword(keyPassword=\"password\",\n password=\"password\")", "def old_password_check(form, field):\n old_password = field.data\n password = current_user.password\n r = pwd_context.verify(old_pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields AuthProvider instances for the provided configfile that match the filters.
def active_authenticators(self, email, username, password): try: for authenticator in self.authenticators: filter_template = authenticator.filter_template if filter_template: filter_str = filter_template.format(email=email, username=username, passw...
[ "def init_auths(config):\n # TODO: handle collisions in authenticator names. Or is this\n # already handled for us by pkg_resources?\n auths = {}\n for entrypoint in pkg_resources.iter_entry_points(\n SETUPTOOLS_AUTHENTICATORS_ENTRY_POINT):\n auth_cls = entrypoint.load()\n auth ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a certificate request.
def createCertRequest(pkey, digest="sha256", **name): req = crypto.X509Req() subj = req.get_subject() for key, value in name.items(): setattr(subj, key, value) req.set_pubkey(pkey) req.sign(pkey, digest) return req
[ "def create_certificate(\n self,\n ) -> Callable[[service.CreateCertificateRequest], Awaitable[resources.Certificate]]:\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a boolean based on user input. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits . It must be True (the default), False or None (meaning an answer is required of the user). The "answer" return value is one of True or False.
def query_user_bool(question, default=True): valid_yes_ans = ["yes", "y"] valid_no_ans = ["no", "n"] if default is None: prompt = " [y/n] " elif default: prompt = " [Y/n] " else: prompt = " [y/N] " while True: sys.stdout.write(question + prompt) choice ...
[ "def boolean_input(self, question, default=False):\n if default is None:\n yes_no = \"y/n\"\n default_text = None\n elif default:\n yes_no = \"[Y/n]\"\n default_text = 'y'\n else:\n yes_no = \"[y/N]\"\n default_text = 'n'\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the mount hole offset for the panels pcb based on
def get_panels_pcb_offset(): mount_hole_offset = arena_assembly['panels_to_hallway_gap'] mount_hole_offset -= arena_assembly['panels_assembly_offset'] mount_hole_offset += 0.5*hallway_bottom_plate['width'] mount_hole_offset += 0.5*panels_pcb['width'] return mount_hole_offset
[ "def setHolesCoordinates(self):\r\n # productive\r\n profprint()\r\n self.p = [[0 for j in range(63)] for j in range(3)]\r\n self.p[0][0] = 35\r\n self.p[1][0] = 34\r\n self.p[0][1] = 25\r\n self.p[1][1] = 36.679\r\n self.p[0][2] = 17.679\r\n self.p[1][2] = 44\r\n self.p[0][3] = 15\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the security groups assigned to an EC2 instance This method assigns the security groups to each elastic network interface attached to the EC2 instance.
def change_instance_security_groups(instance_id, security_group_ids): # Retrieve the IDs of the network interfaces attached to the EC2 instance ec2_client = boto3.client('ec2') try: response = ec2_client.describe_instances(InstanceIds=[instance_id]) except ClientError as e: logging.erro...
[ "def _set_security_group(client, instance_id_list, security_groups):\n logging.info('Setting the security group of instances.')\n for instance_id in instance_id_list:\n client.modify_instance_attribute(InstanceId=instance_id, Groups=security_groups)", "def update_instance_security_group(self, instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Si se busca un APE por sigla, se encuentra
def test_buscar_por_sigla(self): ape1 = APE.objects.get(sigla="APX1") ape2 = APE.buscar_por_sigla("APX1") self.assertIsNotNone(ape1, "El APE encontrado con GET no debería ser None") self.assertIsNotNone(ape1, "El APE encontrado con buscar_por_sigla no debería ser None") self.asse...
[ "def test_buscar_por_sigla_inexistente(self):\n ape = APE.buscar_por_sigla(\"AAA\")\n self.assertIsNone(ape, \"El APE retornado debería ser None\")", "def checkeo_e(jugador, entrenador):\n aliado = jugador.lista_equipo[0] #Se asigna el aliado\n enemigo = entrenador.lista_equipo[0] #Se asigna ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Si se busca un APE usando una sigla que no existe, retorna None
def test_buscar_por_sigla_inexistente(self): ape = APE.buscar_por_sigla("AAA") self.assertIsNone(ape, "El APE retornado debería ser None")
[ "def checkID(self, ID):\n for i in self.alist:\n if i.eaid==ID:\n return i\n return None", "def next_unknown_addr(ea=None, down=True):\n if ea is None:\n ea = ida_kernwin.get_screen_ea()\n if down:\n fl = ida_search.SEARCH_DOWN\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buscar_por_programa encuentra los apes correctos
def test_buscar_por_programa(self): ap2 = APE.objects.create(sigla="AP2", nombre_corto="nc2", nombre_largo="nl2", descripcion="d2") ap3 = APE.objects.create(sigla="AP3", nombre_corto="nc3", nombre_largo="nl3", descripcion="d3") ap4 = APE.objects.create(sigla="AP4", nombre_corto="nc4", nombre_lar...
[ "def buscar_hab(barcos,cruceros,lista_letras): \n while True:\n try:\n \n search=input(\"\"\" Desea buscar por:\n 1. Tipo\n 2. Capacidad\n 3. Tipo+pasillo+numero(ej: SA9)\n 4. Salir\n >>> \"\"\")\n if search==\"1\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scan the DynamoDB table to get all tasks in a service. Input region, ECS ClusterARN and ECS ServiceName
def get(table, region, cluster, service): resp = table.scan( FilterExpression=Attr('group').eq('service') & Attr('groupName').eq(service) & Attr('region').eq(region) & Attr('clusterArn').eq(cluster) ) return(resp)
[ "def scan_dynamodb():\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('yelp-restaurants')\n\n pe = \"id, cuisine\"\n responses = table.scan(ProjectionExpression=pe)['Items']\n return responses", "def scan_table(dynamo_client, *, TableName, **kwargs):\n paginator = dynamo_client....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the ECS cluster name and the region, get the ECS ClusterARN.
def ecs_getClusterArn(region, cluster): client = boto3.client('ecs', region_name=region) response = client.describe_clusters(clusters=[cluster]) logging.debug("ECS Cluster Details: %s", response) if len(response['clusters']) == 1: return (response['clusters'][0]['clusterArn']) else: ...
[ "def get_cluster_label(cls, cluster_name):\n label = {'application': cluster_name}\n return label", "def cluster_name(self) -> str:\n return pulumi.get(self, \"cluster_name\")", "def cluster_name(self):\n return self._cluster_name", "def get_cluster(name: str) -> dict:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query AWS Pricing APIs to find cost of EC2 instance in the region. Given the paramters we use at input, we should get a UNIQUE result.
def ec2_pricing(region, instance_type, tenancy, ostype): svc_code = 'AmazonEC2' region_n = str(aws_region_prices[region]) client = boto3.client('pricing', region_name="us-east-1") response = client.get_products(ServiceCode=svc_code, Filters=[ ...
[ "def get_rds_reserved_instances_prices(filter_region=None, filter_instance_type=None, filter_multiaz=None, filter_db=None):\n\n\tget_specific_region = (filter_region is not None)\n\tget_specific_instance_type = (filter_instance_type is not None)\n\tget_specific_multiaz = (filter_multiaz is not None)\n\tget_specific...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get Cost in USD to run a ECS task where launchMode==EC2. The AWS Pricing API returns all costs in hours. runTime is in seconds.
def cost_of_ec2task(region, cpu, memory, ostype, instanceType, runTime): global pricing_dict global region_table pricing_key = '_'.join(['ec2', region, instanceType, ostype]) if pricing_key not in pricing_dict: # Workaround for DUBLIN, Shared Tenancy and Linux (ec2_cpu, ec2_mem, ec2_cos...
[ "def resource_cost(self, resource_id, start_time=-1, eft=-1, cost_only=True):\r\n tasks_in_resource = [t for t in self.tasksOfResource[resource_id] if not t.task.dummy_task]\r\n if not tasks_in_resource:\r\n if eft == -1:\r\n return 0 if cost_only else (0, 0, 0)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure fit predict works on classification with multi inputs Ensure saving + loading does not cause errors Ensure saving + loading does not change predictions
def test_multifield_classify(self): self.model.fit(self.text_data_train, self.train_targets) self.assertTrue(self.model.is_classification) predictions = self.model.predict(self.text_data_valid) self.model.save(self.save_file) model = LanguageModelGeneralAPI.load(self.save_file) ...
[ "def train_and_predict():\n x_kaggle, y_kaggle, = _load_kaggle_dataset(\"../datasets/kaggle/\")\n x_train_webcam, y_train_webcam = _load_dataset(\"../datasets/segmentation/\")\n\n x_kaggle.extend(x_train_webcam)\n y_kaggle.extend(y_train_webcam)\n\n x_kaggle = np.array(x_kaggle)\n y_kaggle = np.ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pro myscale,factor tmp_data = getdata() tmp_data = tmp_data factor setdata, tmp_data if !g.frozen eq 0 then show end
def myscale(g, factor=1.0): g.setdata(factor * g.getdata()) # if !g.frozen eq 0 then show
[ "def test_set_scale():\n data = io.create_sample_Dataset()\n tmp = data.piv.set_scale(1.0)\n assert np.allclose(tmp[\"x\"], data[\"x\"])\n\n tmp = data.copy()\n tmp.piv.set_scale(2.0)\n tmp_mean = tmp[\"u\"].mean(dim=(\"t\", \"x\", \"y\")).values\n data_mean = data[\"u\"].mean(dim=(\"t\", \"x\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set user for Leave and Overtime requests. This is the default strategy of autosetting the user for a review object. It simply sets the user using a field on the model object that is under review.
def set_staff_request_review_user(review_obj: models.Model): if not review_obj.user: object_under_review = review_obj.content_object staff_profile = getattr(object_under_review, STAFF, None) if staff_profile: review_obj.user = staff_profile.user
[ "def set_user(self, user):\r\n self.user = user", "def save(self, **kwargs):\n kwargs[\"user\"] = self.fields[\"user\"].get_default()\n return super().save(**kwargs)", "def setuser(self, user):\n self.current_user = user", "def set_staff_request_reviewer(review_obj: models.Model):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set reviewer for Leave and Overtime requests.
def set_staff_request_reviewer(review_obj: models.Model): if review_obj.user: staff_member = review_obj.user.staffprofile manager = staff_member.supervisor if ( manager and not Reviewer.objects.filter( review=review_obj, user=manager.user )...
[ "def reviewer(self, reviewer):\n if not reviewer:\n return\n\n from stalker import User\n\n if not isinstance(reviewer, User):\n raise TypeError(\n \"%s.reviewer should be a stalker.User instance, not %s\"\n % (self.__class__.__name__, reviewe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing App resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None, app_name: Optional[pulumi.Input[str]] = None, bundle_id: Optional[pulumi.Input[str]] = None, encoded_icon: Optional[pulumi.Input[str]] = None, industr...
[ "def _query_app_state_by_id(self, app_id: str) -> str:\n state = self.last_known_state\n try:\n response = self.resource_mgr.cluster_application_state(application_id=app_id)\n except Exception as e:\n self.log.warning(f\"Query for application '{app_id}' state failed with e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set operator linking filters
def set_operator(self, operator): self['dimensionFilterClauses']['operator'] = operator.upper() return self
[ "def test_operator(self):\n\t\tfor op in self.ops:\n\t\t\tself.filter.set_operator(op)\n\t\t\tself.assertEqual(self.filter.operator.value, op)", "def filter(self, filters):", "def create_filters(self):", "def filters(self, filters):\n self._filters = filters", "def enableFilter(self, items=None):", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempt to decrypt encrypted_check_phrase and check it against the check phrase to see if the password is the same. This is to avoid user inputting wrong password and accidentally corrupting the data by decrypting it with the wrong key
def check_correct_password(status, pwd): # generate key from raw password key = generate_key_from_password( pwd, salt=status.get("salt") ) f = Fernet(key) try: decrypt_output = f.decrypt(status["encrypted_check_phrase"]) except InvalidToken: return False return decryp...
[ "def check_password(raw_password, enc_password):\n algo, salt, hsh = enc_password.split('$')\n return enc_password == encrypt_password(raw_password, algorithm=algo,\n salt=salt)", "def check_pass(plain,enc):\n return (crypt.crypt(plain, enc[:2]) == enc)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively run function fx on all files within path including all files in subdirectories recursively. The file path will be passed to fx along with args and kwargs
def recursive_file_action(path, fx, *args, **kwargs): # generate list of files to encrypt and encrypt separately # to make a pretty progress bar file_paths = [] print("Collecting files...") for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: # construc...
[ "def get_files(self, path):\n lst1 = get_content(path)\n for item in lst1:\n if item.is_file():\n self.lst.append(item.absolute())\n elif item.is_dir() and self.recursion: # If the -r command was used before the -f command\n self.get_files(item)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Go through all files in the given path and check if they're all decrypted (does not have encrypted file extension)
def check_folder_fully_decrypted(path): for (dirpath, dirnames, filenames) in os.walk(path): for filename in filenames: if os.path.splitext(filename)[1] == settings.ENCRYPTED_FILE_EXTENSION: return False return True
[ "def analyseDecryption(self,filesAddress):\n for i in filesAddress:\n result=[]\n if i[len(i)-5:] == \"crypt\":\n result.append(0)\n else:\n result.append(1)\n if sum(result)==0:\n return True\n else :\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Activates or Deactivates the verification process. Default is `False`, to activate type `[p]verifyset activate True`.
async def active(self, ctx: commands.Context, toggle: bool = None): guild = ctx.guild tog = self.config.guild(guild) role_config = [ await tog.temprole(), await tog.autoroles(), ] if not role_config[1]: role_config[1] = None if toggle i...
[ "def loadOn(self, verify=True):\n self.activate(enable_load=True, enable_remote=True)", "def activate_process(self):\n self.active = True\n LOG.info('resume\\'s process activate')", "def verify(self):\n ACTIVATION_PERIOD = datetime.timedelta(days=14)\n if not self.org_verified:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }