query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Compute celestial WCS of the 2D spectrum array for a specified central wavelength This essentially recenters the celestial SIP WCS such that the desired wavelength was at the object position as observed in the direct image (which has associated geometric distortions etc). | def get_wavelength_wcs(self, wavelength=1.3e4):
wcs = self.grism.wcs.deepcopy()
xarr = np.arange(self.beam.lam_beam.shape[0])
# Trace properties at desired wavelength
dx = np.interp(wavelength, self.beam.lam_beam, xarr)
dy = np.interp(wavelength, self.beam.lam_beam, self.beam.y... | [
"def compute_wcs(self):\n # Assign keyword values of TELRA and TELDEC to\n # crval1/2. These consist in the RA/DEC position\n # of the chopper midpoint (relative to the SI\n # boresight), and already contain dithering offsets.\n\n # convert RA from hours to degrees\n crval1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute exact PA of the dispersion axis, including tilt of the trace and the FLT WCS | def get_dispersion_PA(self, decimals=0, local=False):
from astropy.coordinates import Angle
import astropy.units as u
# extra tilt of the 1st order grism spectra
if 'BEAMA' in self.beam.conf.conf_dict:
x0 = self.beam.conf.conf_dict['BEAMA']
else:
x0 = np.... | [
"def get_dispersion_PA(self, decimals=0):\n from astropy.coordinates import Angle\n import astropy.units as u\n\n # extra tilt of the 1st order grism spectra\n if 'BEAMA' in self.conf.conf_dict:\n x0 = self.conf.conf_dict['BEAMA']\n else:\n x0 = np.array([10,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to fit a Gaussian emission line and a polynomial continuum | def simple_line_fit(self, fwhm=48., grid=[1.12e4, 1.65e4, 1, 4],
fitter='lstsq', poly_order=3):
# Test fit
import sklearn.linear_model
import numpy.linalg
clf = sklearn.linear_model.LinearRegression()
# Continuum
self.compute_model()
self.... | [
"def fit_exponential_plateau(x, y):\n\n M_guess = np.max(y)\n a_guess = -((-1 / x[1:]) * (1 - (y[1:] / M_guess))).mean() # exclude first data point since x = 0\n\n opt, cov = curve_fit(exponential_plateau, x, y, p0=(M_guess, a_guess))\n\n return opt, cov",
"def polynomial():\n np.random.seed(42)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Login Suspended Account | def test_suspended_account_login(self):
form = LoginForm({'user_name':'foo2','password':'bar'})
self.assertFalse(form.is_valid())
self.assertEqual(
form.non_field_errors(),
["Suspended Account"]
) | [
"def test_account_status(self):\n self.api.is_account_blocked.return_value = False\n self.assertFalse(self.api.is_account_blocked())",
"def test_t1invalidLogin(self):\n self.log.info(\"*#\" * 20)\n self.log.info(\"test_t1invalidLogin started\")\n self.log.info(\"*#\" * 20)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Registration Username contains special char | def test_special_char__username(self):
form = RegisterForm({'user_name':'foouser!!!',
'password':'bar',
'confirm_password':'bar',
'email':'j@j.com',
'confirm_email':'j@j.com',}
... | [
"def test_too_short_username_registration(self):\n errorMsg = 'The username must be between 3 and 100 chars long.'\n rv = self.register('bb', 'mister_test@example.com',\n 'password', 'password')\n assert errorMsg in rv.data",
"def test_register_safe_username(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Registration Password Does Not Contain Special Char | def test_special_char_password(self):
form = RegisterForm({'user_name':'foouser1',
'password':'barbarbar',
'confirm_password':'bar',
'email':'j@j.com',
'confirm_email':'j@j.com',}
... | [
"def test_special_char__username(self):\n form = RegisterForm({'user_name':'foouser!!!',\n 'password':'bar',\n 'confirm_password':'bar',\n 'email':'j@j.com',\n 'confirm_email':'j@j.com',}\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Registration Email Does Not Match Confirm Email | def test_email_not_match(self):
form = RegisterForm({'user_name':'foouser1',
'password':'barbarbar!1',
'confirm_password':'barbarbar!1',
'email':'j1@j.com',
'confirm_email':'j2@j.com',}
... | [
"def test_email_confirmation_wrong_mail(self):\n res = self.testapp.reset()\n res = self.testapp.get(\n '/verify/NOTEXISTS@shri.de/ABCDEFGHIJ', status=200)\n #print(res.body)\n self.failUnless(\"something went wrong.\" in res.body)",
"def test_confirmation_invalid(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Application Add Empty Date Updated | def test_empty_date_updated(self):
form = ApplicationForm({'school_program':1,
'status':'Pending',
'date_submitted':'2016-06-29',
'date_updated':'',}
)
self.assertFalse(form.is_valid())
... | [
"def test_update_time_tracking_entry(self):\n pass",
"def test_out_of_date(self):\n self._test_significance(MAJOR_SIGNIFICANCE, \"Immediate Update Needed\")",
"def test_save_alert_w_bad_date(self):\n self.alert.save()\n actual = self.alert.content_date\n expected = None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Application Add Empty Date Submitted | def test_empty_date_submitted(self):
form = ApplicationForm({'school_program':1,
'status':'Pending',
'date_submitted':'',
'date_updated':'2016-06-29',}
)
self.assertFalse(form.is_valid())
... | [
"def test_empty_date_updated(self):\n form = ApplicationForm({'school_program':1,\n 'status':'Pending',\n 'date_submitted':'2016-06-29',\n 'date_updated':'',}\n )\n\n self.assertFalse(form.is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Application Add Empty School Program | def test_empty_school_program(self):
form = ApplicationForm({'school_program':None,
'status':'Pending',
'date_submitted':'2016-06-29',
'date_updated':'2016-06-29',}
)
self.assertFalse(form... | [
"def test_view_can_create_program(self):\n # first create the org to own the program\n org_res = self.client().post('/api/organizations/', data=self.org_data)\n org_id = json.loads(org_res.data.decode())['id']\n # then, create the program under the org\n self.program_data['organiz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Application Add Invalid Date Format | def test_invalid_date_format(self):
form = ApplicationForm({'school_program':1,
'status':'Pending',
'date_submitted':'2016/06/29',
'date_updated':'2016/06/29',}
)
self.assertFalse(form.is_... | [
"def test_invalid_date(self):\n with pytest.raises(ValueError):\n model.Report(case='19-123456', date=datetime.date.min)",
"def test_create_entry_bad_date(self):\n # \"month\" and \"day\" is switched\n r = requests.post(prefix + \"/entry/create\",\n auth=(E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Current Program Add Negative Credit Hours | def test_invalid_credit_hours(self):
form = CurrentProgramForm({'curr_school_program':1,
'curr_gpa':3.8,
'curr_credit_hours':-1,
'curr_start_date':'2016-05-05',
'curr_end_date':'2016-05-05'}
... | [
"def test_invalid_credit_hours(self):\n form = PreviousProgramForm({'prev_school_program':1,\n 'prev_gpa':3.8,\n 'prev_credit_hours':-1,\n 'prev_start_date':'2016-05-05',\n 'prev_end_date':'2016-05... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Previous Program Add Negative Credit Hours | def test_invalid_credit_hours(self):
form = PreviousProgramForm({'prev_school_program':1,
'prev_gpa':3.8,
'prev_credit_hours':-1,
'prev_start_date':'2016-05-05',
'prev_end_date':'2016-05-05'}
... | [
"def test_invalid_credit_hours(self):\n form = CurrentProgramForm({'curr_school_program':1,\n 'curr_gpa':3.8,\n 'curr_credit_hours':-1,\n 'curr_start_date':'2016-05-05',\n 'curr_end_date':'2016-05-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful GRE Score Add Invalid Quant/Verb Score | def test_invalid_score_0(self):
form = GREScoreForm({'verb':-1,
'quant':1,
'write':1,}
)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors.get('verb'),
[u'Score Must Be 0 o... | [
"def test_invalid_score_1(self):\n form = GREScoreForm({'verb':1,\n 'quant':1,\n 'write':-1,}\n )\n self.assertFalse(form.is_valid())\n self.assertEqual(\n form.errors.get('write'),\n [u'Sco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful GRE Score Add Invalid Writing Score | def test_invalid_score_1(self):
form = GREScoreForm({'verb':1,
'quant':1,
'write':-1,}
)
self.assertFalse(form.is_valid())
self.assertEqual(
form.errors.get('write'),
[u'Score Must Be 0 ... | [
"def cal_success_score(self):\n\n if self.number_of_times_letter_requested > 0:\n self.total_score = self.total_score+1/self.number_of_times_letter_requested\n\n for i in range(self.bad_guesses):\n self.total_score *= 0.9",
"def test_invalid_score_0(self):\n form = GRESc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful TOEFL Score Add Invalid Score | def test_invalid_score(self):
form = TOEFLScoreForm({'writing':-1,
'listening':1,
'speaking':1,
'reading':1}
)
self.assertFalse(form.is_valid())
self.assertEqual(
form.e... | [
"def test_invalid_score_1(self):\n form = GREScoreForm({'verb':1,\n 'quant':1,\n 'write':-1,}\n )\n self.assertFalse(form.is_valid())\n self.assertEqual(\n form.errors.get('write'),\n [u'Sco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Unsuccesful Credit Card Add Invalid CC Number | def test_invalid_cc_number(self):
form = CreditCardForm({'city':'gastonia',
'card_type':'Visa',
'first_name':'First',
'last_name':'Last',
'number':'999',
'se... | [
"def isValidCC(passed_cc):\n ccRegex = re.compile(r'\\b(4)(\\d)(\\d)(\\s?)(\\d)(\\s?)(\\d)(\\d)(\\s?)(\\d)(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}(\\s?)(\\d){0,1}\\b')\n ccTest = ccRegex.search(passed_cc)\n if ccTest is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a error on compile and causes RuntimeError | def raise_error(self, message):
# On compile, exec_pos stores the index of lines being compiled
# so the bad line number is [exec_pos+1]
print("In line " + str(self.exec_pos + 1) + ",")
print(message)
raise RuntimeError | [
"def raise_runtime_error(self, message):\n print(\"Iceberg Runtime ERROR!\")\n print(\"In instruction number \" + str(self.exec_pos) + \",\")\n print(message)\n raise RuntimeError",
"def error(what,say):\n print 'ERROR: ', what, say",
"def error(s):\n print('Robotics toolbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a error on runtime and causes RuntimeError | def raise_runtime_error(self, message):
print("Iceberg Runtime ERROR!")
print("In instruction number " + str(self.exec_pos) + ",")
print(message)
raise RuntimeError | [
"def raise_error(self, message):\n # On compile, exec_pos stores the index of lines being compiled\n # so the bad line number is [exec_pos+1]\n print(\"In line \" + str(self.exec_pos + 1) + \",\")\n print(message)\n raise RuntimeError",
"def error(s):\n print('Robotics toolbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
print a warning on runtime and causes RuntimeError a warning tells users a suspicious instruction that might be caused by bug(s) in the script | def raise_runtime_warning(self, message):
print("WARNING: In instruction number " + str(self.exec_pos) + ",")
print(message) | [
"def warning(msg):\r\n sys.stderr.write(msg+\"\\n\")",
"def raise_error(self, message):\n # On compile, exec_pos stores the index of lines being compiled\n # so the bad line number is [exec_pos+1]\n print(\"In line \" + str(self.exec_pos + 1) + \",\")\n print(message)\n raise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert a line of script into Instruction class if there is a error in syntax, the function calls self.raise_error() | def parse_oneline(self, line, list_script):
if not ' ' in line:
# must be a instruction with no argument
instr = line
if instr in self.const_opcode:
# valid instruction
# if number of arguments is wrong compilation fails here
se... | [
"def c_inst_parser(line):\r\n destination, comp, jump = 'null', 'null', 'null'\r\n if line.find(EQUATION) != -1:\r\n destination, comp_jump = line.split(EQUATION)[0], line.split(EQUATION)[1]\r\n if line.find(SEMICOLON) != -1:\r\n comp, jump = comp_jump.split(SEMICOLON)[0], comp_jump.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create label table out of list of Instructions | def set_label(self, list_script):
label_table = {}
for i,inst in enumerate(list_script):
if inst.opcode.find('@') == 0:
label_table[inst.opcode] = i
# Trivia: Actually, labels are treated as nop instructions. In branch instructions such as when or goto, label ... | [
"def _generate_labels(self, sentence: str, anno_list:list) -> list:\n anno_list.sort(key = lambda x:x[2])\n last_pos = 0\n sentence_lst = list()\n label_lst = list()\n for item in anno_list:\n start_pos = item[2]\n end_pos = item[3]\n part = word_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compile a script into Bytecode class. | def gen_bytecode(self, script):
(list_script, label_table) = self.parse_script(script)
return Bytecode(list_script, label_table) | [
"def compile_script(bogscript):\n\n ## Step 1: Convert source script into tokens\n tokens = lexer(bogscript)\n #print tokens\n\n ## Step 2: Convert tokens into Python Source\n pycode = pygen(tokens)\n #print '\\n' + pycode + '\\n'\n\n ## Step 3: Compile Python Source into bytecode\n bytecode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert argument to pythonic value. the type flag of the argument should be included in type_flag or the function calls self.raise_runtime_error() also, if arg was symbol and this is not in symbol tables(const_table, var_table), the function calls self.raise_runtime_error() | def get_argument(self, arg, type_flag):
# Defined symbol?
if arg in self.const_table:
if type_flag & self.get_type_flag(self.const_table[arg]):
return self.const_table[arg]
else:
self.raise_runtime_error("Type ERROR: Type mismatch")
if arg ... | [
"def coerce_value(self, arg, ba):\n try:\n ret = self.conv(arg)\n except errors.CliValueError as e:\n exc = errors.BadArgumentFormat(e)\n exc.__cause__ = e\n raise exc\n except ValueError as e:\n exc = errors.BadArgumentFormat(repr(arg))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
assign value to symbol. if specified symbol exists, the type of the symbol is checked. if it does not match the type of value, self.raise_runtime_error() will be called instead of assigning if the symbol does not exist, new symbol entry will be created in var_table. the symbol cannot be constant such as number, and sta... | def assign_var(self, symbol, value):
# is symbol already assigned?
if symbol in self.var_table:
# update value if the type matches(you cannot alter type!)
if type(self.var_table[symbol]) == type(value):
self.var_table[symbol] = value
else:
... | [
"def assignment(self, symbol_table):\n symbol_table[self.key] = self.value.evaluate(self.value, symbol_table)",
"def put_symbol(self, s):\n self._check(pn_data_put_symbol(self._data, s))",
"def add_symbol(self, symbol):\n if symbol in self.stoi:\n return\n N = len(self.stoi)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function for instruction 'nop' the actual behavior of every instructions is determined by functions like inst_nop(self, args)(this function) or inst_let(self, args). the function should be method of IcebergVM or its children and take list of arguments as the second argument. Its return value will be ignored. inst_when ... | def inst_nop(self, args):
pass | [
"def handle_nop(self, cmd):\n self.log.debug('IAC NOP: Null Operation')",
"def nop(self, argument: int):\n self.jmp(1)",
"def nopout(self, ea, sz):\n nsuccess, nop_instr = idautils.Assemble(ea, 'nop')\n if not nsuccess:\n return nsuccess, nop_instr\n return self.ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates documents according to plsi, ctm, or lda | def generate_docs(num_topics, num_docs, words_per_doc=50, vocab_size=30,
alpha=None, beta=None, noise=-1, plsi=False, ctm=False,
pareto=False):
#@TODO: integrate ctm parameters (ie mu and sigma) into alpha and beta
mu = np.zeros(num_topics)
sigma = np.ones((num_topics, n... | [
"def create_corpus():\n\n num_queries = input(\"\\nNumber of queries: \")\n\n global NUM_DOCS_DOWNLOAD\n NUM_DOCS_DOWNLOAD = input(\"Number of docs for each query: \")\n\n global TOTAL_DOCS\n TOTAL_DOCS = num_queries * NUM_DOCS_DOWNLOAD\n\n print \"Total docs = %d\" % TOTAL_DOCS\n\n for i in ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writes the data generated by generate_docs to various files Writes four files, one containing the generated data, one containing the model used to generate the data, one containing the options given at the command line, and one containing various statistics from the data (see the file description below for details). Al... | def write(data, args):
docs, doc_topics, words, topics = data
if args.plsi and args.ctm:
print "plsi and ctm flags cannot both be active (returning None)"
return None
output_dir = 'output'
try:
os.mkdir(output_dir)
except OSError:
pass
dir = output_dir +... | [
"def createDataFiles(self):\n\n a_patterns = self.readDataFile()\n self.randomizeAndWriteTrainAndTest(a_patterns)",
"def write_to_file(model_data, output_directory, write_csv = False, precision = np.float32):\n for p_level_data in model_data:\n p_level = p_level_data['pLevel']\n # c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the config, creating it if it doesn't exist. Test server connection Start background thread for getting user input during streaming | def __init__(self, config):
# If no config file exists we should create one and
if not os.path.isfile(config):
self.set_default_config(config)
click.secho('Welcome to pSub', fg='green')
click.secho('To get set up, please edit your config file', fg='red')
c... | [
"def load_config(self):\n # Open the file at default lcoation, unless something else\n # is passed in instead\n self.logger.info('Running load_config() for HerdClient')\n if self.config is not None:\n self.logger.debug(\"There's a config file passed in\")\n f = file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return random salted md5 hash of password | def hash_password(self):
characters = string.ascii_uppercase + string.ascii_lowercase + string.digits
salt = ''.join(SystemRandom().choice(characters) for i in range(9))
salted_password = self.password + salt
token = hashlib.md5(salted_password.encode('utf-8')).hexdigest()
return... | [
"def make_salt():\n return uuid.uuid4().hex",
"def hash_password(password):\n password = password.encode('utf-8')\n salt = app.config['SECRET_KEY']\n return hashlib.md5(salt + password).hexdigest()",
"def salt():\n return uuid.uuid4().hex",
"def _create_salt():\n return base64.b64enc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather list of Artists from the Subsonic server | def get_artists(self):
artists = self.make_request(url=self.create_url('getArtists'))
if artists:
return artists['subsonic-response']['artists']['index']
return [] | [
"def artists(self, artists):\n\n tlist = [self._get_id(\"artist\", a) for a in artists]\n return self._get(\"artists/?ids=\" + \",\".join(tlist))",
"def get_artists(self, search, start=0, max_items=100):\r\n return self.get_music_service_information('artists', search, start,\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of available playlists from the server | def get_playlists(self):
playlists = self.make_request(url=self.create_url('getPlaylists'))
if playlists:
return playlists['subsonic-response']['playlists']['playlist']
return [] | [
"def get_playlists(self, search, start=0, max_items=100):\r\n return self.get_music_service_information('playlists', search, start,\r\n max_items)",
"def get_user_playlists():\n playlists_info = sp.current_user_playlists(limit=50, offset=0)['items']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather list of Music Folders from the Subsonic server | def get_music_folders(self):
music_folders = self.make_request(url=self.create_url('getMusicFolders'))
if music_folders:
return music_folders['subsonic-response']['musicFolders']['musicFolder']
return [] | [
"def fetch_songs(self):\n if len(self.songs) == 0:\n for file in self.MUSIC_DIR.joinpath (\"./songs\").iterdir():\n if file.is_file():\n self.songs.append (file)\n return self.songs",
"def get_music_directory(self, dir_id):\n music_folders = self.m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather list of Music Directories from the Subsonic server | def get_music_directory(self, dir_id):
music_folders = self.make_request('{}&id={}'.format(self.create_url('getMusicDirectory'), str(dir_id)))
if music_folders:
return music_folders['subsonic-response']['directory']
return [] | [
"def fetch_songs(self):\n if len(self.songs) == 0:\n for file in self.MUSIC_DIR.joinpath (\"./songs\").iterdir():\n if file.is_file():\n self.songs.append (file)\n return self.songs",
"def list_songs(self):\n response = requests.get('http://localho... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gather random tracks from the Subsonic server and playthem endlessly | def play_random_songs(self, music_folder):
url = self.create_url('getRandomSongs')
if music_folder != 0:
url = '{}&musicFolderId={}'.format(url, music_folder)
playing = True
while playing:
random_songs = self.make_request(url)
if not random_songs:
... | [
"def play_album(self, album_id, randomise):\n\n songs = self.get_album_tracks(album_id)\n\n if self.invert_random:\n randomise = not randomise\n\n if randomise:\n shuffle(songs)\n\n playing = True\n\n while playing:\n for song in songs:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get songs similar to the supplied id and play them endlessly | def play_radio(self, radio_id):
playing = True
while playing:
similar_songs = self.make_request(
'{}&id={}'.format(self.create_url('getSimilarSongs2'), radio_id)
)
if not similar_songs:
return
for radio_track in similar_so... | [
"def find_song(name):\n\tglobal abort_playback\n\tabort_playback = False\n\tpiezo.init()\n\n\tfor song in SONGS:\n\t\tsong_name = song.split(\":\")[0]\n\t\tif song_name == name:\n\t\t\ttune = RTTTL(song)\n\n\t\t\tfor freq, msec in tune.notes():\n\t\t\t\tplay_tone(freq, msec)\n\t\t\t\tif abort_playback:\n\t\t\t\t\tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the songs by the given artist_id and play them | def play_artist(self, artist_id, randomise):
artist_info = self.make_request('{}&id={}'.format(self.create_url('getArtist'), artist_id))
songs = []
for album in artist_info['subsonic-response']['artist']['album']:
songs += self.get_album_tracks(album.get('id'))
if self.inve... | [
"def play_album(self, album_id, randomise):\n\n songs = self.get_album_tracks(album_id)\n\n if self.invert_random:\n randomise = not randomise\n\n if randomise:\n shuffle(songs)\n\n playing = True\n\n while playing:\n for song in songs:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the songs for the given album id and play them | def play_album(self, album_id, randomise):
songs = self.get_album_tracks(album_id)
if self.invert_random:
randomise = not randomise
if randomise:
shuffle(songs)
playing = True
while playing:
for song in songs:
if not playin... | [
"def playid(self, song_id):\n self.call.AudioPlaylist.Play(song_id)",
"def get_album_tracks(self, album_id):\n response = self.__get_data(self.url.albums_tracks_url().format(id=str(album_id)))\n tracks = []\n for album_track in response['tracks']['items']:\n track = self.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the tracks from the supplied playlist id and play them | def play_playlist(self, playlist_id, randomise, start):
playlist_info = self.make_request(
url='{}&id={}'.format(self.create_url('getPlaylist'), playlist_id)
)
songs = playlist_info['subsonic-response']['playlist']['entry']
if self.invert_random:
randomise = not ... | [
"def playid(self, song_id):\n self.call.AudioPlaylist.Play(song_id)",
"def fetch_playlist(id: str):\n sp = get_client()\n\n from span.tasks.library import get_playlist_from_id\n\n playlist = get_playlist_from_id(sp, id)\n\n # export data\n sys.stdout.write(jsonpickle.encode(playlist))",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given track data, generate the stream url and pass it to ffplay to handle. While stream is playing allow user input to control playback | def play_stream(self, track_data, is_video=False):
stream_url = self.create_url('stream')
song_id = track_data.get('id')
if not song_id:
return False
track_data_title = track_data.get('title', '')
track_data_artist = track_data.get('artist', '')
if sys.versio... | [
"def play(self, track):\n raise NotImplementedError",
"async def process_song(self, track):\n\n host = link_utils.identify_url(track)\n is_playlist = link_utils.identify_playlist(track)\n\n if is_playlist != link_utils.Playlist_Types.Unknown:\n await self.process_playlist(is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method runs in a separate thread (started in __init__). When the play.lock file exists it waits for user input and wrties it to a Queue. The play_stream method above deals with the user input when it occurs | def add_input(self):
while True:
if not os.path.isfile(os.path.join(click.get_app_dir('pSub'), 'play.lock')):
continue
time.sleep(1)
self.input_queue.put(click.prompt('', prompt_suffix='')) | [
"def start_play():",
"async def _stream(self):\n while True:\n self._current_song = await self._playlist.get()\n await self.bot.command_channel.send(f\"Currently playing: {self._current_song.url}.\")\n # We do not use the Python library here because it doesn't provide\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show a standardized banner with custom message and controls for playback | def show_banner(message):
click.clear()
click.echo('')
click.secho(' {} '.format(message), bg='blue', fg='black')
click.echo('')
click.secho('n = Next\nb = Beginning\nx = Exit\nl = Next Lyric\nv = Previous Song', bg='yellow', fg='black')
click.echo('') | [
"def display_banner():\n\n banner = \"\"\"\n __ _____ ___ ___ __ \n / / / / _ \\/ _ \\ ____/ (_)__ ___ / /_\n / /_/ / // / ___/ / __/ / / -_) _ \\/ __/\n \\____/____/_/ \\__/_/_/\\__/_//_/\\__/ \n\n \"\"\"\n print(banner, flush=True)",
"def banner(self, irc, msg, ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes inverse of g mod n. | def mod_inverse(g: int, n: int) -> int:
assert g > 0 and n > 1, "Inappropriate values to compute inverse"
# g = g mod n
# The inverse wouldn't change if the input was g or g mod p
g = g % n
# Inverse of g exists mod n iff gcd (g,n) == 1
# In case the inverse exists it is v
# where v i... | [
"def modulo_inverse(x: int, n: int) -> int:\n\n def egcd(a: int, b: int) -> typing.Tuple[int, int, int]:\n \"\"\"Euler's extended algorithm for GCD\"\"\"\n if a == 0:\n return b, 0, 1\n else:\n g, y, x = egcd(b % a, a)\n return g, x - (b // a) * y, y\n\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a random hand containing n lowercase letters. At least n/3 the letters in the hand should be VOWELS. Hands are represented as dictionaries. The keys are letters and the values are the number of times the particular letter is repeated in that hand. | def dealHand(n):
hand={}
numVowels = n / 3
for i in range(numVowels):
x = VOWELS[random.randrange(0,len(VOWELS))]
hand[x] = hand.get(x, 0) + 1
for i in range(numVowels, n):
x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
hand[x] = hand.get(x, 0) + 1
return hand | [
"def deal_hand(n):\n hand = {}\n num_vowels = n / 3\n \n for i in range(num_vowels):\n x = VOWELS[random.randrange(0, len(VOWELS))]\n hand[x] = hand.get(x, 0) + 1\n \n for i in range(num_vowels, n): \n x = CONSONANTS[random.randrange(0, len(CONSONANTS))]\n hand[x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Install or reinstall Calico endpoints based on whether we are restarting a container. | def _install_or_reinstall_endpoints(self, client_request, cont, cid):
# Grab the running pid from Docker
pid = cont["State"]["Pid"]
_log.debug('Container PID: %s', pid)
# Grab the list of endpoints, if they exist.
eps = self.datastore.get_endpoints(hostname=hostname, workload_id... | [
"def restart(self):\n cfg.CONF.reload_config_files()\n self.services.restart()",
"def _install_endpoint(self, client_request, cont, cid, pid):\n try:\n _log.debug(\"Installing endpoint for cid %s\", cid)\n\n # Attempt to parse out environment variables\n env_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Install a Calico endpoint (veth) in the container referenced in the client request object. | def _install_endpoint(self, client_request, cont, cid, pid):
try:
_log.debug("Installing endpoint for cid %s", cid)
# Attempt to parse out environment variables
env_list = cont["Config"]["Env"]
env_list = env_list if env_list is not None else []
env_d... | [
"def _install_or_reinstall_endpoints(self, client_request, cont, cid):\n # Grab the running pid from Docker\n pid = cont[\"State\"][\"Pid\"]\n _log.debug('Container PID: %s', pid)\n\n # Grab the list of endpoints, if they exist.\n eps = self.datastore.get_endpoints(hostname=hostna... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the response for a /container//json (docker inspect) request. Since we've patched the docker networking using net=none, docker inspect calls will not return any IP information. This is required for some orchestrators (such as Kubernetes). Insert the IP for this container into the config dict. | def _update_container_info(self, cid, server_response):
_log.debug('Getting container config from etcd')
try:
# Get a single endpoint ID from the container, and use this to
# get the Endpoint.
ep_id = self.datastore.get_endpoint_id_from_cont(hostname, cid)
... | [
"def _fetch_ipconfig_infomation():\n \n # Launch up a shell, get the feedback\n process = portable_popen.Popen([\"ipconfig\", \"/all\"])\n\n # Get the output\n outputdata = process.stdout.readlines()\n \n # Close the pipe\n process.stdout.close()\n \n # Stores the info\n info_dict = {}\n \n # Store the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assign a IPv4 address from the configured pools. | def assign_ipv4(self):
ip = None
# For each configured pool, attempt to assign an IP before giving up.
for pool in self.datastore.get_ip_pools("v4"):
assigner = SequentialAssignment()
ip = assigner.allocate(pool)
if ip is not None:
ip = IPAddr... | [
"def ipv4(self, ipv4: SubUnnumberedTop):\n\n self._ipv4 = ipv4",
"def ipv4address():\n class IPv4AddrFactory():\n \"\"\"Generates random ipv4 addreses.\"\"\"\n def get(self):\n \"\"\"Return an ipv4 address.\"\"\"\n ipaddr = str(randint(1, 255)) + '.' + \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Examine a ClientRequest object to determine whether the ENV_IP environment variable is present. We don't set up Calico networking for container requests if the ENV_IP variable is absent. | def _calico_ip_in_request(client_request):
try:
# Body is passed as a string, so deserialize it to JSON.
body = json.loads(client_request["Body"])
env = body["Env"]
except KeyError:
_log.warning("Client request object had no 'Env' in 'Body': %s",
client_requ... | [
"def validate_environment(\n cpix_client: clients.cpix_client.CpixClient,\n) -> Union[None, str]:\n required_vars = [\"PROJECT\"]\n required_vars.extend(cpix_client.required_env_vars())\n for required_var in required_vars:\n if required_var not in os.environ:\n return http_response(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify the client_request in place to set net=None Docker option. | def _client_request_net_none(client_request):
try:
# Body is passed as a string, so deserialize it to JSON.
body = json.loads(client_request["Body"])
host_config = body["HostConfig"]
_log.debug("Original NetworkMode: %s",
host_config.get("NetworkMode", "<unset>"))... | [
"def optionsFromClient(dk):\n tls_flag = False\n # extract and convert host base_url from docker-py client\n host_url=dk.base_url\n # if host_url starts with https -> replace with tcp\n parts = host_url.split('://', 1)\n if parts[0] == 'https':\n host_url = '%s://%s' % ('tcp', parts[1])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that correct response is returned by get_auth | def test_get_auth(self, mock_get):
# mock return response
mock_resp = self._mock_response(content=json.dumps(self.auth_resp))
mock_get.return_value = mock_resp
response = self.client.get_auth()
# confirm response matches the mock
assert_dict_equal(response, self.auth_res... | [
"def test_get_with_auth(self):\n response = self.client.get(\n '/api/v1/restock/',\n HTTP_AUTHORIZATION='Token {}'.format(self.token)\n )\n\n # Access allow\n self.assertEqual(response.status_code, 200)\n\n self.assertEqual(response.json(), self.data)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing that mfa_response returns the correct json | def test_mfa_response(self, mock_post, mock_input=None):
# mock all the things
mock_post.return_value = self._mock_response(content=json.dumps(self.mfa_data))
response = self.client.get_mfa(self.auth_resp)
# confirm the json matches
assert_dict_equal(response, self.mfa_data) | [
"def test_multi_mfa_response(self, mock_post, mock_input=None):\n # mock all the things\n mock_post.return_value = self._mock_response(content=json.dumps(self.mfa_data))\n\n response = self.client.get_mfa(self.auth_resp_multi)\n\n # confirm the json matches\n assert_dict_equal(res... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing that mfa_response returns the correct json when there are multiple MFAs available | def test_multi_mfa_response(self, mock_post, mock_input=None):
# mock all the things
mock_post.return_value = self._mock_response(content=json.dumps(self.mfa_data))
response = self.client.get_mfa(self.auth_resp_multi)
# confirm the json matches
assert_dict_equal(response, self.... | [
"def test_mfa_response(self, mock_post, mock_input=None):\n # mock all the things\n mock_post.return_value = self._mock_response(content=json.dumps(self.mfa_data))\n\n response = self.client.get_mfa(self.auth_resp)\n\n # confirm the json matches\n assert_dict_equal(response, self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Padd or cut off the string to make sure it is `length` long | def set_string_length(string: str, length: int) -> str:
if len(string) == length:
return string
elif len(string) < length:
return string + ' ' * (length - len(string))
else: # len(string) > length
return string[:length - 3] + '...' | [
"def LimitString(length=80, endchar='...'):\n def _Limit(string, length=length, endchar=endchar):\n if len(string) > length:\n return string[:length] + endchar\n return string\n return _Limit",
"def cut(string, l):\n\tif len(string) <= l:\n\t\treturn string\n\treturn string[:l-3]+\"...\"",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the next cashflow date from a give settlement date | def get_next_cashflow_date(settle_date, delay, offset_months=0):
delay_plus_one = delay+1
day = settle_date.day
offset = 1 + offset_months if (delay_plus_one <= day) and (delay > 0) else offset_months
date = settle_date + relativedelta(months=offset)
date = date.replace(day=... | [
"def get_real_settlement_date( settlement_date, currency ):\n\n\t\tdays_to_add = 0\n\t\tweek_day = settlement_date.weekday()\n\n\t\tif currency in ( Currency.AED, Currency.SAR ):\n\t\t\tif week_day in ( Weekday.Friday, Weekday.Saturday ):\n\t\t\t\tdays_to_add = 6 - week_day\n\t\telse:\n\t\t\tif week_day in ( Weekda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a greedy policy based on Q values. | def create_greedy_policy(Q):
def policy_fn(state):
# All actions that available in the given state
actions = np.arange(len(Q[state]))
best_action = np.random.choice(actions[Q[state] == np.max(Q[state])])
A = np.where(actions == best_action, 1.0, 0.0)
return A
return pol... | [
"def create_greedy_policy(Q):\n\n def policy_fn(observation):\n A = np.zeros_like(Q[observation], dtype=float) #probabilities of two actions\n a_greedy = np.argmax(Q[observation])\n A[a_greedy] = 1.0 # set probability of greedy action to 1 and other remains 0.\n return A\n return policy_fn",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a epsilon greedy policy based on Q values. | def create_epsilon_greedy_policy(Q, epsilon):
def policy_fn(state):
# All actions that available in the given state
actions = np.arange(len(Q[state]))
best_action = np.random.choice(actions[Q[state] == np.max(Q[state])])
ramdomProb = epsilon / len(Q[state])
A = np.where(acti... | [
"def epsilon_greedy(env, Q, epsilon):\n def policy(obs):\n P = np.ones(env.action_space.n, dtype=float) * epsilon / env.action_space.n #initiate with same prob for all actions\n best_action = np.argmax(Q[obs]) #get best action\n P[best_action] += (1.0 - epsilon)\n return P\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes focus to the new main tile. takes a row and column integer as inputs, must be between 02 for both. | def change_focus(row, column):
# sets all foci to false
for rw in main_board:
for game in rw:
game.focus = False
# goes to the single board that should be in focus and sets its focus
main_board[column][row].focus = True
print('focus on:', column, row) | [
"def setTile(tile):\n row = int(math.floor(mousePos[1] / 20))\n column = int(math.floor(mousePos[0] / 20))\n slidergame.levelGrid[row][column] = tile",
"def BeginEdit(self, row, col, grid):\n\n self.startValue = grid.GetTable().GetValue(row, col)\n self.tc.SetValue(self.startValue)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the index of the cell that is in focus | def get_board_focus():
for i, row in enumerate(main_board):
for o, column in enumerate(row):
if column.focus == 1:
return str(i) + ':' + str(o)
return 'none in focus' | [
"def get_cursor_row():\n row, col = vim.current.window.cursor\n return row - 1",
"def indexOfCurrentElement(self):\r\n return self.tableOfContact.indexOfTopLevelItem(self.tableOfContact.currentItem())",
"def _index_of_cell(self, query):\n x = 0\n for table in self.doc.tables:\n y = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate generates a solved Sudoku board (unless it runs out of time) getPerfectBoard will keep trying generate until a perfect board is generated | def getPerfectBoard(self):
while True:
b = self.generate()
if self.perfectBoard(b):
return b | [
"def _generate(difficulty):\n generated = Sudoku()\n tiles_amount = {\"really hard\": 17,\n \"hard\": choice(range(18, 22)),\n \"medium\": choice(range(22, 26)),\n \"easy\": choice(range(26, 30))}[difficulty]\n fillable = [(i,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a solved Sudoku board! Using local search, the algorithm first generates a start state, and then continues until a perfect board is achieved, or until it times out (meaning, we've succeeded our self.maxiterations). More often than not, an invalid Sudoku board is printed out. For now, this is okay as a starting... | def generate(self, step=False):
# select random initial state (initial guess at solution)
board = np.zeros(self.size**4).reshape(self.size**2, self.size**2)
for i in range(self.size**2):
arr = []
for j in range(self.size**2):
arr.append(j + 1)
np.random.shuffle(arr)
board[i]... | [
"def _generate(difficulty):\n generated = Sudoku()\n tiles_amount = {\"really hard\": 17,\n \"hard\": choice(range(18, 22)),\n \"medium\": choice(range(22, 26)),\n \"easy\": choice(range(26, 30))}[difficulty]\n fillable = [(i,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the board generated is a perfect Sudoku board! | def perfectBoard(self, board):
for i in range(self.size**2):
row = board[i]
col = board[:, i]
for x in range(self.size**2):
if not (x+1 in row and x+1 in col):
return False
for i in range(self.size):
for j in range(self.size):
square, _, _ = self.getSquareRowCo... | [
"def check_9x9_columns(board):\n for j in range(len(board)):\n if duplicates_present(board[:][j]):\n return False\n return True",
"def valid_sudoku(table):\r\n for row in range(0,9):\r\n row_map = {}\r\n for col in range(0,9):\r\n tile = table[row][col]\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the missing numbers in a numpy array lst, in theory, should be a list of consective numbers 1 through N2 inclusive | def getMissing(self, lst):
items = []
for i in range(1,self.size**2 + 1):
if i not in lst:
items.append(i)
return items | [
"def _find_missing_elements(element_list):\n \n start, end = element_list[0], element_list[-1]\n \n missing_elements = sorted(set(range(start, end + 1)).difference(element_list))\n \n return missing_elements",
"def NaN_ranges(lst):\n idx = list(np.where(np.isnan(lst))[0])\n return np.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For a row, switch the item that's at the current index with whichever index the missing number is row = [4, 6, 3, 1, 2] currIndex = 2 missingNumber = 4 new row = [3, 6, 4, 1, 2] | def switch(self, row, currIndex, missingNumber):
missingIndex = np.where(row == missingNumber)
missingIndex = missingIndex[0][0]
# if missingIndex / self.size * self.size == currIndex / self.size * self.size:
# return row
row[missingIndex] = row[currIndex]
row[currIndex] = missingNumber
re... | [
"def __swap_rows(self):\n pos = self.__find_random_position()\n self.solved[[pos[0], pos[1]]] = self.solved[[pos[1], pos[0]]]",
"def _not_in_row(self, row, number):\n return number not in self.grid[row]",
"def test_three(self):\n a = [[1],[9],[0]]\n expected = [[0],[9],[1]]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test how many perfect boards we get | def test():
perfect = 0.
for i in range(self.maxiterations):
b = generate()
if perfectBoard(b):
perfect += 1
print perfect / self.maxiterations | [
"def check_boardsize():\n return BOARD_SIZE % 2 == 0",
"def test_mine_count(self):\n test_board = MynesBoard()\n count = 0\n for x in range(test_board.width):\n for y in range(test_board.height):\n if test_board.board[y][x].value == -1:\n count ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to get default model from context and find approriate res.tag.model record ID | def _get_default_model_id(self, cr, uid, context=None):
if context is None:
context = {}
default_model = context.get('default_model', False)
if default_model:
tag_model_obj = self.pool.get('res.tag.model')
model_ids = tag_model_obj.search(cr, uid, [('model', ... | [
"def _get_identifier(model):\n pass",
"def get_context():\n return _model",
"def get_id_from_model(self, model):\n for item in self.models_to_ids:\n if model == item[0][1]:\n return item[1]\n return None",
"def model_id(self) -> str:\n pass",
"def _ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of IDs of tags for specified model name by (code, name) pair | def get_tag_ids(self, cr, uid, model, code=None, name=None, context=None):
assert bool(code) or bool(name), "code or name must not be None! (code=%s;name=%s)" % (code, name)
tag_domain = [('model_id.model', '=', model)]
if code is not None:
tag_domain.append(('code', '=', code))
... | [
"def tags(self) -> List:",
"def get_tags_from_names(session,taglist):\r\n return session.query(Tag).filter(Tag.name.in_(taglist)).all()",
"def get_tag_id_list(tags, snap_name):\n\n tag_name = \":\".join([\"sc:snap\", snap_name])\n\n def get_id(tag):\n return tag[\"id\"]\n\n return [get_id(tag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log tag related changes | def _log_tag_changes(self, cr, uid, ids, tags_val, context=None):
if self._track_tags and hasattr(self, '_track'):
for obj_id in ids:
message = ""
for args in tags_val:
act, arg = args[0], args[1:]
msg = ""
i... | [
"def on_pre_sync(self, changed):\n _add_tags(changed)",
"def update_tags(self):\n raise NotImplementedError",
"def tagChanged(self, tag: ghidra.program.model.listing.FunctionTag, type: int, oldValue: object, newValue: object) -> None:\n ...",
"def add_tagalong_time(session, tree):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if all of supplied objects have tag with specified code and/or name Return True if all object ids has specified tags | def check_tag(self, cr, uid, ids, code=None, name=None, context=None):
assert bool(code is not None) or bool(name is not None), "code or name must not be None"
tag_domain = [('id', 'in', ids)]
if code is not None:
tag_domain.append(('tag_ids.code', '=', code))
if name is not ... | [
"def exists_tags(self, tags : List[str]) -> bool:\n return all([x in tags for x in self.tags])",
"def contains_all(self, obj):\n for e in list:\n if not self.get_java_object().contains(e.get_java_object()):\n return False\n return True",
"def has_desired_tag(tags):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if all of supplied objects have tag with specified category code and/or category name Return True if all object ids has specified tag category | def check_tag_category(self, cr, uid, ids, code=None, name=None, context=None):
assert bool(code is not None) or bool(name is not None), "code or name must not be None"
tag_domain = [('id', 'in', ids)]
if code is not None:
tag_domain.append(('tag_ids.category_id.code', '=', code))
... | [
"def check_tag(self, cr, uid, ids, code=None, name=None, context=None):\n assert bool(code is not None) or bool(name is not None), \"code or name must not be None\"\n tag_domain = [('id', 'in', ids)]\n if code is not None:\n tag_domain.append(('tag_ids.code', '=', code))\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A way to figure out the boot time directly on Linux. | def _boottime_linux():
global __boottime
try:
f = open('/proc/stat', 'r')
for line in f:
if line.startswith('btime'):
__boottime = int(line.split()[1])
if datetime is None:
raise NotImplementedError('datetime module required.')
return dat... | [
"def boot_time():\n b_time = psutil.get_boot_time()\n return datetime.datetime.fromtimestamp(b_time).strftime(\"%Y-%m-%d %H:%M:%S\")",
"def uptime():\n if __boottime is not None:\n return time.time() - __boottime\n\n return _uptime_linux()",
"def booted_time_secs(self):\n return self.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns uptime in seconds if even remotely possible, or None if not. | def uptime():
if __boottime is not None:
return time.time() - __boottime
return _uptime_linux() | [
"def get_uptime():\n\n now = datetime.datetime.utcnow()\n uptime = None\n\n # boot timestamp exists + boot-time timesync in update check successful on this boot + webui has time synced at least once\n try:\n if os.path.exists(constants.BOOT_TIMESTAMP_FILE) and \\\n os.path.exists(co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns boot time if remotely possible, or None if not. | def boottime():
global __boottime
if __boottime is None:
up = uptime()
if up is None:
return None
if __boottime is None:
_boottime_linux()
if datetime is None:
raise RuntimeError('datetime module required.')
return datetime.fromtimestamp(__boottime or t... | [
"def boot_time():\n b_time = psutil.get_boot_time()\n return datetime.datetime.fromtimestamp(b_time).strftime(\"%Y-%m-%d %H:%M:%S\")",
"def uptime():\n if __boottime is not None:\n return time.time() - __boottime\n\n return _uptime_linux()",
"def get_hwclock():\n # Need to search for a way... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manually create a genesis block or the starting block with arbitrary data and some previous hash Let's have the format like this (index, timestamp, previous_hash, data) | def create_genesis_block():
return Block(0, date.datetime.now(), "010101", {"VIN": 123456, "Owner": "Qwertz", "Mileage": 0},
hash_a_block(0, date.datetime.now(), "010101", {"VIN": 123456, "Owner": "Qwertz", "Mileage": 0})) | [
"def __create_block(self, data, genesis=0):\n previous = 0\n if not genesis:\n previous = self.__blocks[::-1][0]\n\n block = Block (\n data, \n len(self.__blocks),\n previous\n )\n\n _hash = ''\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an MS2PIP PEPREC file starting from the MaxQuant Evidence.txt and MSMS.txt files. | def maxquant_to_peprec(evidence_file, msms_file,
ptm_mapping={'(ox)': 'Oxidation', '(ac)': 'Acetyl', '(cm)': 'Carbamidomethyl'},
fixed_modifications=[]):
for (aa, mod) in fixed_modifications:
if re.fullmatch('[A-Z]|n_term', aa) is None:
raise ValueE... | [
"def makePoem():\n adjFile = r\"C:\\Users\\shockma\\Documents\\Special\\Python\\extract\\adj.txt\"\n advFile = r\"C:\\Users\\shockma\\Documents\\Special\\Python\\extract\\adv.txt\"\n nounFile = r\"C:\\Users\\shockma\\Documents\\Special\\Python\\extract\\noun.txt\"\n prepFile = r\"C:\\Users\\shockma\\Doc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the committee membership information for a specific person | def getMembershipInformation(self, person):
refCatalog = getToolByName(self, 'reference_catalog')
refs = refCatalog.getReferences(self, 'CommitteeMembership', person)
if not refs:
return None
else:
return refs[0].getContentObject() | [
"def committee_membership(member, congress='114'):\n member = member.upper()\n committees = []\n cdict = load_committees(committees_file)\n chambers = cdict['congress'][congress]['chamber']\n for chamber, committees_dict in chambers.items():\n for committee_dict in committees_dict.values():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the people in this committee. Mainly for contextsensitive classifications | def getPeople(self):
return self.getMembers() | [
"def people(self):\n return self.items",
"def get_people(self):\n \n return set(self.people)",
"def getPeople(self):\n\n secman = getSecurityManager()\n \n #There *has* to be a better way to do this...\n localPeople = self.getReferences(relationship='classificati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the user's parse history | async def get_history():
# Retrieve the parse history from the database or from a stored variable
parse_history = [
{"sentence": "The dog chased the cat", "grammar": "English", "c-structure": True, "f-structure": False, "date": "2022-01-01"},
{"sentence": "Le chat a poursuivi le chien", "grammar... | [
"def getHistory(self):\n attrs = self.t.val.attrs._f_list(\"user\")\n attrs.sort()\n history_list = []\n for attr in attrs:\n if attr[:-3] == 'HISTORY':\n history_list.append(self.t.val.attrs[attr])\n if len(history_list) == 0:\n history_str = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a parse history entry | async def delete_history(id: int):
try:
# Delete the specified entry from the database or stored variable
pass
except:
raise HTTPException(status_code=404, detail="Parse history entry not found") | [
"def delete(self):\n return self._server.query(self.historyKey, method=self._server._session.delete)",
"def test_delete_history_using_delete(self):\n pass",
"def delete(self, filename):\n logger.debug(\"-> deleting build history \" + filename)\n pathname = os.path.join(self._basename... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a report for an event, write it to disk and optionally send it as an email. | def generateReport(self, evID):
sout = self.report_head
for _i in sorted(self.event_dict[evID]['updates'].keys()):
ed = self.event_dict[evID]['updates'][_i]
sout += "%4.2f|" % ed['magnitude']
sout += "%6.2f|" % ed['lat']
sout += "%6.2f|" % ed['lon']
... | [
"def generate_report():",
"def send_data(config):\n enterprise_customer_name = config['enterprise_customer']['name']\n LOGGER.info('Kicking off job to send report for {}'.format(enterprise_customer_name))\n\n try:\n reporter = EnterpriseReportSender.create(config)\n reporter.send_enterprise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove outdated events from the event dictionary. | def garbageCollector(self):
tcutoff = self.latest_event - TimeSpan(self.expirationtime)
for evID in self.event_dict.keys():
evt = self.cache.get(seiscomp3.DataModel.Event, evID)
if self.event_dict[evID]['timestamp'] < tcutoff:
self.event_dict.pop(evID) | [
"def remove_event(self,event):\n\t\tself.events = [i for i in self.events if i[0] != event ]",
"def prune_old_events(events, now):\n for event in events: # for each event\n try:\n end_time = dateutil.parser.parse(event['end']['dateTime']).date()\n except KeyError:\n end_tim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update or publish events based on incoming MVS magnitude comments. | def handleComment(self, comment, parentID):
try:
if comment.id() == 'update':
seiscomp3.Logging.debug("update comment received for magnitude %s " % parentID)
magID = parentID
orgID = self.origin_lookup[magID]
evID = self.event_lookup[or... | [
"def on_comments_changed(self, old, new):",
"def _media_changed(self, event):\n self._log.info(\"Track changed: {}\".format(self._player.get_media().get_mrl()))\n self._server.message_all(self._player.get_media().get_mrl() + \"\\n\")\n self._sout_updated()",
"def update_mag(self, msg):\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we can construct ElementaryLine object correctly. | def test_construction_and_query(self):
line = ElementaryLine([0.0, 1.2, 0.7], n=2)
ret_x = line.x.tolist()
ref_x = [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]
self.assertListEqual(ret_x, ref_x)
ret_y = line.y.tolist()
ref_y = [0.0, 0.0, -3.4426554548552387e-18, 0.7, 0.7, 0.7]
... | [
"def testMakeLine(self):\n self.assertEqual(\n r'\\path [line] (test1-0) -- (test1-1);',\n self.sf._makeLine(0, 1)\n )",
"def test_create_line():\n start = np.array([1, 2, 3])\n stop = np.array([4, 5, 6])\n wrong = np.array([1, 2])\n with pytest.raises(AssertionErro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure all points in line can be translated correctly. | def test_translate(self):
line = ElementaryLine([0.0, 1.2, 0.7], n=2)
line.translate(0.5, "x")
ref_x = [0.5, 1.5, 1.5, 2.5, 2.5, 3.5]
self.assertListEqual(line.x.tolist(), ref_x)
line.translate(-0.5, "y")
ref_y = [-0.5, -0.5, -0.5,
0.19999999999999996,
... | [
"def check_valid_points(self,n):\n if all(i == 0 for i in n):\n print(\"Points are the same or in one line. This leads to an ambiguous assignement of a plane.\")\n raise ValueError",
"def test_translate_state(self):\n line = ElementaryLine([0.0, 1.3, 0.8])\n\n # Translat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we can get correct eigen points for an elemnetary line. | def test_eigen_pts(self):
line = ElementaryLine([0.0, 1.2, 0.8])
eigen_pts = line.eigen_points
self.assertTrue(eigen_pts.has_barrier)
self.assertTupleEqual(eigen_pts.A, (0.0, 0.0))
self.assertTupleEqual(eigen_pts.B, (1.0, 0.0))
self.assertTupleEqual(eigen_pts.C, (1.51515... | [
"def test_construction_and_query(self):\n line = ElementaryLine([0.0, 1.2, 0.7], n=2)\n\n ret_x = line.x.tolist()\n ref_x = [0.0, 1.0, 1.0, 2.0, 2.0, 3.0]\n self.assertListEqual(ret_x, ref_x)\n\n ret_y = line.y.tolist()\n ref_y = [0.0, 0.0, -3.4426554548552387e-18, 0.7, 0.7... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we can translate specific state correctly. | def test_translate_state(self):
line = ElementaryLine([0.0, 1.3, 0.8])
# Translate IS.
line.translate_state("IS", -0.2)
self.assertEqual(line.y[0], -0.2)
# Translate TS.
ref_y = line.eigen_points.C[1] + 0.1
line.translate_state("TS", 0.1)
self.assertAlmo... | [
"def test_get_human_state(self):\n referral = ReferralFactory()\n with translation.override(\"en\"):\n self.assertEqual(referral.get_human_state(), \"Received\")\n with translation.override(\"fr\"):\n self.assertEqual(referral.get_human_state(), \"Reçue\")\n\n refer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds an entry from a database row. | def FromRow(cls, row):
return Entry(*row) | [
"def initFromDbRow(self, aoRow):\n if aoRow is None:\n raise TMRowNotFound('Build not found.');\n\n self.idBuild = aoRow[0];\n self.tsCreated = aoRow[1];\n self.tsEffective = aoRow[2];\n self.tsExpire = aoRow[3];\n self.uidAut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prettyprints a resource to stdout. | def _PrettyPrintResource(cls, resource):
print 'score: %d' % cls._ComputeResourceScore(resource)
print resource | [
"def pprint(self, resource):\n pretty_print = pprint.PrettyPrinter(indent=4)\n if (isinstance(resource, dict) and\n 'object' in resource and\n 'resource' in resource):\n if SOURCE_RE.match(resource['resource']):\n print \"%s (%s bytes)\" % (resource['objec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints the candidates for prefetch. | def PrettyPrintCandidates(self):
print 'primary_key: %s' % self.prefetch_data.primary_key
for resource in self.prefetch_data.resources:
confidence = float(resource.number_of_hits) / (
resource.number_of_hits + resource.number_of_misses)
if resource.number_of_hits < 2 or confidence < .7:
... | [
"def pprint(self):\r\n self.refresh()\r\n print(self.pool)",
"def print_candidates(self, rel_info, doc_name=\"\", max_output=20, keywords=[]):\n\n try:\n # getting list of extracted candidates\n if doc_name == \"\":\n candidates_query = \"SELECT id, {0}_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
feed_forward_model specification list Create a feed forward model given a specification list Each element of the list represents a layer and is formed by a tuple. (layer_constructor, positional_parameter_list, keyword_parameter_dictionary) Example, create M dimensional input to a 3 layer network with 20 unit ReLU hidde... | def feed_forward_model(specification):
model = Sequential()
for item in specification:
layertype = item[0]
# Construct layer and add to model
# This uses Python's *args and **kwargs constructs
#
# In a function call, *args passes each item of a list to
# the... | [
"def __init__(self,num_bins):\r\n super(FeedForwardModel, self).__init__()\r\n \r\n # Training hyperparamaters\r\n self.batch_size = 256\r\n self.learning_rate = .001\r\n self.optimizer = tf.keras.optimizers.Adam(learning_rate = self.learning_rate)\r\n self.num_bins ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
train_and_evaluate__model(examples, labels, train_idx, test_idx, model_spec, batch_size, epochs) | def train_and_evaluate__model(self, examples, labels, train_idx, test_idx,
model_spec, batch_size=100, epochs=100):
# Convert labels to a one-hot vector
# https://keras.io/utils/#to_categorical
onehotlabels = np_utils.to_categorical(labels)
# Get ... | [
"def test_model(args, specific_folds=None, specific_input_configs=None, verbose=True):\n\n # Generate the model configuration from the hyper-parameters specified in the config.json file.\n model_config = generate_model_configuration(args)\n\n # Get the folds on which the model will be trained.\n test_on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set of reset types that can be used with this target. | def supported_reset_types(self) -> Set[ResetType]:
raise NotImplementedError() | [
"def AllTypes():\n return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,\n AssetType.UtilityToken, AssetType.Currency, AssetType.Share,\n AssetType.Invoice, AssetType.Token]",
"def atom_type_library(self):\n return list(set(self.atom_type))",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a `astropy.wcs.WCS` instance for a TPF given its target index metadata. | def create_wcs(row):
# First we create a WCS object from the metadata
metadata = {}
metadata['CTYPE1'] = 'RA---TAN'
metadata['CTYPE2'] = 'DEC--TAN'
for kw in ['naxis1', 'naxis2', 'crpix1', 'crpix2', 'crval1', 'crval2',
'cdelt1', 'cdelt2', 'pc1_1', 'pc1_2', 'pc2_1', 'pc2_2',
... | [
"def get_WCS_from_fits(clustername):\n hdu_map,img_map,weight_map= load_Data(clustername)\n w=wcs.WCS(hdu_map.header)\n return w",
"def _make_wcs(cont_table):\n\n output = dict()\n data = cont_table[1].data\n for ary in ['SLW', 'SSW']:\n ind_ary = np.where(data['array'] == ary)[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the corners of a target mask given its target index row. | def mask_corners(row):
mywcs = create_wcs(row)
# Then figure out the corners
x, y = row['naxis1'], row['naxis2'] # Mask dimensions
corners = mywcs.all_pix2world([-0.5, -0.5, x-0.5, x-0.5],
[-0.5, y-0.5, y-0.5, -0.5],
0)
del mywcs
... | [
"def get_background(mask, offset_radius, background_radius):\n offset = ndimage.binary_dilation(mask, iterations=offset_radius)\n background = ndimage.binary_dilation(offset, iterations=background_radius)\n return background ^ offset",
"def getCorners(self):\n px,py=self.position\n sx,sy=se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds corner coordinate columns to the target index dataframe. | def add_corners(df):
col_corners, col_ra_min, col_ra_max, col_dec_min, col_dec_max = [], [], [], [], []
for idx, row in tqdm(df.iterrows(), desc="Adding corner coordinates", total=len(df)):
corners = mask_corners(row)
# String serialization
str_repr = ";".join(["{:.6f},{:.6f}".format(cor... | [
"def index_to_columns(self) -> pd.DataFrame:\n if \"start_locus\" in self._obj.columns and \"end_locus\" in self._obj.columns:\n return self._obj\n obj = self._obj.copy()\n obj.loc[:, \"start_locus\"] = obj.index.left\n obj.loc[:, \"end_locus\"] = obj.index.right\n obj ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
accepts as input a data frame with a message column of strings. returns the data frame with a new column names edited message which is the messaage colum with the string_trunc function appled to it | def message_trunc(df):
df['edited message']=df['message'].apply(string_trunc)
return df | [
"def MessagesCharac(df):\n #Generating a vector with the message words lengths\n MessLens = []\n for message in df.message:\n MessLens.append(len(message.split()))\n\n #Removing outliers from the messages words lengths vector \n MessLens = np.asarray(MessLens)\n q3, q1 = np.percentile(MessL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes as input a string and returns true if the string is one letter that is no a or I and false otherwise | def single_letter(word):
if len(word)==1 and word!='a' and word!='I':
return True
return False | [
"def not_letter(character: str) -> bool:\n return character not in LETTERS",
"def my_isalpha(s):\n registry_1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n registry_2 = registry_1.lower()\n alpha = True\n if len(s) > 0:\n for i in range(0, len(s)):\n if s[i] not in registry_1 or s[i] not in re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string and a spell check (denoted by d) returns the number of words delimated by no english characters | def number_of_word(string,d):
words = re.split('[^a-z]',string)
words = filter(lambda x: x != '', words)
number = 0
if words == []:
return 0
for word in words:
if d.check(word) and not single_letter(word):
number = number +1
return number | [
"def spelling_checker(text):\n \n text = text.lower()\n tokens = [token for token in nltk.word_tokenize(text)]\n tokens = [token if not wordnet.synsets(token) \n else Word(token).correct() for token in tokens]\n text = \" \".join(tokens)\n return text",
"def wordcount(s):\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a string and a list returns the number of words in the string that are in the list where words are seperated by nonenglish characters | def number_of_words_in_list(string,_list):
words = re.split('[^a-z]',string)
words = filter(lambda x: x != '', words)
number = 0
if words == []:
return 0
for word in words:
if word in _list:
number = number +1
return number | [
"def number_of_word(string,d):\n\twords = re.split('[^a-z]',string)\n\twords = filter(lambda x: x != '', words)\n\tnumber = 0\n\tif words == []:\n\t\treturn 0\n\tfor word in words:\n\t\tif d.check(word) and not single_letter(word):\n\t\t\tnumber = number +1\n\treturn number",
"def wordcount(s):\r\n return len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncates X to include only the most important n fetures | def shrink_fearutes(n,X,importance):
indices = sorted(range(100),key=lambda x:importance[x])[-n:]
X_words=X[:100]
X_tail=X[100:]
new_words=[]
for i in indices:
new_words.append(X[i])
return list(new_words)+list(X_tail) | [
"def truncate_features(timeseries: dict, max_len: int) -> dict:\n for key in (\n FieldName.FEAT_DYNAMIC_CAT,\n FieldName.FEAT_DYNAMIC_REAL,\n ):\n if key not in timeseries:\n continue\n timeseries[key] = [feature[:max_len] for feature in timeseries[key]]\n\n return ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |