query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Writes a dict representation of the user_map to a database | def write_user_map_to_db(user_map):
print("writing user_map to db")
try:
for user in user_map:
put_user_in_table(user_map[user].to_dict())
user_map[user].set_is_new_user(False)
except IOError:
print("Error writing to DB.") | [
"def load_user_map_from_db():\n user_map = {}\n\n try:\n users = get_users_from_table()\n for user in users:\n user_dict = {\n \"user_id\" : user[0],\n \"username\" : user[1],\n \"id_last_message_sent\" : user[2],\n \"id_last... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads database users into the bot's user_map | def load_user_map_from_db():
user_map = {}
try:
users = get_users_from_table()
for user in users:
user_dict = {
"user_id" : user[0],
"username" : user[1],
"id_last_message_sent" : user[2],
"id_last_message_stickered" : ... | [
"def __loadUsers(self):\n\t\tcursor = self.__getCursor()\n\t\tcursor.execute('SELECT `id`,`name` FROM `users`') \n\t\tusersResult = cursor.fetchall()\n\t\tself.users = {}\n\t\tfor i in usersResult:\n\t\t\t#groupsResult = cursor.fetchall()\n\t\t\tself.users[str(i['name'])] = int(i['id'])\n\t\tcursor.close()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the number of days since 111900 (the Excel Epoch) | def get_current_days_excel_epoch():
f_date = datetime.date(1900, 1, 1)
l_date = datetime.datetime.today().date()
delta = l_date - f_date
return delta.days | [
"def epoch_days():\n return int(time.time() / 86400)",
"def days_since_epoch():\n days = int(now / 86400)\n return f'Days from Epoch: {days}.'",
"def epoch_seconds(self,date):\n\n epoch = datetime(1970, 1, 1)\n td = date - epoch\n return int(td.days * 86400 + td.seconds + (float(td... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> string_chopped_to_float('hello75494758test', 'hello', 'test') 75494758.0 >>> string_chopped_to_float('hello1test', 'hello', 'test') 1.0 | def string_chopped_to_float(input_string, chop_up, chop_low):
input_string = str(input_string)
return float(string_chop_up(string_chop_low(input_string, chop_up), chop_low)) | [
"def str2float(string):\r\n if string.strip() != \"\":\r\n number = float(string[:-4])\r\n number *= 10**(int(string[-3:]))\r\n return number\r\n else:\r\n return numpy.nan",
"def ffloat(string):\n try:\n return float(string.strip())\n except:\n return 0",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> string_chop_low('hello my name is test', 'hello') ' my name is test' >>> string_chop_low('tests are the worst', 'tests') ' are the worst' >>> string_chop_low('tests are the worst', 'tests ') 'are the worst' >>> string_chop_low('tests are the worst', 'hello ') 'failed to find chop value in input; tests are the worst... | def string_chop_up(input_string, chop_up):
if type(input_string and chop_up) is str:
if chop_up in input_string:
return input_string[:input_string.find(chop_up)]
else:
return 'failed to find chop value in input; ' + input_string + ' ' + chop_up
else:
return 'inco... | [
"def string_chop_low(input_string, chop_low):\n\n if type(input_string and chop_low) is str:\n if chop_low in input_string:\n return input_string[input_string.find(chop_low) + len(chop_low):]\n else:\n return 'failed to find chop value in input; ' + input_string + ' ' + chop_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> string_chop_up('hello my name is test', 'test') 'hello my name is ' >>> string_chop_up('hello my name is test', 'hello') '' >>> string_chop_up('tests are the worst', 'hello') 'failed to find chop value in input; tests are the worst hello' | def string_chop_low(input_string, chop_low):
if type(input_string and chop_low) is str:
if chop_low in input_string:
return input_string[input_string.find(chop_low) + len(chop_low):]
else:
return 'failed to find chop value in input; ' + input_string + ' ' + chop_low
else... | [
"def string_chop_up(input_string, chop_up):\n\n if type(input_string and chop_up) is str:\n if chop_up in input_string:\n return input_string[:input_string.find(chop_up)]\n else:\n return 'failed to find chop value in input; ' + input_string + ' ' + chop_up\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> r1, r2 = netvals() >>> isinstance(r1, float) True >>> isinstance(r2, float) True | def netvals():
net = psutil.net_io_counters()
values1 = string_chopped_to_float(net, 'ts_sent=', ', packets_recv=')
values2 = string_chopped_to_float(net, 'ts_recv=', ', errin=')
if type(values1 or values2) is str:
return 0.0, 0.0
else:
return values1, values2 | [
"def test_RecurrentNeuralNetwork_probas_to_classes():\n arr1 = np.asarray([0.1, 0.2, 0.7], dtype=np.float32)\n arr2 = np.asarray([0.1], dtype=np.float32)\n assert RecurrentNeuralNetwork.probas_to_classes(arr1) == 2\n assert RecurrentNeuralNetwork.probas_to_classes(arr2) == 0",
"def test_rmul():\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> doc = get_cpuvals() >>> type(doc) >>> type(doc.get('CPUCore1')) >>> type(doc.get('CPUCore2')) >>> type(doc.get('CPUCore3')) >>> type(doc.get('CPUCore4')) >>> type(doc.get('CPU')) | def get_cpuvals(inteval = 1):
cpu_array = psutil.cpu_percent(inteval, percpu=True)
return {
'CPUCore1': cpu_array[0],
'CPUCore2': cpu_array[1],
'CPUCore3': cpu_array[2],
'CPUCore4': cpu_array[3],
'CPU': sum(cpu_array)/4
} | [
"def readCPUInfo():\n if not os.path.exists(\"/proc/cpuinfo\"):\n return []\n\n try:\n handle = open(\"/proc/cpuinfo\", \"r\")\n content = handle.readlines()\n handle.close()\n except Exception,ex:\n return []\n result = []\n currentCPU = None\n for line in conte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> doc = get_hdd() >>> type(doc) >>> type(doc.get('HDD')) | def get_hdd():
return {
'HDD': string_chopped_to_float(psutil.disk_usage('/'), 'percent=', ')'),
} | [
"def drive_type():",
"def get_type_from_doc(doc):\n try:\n return doc.replace('\\n',' ').split('-> ')[1].split(' ')[0]\n except:\n return None",
"def getDocStr(self, param):\n return getattr(self, '{}.doc'.format(param))",
"def getdocfield(fieldname):\t\t\n\tl = [d for d in doctype... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> doc = get_net(155.0,155.0,150.0,150.0) >>> type(doc) >>> type(doc.get('NETPKTSNT')) >>> type(doc.get('NETPKTRCV')) >>> doc.get('NETPKTSNT') 5.0 >>> doc.get('NETPKTRCV') 5.0 | def get_net(netsnt, netrcv, tempsnt, temprcv):
return {
'NET-PKT-SNT': (netsnt - tempsnt),
'NET-PKT-RCV': (netrcv - temprcv),
} | [
"def retrieve_wordnet():\n try:\n from nltk.corpus import wordnet\n except:\n import nltk\n nltk.download('wordnet')\n from nltk.corpus import wordnet\n\n return wordnet",
"def _get_cost(self, doc_id, element_type):\r\n if self.cost_lookup is None:\r\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the Jinja2 library by generating text from a template. | def test_jinja2(device_inventory):
test_template = """
interface Ethernet{{ intf_id }}
ip address {{ intf_ip }}
"""
test_result = """
interface Ethernet1
ip address 1.2.3.4/24
"""
template = Template(test_template)
result = template.render(intf_id=1, intf_ip="1.2.3.4/24")
... | [
"def test_can_find_template(self):\n env = create_jinja_env()\n template = env.get_template('CMakeLists.txt.jinja')",
"def jinja():\n template_path = '/tmp/pycheat-jinja-template.html'\n output_path = '/tmp/pycheat-jinja-output.html'\n\n # create the testing template\n with open(template... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. | def run_migrations_online():
# specify here how the engine is acquired
engine = create_engine(db_url)
if isinstance(engine, Engine):
connection = engine.connect()
else:
raise Exception(
'Expected engine instance got %s instead' % type(engine)
)
# pylint:disable=E1... | [
"def run_migrations_online():\n # Allow config object to have a connection already added\n connectable = config.attributes.get(\"connection\", None)\n\n if connectable is None:\n # only create Engine if we don't have a Connection\n # from the outside\n connectable = target_metadata.bin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function uses the readability library for feature engineering. It includes textual statistics, readability scales and metric, and some pos stats | def readability_measurements(passage: str):
results = readability.getmeasures(passage, lang='en')
chars_per_word = results['sentence info']['characters_per_word']
syll_per_word = results['sentence info']['syll_per_word']
words_per_sent = results['sentence info']['words_per_sentence']
kinca... | [
"def calculate_readability(content):\n content['readability'] = textstat.flesch_reading_ease(content['clean_text'])\n return content",
"def flesch_reading_score(text):\n \n # note this has to be completed before text preprocessing\n readability_score = round(textstat.flesch_reading_ease(text), 2)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor vcs reference to the Mercurial vcs object Hg | def __init__(self, vcs):
super(Histedit, self).__init__(vcs) | [
"def __init__(self, vcsObject, projectObject, parent=None, name=None):\n VcsProjectHelper.__init__(self, vcsObject, projectObject, parent, name)",
"def __init__(self, *args):\n _snap.TChVV_swiginit(self, _snap.new_TChVV(*args))",
"def __init__(self, *args):\n _hypre.HypreEuclid_swiginit(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to start a histedit session. name file/directory name str rev revision to start histedit at str flag indicating that the project should be reread bool | def hgHisteditStart(self, name, rev=""):
# find the root of the repo
repodir = self.vcs.splitPath(name)[0]
while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
repodir = os.path.dirname(repodir)
if os.path.splitdrive(repodir)[1] == os.sep:
re... | [
"def hgHisteditContinue(self, name):\n # find the root of the repo\n repodir = self.vcs.splitPath(name)[0]\n while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):\n repodir = os.path.dirname(repodir)\n if os.path.splitdrive(repodir)[1] == os.sep:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to continue an interrupted histedit session. name file/directory name str flag indicating that the project should be reread bool | def hgHisteditContinue(self, name):
# find the root of the repo
repodir = self.vcs.splitPath(name)[0]
while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
repodir = os.path.dirname(repodir)
if os.path.splitdrive(repodir)[1] == os.sep:
return ... | [
"def hgHisteditAbort(self, name):\n # find the root of the repo\n repodir = self.vcs.splitPath(name)[0]\n while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):\n repodir = os.path.dirname(repodir)\n if os.path.splitdrive(repodir)[1] == os.sep:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Public method to abort an interrupted histedit session. name file/directory name str flag indicating that the project should be reread bool | def hgHisteditAbort(self, name):
# find the root of the repo
repodir = self.vcs.splitPath(name)[0]
while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
repodir = os.path.dirname(repodir)
if os.path.splitdrive(repodir)[1] == os.sep:
return Fal... | [
"def abort(self):",
"def set_abort_flag(self):\r\n self.abort_flag = True",
"def interrupted(self):\n print(\"Macro interrupted!\")",
"def flag_aborted(_tm_env, container_dir, exc=None):\n with open(os.path.join(container_dir, 'aborted'), 'w+') as f:\n if exc:\n f.write(str(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print out prune rate for each layer and the whole network | def prune_rate(model, verbose=True):
total_nb_param = 0
nb_zero_param = 0
layer_id = 0
for parameter in model.parameters():
param_this_layer = 1
for dim in parameter.data.size():
param_this_layer *= dim
total_nb_param += param_this_layer
# only pruning lin... | [
"def prune():\n with tf.Graph().as_default() as g:\n # Input evaluation data\n images, labels = rn.inputs(eval_data=True)\n\n # inference model.\n logits = rn.inference(images, 15)\n\n # Calculate predictions.\n top_k_op = tf.nn.in_top_k(logits, labels, 1)\n\n # C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
nonzero argmin of a nonnegative array | def arg_nonzero_min(a):
if not a:
return
min_ix, min_v = None, None
# find the starting value (should be nonzero)
for i, e in enumerate(a):
if e != 0:
min_ix = i
min_v = e
if not min_ix:
print('Warning: all zero')
return np.inf, np.inf
#... | [
"def nanargmin(a, axis=None):\n y = array(a, subok=True)\n if not issubclass(y.dtype.type, _nx.integer):\n y[isnan(a)] = _nx.inf\n return y.argmin(axis)",
"def custom_argmin(arr):\n return np.random.choice(np.flatnonzero(arr == arr.min()))",
"def argmin(tensor):\n raise NotImplementedE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prints menu guide for headless | def printMenu():
# tWelc = PrettyTable(['Welcome to the CLI-of the repository classifier'])
print('Welcome to the CLI of the repository classifier')
print(strStopper1)
t = PrettyTable(['Action', ' Shortcut '])
t.add_row(['Show Menu', '- m -'])
t.add_row([' Predict repositories form txt... | [
"def display_menu(self):\n print 57 * '#'\n print '# WELCOME TO THE PYTHON/WEBDEV WALL #'\n print '# ---------------------------------------------- #'\n print '# Here, we will dial in on your python skills by #'\n print '# providing an interac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the shortest path for each agent to its target and the action to be taken to do so. The paths are derived from a `DistanceMap`. If there is no path (rail disconnected), the path is given as None. The agent state (moving or not) and its speed are not taken into account | def get_shortest_paths(distance_map: DistanceMap, agent_pos, agent_dir, max_depth: Optional[int] = None, agent_handle: Optional[int] = None) \
-> Dict[int, Optional[List[Waypoint]]]:
shortest_paths = dict()
def _shortest_path_for_agent(agent,agent_pos,agent_dir):
if agent_pos is None :
... | [
"def path(self, source, target, path=[]):\n path = path + [source]\n if source == target:\n return path\n if source not in self.rooms:\n return None\n shortest = None\n for room in source.get_targets():\n if room not in path:\n newpa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the weighted logprobabilities, log P(X | Z) + log weights. | def _estimate_weighted_log_prob(self, X, precision_cholesky):
return self._estimate_log_prob(X, precision_cholesky) + self._estimate_log_weights(X.location) | [
"def compute_log_prob(self,params: ndarray) -> float:\n return self.compute_log_prior(params) + self.compute_log_likelihood(params)",
"def _log_likelihood(self, *, input: Inputs, output: Outputs) -> float:\n logp = self._model.logp\n weights = self._trace[\"weights\"]\n self._training_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
每次顺序从每个 item 中取出一个元素,跳过已经被迭代完毕的 item. | def iter_one_by_one(items, stop_immediately=False):
iters = list(map(iter, items))
while len(iters):
for i, it in enumerate(iters):
try:
yield next(it)
except StopIteration:
if stop_immediately:
return # 立即停止迭代
... | [
"def repeatlast(it):\r\n for item in it:\r\n yield item\r\n while 1: # pragma: no cover\r\n yield item",
"def caboose(seq: Iterable[TItem], el: TElement) -> Iterable[Union[TElement, TItem]]:\n yield from seq\n yield el",
"def last(iterator):\n item = None\n for item in iterator:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
过滤掉判断为 False 的 items | def filter_truth(items):
return filter(truth, items) | [
"def keep_if(filter_fn, s):\n return [x for x in s if filter_fn(x)]",
"def filterfalse(pred, iterable):\n return Iter(itertools.filterfalse(pred, iterable))",
"def true_false_both_filter(request, items, parameter):\n if parameter in request['args']:\n test = request['args'][parameter].lower()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
注册 成功:返回 ACC_MNG_OK 失败:返回 REG_FAIL_INV_ACC | def register(mail, pwd, invite):
# 检查是否存在acnt + invite
if team.is_team_inv_match(mail, invite):
# 如果存在则更新pwd
team.update_team_pwd(mail, pwd)
return ACC_MNG_OK
else:
# 如果不存在提示账号不存在或邀请码错误
return REG_FAIL_INV_ACC | [
"def register(self):\n pass",
"async def _perform_register(self):\n data = {\"username\": self.user, \"password\": self.password}\n return await self._perform_request(\"register\", data, lambda r: r.text())",
"def register(input_user, input_pass):\n try:\n self.send_messag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
发送密码重置邮件,记录链接发送的时间 成功:发送重置邮件并返回OK_RESTE_MAIL 失败:返回ERR_RESET_MAIL_NOTEXIST 或ERR_RESET_MAIL_DB | def send_reset_mail(mail):
tid = mail_team(mail)
if tid is None:
return ACC_NO_FOUND
else:
# 账号密文
hash_tid = encrypt(str(tid))
team.reset_team(mail, hash_tid)
send_mail('来自WeMeet', reset_mail_content(hash_tid, mail), # TODO(hjf): 修改邮件内容、收发邮箱
'm18826... | [
"def request_password_reset():",
"def forget_password_request():\n form = EmailForm(request.form)\n if request.method == 'POST':\n if form.validate():\n account_email = form.email.data\n user = User.query.filter_by(email=account_email).first_or_404()\n send_mail(form.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
验证凭据激活账号修改密码 成功:激活账号,修改密码, 返回OK_CHANGE_PWD 失败:返回ERR_CHANGE_PWD_NOTEXIST 或ERR_CHANGE_PWD_WRONG_CREDENTIAL 或ERR_CHANGE_PWD_DB | def update_pwd(mail, hash_tid, pwd):
ret = team.update_pwd(mail, hash_tid, pwd)
if ret == DB_OK:
return ACC_MNG_OK
elif ret == DB_ACC_NOT_FOUND:
return ACC_NO_FOUND | [
"def cp_verify():\n\n account = session['admin']['account'] # 获取当前用户账户\n original = request.form.get('original') # 从表单中获取用户输入的旧密码\n\n if Admin.query.filter_by(account=account, password=common.my_md5(original)).first():\n token = Token(f'__cp__{account}', deadline=Token.set_deadline({'minutes': 10}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
guess the indent and block sequence indent of yaml stream/string returns round_trip_loaded stream, indent level, block sequence indent block sequence indent is the number of spaces before a dash relative to previous indent if there are no block sequences, indent is taken from nested mappings, block sequence indent is u... | def load_yaml_guess_indent(stream, **kw):
# type: (StreamTextType, Any) -> Any
from .main import round_trip_load
# load a YAML document, guess the indentation, if you use TABs you're on your own
def leading_spaces(line):
# type: (Any) -> int
idx = 0
while idx < len(line) and lin... | [
"def _open_yaml(stream, original_file=None, substitutions_dict={}):\n try:\n yaml_contents = yaml.load(stream, Loader=yaml_SafeLoader)\n\n return _get_yaml_contents_without_documentation_complete(yaml_contents, substitutions_dict)\n except DocumentationNotComplete as e:\n raise e\n exc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
walks over a ConfigObj (INI file with comments) generating corresponding YAML output (including comments | def configobj_walker(cfg):
# type: (Any) -> Any
from configobj import ConfigObj # type: ignore
assert isinstance(cfg, ConfigObj)
for c in cfg.initial_comment:
if c.strip():
yield c
for s in _walk_section(cfg):
if s.strip():
yield s
for c in cfg.final_com... | [
"def patch_config(self_config, indict):\n for key in self_config:\n if isinstance(self_config[key], Section) \\\n and key in indict and isinstance(indict[key], Section):\n self_config[key].parent = self_config\n self_config[key].main = self_config.main\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
updates curis with crawlinfo in bulk. not implemented noop. this is too slow anyways. | def update_crawlinfo(self, curis):
pass
# tasks = [(self._set_crawlinfo, (curi,))
# for curi in curis if 'a' not in curi]
# if tasks:
# b = TaskBucket(tasks)
# b.execute_wait(executor, 4) | [
"def update_cid(cid):\n st = time.time()\n count = 0\n for i, g in enumerate(query_to_tuples(\"select distinct group_id from hits_mv where crawl_id = %s\", cid)):\n g = g[0]\n if i == 0:\n log.info(\"processing %s, %s %s\", i, cid, g)\n\n updatehitgroup(g, cid)\n cou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a query string in from a file | def load_query(query_filename):
with open(query_filename) as f:
return f.read() | [
"def read_file(filepath: str, query_params: dict) -> list:\r\n\r\n # Get start and end line #'s from query_params (if they exist)\r\n if 'startln' in query_params:\r\n startln = query_params['startln']\r\n else:\r\n startln = 0 # Default to line 0 (index 0)\r\n if 'endln' in query_params:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transforms the db cursor into a list of records, where the first item is the header | def construct_list(cursor):
header = [h[0] for h in cursor.description]
data = cursor.fetchall()
return header, data | [
"def __toListOfDict(self, cursor):\n lst = []\n for row in cursor.fetchall():\n # first convert row to a dictionary\n rowdict={}\n for idx, col in enumerate(cursor.description):\n rowdict[col[0]] = row[idx]\n lst.append(rowdict)\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transforms the db cursor rows into a csv file string | def construct_csv(cursor):
header, data = construct_list(cursor)
# python 2 and 3 handle writing files differently
if sys.version_info[0] <= 2:
output = io.BytesIO()
else:
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(header)
for row in data:
wri... | [
"def _as_csv(self,res):\n outfile = StringIO.StringIO()\n cw = csv.writer(outfile, quotechar = '\"', quoting=csv.QUOTE_MINIMAL,skipinitialspace=True)\n cw.writerow( self._get_cols( res ) )\n cw.writerows(self.conn.execute(res).fetchall())\n return outfile.getvalue()",
"def sendT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the original data and the cluster assignments from the given handles. | def load_data(original_input_handle, cluster_input_handle):
info('Loading original data from {}'.format(original_input_handle.name))
original_data = pd.read_csv(original_input_handle, index_col=0)
info('Loaded a table with shape {}'.format(original_data.shape))
clusters = None
if cluster_input_... | [
"def update_plot_clusters(cluster_handles, data_points, cluster_ids):\n for handle, cluster_id in zip(cluster_handles, np.unique(cluster_ids)):\n loc = cluster_id == cluster_ids\n handle.set_data(data_points[loc, 0], data_points[loc, 1])",
"def _load_indices(self):\n if not UMLS.is_initali... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits the given data by the given cluster assignments. | def split_data(df_data, clusters):
if clusters is None:
return {0: df_data}
return {
k: df_data.loc[clusters.index[clusters == k]]
for k in clusters.unique()
} | [
"def split_clusters(clusters, new):\n pass",
"def split_by_link(data):\n\n split_data = {}\n\n data.loc[:, 'cluster_id'] = data['ds1_cluster'] + \"-\" + data['ds2_cluster']\n\n grouped = data.groupby('cluster_id')\n\n for x in grouped.groups:\n split_data[grouped.get_group(x)['cluster_id'][0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to extract a version number for the sgjirabridge module. This will attenmpt to extract the version number from git if installed from a cloned repo. If a version is unable to be determined, or the process fails for any reason, we return "dev" | def get_sg_jira_bridge_version():
# Note: if you install from a cloned git repository
# (e.g. pip install ./tk-core), the version number
# will be picked up from the most recently added tag.
try:
version_git = subprocess.check_output(
["git", "describe", "--abbrev=0"]
).rstri... | [
"def get_version_from_git():\n # grab the version from git describe\n version = (\n subprocess.check_output(\n [\"git\", \"describe\", \"--always\", \"--long\", \"--dirty\", \"--tags\"]\n )\n .strip()\n .decode(\"utf-8\")[1:]\n )\n # process the string to be PEP 44... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of sync settings this server handles. | def sync_settings_names(self):
return self._sg_jira.sync_settings_names | [
"def get_all_settings(self):\n return self._data",
"def settings_get_sync_settings(self, **kwargs):\n kwargs['_return_http_data_only'] = True\n if kwargs.get('callback'):\n return self.settings_get_sync_settings_with_http_info(**kwargs)\n else:\n (data) = self.set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle a request to sync between ShotGrid and Jira in either direction. At this point, only the action (the first path_part) from the request path has been validated. The rest of the path_parts still need to be validated before we proceed. We expect the path to for this request to | def _handle_sync_request(self, path_parts, parameters):
entity_type = None
entity_key = None
if len(path_parts) == 4:
direction, settings_name, entity_type, entity_key = path_parts
elif len(path_parts) == 2:
direction, settings_name = path_parts
else:
... | [
"def _try_handle_sync(self, identity, request):\n if all(key in request for key in [JSON_TOKEN.INIT, JSON_TOKEN.DIFF,\n JSON_TOKEN.MODE, JSON_TOKEN.CURSORS]):\n log.info('handle sync-request from %r\\n' % identity)\n self._check_init(identity, re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle admin request to the server. Currently handles a single action, ``reset`` which resets the Bridge in order to clear out the ShotGrid schema cache. At this point, only the action (the first path_part) from the request path has been validated. The rest of the path_parts still need to be validated before we proceed... | def _handle_admin_request(self, path_parts, parameters):
# The only function we respond to now is reset
if len(path_parts) != 2 or path_parts[1] != "reset":
raise SgJiraBridgeBadRequestError(
"Invalid admin path '%s'. Action is not set or unsupported." % self.path
... | [
"def batchadmin_dispatch(self, request, changelist, action):\n action_func = getattr(self, action, None)\n if callable(action_func):\n return action_func(request, changelist)",
"def pre_process_request(self, req, handler):\n if isinstance(self.env, ProductEnvironment) and \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an ordinal of a number, e.g. 'st' in 1st or 'th' in 5th | def ordinal(num):
if num > 9:
secondToLastDigit = str(num)[-2]
if secondToLastDigit == '1':
return 'th'
lastDigit = num % 10
if (lastDigit == 1):
return 'st'
elif (lastDigit == 2):
return 'nd'
elif (lastDigit == 3):
return 'rd'
else:
re... | [
"def ordinal(n):\n ord_dict = {1: \"st\", 2: \"nd\", 3: \"rd\"}\n return str(n + 1) + ord_dict.get((n + 1) if (n + 1) < 20 else (n + 1) % 10, \"th\")",
"def ordinal(num):\n num = str(num)\n if num[-2:] == \"11\" or num[-2:] == \"12\" or num[-2:] == \"13\":\n return f\"{num}th\"\n elif num[-1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the number to an internal data structure. | def add(self, number):
self.num[number] = self.num.get(number, 0) + 1 | [
"def add(self, number: int) -> None:\n self.data.append(number)",
"def add(self, number: int) -> None:\n self.nums[number] += 1",
"def addNum(self, num):\n i = self._binarySearch(num)\n self._data.insert(i, num)",
"def add(self, number):\n self.map[number] += 1",
"def add(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that the cli import command for barred list is working properly. | def test_cli_barred_list_importer(postgres, db_conn, tmpdir, mocked_config, logger):
here = path.abspath(path.dirname(__file__))
data_dir = path.join(here, 'unittest_data/barred_tac_list')
valid_data_file_name = 'sample_barred_tac_list.csv'
valid_data_file = path.join(data_dir, valid_data_file_name)
... | [
"def test_importtleCommandExists(self):\n self.assertIn('importtle', get_commands())",
"def test_command(self):\n out = io.StringIO()\n management.call_command('import_data', stdout=out)\n self.assertIn(\"Successfully imported\", out.getvalue())",
"def test_pre_cli_list(run):\n ou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that the barred list data is not imported if a header column is missing. | def test_missing_header(barred_tac_list_importer, logger, db_conn):
expect_failure(barred_tac_list_importer, exc_message='Metadata header, cannot find the column headers - tac, '
'10000110') | [
"def test_missing_column_raises(self, csv_missing_fields_in_header):\n missing_df = pd.read_csv(csv_missing_fields_in_header)\n with pytest.raises(pandera.errors.SchemaError):\n crowsetta.formats.seq.generic.GenericSeqSchema.validate(missing_df)",
"def test_missing_headers(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that barred list import fails historical check. | def test_historical_check_percent_fails(barred_tac_list_importer, logger, mocked_statsd, db_conn, mocked_config,
metadata_db_conn, tmpdir):
expect_success(barred_tac_list_importer, 20, db_conn, logger)
with get_importer(BarredTacListImporter,
db_conn... | [
"def test_admin_see_the_full_error_list_from_failed_book_import_7652(self):\n self.ps.test_updates['name'] = 'cc1.04.002' \\\n + inspect.currentframe().f_code.co_name[4:]\n self.ps.test_updates['tags'] = [\n 'cc1',\n 'cc1.04',\n 'cc1.04.002',\n '7... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that Barred List data is not imported if the filename format is invalid. | def test_invalid_file_type(barred_tac_list_importer):
expect_failure(barred_tac_list_importer, exc_message='Wrong suffix') | [
"def test_schema_invalid_format(self):\n bad_schema = [int, int, float, float, str]\n with self.assertRaisesRegexp(Exception, \"more than one char\"):\n self.context.frame.import_csv(self.dataset, bad_schema)",
"def test_bad_filename(self):\n log.debug('===== START TEST BAD FILENAM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
查看当前数据库中的数据情况。 DATABASE_STATUS GROUP_ID | UPLOAD_TIME | UPLOAD_NAME | START_TIME | PACKETS | CALC_CFLOW 15.28.15.23cdxy1000.00 25.28.15.23cdxy1000.0547 31111cdxyreal11000.026542 51111cdxyreal11000.0105329 61111cdxyreal11000.017186382 7111 cdxyreal1000.010207 8111 cdxyreal1000.062008 9111 cdxyreal1000.061997 101 cdxytes... | def show_database_status():
db = MySQLdb.connect(conf.DB.HOST, conf.DB.USER, conf.DB.PASS, conf.DB.NAME)
cursor = db.cursor()
sql = """
select ID,UPLOAD_TIME,UPLOAD_NAME,START_TIME,
(select count(*) from Packets where Packets.GROUP_ID=DataGroup.ID) as packets,
IF( EXISTS (select * f... | [
"def _getDBStatus(self):\n msg = self.asyncRead()\n dbo = DatabaseObject()\n path = msg[\"path\"]\n if \"absolute\" not in msg:\n path = os.path.join(self.parent.sessionPath, path)\n dbo.setDB(path, msg[\"type\"])\n if msg[\"type\"] == \"HDF5TXT\":\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the models agree with the different surface forms | def test_compare_outputs_surface_form(self):
# load models
options = [
{"surface form": cap} for cap in ["false", "differential", "algebraic"]
]
model_combos = [
([pybamm.lead_acid.LOQS(opt) for opt in options]),
([pybamm.lead_acid.Full(opt) for opt in... | [
"def verifyModels(self):\r\n\r\n #\r\n # now check that all models have the same poly data in the\r\n # model node as in the display node\r\n #\r\n polyDataInScene = []\r\n fileNamesInScene = []\r\n success = True\r\n numModels = slicer.mrmlScene.GetNumberOfNodesByClass( \"vtkMRMLModelNode\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates json files for all csv origin files in the translations directory. | def build():
for root, dirs, files in os.walk(IN_PATH):
for filename in files:
if filename.endswith('.csv'):
with open(os.path.join(IN_PATH, filename), encoding='utf-8') as f:
reader = csv.reader(f)
next(reader)
data = n... | [
"def main():\n for db_csv_export in current_dir.glob(\"template*.csv\"):\n data_projects = load_projects(db_csv_export)\n json_path = db_csv_export.with_suffix(\".json\")\n with open(json_path, \"w\") as fh:\n json.dump(data_projects, fh, indent=2)",
"def build_json():\n data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a locale from json file. FileNotFound exception if locale does not exist or is not built. | def load(locale):
if not locale:
locale = 'en_US'
filepath = os.path.join(OUT_PATH, locale + '.json')
with open(filepath, encoding='utf-8') as f:
return json.load(f) | [
"def __load_locale(self, locale_path: str) -> dict:\n return FileManager.read_json(locale_path)",
"def get_translation_dict_from_file(path, lang, app):\n\tjson_content = {}\n\tif os.path.exists(path):\n\t\twith open(path, 'r') as f:\n\t\t\tjson_content = json.loads(f.read())\n\n\treturn json_content",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Report the memory usage of the tensor.storage in pytorch Both on CPUs and GPUs are reported if print_all is True, print size and shape info for each tensor | def mem_report(print_all: bool = False) -> None:
def _mem_report(tensors: Iterable, mem_type: str) -> None:
"""Print the selected tensors of type
There are two major storage types in our major concern:
- GPU: tensors transferred to CUDA devices
- CPU: tensors remaining on t... | [
"def _print_memory_usage() -> None:\r\n import gc\r\n import operator as op\r\n from functools import reduce\r\n for obj in gc.get_objects():\r\n # noinspection PyBroadException\r\n try:\r\n if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies the model parameters of one net to another. | def copy_model_parameters(sess, net1, net2):
copy_scope_parameters(sess, net1.scope, net2.scope) | [
"def hard_update(source_net, target_net):\n for target_param, param in zip(target_net.parameters(), source_net.parameters()):\n target_param.data.copy_(param.data)",
"def copy_weights(self, net_to_copy):\n variables1 = self.network.trainable_variables\n variables2 = net_to_copy.network.tra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inverse of integral funcition. | def inverseintegrate(x, power):
if power == -1:
return exp(x)
else:
return pow(x*(power+1.), 1./(power+1.)) | [
"def inverse_inc(self, inc) -> tf.Tensor:\n return (inc - self.inc_min) / self.inc_range",
"def inverse_inc(self, inc):\n return (inc - self.inc_min) / self.inc_range",
"def calc_inverse(val):\n\treturn val**(-1)",
"def _inverse(G):\n # TODO: implement this.\n pass",
"def additiv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given xmin and xmean, calculate xmax. | def _calc_xmax(self, xmin, xmean):
self.xmin = xmin
self.xmax = xmean+.01
for i in itertools.count():
self.norm = self._integrate(self.xmax)-self._integrate(self.xmin)
newmean = self.mean()
delta = xmean - newmean
#print self.xmin, newmean, self.xm... | [
"def _calc_xmin(self, xmax, xmean):\n self.xmin = xmean-.01\n self.xmax = xmax\n for i in itertools.count():\n self.norm = self._integrate(self.xmax)-self._integrate(self.xmin)\n newmean = self.mean()\n delta = - newmean + xmean\n #print self.xmin, ne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given xmax and xmean, calculate xmin. | def _calc_xmin(self, xmax, xmean):
self.xmin = xmean-.01
self.xmax = xmax
for i in itertools.count():
self.norm = self._integrate(self.xmax)-self._integrate(self.xmin)
newmean = self.mean()
delta = - newmean + xmean
#print self.xmin, newmean, self.... | [
"def get_xmin(self):\n return self.__xmin",
"def normalize(self,x,xmin,xmax):\n return (x-xmin)/(xmax-xmin)",
"def xmin(self):\n\n return self.bbox[1]",
"def get_minx_maxx(self, normalized=True):\n minx = np.array([[0.0] * len(self.encoded_feature_names)])\n maxx = np.ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the IOLoop until stop is called or timeout has passed. In the event of a timeout, an exception will be thrown. If condition is not None, the IOLoop will be restarted after stop() until condition() returns true. | def execute(self, condition=None, timeout=90):
if not self.stopped:
if timeout:
def timeout_func():
try:
raise Exception('Async operation timed out after {} seconds'.format(timeout))
except:
self.... | [
"def wait(self, condition=None, timeout=None):\r\n if timeout is None:\r\n timeout = get_async_test_timeout()\r\n\r\n if not self.__stopped:\r\n if timeout:\r\n def timeout_func():\r\n try:\r\n raise self.failureException(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decodes the access token | def decodeAccesshTokenForRefreshToken( accessToken):
try:
payload = jwt.decode(accessToken, ApiJWTAuthentication.secretKey_access)
return {"message": "success","refresh_token": payload['refresh_token']}
except jwt.ExpiredSignatureError:
return {"message": "Expired Acc... | [
"def decode(encoded_token):\n return jwt.decode(encoded_token, key=settings.JWT_AUTH['JWT_SECRET_KEY'])",
"def decode_auth_token(self, auth_token):\n try:\n LOGGER.debug(auth_token)\n payload = jwt.decode(auth_token, self._pulic_key())\n return payload\n except:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper to complete the current task. Uses the current date for the completion date. | def complete(self):
self.completed = peewee.datetime.date.today()
self.save() | [
"def complete_task(self, user_id, task_id, completed=datetime.now()):\n\n sql = \"select complete_task(%s, %s, %s)\"\n data = (user_id, task_id, completed)\n self._query_insert(sql, data)",
"def complete_task(self, tid):\n self.task_controller.complete_task(tid)",
"def complete_task(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the URL for marking this task as completed. | def complete_url(self):
return url_for('complete',id=self.id) | [
"def get_complete_url(self):\n return ('complete-task', (), {'slug': self.todolist.slug, 'task_slug': self.slug})",
"def get_completed(self):\n\n return \"Completed Tasks: \\n\" + self.success",
"def get_status_url(self):\n status_handler_view = 'appraise.evaluation.views.status_view'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get primary key properties for a SQLAlchemy model. | def get_primary_keys(model):
mapper = model.__mapper__
return [mapper.get_property_by_column(column) for column in mapper.primary_key] | [
"def primary_key_names(model):\n return [key for key, field in inspect.getmembers(model)\n if isinstance(field, QueryableAttribute)\n and isinstance(field.property, ColumnProperty)\n and field.property.columns[0].primary_key]",
"def get_primary_key_columns(cls):\n return in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize a serialized value to a model instance. If the parent schema is transient, create a new (transient) instance. Otherwise, attempt to find an existing instance in the database. | def _deserialize(self, value, *args, **kwargs):
if not isinstance(value, dict):
if len(self.related_keys) != 1:
keys = [prop.key for prop in self.related_keys]
raise self.make_error("invalid", value=value, keys=keys)
value = {self.related_keys[0].key: valu... | [
"def _deserialize(self, value, *args, **kwargs):\n if not isinstance(value, dict):\n if len(self.related_keys) != 1:\n keys = [prop.key for prop in self.related_keys]\n raise self.make_error(\"invalid\", value=value, keys=keys)\n value = {self.related_keys[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Here I will use two dictionary to find the judge. The judge has two requirement. 1. He trust nobody 2. He is trusted by everyone So the judge will not appear in the trust dictionary and The judge in the trusted dictionary will be n1 | def findJudge(self, N, trust):
if trust == []:
return 1
trust_dict = {}
trusted_dict = {}
for i in range(len(trust)):
trust_dict[trust[i][0]] = trust_dict.get(trust[i][0], 0) + 1
for i in range(len(trust)):
... | [
"def answers_db() -> Dict[str, List]:\n return{\"lawyer\":[\"either\",\"other\",\"law\",\"boy\"],\n \"cot_caught\":[\"different\",\"other\",\"same\"],\n \"second_person_plural\":[\"other\",\"y'all\",\"yins\",\n \"you\",\"you'uns\",\"you all\",\"you guys\",\"you lot\",\n \"yous, yo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Undoes the last cooldown counter for usererror cases. | def revert_cooldown_counter(command: commands.Command, message: Message) -> None:
if command._buckets.valid:
bucket = command._buckets.get_bucket(message)
bucket._tokens = min(bucket.rate, bucket._tokens + 1)
logger.debug(
"Cooldown counter reverted as the com... | [
"def reset_cooldown(self):\n\n self.cooldown = self.init_time",
"def reset_fedcm_cooldown(self):\n pass",
"def reset_cooldown_timer(backend):\n global cooldown_timer\n if cooldown_timer: cooldown_timer.cancel()\n cooldown_timer = Timer(60, random_scale_down, [backend])\n cooldown_timer.start()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a basic embed with red colour and either a random error title or a title provided. | def error_embed(message: str, title: Optional[str] = None) -> Embed:
title = title or random.choice(ERROR_REPLIES)
embed = Embed(colour=Colours.soft_red, title=title)
embed.description = message
return embed | [
"def _error_embed_helper(title: str, description: str) -> discord.Embed:\n return discord.Embed(title=title, description=description, colour=discord.Colour.red())",
"def _get_error_embed(self, title: str, body: str) -> Embed:\n return Embed(\n title=title,\n colour=0xFF0000,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Score is precision @ k Relevance is binary (nonzero is relevant). | def precision_at_k(r, k):
assert k >= 1
r = np.asarray(r)[:k] != 0
if r.size != k:
raise ValueError('Relevance score length < k')
return np.mean(r) | [
"def precision_at_k(r, k):\n assert k >= 1\n r = np.asarray(r)[:k] != 0\n if r.size != k:\n raise ValueError('Relevance score length < k')\n return np.mean(r)",
"def precision_at_k(ground_truth, predictions, k=5, pos_label=1):\n assert len(ground_truth) == len(predictions), \"P@k: Length mis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find duplicate number in nums. Given a list of nums with, at most, one duplicate, return the duplicate. If there is no duplicate, return None >>> find_the_duplicate([1, 2, 1, 4, 3, 12]) 1 >>> find_the_duplicate([6, 1, 9, 5, 3, 4, 9]) 9 >>> find_the_duplicate([2, 1, 3, 4]) is None True | def find_the_duplicate(nums):
# frequency = {}
# for num in nums:
# frequency[num] = frequency.get(num, 0) + 1
# for num in frequency:
# if frequency[num] == 2:
# return num
##########
# nums_dict = list(enumerate(sorted(nums)))
# for i, num in nums_dict:
# ... | [
"def removeDuplicates(self, nums):\n if (len(nums) == 0):\n return 0\n\n count = 1\n old = nums[0]\n\n for i, num in enumerate(nums):\n if num == old:\n continue\n nums[count] = num\n old = num\n count += 1\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a single or a list of variables to the table. If a list is added, a common nD halton sequence is generated and the variables are transformed according to their distribution. | def add(self, variables):
if not isinstance(variables, (list, tuple)):
variables = [variables]
for v in variables:
if isinstance(v, Variable):
self.list.append(v)
elif isinstance(v, dict):
self.list.append(Variable.create(**v))
... | [
"def add_variables(self, variables):\n for variable in variables:\n self.variables.append(variable)",
"def addVariables(self, variables, domain):\n for variable in variables:\n self.addVariable(variable, domain)",
"def add_variables_from_list(self, variables):\n for va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes one or more variables from the table. | def delete_variable(self, columns):
if not isinstance(columns, (list, tuple)):
columns = [columns]
for col in columns:
if isinstance(col, str):
col = [i for i, v in enumerate(self.list) if v.name == col][0]
self.list.pop(col) | [
"def remove_variables(self, var_ids):\n pass",
"def deleteVar(self, varName):\n if type(varName) != str:\n raise TypeError, 'variable name must be a string'\n\n op = 'delete var'\n\n self.send('0003%020d%s%020d%s%020d%s' % (len(op), op, len(self.curWs), self.curWs, len(varNa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a common halton sequence for all variables where this is possible and transforms them according to their distribution. | def generate_from_halton(self):
halton_variables = [
v for v in self.list if v.kind.lower() not in EXCLUDE_FROM_HALTON
]
if halton_variables:
nd_halton_seq = halton((self.samples, len(halton_variables)))
for idx, v in enumerate(halton_variables):
... | [
"def halton_sequence(values, feature, parent):\r\n \r\n index = values[0]\r\n base = values[1]\r\n return halton(index, base)",
"def halton(dimensions: int, size: int, start: int, scramble: bool, state: np.random.RandomState) -> Tuple[Array, Array]:\n\n # generate Halton sequences\n sequences = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a Variable instance from a string. E.g. 'Uniform(3.4, 7.8)' | def create_from_str(cls, name, size, v_str):
from re import split
def try_parse(s):
funcs = [int, float]
for f in funcs:
try:
return f(s)
except ValueError:
pass
return s
if isinstance(t... | [
"def _variable(el):\n el = str(el).split('_')\n name = el[0]\n try:\n indices = el[1]\n except IndexError:\n # No indices\n indices = \"\"\n return Variable(name=name, indices=tuple(indices))",
"def _from_string(self,string):\n logger.debug(\"INIT: string\")\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pads the string on the left side by adding the add string to the left as many times as necessary such that the output is "[add,]string" | def pad_str_left(string, length: int, add: str) -> str:
out_string = string
while len(out_string) < length:
out_string = add + out_string
return out_string | [
"def _pad_shorter(sequence: str) -> str:\n return sequence.ljust(3, \"X\")",
"def pad_left(s, target_len):\n return ' ' * (target_len - len(s)) + s",
"def zeroPad(numberString, zeros, left = True):\n for i in range(zeros):\n if left:\n numberString = '0' + numberString\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
extract words from the text with the filters given above. | def extract_words_from_text_with_filters(text: str, char_filters: Union[str, List[str]]) -> List[str]:
translate_dict = dict((c, " ") for c in char_filters)
new_text = Str.get_string_from_translate_dict(text.lower(), translate_dict)
return [word for word in new_text.split(" ") if len(word) > 0] | [
"def words( text ):\n stext = str(text)\n if ( not stext ):\n return []\n \n # first, split all the alphanumeric characters up\n phrases = EXPR_PHRASE.findall(stext)\n \n # second, split all the camel humped words\n output = []\n for phrase in phrases:\n output += EXPR_WORD.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove the characters chars from the string | def remove_chars_from_string(string: str, chars: str) -> str:
translate_dict = dict((c, "") for c in chars)
return Str.get_string_from_translate_dict(string, translate_dict) | [
"def remove_chars(old_str, chars):\n new_string = old_str\n for char in chars:\n new_string = new_string.replace(char, '')\n \n return new_string",
"def rmchars(value):\n value = re.sub(\"[^A-Za-z0-9.-]+\", \"\", value)\n return value",
"def remove_special_characters(self, txt: str) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks whether the date is before the target date | def is_date_is_before(date: str, target_date: str) -> bool:
year, month, day = [int(v) for v in get_year_month_day_from_date(date)]
t_year, t_month, t_day = [int(v) for v in get_year_month_day_from_date(target_date)]
return datetime.date(year, month, day) < datetime.date(t_year, t_month, t_day) | [
"def is_before(self,other_date):",
"def isBefore(date):\n return date and datetime.datetime.utcnow() < date",
"def isBefore(self, d2):\n if self.year < d2.year:\n return True\n elif self.year == d2.year and self.month < d2.month:\n return True\n elif self.year == d2.year and self.month == d2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Give a list of dates from the start date until the until date | def get_dates_from(start_date: str, until_date: str) -> list:
date_start_date = extract_date_from_date_time(start_date)
assert is_date_is_before(date_start_date, until_date), "start_date must come before until_date"
dates = [date_start_date]
current_date = date_start_date
while True:
if curr... | [
"def constructDateRanges():\n fromDate = ent_startdate.get_date()\n untilDate = ent_enddate.get_date()\n mFrom = fromDate.month\n yFrom = fromDate.year\n mUntil = fromDate.month + 1\n yUntil = fromDate.year\n if mUntil > 12:\n mUntil = 1\n yUntil = yUntil + 1\n fromDates = [fro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts the string into a valid JSON string — a string that can be parsed as JSON. | def make_string_json_valid(string) -> str:
# make sure we have no new single quotes because JSON
# requires double quotes
return string.replace("'", '"') | [
"def __valid_json(string):\n try:\n obj = json.loads(string)\n except ValueError:\n return False\n else:\n return json.dumps(obj)",
"def convert_to_json(self, string):\n return json.dumps(string)",
"def try_json(string):\n try:\n return json... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
normalization function; x is the array with the performances and y is the normalization method. For vector input 'v' and for linear 'l' | def norm(x, y):
if y == 'v':
k = array(cumsum(x**2, 0))
z = array([[round(x[i, j] / sqrt(k[x.shape[0] - 1,
j]), 3) for j in range(x.shape[1])]
for i in range(x.shape[0])])
return z
else:
yy = []
for i in range(x.shape[1]):
yy.append(ama... | [
"def normalize_l2(x):\n return x / (npla.norm(x))",
"def normalize(v):\n return v / np.linalg.norm(v)",
"def normalize(v):\n return np.array(v) / np.linalg.norm(v)",
"def fun(self, x):\n return l1l2norm(x, self._axis)",
"def normalize(y, x=None):\n x = 1. if x is None else x\n return (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
multiplication of each evaluation by the associate weight; r stands for the weights matrix and t for the normalized matrix resulting from norm() | def mul_w(r, t):
z = array([[round(t[i, j] * r[j], 3)
for j in range(t.shape[1])]
for i in range(t.shape[0])])
return z | [
"def spectral_norm_parallel(self):\n weights = {}\n for l in self.all_conv_layers:\n weight = l.weight_normalized\n weight_mat = weight.view(weight.size(0), -1)\n if weight_mat.shape not in weights:\n weights[weight_mat.shape] = []\n weights[w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
matrix is the initial decision matrix, weight is the weights matrix, norm_m is the normalization method, id_sol is the action used, and pl is 'y' for plotting the results or any other string for not | def topsis(matrix, weight, norm_m, id_sol):
z = mul_w(weight, norm(matrix, norm_m))
s, f = zenith_nadir(z, id_sol)
p, n = distance(z, s, f)
final_s = array([n[i] / (p[i] + n[i])
for i in range(p.shape[0])])
if pl == 'y':
q = [i + 1 for i in range(matrix.shape[0])]
return final_s | [
"def scaled_problem_1_solinit():\n\n sol_y = [[ 1.00000000e+00, 9.99937500e-01, 9.99312493e-01, 9.98687474e-01,\n 9.98062443e-01, 9.97437400e-01, 9.96812345e-01, 9.96187278e-01,\n 9.95562199e-01, 9.94937109e-01, 9.94312006e-01, 9.93749404e-01],\n [ 0.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
connect to BBG Desktop API streaming service | def connect(self, service='//blp/mktdata', host='localhost', port=8194):
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(host)
sessionOptions.setServerPort(port)
# Create a Session
session = blpapi.Session(sessionOptions)
# start the session
... | [
"def _connect_to_stream(self):\n\n # Reformating pairs list to be URL compatible\n encoded_pairs = [\"%s_%s\" % (p[:3], p[3:]) for p in self.pairs]\n try:\n session = requests.Session()\n # Setting URL to stream from\n if self.api_source == \"practice\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a generator, and returns the elements, with the previous element. The first element only appears as previous. (and the last neveras) | def with_prev(gen):
prev = next(gen)
for el in gen:
yield prev, el
prev = el | [
"def with_previous_s2(sequence):\n items = []\n for curr, prev in zip(sequence, [None] + list(sequence)):\n items.append((curr, prev))\n return items",
"def with_previous(iterable, *, fillvalue=None):\n previous = fillvalue\n for item in iterable:\n yield previous, item\n previ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
thread function which parses through data dictionary of datetimevalue pairs and uploads values to Google Sheets | def upload_protocol(sheet_no, data_struct):
global num_uploads
client = gspread.authorize(creds)
sheet = client.open('Fridge Data Testing').get_worksheet(sheet_no)
print('uploading...')
for key, val in data_struct.items():
time.sleep(7)
d = key.strftime('%m/%d/%Y ')
t = ... | [
"def fetch_Data_From_Sheet(self, google_sheet, start_date, end_date):\n list_of_records = google_sheet.get_all_records()\n Email_id_list = []\n Name_list = []\n MobileNumber_list = []\n University_list = []\n FinalUniversity_list = []\n CurrentLocation_list = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
EX_PLOT_SOLVER_WEIGHTS Example showing how to plot the first layer weights in a solver object | def ex_plot_solver_weights(ax, fname, title=None):
if title is None:
title = "Layer 1 weights"
solv = solver.Solver(None, None)
solv.load_checkpoint(fname)
vis_solver.plot_model_first_layer(ax, solv.model, cname)
ax.set_title(title) | [
"def plot_weights(self,):\n \n weights_evolution = pd.DataFrame(self.predict[\"weights\"].values.tolist(), columns=[*self.models.keys()])\n\n plt.figure(figsize=(8, 5))\n\n for name in weights_evolution.columns:\n plt.plot(weights_evolution[name], label=name)\n\n plt.ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
EX_PLOT_SEQUENCE Example wrapper for vis_solver.plot_model_first_layer showing a possible inner loop for a weight visualization animation | def ex_plot_sequence(ax, path, fname, num_checkpoints, prefix=None, step=1, pause_time=0.01):
if type(num_checkpoints) is tuple:
if len(num_checkpoints) > 2:
raise ValueError("Cannot accept more than 2 limits for num_checkpoints")
if num_checkpoints[0] == 0:
n_min = 1
... | [
"def create_plot_variational_weights(model, ax1, ax2, plot_pdf = True):\n l = 0\n for VBmodel in model.VBmodels:\n l+=1\n if (VBmodel.type_layer == \"linear\"):\n sigma_W = Vil.softplus(VBmodel.rho_weight).detach().cpu().numpy().flatten()\n mu_W = VBmodel.mu_weight.detach()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to move all of the bricks when they're in the process of getting hit | def moveBricks(questionBricks, interactBricks, breakingBrick):
BRICKVY, IDLE, TYPE = 4, 5, 6
# Moving all question blocks that are hit
for brick in questionBricks: # Going through each question block
if brick[BRICKVY] != 3.5 and brick[IDLE] == 1: # Checking if the block is back at its original pos... | [
"def __move_ball(self):\n while not self.__game_is_over():\n self.__ball.move(self.__dx, self.__dy)\n self.__handle_wall_collision()\n if self.__num_lives == 0:\n self.__game_over_picture()\n break\n elif self.__bricks_total == 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to allow coins and points to float up | def floatObjects(moveCoins, points):
X, Y, COINVY = 0, 1, 4
PTSCOUNT, PTSNUM = 2, 3
for coin in range(len(moveCoins) - 1, -1, -1): # Going through each moving coin
if moveCoins[coin][COINVY] != 5: # Checking if the animation is still going by checking VY
moveCoins[coin][COINVY] += 0.5 ... | [
"def process_coins():\r\n print(\"Please insert coins.\")\r\n quarters = int(input(\"How many quarters?:\"))\r\n dimes = int(input(\"How many dimes?:\"))\r\n nickels = int(input(\"How many nickels?:\"))\r\n pennies = int(input(\"How many pennies?:\"))\r\n total_amount = (quarters * 0.25) + (dimes ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to draw Mario's stats on screen (Points, coins, level number, and time left) | def drawStats(mario, marioInfo, points, coins, startTime, level, fastMode, timesUp, coinPic, spriteCount, forceTime = None):
ONGROUND, JUMPFRAMES, INGROUND, ISCROUCH, ONPLATFORM, ISFALLING, ISANIMATING, INVULFRAMES = 0, 1, 2, 3, 4, 5, 6, 7
X, Y, VX, VY, DIR, STATE = 0, 1, 2, 3, 4, 5
currentTime = 200 - int(... | [
"def draw_info(self) -> None:\n\n icon_size = INFO_HEIGHT - 6\n\n for i in range(self.lives):\n life_icon = pg.image.load(\n path.join(image_dir, f\"pengo_left.png\")\n ).convert_alpha()\n life_icon = pg.transform.scale(life_icon, (icon_size, icon_size))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to draw the pause screen on top of the surface | def drawPause():
alphaSurface = Surface((800, 600)) # Making a surface
alphaSurface.set_alpha(128) # Giving it alpha functionality
alphaSurface.fill((0, 0, 0)) # Fill the surface with a black background
screen.blit(alphaSurface, (0, 0)) # Blit it into the actual screen
# Blitting pause screen te... | [
"def pause_screen():\n # draws a black pause screen that is activated with the ESC key\n scale = 0.5\n texture = arcade.load_texture(\"pause_screen.jpg\")\n arcade.draw_texture_rectangle(500, 350, scale * texture.width,\n scale * texture.height, texture, 0)",
"def drawPa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function for the pole grabbing animation | def movePole(mario, marioStats, marioScore, frame, flagInfo, unisprite, isDone, forceTime):
PTS, COIN, LIVES = 0, 1, 2
X, Y, VX, VY, DIR, STATE = 0, 1, 2, 3, 4, 5
ONGROUND, JUMPFRAMES, INGROUND, ISCROUCH, ONPLATFORM, ISFALLING, ISANIMATING, INVULFRAMES = 0, 1, 2, 3, 4, 5, 6, 7
# Declaring flag pole Rect... | [
"def spinAround(self):",
"def draw(self, DISPLAYSURF, frame:int):\r\n\r\n #Pac-Man gets drawn\r\n pg.draw.circle(DISPLAYSURF, Colors.colors['YELLOW'], (self.pos[0] + self.grid_size // 2, self.pos[1] + self.grid_size // 2), self.radius)\r\n\r\n\r\n #The rest of the function has to do with Pacm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to apply commands to all mixer channels | def globalSound(command):
for id in range(mixer.get_num_channels()): # Going through each mixer channel
if command == "stop":
mixer.Channel(id).stop() # Stopping all playback on the channel
elif command == "pause":
mixer.Channel(id).pause() # Pausing playback on the channe... | [
"def func(self):\n from evennia.comms.models import ChannelDB\n\n caller = self.caller\n if self.args not in (\"on\", \"off\"):\n return super(CmdArxAllCom, self).func()\n if self.args == \"on\":\n # get names of all channels available to listen to\n # an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to progress the universal sprite counter | def spriteCounter(counter):
counter += 0.2 # Adding to the counter
if counter > 10: # Checking if the counter hits the limit and resetting it
counter = 0
return counter # Returning the new counter | [
"def increment(self):\n self.pos += 1\n if self.pos == len(self.progress) - 1:\n self.pos = 0",
"def RenderProgress(self) -> float:",
"def increase_progress(self, value):\r\n\r\n pass",
"def increment_count(self):\n self.image_count +=1\n if self.image_count > sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changing ownership, permission of resolv.conf and named.conf files. This is required to so that enum server runs properly | def changeOwn():
os.system('sudo chown -R test:users /etc/resolv.conf')
os.system('sudo chown -R test:named /etc/named.conf') | [
"def _fix_r_res(res, o, g, p):\n print green(\"Setting remote resource %s parameters %s, %s, %s\" %\n (res, o, g, p))\n run('chown %s:%s %s' % (o, g, res))\n run('chmod %s %s' % (p, res))",
"def setowners():\r\n hostout = api.env.get('hostout')\r\n buildout = api.env['buildout-user']\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy "e164.zone" file from /var/opt/nextest/tdb/production_components.qms/enum.qms to /var/lib/named. Modify the file so that it will contain the actual ip addresses. | def zone(enum_path):
lip = socket.gethostbyname('mygen')
sipb = socket.gethostbyname('prv_rsa')
sip1 = socket.gethostbyname('public8')
#34101 Modified realmIP to endpoint IP so that SETUP/INVITE message will go through enum_realm
h323b = socket.gethostbyname('private8')
h323c = socket.gethostbyn... | [
"def modifyNamed():\n try:\n nconfile = open('/etc/named.conf',\"r\")\n nconf=nconfile.readlines()\n nconfile.close()\n if (nconf.__contains__('zone \"e164.com\" in {\\n') == False):\n # Back up the original file on local host\n if (os.path.isfile('/etc/named.con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify named.conf file on host machine This function will add the following lines before line include "/etc/named.conf.include"; in the /etc/named.conf file zone "e164.com" in { type master; file "e164.zone"; }; | def modifyNamed():
try:
nconfile = open('/etc/named.conf',"r")
nconf=nconfile.readlines()
nconfile.close()
if (nconf.__contains__('zone "e164.com" in {\n') == False):
# Back up the original file on local host
if (os.path.isfile('/etc/named.conf.bkup') == False... | [
"def modifyNamed_mdns():\n try:\n nconfile = open('/etc/named.conf',\"r\")\n nconf=nconfile.readlines()\n nconfile.close()\n if (nconf.__contains__('zone \"abc.com\" in {\\n') == False):\n # Back up the original file on local host\n if (os.path.isfile('/etc/named... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify named.conf file on host machine This function will add the following lines before line include "/etc/named.conf.include"; in the /etc/named.conf file zone "abc.com" in { type master; file "abc.zone"; }; | def modifyNamed_mdns():
try:
nconfile = open('/etc/named.conf',"r")
nconf=nconfile.readlines()
nconfile.close()
if (nconf.__contains__('zone "abc.com" in {\n') == False):
# Back up the original file on local host
if (os.path.isfile('/etc/named.conf.bkup') == F... | [
"def modifyNamed():\n try:\n nconfile = open('/etc/named.conf',\"r\")\n nconf=nconfile.readlines()\n nconfile.close()\n if (nconf.__contains__('zone \"e164.com\" in {\\n') == False):\n # Back up the original file on local host\n if (os.path.isfile('/etc/named.con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify "/etc/resolv.conf" file on host machine to configure the host machine as DNS server and e164.com as the domain On the MSX machine for as per MDN feature the resolve.conf should have the loopback ip as the nameserver | def modifyResolve_6_0(msw):
hostip = socket.gethostbyname('mygen')
name = 'nameserver ' + hostip+'\n'
name1 = 'search e164.com'+'\n'
newFileContents = [name,name1]
name_msw='nameserver 127.0.0.1\n'
try:
# Back up the original file on local host
if (os.path.isfile('/etc/resolv.co... | [
"def _get_dns_server_ip():\n # _clear()\n resolv_file = '/etc/resolv.conf'\n nameserver = '8.8.8.8'\n with open(resolv_file, 'r') as rf:\n for rf_line in rf:\n if 'nameserver' in rf_line:\n nameserver = rf_line.split()[1]\n break\n return nameserver",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify "/etc/resolv.conf" file on host machine and on iserver to configure the host machine as DNS server and e164.com as the domain | def modifyResolve(msw):
hostip = socket.gethostbyname('mygen')
name = 'nameserver ' + hostip+'\n'
name1 = 'search e164.com'+'\n'
newFileContents = [name,name1]
try:
# Back up the original file on local host
if (os.path.isfile('/etc/resolv.conf.bkup') == False):
os.system... | [
"def dns_setup_sipserver(sip_server, config):\n try:\n if sip_server:\n sip_server.prefer_ipv4()\n sip_server.sendline('echo \"nameserver 8.8.8.8\" > /etc/resolv.conf')\n apt_install(sip_server, \"dnsmasq\")\n sip_server.setup_dnsmasq(config)\n add_dn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify server.cfg to configure enum policy This function will add the following line before maxhunt policy enumdomain "e164.com" mswName Name of the MSW | def modifyIserver(mswName):
serverpath = "/usr/local/nextone/bin/server.cfg"
try:
bkupFile = '/tmp/server.cfg.%s.bkup' %mswName
# Copy the server.cfg file from MSW to the local host
if (os.path.isfile(bkupFile) == False):
os.system("scp -q root@" + mswName + "... | [
"def test_create_hyperflex_ucsm_config_policy(self):\n pass",
"def test_update_hyperflex_ucsm_config_policy(self):\n pass",
"def test_patch_hyperflex_ucsm_config_policy(self):\n pass",
"def testRaisesDifferentPolicyNameErrorWhenDifferentPolicyNames(self):\n with self.assertRaises(gcp_h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function restarts named on the MSX machine | def remoteNamedRestart(msw):
try:
msw.assertCommand('/etc/init.d/named restart')
time.sleep(20)
namedStatus = msw.filter("pgrep -x named")
namedStatus = namedStatus.strip('|')
if not namedStatus:
print "Named not running on MSX"
log.error("Named not r... | [
"def restart():\n pass",
"def restart():\n log.info('restart')\n samuraix.restarting = True\n samuraix.app.stop()",
"def restart(self):\n self.kill()\n self.start()",
"def restart(event):\n elements.REMOTE_SERVER.restart()",
"def _restart(self):\n pass",
"def restart_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns an array into a tuple. | def arr_to_tup(a):
return tuple(a.reshape(1, -1)[0]) | [
"def array_to_tuple(arr):\n return tuple(tuple(row) for row in arr.tolist())",
"def numpy_array_to_tuple_numpy(values: np.array) -> np.array:\n\n if len(values) == 0:\n return np.array([ ], dtype=object)\n\n result = np.empty(np.shape(values)[:-1], dtype=object)\n result[:] = [ tuple(value)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the fit range for a single Lorentzian. | def find_single_fit_range(lorentz_params):
f0 = lorentz_params[1]
FWHM = lorentz_params[2]
return (f0 - 4 * FWHM, f0 - 2 * FWHM, f0 + 2 * FWHM, f0 + 4 * FWHM) | [
"def find_full_fit_range(lorentz_params_array):\n (f_low_stop_list, f_low_list, f_high_list,\n f_high_stop_list) = find_all_fit_ranges(lorentz_params_array)\n f_low_stop = min(f_low_stop_list)\n f_low = min(f_low_list)\n f_high = max(f_high_list)\n f_high_stop = max(f_high_stop_list)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |