query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
send 200 OK response, and set server.stop to True | def do_QUIT(self):
self.send_response(200)
self.end_headers()
self.server.stop = True | [
"def respond_ok(self):\n self.send_response(200)\n self.send_header(\"Content-Type\", \"text/html\")\n self.send_header(\"Content-Length\", 0)\n self.end_headers()\n self.close_connection = 1",
"def send_200_resp(self, response, content_type):\n self.send_response(200)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
emulate post request with get handler, we don't need the data | def do_POST(self):
self.do_GET() | [
"def post(self, request, *args, **kwargs):\n return self.get(request, *args, **kwargs)",
"def post(self, request, *args, **kwargs):\n pass",
"def _post(self, *args, **kwargs):\n return self._request('post', *args, **kwargs)",
"def post_request(dummy_request):\n dummy_request.method = \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.http_request_headers. Return True for success, False for failure; on failure, an error is sent back. | def parse_request(self):
self.command = None # set in case of error on the first line
self.request_version = version = self.default_request_version
self.close_connection = 1
requestline = self.raw_requestline
# hack: quick and dirty fix for doubled request with bad data
... | [
"def parse_request(self):\n self.command = None # set in case of error on the first line\n self.request_version = version = self.default_request_version\n self.close_connection = True\n requestline = self.raw_requestline\n if not six.PY2:\n requestline = requestline.de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle one request at a time until stopped. | def serve_forever(self, unused_parameter=0.5):
self.stop = False
while not self.stop:
self.handle_request() | [
"def handle_one_request(self):\n self.reset()\n BaseHTTPRequestHandler.handle_one_request(self)",
"def serve_forever(self):\n self.stop = False\n while not self.stop:\n self.handle_request()",
"def handle(self):\n # print(\"handle multiple requests ..\")\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate machine id based on default adapters mac address. | def _generate_machine_id(self):
mach_id = "machine_"
try:
gws = netifaces.gateways() # get all gateways
default = gws['default'] # get the default gw
adapter = default[2][1] # get the adapter identifier
real_adapter = netifaces.ifaddresses(adapter... | [
"def get_machine_id():\n return urlsafe_b64encode(hash256(bytes(uuid.getnode()))[:6])",
"def _generate_mac(topology_id):\n tid = int(topology_id)\n global mac_counter\n global used_macs\n base = '52:54:00:00:00:00'\n ba = base.split(':')\n ba[2] = '%02x' % int(tid / 256)\n ba[3] = '%02x' %... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push a file to cnc server with optional rc4 encryption. | def push_file_to_server(cnc_bot, filename, content, encryption_key=None):
c = content
if encryption_key is not None:
c = rc4.encrypt(c, encryption_key, salt_length=0) # encrypt content via rc4
cfg = {'filename': filename, 'content': c}
cnc_bot.host_orders(cPickle.dumps(... | [
"def swift_push_file(job_log_dir, file_path, swift_config):\n with open(file_path, 'r') as fd:\n name = os.path.join(job_log_dir, os.path.basename(file_path))\n con = swiftclient.client.Connection(\n authurl=swift_config['authurl'],\n user=swift_config['user'],\n ke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a short_lineage, return the full lineage required to find exact lineage match within ID3C. | def get_full_lineage(short_lineage):
lineage_map = {
'h1n1pdm': 'Influenza.A.H1N1',
'h3n2': 'Influenza.A.H3N2',
'vic': 'Influenza.B.Vic',
'yam': 'Influenza.B.Yam'
}
return lineage_map[short_lineage] | [
"def find_similarity(long, short):\n similarity1 = 0\n similarity2 = 0\n for i in range(len(long)-len(short)+1):\n a = 0\n part = long[i:i+len(short)]\n for j in range(len(part)):\n if part[j] == short[j]:\n a += 1\n if a == len(short):\n sim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the full URL for the API endpoint to get sequences of a specific lineage and segment | def generate_full_url(base_url, lineage, segment):
params = "/".join([lineage, segment])
return urljoin(base_url, params) | [
"def url_gen(series_code: str = \"B1770\", period = \"*\", api_key: str = apikey, date_str: str = prev_date_str):\n url = \"https://api.bmreports.com/BMRS/\" + series_code + \"/v1?APIKey=\" + api_key + \"&SettlementDate=\" + date_str + \"&Period=\" + str(\n period) + \"&ServiceType=csv\"\n return url",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET sequences from ID3C server with provided lineage and segment | def get_sequences_from_id3c(url, username, password, lineage, segment, output):
r = requests.get(url, auth=(username,password), stream=True)
r.raise_for_status()
with open(output, 'w+') as fasta_file:
for line in r.iter_lines():
if line:
sequence = json.loads(line)
... | [
"def get_genomic_data(lineage, segment, session):\n LOG.debug(f\"Exporting genomic data for lineage <{lineage}> and segment <{segment}>\")\n\n sequences = datastore.fetch_genomic_sequences(session, lineage, segment)\n\n return Response((row[0] + '\\n' for row in sequences), mimetype=\"application/x-ndjson\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the unique IDs to a file, but add a self.prefix to each element of the array. For example, if self.unique_ids is ['image_1.jpg', 'image_2.jpg'] then if the self.prfix is './folder/', then out_file would be written as ./folder/image_1.jpg ./folder/image_2.jpg | def write_unique_ids(self, out_file):
with open(out_file,'w') as f:
f.writelines([self.prefix+x+'\n' for x in self.unique_ids])
return | [
"def prependUniqueIDs(fas, outputDir):\n uniqueID = 0\n ret = []\n for fa in fas:\n outPath = os.path.join(outputDir, os.path.basename(fa))\n out = open(outPath, 'w')\n for line in open(fa):\n if len(line) > 0 and line[0] == '>':\n tokens = line[1:].split()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the unique IDs from in_file, but remove a self.prefix from each element of the array. For example, if the in_file is ./folder/image_1.jpg ./folder/image_2.jpg and the self.prefix is './folder/', then self.unique_ids would be written as ['image_1.jpg', 'image_2.jpg'] | def read_unique_ids(self, in_file, prefix=None):
if prefix is None:
prefix = self.prefix
with open(in_file) as f:
self.unique_ids = [x.strip().replace(prefix, '') for x in f]
return | [
"def write_unique_ids(self, out_file):\n with open(out_file,'w') as f:\n f.writelines([self.prefix+x+'\\n' for x in self.unique_ids])\n return",
"def prependUniqueIDs(fas, outputDir):\n uniqueID = 0\n ret = []\n for fa in fas:\n outPath = os.path.join(outputDir, os.path.ba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly select images from the CCD dataset to be included in the experiments. Make sure that there are at least CAP number of images in each intersection for age, gender, lighting condition, and skin groups. | def select_unique_ids(self):
ccd = self.metadata
ccd_ids = []
for dg in set(ccd['isDark']):
for gg in set(ccd['Gender']):
for sg in set(ccd['Skin']):
for ag in set(ccd['Age']):
try:
intersection_i... | [
"def randomly_select_images():\r\n global images_a, images_b, images_total\r\n images_a = random.sample(images_a, int(number_of_images_a.get()))\r\n if number_of_images_b.get() != \"\": #check if images_b empty\r\n images_b = random.sample(images_b, int(number_of_images_b.get()))\r\n else:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
First only select those MIAP images that have 1 object in them. Then randomly select images to be included in the experiments. Make sure that there are at least CAP number of images in each intersection for age and gender groups. | def select_unique_ids(self):
miap = self.metadata
miap_single = miap[miap.ImageID.isin(list(miap_single[miap_single == 1].index))]
miap_ids = []
for gp in set(miap_single['GenderPresentation']):
for ap in set(miap_single['AgePresentation']):
try:
... | [
"def select_unique_ids(self):\n ccd = self.metadata\n ccd_ids = []\n for dg in set(ccd['isDark']):\n for gg in set(ccd['Gender']):\n for sg in set(ccd['Skin']):\n for ag in set(ccd['Age']):\n try:\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The metadata for the UTK dataset are in the file names, so pass a list of utk files | def load_metadata(self, utkface_filenames):
def utk_resolve_age_label(file):
x = file.split('_')
if len(x) != 4:
return -1
age = int(file.split('_')[0])
if age in range(18):
age_id = 0
elif age in range(18,45):
... | [
"def metadata_listdir(name):",
"def upload_output_files_metadata(self):\n if os.environ.get('TEST_POSTJOB_NO_STATUS_UPDATE', False):\n return\n edm_file_count = 0\n for file_info in self.output_files_info:\n if file_info['filetype'] == 'EDM':\n edm_file_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the total receptive field of this model as of frames. | def receptive_field(self):
frames = 0
for f in self.pad:
frames += f
return 1 + 2 * frames | [
"def total_rewards(self) -> float:\n return self.__total_rewards",
"def reflectance(self) -> float:\n\n return self.reflectivity**2",
"def patrimony_total(self):\n pass",
"def get_prop(self):\n\t\tnewframe = copy.deepcopy(self)\n\t\tfor f in newframe.header[1:]:\n\t\t\tsum = newframe.sum_fiel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get coordinates of given films | def get_location_coordinates(films_set, film_number=0):
if not film_number:
film_number = len(films_set)
films_list = sorted(list(films_set))
print(f'List has {len(films_list)} films with specified year. '
f'\nAmount of films to analyze: {film_number} '
f'\n---------------------... | [
"def get_coordinates(films_by_year: list) -> list:\n locations = []\n for i, film in enumerate(films_by_year):\n try:\n location = geolocator.geocode(film[1])\n except GeocoderUnavailable:\n continue\n if location is None:\n continue\n locations.app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function finds the nearest films near user specified location | def get_nearest_films(films_list, number, input_location):
output_list = []
for film_data in films_list:
film_dist = int(distance.distance(film_data[1], input_location).km)
film_data.append(film_dist)
output_list.append(film_data)
output_list.sort(key=lambda x: x[-1])
if ... | [
"def get_nearest_films_filming_from_file(path, user_coordinates):\n data = pandas.read_csv(path, sep=';\\t', engine='python')\n locations, films = data['location'], data['films']\n lat, long = data['latitude'], data['longitude']\n\n distance_list = []\n for location, x, y, film in zip(locations, lat,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If East is in the same guild, Talos will ask them a favor... Otherwise, Talos isn't doing it | async def favor(self, ctx):
east = ctx.guild.get_member(339119069066297355)
if not east or east.status != discord.Status.online:
await ctx.send(f"I'm afraid I can't do that, {ctx.author.display_name}.")
return
await ctx.send("&East, could I ask you for a favor? I need som... | [
"async def cog_check(self, ctx: commands.Context):\r\n\t\tif ctx.guild.id in self.premiumGuilds:\r\n\t\t\treturn True\r\n\t\tif await self.bot.is_team_owner(ctx.author):\r\n\t\t\treturn True\r\n\t\telse:\r\n\t\t\treturn False",
"def cheer(self, songs):\n if self.favourite_song in songs:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets an XKCD comic with the given number, or the current one if one isn't specified, and displays it. | async def xkcd(self, ctx, comic: int = 0):
if comic < 0:
await ctx.send("Requested XKCD can't be negative")
return
data = await self.bot.session.get_xkcd(comic or None)
if data is None:
await ctx.send(f"No comic for ID `{comic}` found")
return
... | [
"async def get_xkcd(self, ctx, number = \"random\"):\n if not self.module_check(ctx): return\n if number == \"latest\":\n r = requests.get('https://xkcd.com/info.0.json')\n elif number == \"random\":\n r = requests.get('https://xkcd.com/info.0.json')\n r = json.loads(r.text)\n random_xk... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up the JokeCommands extension. Adds the JokeCommands cog to the bot | def setup(bot):
bot.add_cog(JokeCommands(bot)) | [
"def setup(bot):\n bot.add_cog(Quoting())",
"def setup(bot: commands.Bot):\n\n bot.add_cog(jishaku_nextcord(bot=bot))",
"def setup(bot):\n bot.add_cog(AdminCommands(bot))",
"def setup(bot: commands.Bot):\n bot.add_cog(WordTrigger(bot))\n print(\"Loaded Cog: WordTrigger\")",
"def setup(bot):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A method to get interpolated weight spectrumn for a given spw and row id Should be implemented in child class | def _get_interpolated_wtsp(self, *args, **kwargs):
raise NotImplementedError | [
"def get_weight_row(self, i):\n return self.weights[i]",
"def get_external_weight_data(self, weight_id):\n sql = select([self.weights_external.c.id,\n self.weights_external.c.nominal,\n self.weights_external.c.density,\n self.weights_ext... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the column exists in the table | def _column_exists(self, tbname, colname):
self._check_file(tbname)
tb = tbtool()
tb.open(tbname)
cols = tb.colnames()
tb.close()
return (colname in cols) | [
"def is_column_in_table(table_name: str, column_name: str) -> bool:\n query = sql.SQL(\n 'SELECT EXISTS (SELECT 1 FROM information_schema.columns '\n + 'WHERE table_name = {0} AND column_name = {1})',\n ).format(sql.Literal(table_name), sql.Literal(column_name))\n\n with connection.connection... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a polynomial array of length nchan. The polynomial coefficients should be given in ascending order, i.e., when coeff = [1.0, 2.0, 3.0] elements of the return array will be polyarr[ichan] = 1.0 + 2.0ichan + 3.0ichan2 (ichan=0~nchan1) | def _generate_poly_array(self, nchan, coeff=[]):
if nchan < 0:
raise ValueError, "nchan should be >=0"
if len(coeff)==0:
if nchan ==0: return []
else: raise ValueError, "No valid coefficient given."
polyarr = numpy.zeros(nchan)
for iorder in range(len(... | [
"def _create_ploynomial_array(self, coeff, x):\n xarr = numpy.array(x)\n yarr = numpy.zeros(len(xarr))\n for idim in range(len(coeff)):\n ai = coeff[idim]\n yarr += ai*xarr**idim\n return yarr",
"def generate_polynomial():\n degree = numpy.random.choice(range(3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compares two arrays and returns True if they are within a tolerance. checks shapes | def _compare_arrays(self, data, reference, atol=1.e-5, rtol=1.e-5):
if not (data.shape==reference.shape): return False
ret=numpy.allclose(data,reference, atol=atol, rtol=rtol)
return ret | [
"def in_array(a, b, tolerance=EPSILON):\n\n a = np.asarray(a)\n b = np.asarray(b)\n\n d = np.abs(np.ravel(a) - b[..., np.newaxis])\n\n return np.any(d <= tolerance, axis=0).reshape(a.shape)",
"def equals(arr1, arr2):\n return np.power(arr1 - arr2, 2).sum() < EPSILON",
"def array_equal(a, b, unit_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert interpolation string to a list of interpolations in time (should be defined) and frequency (default is 'linear') E.g. 'linear,cspline' > ['linear', 'cpline'] 'nearest' > ['nearest', 'linear' (using the default)] | def interpolation_to_list(self, interpolation):
interplist = interpolation.split(',')
if len(interplist) == 0:
interplist = ['linear', 'linear']
elif len(interplist) == 1:
interplist += ['linear']
return interplist[0:2] | [
"def freq_or_freq_range(string):\n return [float_with_multiplier(f) for f in string.split(':')]",
"def interpolateCubicPeriodic() :\n\n S = []\n\n # for all parameters\n for i in range(11):\n y = []\n # get i-th parameter\n for k in range(len(keyframe)):\n y.append(keyf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Array comparison. Duplicate reference for pol if necessary, i.e., If cell.shape==reference.shape, this method compares cell and reference directly if cell.shape!=reference.shape (e.g., cell.shape=[npol, nchan] while reference.shape=[nchan]), | def _testCell(self, cell, reference, atol=1.e-5, rtol=1.e-5):
cellarr = numpy.array(cell)
refarr = numpy.array(reference)
if cellarr.ndim != refarr.ndim:
# pol loop
for ipol in range(cellarr.shape[0]):
testarr = cellarr[ipol]
self._testCell... | [
"def _compare_arrays(self, data, reference, atol=1.e-5, rtol=1.e-5):\n if not (data.shape==reference.shape): return False\n ret=numpy.allclose(data,reference, atol=atol, rtol=rtol)\n return ret",
"def _compare_mased_array( self, testval, refval, reltol=1.0e-5 ):\n maskok = (testval.mas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns an array of 1./in_arr^2 This corresponds to WEIGHT_SPECTRUM by 1./Tsys^2 in case input is Tsys spectrum | def tsysweightsp_from_tsysarr(self, in_arr):
return 1./(numpy.array(in_arr)**2) | [
"def weight_from_meantsys(self, in_arr):\n return 1./(numpy.mean(in_arr)**2)",
"def comp_input_spectra(self):\n \n self.nx=int(self.nx)\n\n \n inputs_mat=self.inputs_flat.reshape(self.nx,self.nx,self.N)\n\n in_allfreqs = fftshift(fftfreq(self.nx,d=float(self.L)/self.nx))\n self.in_freqs=i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns 1./mean(in_arr)^2 This corresponds to WEIGHT by 1./Tsys^2 in case WEIGH_SPECTRUM does not exists. | def weight_from_meantsys(self, in_arr):
return 1./(numpy.mean(in_arr)**2) | [
"def tsysweightsp_from_tsysarr(self, in_arr):\n return 1./(numpy.array(in_arr)**2)",
"def har_mean(array):\n return ((sum([1/x for x in array]))**(-1))*len(array)",
"def normalized_intensity(self, freq):\n return 1",
"def _get_weight_norm_(self):\r\n if not self.is_kernel_initialized a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a median value of an array. if takeEvenMean, middle two values are average if the number of elements in in_array is even. if not sort in_array in ascending order and returns an (n1)/2th element. | def _median(self, in_arr, takeEvenMean):
if takeEvenMean:
return numpy.median(in_arr)
else:
return numpy.sort(in_arr, axis=None)[(in_arr.size-1)/2] | [
"def median(self, array):\n # https://www.mathsisfun.com/median.html \n n = len(array)\n if n < 1:\n return None\n if n % 2 == 1:\n # for an odd array, return the middle number\n return sorted(array)[n // 2]\n else:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test wtmode='tsys', interp='nearest,nearest', dowtsp=True | def testTsysNNSp(self):
self._runTest('tsys', True, self.tsys_funcs.keys(), 'nearest,nearest') | [
"def testTinttsysNNSp(self):\n self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTinttsysLCSp(self):\n self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTsysMapNNSp(self):\n self._runTest('tsys', True, [1,3,5,7,9,15], '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test wtmode='tinttsys', interp='nearest,nearest', dowtsp=True | def testTinttsysNNSp(self):
self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest') | [
"def testTsysNNSp(self):\n self._runTest('tsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTinttsysLCSp(self):\n self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test wtmode='tinttsys', interp='linear,cspline', dowtsp=True | def testTinttsysLCSp(self):
self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest') | [
"def testTinttsysNNSp(self):\n self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTinttsysMapLCSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,11,13,15], 'linear,cspline',self.spwmap)",
"def testTsysNNSp(self):\n self._runTest('tsys', True, self.tsy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tinttsys', interp='nearest,nearest' | def testTinttsysMapNN(self):
self._runTest('tinttsys', False, [1,3,5,7,15], 'nearest,nearest',self.spwmap) | [
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysNNSp(self):\n self._runTest('tinttsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTsysMapNNSp(self):\n self._runTest('tsys', True, [1,3,5,7,9... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tinttsys', interp='linear,cspline' | def testTinttsysMapLC(self):
self._runTest('tinttsys', False, [1,3,5,7,9,11,13,15], 'linear,cspline',self.spwmap) | [
"def testTinttsysMapLCSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,11,13,15], 'linear,cspline',self.spwmap)",
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysMapLLSp(self):\n self._runTest('tinttsy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tsys', interp='nearest,nearest', dowtsp=True | def testTsysMapNNSp(self):
self._runTest('tsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap) | [
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTsysNNSp(self):\n self._runTest('tsys', True, self.tsys_funcs.keys(), 'nearest,nearest')",
"def testTinttsysNNSp(self):\n self._runTest('tinttsys', True, self.tsys_fun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tinttsys', interp='nearest,nearest', dowtsp=True | def testTinttsysMapNNSp(self):
self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap) | [
"def testTsysMapNNSp(self):\n self._runTest('tsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysMapNN(self):\n self._runTest('tinttsys', False, [1,3,5,7,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysNNSp(self):\n self._runTest('tinttsys', True, self.tsys... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tinttsys', interp='linear,linear', dowtsp=True | def testTinttsysMapLLSp(self):
self._runTest('tinttsys', True, [1,3,5,7,9,11,15], 'linear,linear',self.spwmap) | [
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTsysMapNNSp(self):\n self._runTest('tsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysMapNN(self):\n self._runTest('tinttsys', False, [1,3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test spwmap wtmode='tinttsys', interp='linear,cspline', dowtsp=True | def testTinttsysMapLCSp(self):
self._runTest('tinttsys', True, [1,3,5,7,9,11,13,15], 'linear,cspline',self.spwmap) | [
"def testTinttsysMapNNSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,15], 'nearest,nearest',self.spwmap)",
"def testTinttsysMapLLSp(self):\n self._runTest('tinttsys', True, [1,3,5,7,9,11,15], 'linear,linear',self.spwmap)",
"def testTinttsysMapLC(self):\n self._runTest('tinttsys', Fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a darker color. | def darken(color):
hue, saturation, value = rgb_to_hsv(color.red, color.green, color.blue)
value /= 1.5
saturation /= 1.25
return hsv_to_rgb(hue, saturation, value) + (color.alpha,) | [
"def darker(self, force=1):\n nb = clamp(force, 1)\n rgb = (clamp(x - 10*nb, 0, 255) for x in self.get_rgb())\n return Color.from_rgba(*rgb, self.a)",
"def darker(clr, step=0.2):\n h, s, b = rgb_to_hsb(clr.r, clr.g, clr.b)\n r, g, b = hsb_to_rgb(h, s, max(0, b-step))\n return Color(r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the given PageBox. | def draw_page(page, stream):
bleed = {
side: page.style[f'bleed_{side}'].value
for side in ('top', 'right', 'bottom', 'left')}
marks = page.style['marks']
stacking_context = StackingContext.from_page(page)
draw_background(
stream, stacking_context.box.background, clip_box=False, ... | [
"def drawPages(self, pageSelection=None):\n doc = self.parent\n\n w, h, _ = doc.getMaxPageSizes(pageSelection)\n w2 = 2*w # Make spread width\n for pn, pages in doc.getSortedPages():\n #if pageSelection is not None and not page.y in pageSelection:\n # continue\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a ``stacking_context`` on ``stream``. | def draw_stacking_context(stream, stacking_context):
# See https://www.w3.org/TR/CSS2/zindex.html
with stacked(stream):
box = stacking_context.box
stream.begin_marked_content(box, mcid=True)
# apply the viewport_overflow to the html box, see #35
if box.is_for_root_element and (... | [
"def generate_stack(self, **kwargs: Any) -> Stack:\n definition = CfnginStackDefinitionModel.construct(\n name=self.stack_name, tags=self.args.tags, **kwargs\n )\n stack = Stack(definition, self.context)\n stack._blueprint = self.blueprint # pylint: disable=protected-access\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the background color and image to a ``document.Stream``. If ``clip_box`` is set to ``False``, the background is not clipped to the border box of the background, but only to the painting area. | def draw_background(stream, bg, clip_box=True, bleed=None, marks=()):
if bg is None:
return
with stacked(stream):
if clip_box:
for box in bg.layers[-1].clipped_boxes:
rounded_box_path(stream, box)
stream.clip()
stream.end()
# Backgrou... | [
"def draw_page(page, stream):\n bleed = {\n side: page.style[f'bleed_{side}'].value\n for side in ('top', 'right', 'bottom', 'left')}\n marks = page.style['marks']\n stacking_context = StackingContext.from_page(page)\n draw_background(\n stream, stacking_context.box.background, clip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the box border to a ``document.Stream``. | def draw_border(stream, box):
# We need a plan to draw beautiful borders, and that's difficult, no need
# to lie. Let's try to find the cases that we can handle in a smart way.
def get_columns_with_rule():
"""Yield columns that have a rule drawn on the left."""
skip_next = True
for ... | [
"def draw_box(self):\n self.image.fill(self.BACKGROUND_COLOR)\n pygame.draw.rect(self.image, self.BORDER_COLOR, self.image.get_rect(), self.BORDER_WIDTH)",
"def draw_page(page, stream):\n bleed = {\n side: page.style[f'bleed_{side}'].value\n for side in ('top', 'right', 'bottom', 'l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yield columns that have a rule drawn on the left. | def get_columns_with_rule():
skip_next = True
for child in box.children:
if child.style['column_span'] == 'all':
skip_next = True
elif skip_next:
skip_next = False
else:
yield child | [
"def get_columnrules(self, index, M):\n return list(itertools.chain.from_iterable(\n [[[self.strip(index[0], index[1], i), self.strip(index[0], x, i)]\n for x in range(1, M+1) if x != index[1]]\n for i in range(1, M+1)]\n ))",
"def iter_columns(self, rad):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the length of the half of one ellipsis corner. Inspired by [Ramanujan, S., "Modular Equations and Approximations to pi" Quart. J. Pure. Appl. Math., vol. 45 (19131914), pp. 350372], wonderfully explained by Dr Rob. | def corner_half_length(a, b):
x = (a - b) / (a + b)
return pi / 8 * (a + b) * (
1 + 3 * x ** 2 / (10 + sqrt(4 - 3 * x ** 2))) | [
"def spoke_length(n, length):\n\n\tinterior_angle = (2 * math.pi) / n #finds the interior angle in radians\n\treturn ((length**2) / (2 * (1 - math.cos(interior_angle))))**(1/2)",
"def half_high(self):\r\n\r\n return round(0.1 + self.thickness / 2)",
"def length(self):\n def func(x):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw borders of table cells when they collapse. | def draw_collapsed_borders(stream, table):
row_heights = [
row.height for row_group in table.children
for row in row_group.children]
column_widths = table.column_widths
if not (row_heights and column_widths):
# One of the list is empty: don’t bother with empty tables
return
... | [
"def draw_border(self, thick=4):\n left, top = self.left_top_coords(0, 0)\n width = (self.size + self.gap) * self.nb_column\n height = (self.size + self.gap) * self.nb_row\n pygame.draw.rect(self.display, self.border_color,\n (left-thick/2, top-thick/2, width+thick... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw textdecoration of ``textbox`` to a ``document.Stream``. | def draw_text_decoration(stream, textbox, offset_x, offset_y, thickness,
color):
draw_line(
stream, textbox.position_x, textbox.position_y + offset_y,
textbox.position_x + textbox.width, textbox.position_y + offset_y,
thickness, textbox.style['text_decoration_style']... | [
"def text_draw(self, x, y, text, style={}):",
"def _append_text(self, text, style):\n self.text_ctrl.BeginStyle(style)\n self.text_ctrl.WriteText(text)\n self.text_ctrl.EndStyle()",
"def draw_text(\n self, text: str, page_number: int, x: Union[float, int], y: Union[float, int]\n )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiate the scope by keys. e.g. PullRequest.init_by_keys(organization='octocat', repository='HelloWorld', number=1) > PullRequest(organization='octocat', repository='HelloWorld', number=1) | def init_by_keys(cls, **query):
raise NotImplementedError() | [
"def __init__(self, name, version, *keys):\n self.name = name\n try:\n (major, minor) = map(int, version)\n except (ValueError, TypeError):\n raise KeysDictionaryError(\n \"Invalid version: expected (major,minor) tuple of integers, got %r\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether this endpoint scope is a singleton or not. | def is_singleton_scope(cls):
return not cls.primary_keys | [
"def has_singleton(cls):\n return ResourceClientSingleton.__singleton is not None",
"def is_singleton(self):\n return self._is_singleton",
"def singletonCreated():\r\n if cls.__singleton__ is None:\r\n return False\r\n else:\r\n return True",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the hash for the event using ID only | def hash_by_id(cls, event_id):
return '{}::{}'.format(cls.Endpoint.key, event_id) | [
"def existing_hash(self, id):\r\n return self._read_sha_by_id(id)",
"def _calculate_hash(self, entry):\n entry.pop('id', None)\n return hashlib.sha224(json.dumps(\n entry, cls=DjangoJSONEncoder).encode('utf-8')).hexdigest()",
"def id_hash(self, data):\n return HMAC(self.id_key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build new_events This factory method is actually the events factory. | def build_events(self) -> list:
raise NotImplementedError() | [
"def new_event(self) -> Event:\n ...",
"def from_events(cls, events, **kwargs):\n def make_event(e):\n if isinstance(e, TraceEventCheckerBase):\n return e\n else:\n return TraceEventChecker(e)\n\n return cls({\n make_event(e)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collecting new events and push them into the events buffer | def collect_new_events(self) -> list:
self.logger.debug('Collecting new events...')
events = self.build_events()
if not events:
self.logger.debug('No new events.')
for event in events:
self.logger.info('A new event has been detected: {}'.format(event))
... | [
"def fetch_events(self):\n while 1:\n try:\n self.events_local.append(self._q.get(False))\n except queue.Empty:\n break",
"def slurp_events(self):\n while self.has_event():\n self.get_event()",
"def record_event(event):\n events... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the conditional tasks of this bot. | def get_conditional_tasks(self, scope: EndpointScope=None):
from nudgebot.tasks import ConditionalTask
conditional_tasks = [task for task in self._tasks if issubclass(task, ConditionalTask)]
if scope:
static_hierarchy = [ps.__class__ for ps in scope.hierarchy]
conditional... | [
"def get_created_tasks(self):\n tasks = []\n for task_config in get_task_configs(self.context):\n task = task_config.get_created_task(self.context)\n if not task:\n continue\n matched, not_matched = task.start_conditions_status()\n if not not_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the bot is pollable, performing a poll, collecting all the scopes from the scopes collectors, updating statistics and handling tasks. | def poll(self):
if not self.pollable:
self.logger.warning('Poll has been triggered but the bot is not pollable! Return;')
return
self._busy_mutext.acquire()
try:
self.logger.info('Stating poll')
for scope in self.ScopeCollector.collect_all():
... | [
"def on_before_poll(bot):",
"async def poll(self, ctx, choice=None):\n\n if choice is None or choice.lower() in (\"online\", \"voice\"):\n suggestions = get_suggestions(get_users(ctx, choice))\n\n if suggestions:\n poll_id = create_strawpoll(\"What to play?\", suggestio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulling new events from the event factory, collecting statistics and handling tasks | def handle_events(self):
self._busy_mutext.acquire()
try:
event = self.EventsFactory.pull_event()
while event:
self.logger.debug('Handling new event: {}'.format(event.id))
event_endpoint_scope_classes = event.EndpointScope.get_static_hierarchy()
... | [
"def _events(self):\n try:\n latest_event = Event.objects.latest('start_time')\n last_update = latest_event.start_time\n except Event.DoesNotExist:\n last_update = timezone.make_aware(datetime.min,\n timezone.get_default_tim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return feature complexity value | def complexity(self):
raise NotImplementedError() | [
"def complexity(model):\n size = cfg.TRAIN.IM_SIZE\n cx = {\"h\": size, \"w\": size, \"flops\": 0, \"params\": 0, \"acts\": 0}\n cx = model.complexity(cx)\n return {\"flops\": cx[\"flops\"], \"params\": cx[\"params\"], \"acts\": cx[\"acts\"]}",
"def complexity(model):\n size = cfg.TRAIN.IM_SIZE\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""compute amplitude phase error compute amplitude phase error of two complex valued matrix | def ampphaerror(orig, reco):
amp_orig = np.abs(orig)
amp_reco = np.abs(reco)
pha_orig = np.angle(orig)
pha_reco = np.angle(reco)
# print(np.abs(amp_orig - amp_reco))
# print(np.abs(pha_orig - pha_reco))
# print(np.mean(np.abs(amp_orig - amp_reco)))
# print(np.mean(np.abs(pha_... | [
"def get_phase(a,ta, b, tb):\n a = get_xmin(a,ta)\n b = get_xmin(b,tb)\n a = a[:10]\n b = b[:10]\n c = a-b\n if np.sum(c)>0:\n c=np.mean(c)\n else:\n c=np.mean(b-a)\n \n return c",
"def phaseangle(complexr):\n return numpy.arctan2(complexr.imag,complexr.real)",
"def _am... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print 6 power 3 | def six_cubed():
print(math.pow(6, 3)) | [
"def six_cubed():\n print(math.pow(6, 3))\n return",
"def print_power(x):\r\n if(type(x)!=int):\r\n if(power(x)==1 or power(x)==0):\r\n print(calc_power(x))\r\n else:\r\n print(\"{0}^{1}\".format(base(x),power(x)))\r\n else:\r\n print(x)",
"def main():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the hypotenuse of straight angled triangle with 3 and 5 rib lengths | def hypotenuse():
print(math.sqrt(5*5 + 3*3)) | [
"def triangular_area():\n print(1*1/2, 2*2/2, 3*3/2, 4*4/2, 5*5/2, 6*6/2, 7*7/2, 8*8/2, 9*9/2,\n 10*10/2)",
"def triangular_area():\n print(\n math.pow(1, 2)/2,\n math.pow(2, 2)/2,\n math.pow(3, 2)/2,\n math.pow(4, 2)/2,\n math.pow(5, 2)/2,\n math.pow(6, 2)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the citations that consist of a pair of brackets having a substring containing at least one digit inside them. | def remove_citations(text: str) -> str:
text = re.sub("\[[a-zA-Z]\]", "", text)
return re.sub(r"\[(\s|\w)*\d+(\s|\w)*\]", "", text) | [
"def _remove_between_square_brackets(text):\n return re.sub('\\[[^]]*\\]', '', text)",
"def remove_text_between_brackets(text: str) -> str:\n new_text = []\n nested = 0\n for char in text:\n if char == \"(\":\n nested += 1\n new_text = new_text[:-1] if new_text[-1] == \" \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a JSON Web Token that stores this user's ID and has an expiry date set to 60 days into the future. | def _generate_jwt_token(self):
import jwt
from datetime import datetime, timedelta
from django.conf import settings
dt = datetime.now() + timedelta(days=60)
token = jwt.encode({
'id': self.pk,
'username': self.username,
'exp': int(dt.strftime... | [
"def generate_token(self):\n expiration = datetime.utcnow() + timedelta(minutes=20)\n payload = {\n 'exp': expiration,\n 'user': self.id\n }\n return jwt.encode(payload, secret).decode('utf-8')",
"def _generate_jwt_token(self):\n token_expiry = datetime.now... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates if all ConfigurationOption names are unique in the ConfigurationOptions instance. | def configuration_options_object_processor(configuration_options):
option_names = [option.name for option in configuration_options.configuration_options]
for option_name in option_names:
if option_names.count(option_name) > 1:
raise WashError(f'Configuration option with the name {option_name... | [
"def clean(self):\n\t\tif any(self.errors):\n\t\t\treturn\n\n\t\tnames = []\n\t\tduplicates = False\n\n\t\tfor form in self.forms:\n\t\t\tif form.cleaned_data:\n\t\t\t\tname = form.cleaned_data['name']\n\n\t\t\t\t# Check that no two options have the same name\n\t\t\t\tif name in names:\n\t\t\t\t\tduplicates = True\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates if all ConfigurationOptionParameter names are unique in the ConfigurationOption instance. Also validates if at least one required parameter is specified in the ConfigurationOption instance. | def configuration_option_object_processor(configuration_option):
parameter_names = [parameter.name for parameter in configuration_option.parameters]
for parameter_name in parameter_names:
if parameter_names.count(parameter_name) > 1:
raise WashError(f'Parameter with the name {parameter_name}... | [
"def _validate_parameter_combinations(self):\n parameters = [\"type\", \"path\", \"mode\", \"default\", \"min\", \"max\"]\n parameters = {key: getattr(self, key, None) for key in parameters}\n type = parameters.pop(\"type\")\n\n # validate parameter combination\n if type in self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a marker's initial pose if it was passed in. | def initial_pose(self):
return self._initial_pose | [
"def _set_init_pose(self):\n raise NotImplementedError()",
"def __pub_initial_position(self, x, y, theta):\n initpose = PoseWithCovarianceStamped()\n initpose.header.stamp = rospy.get_rostime()\n initpose.header.frame_id = \"map\"\n initpose.pose.pose.position.x = x\n initpose.pose.pose.posi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the interactive marker map of this marker template. | def marker_map(self):
return self._marker_map | [
"def marker(self):\n return self[\"marker\"]",
"def marker(self):\n return self._marker",
"def map(self) -> folium.Map: # noqa:WPS125\n return self.city.map",
"def get_hit_marker(self):\r\n return Marker((0, 0, 0), self._screen)",
"def mapdata(self):\n return {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the callback map of this marker template. | def callback_map(self):
return self._callback_map | [
"def marker_map(self):\n return self._marker_map",
"def get_map_array(self):\n return self.map",
"def get_callback(self):\n return self.callbacks[self.type]",
"def get_mapping(self):\n return self.map_fn.__doc__",
"def marker(self):\n return self[\"marker\"]",
"def map( ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the menu handler of this marker template. | def menu_handler(self):
return self._menu_handler | [
"def get_menu(self):\n return self.menu",
"def get_menu ( self, object, row ):\n return self.menu",
"def GetMenu(self):\n return self._menu",
"def menu(self):\n try:\n return get_template('{}/menu.html'.format(self.label))\n except TemplateDoesNotExist:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns dictionary for CDP neighbor phone | def phone_parse(neighbor):
mgmt_ip = neighbor[mgmt_ip_s]
hostname = neighbor[hostname_s].split('.')[0]
if nxos:
sysname = neighbor['sysname']
if sysname != '':
hostname = sysname
if mgmt_ip == '':
... | [
"def parse_cdp_neighbors(in_str):\n\n in_line = list(val.strip() for val in in_str.strip().split('\\n') if val.strip().startswith(\"R\") or val.strip().startswith(\"SW\"))\n return {\n (in_line[0][0:in_line[0].find(\">\")], #the first part of the dictionary key, in first line in the text search na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given TEXTFSM CDP neighbor, checks type of device and runs through corresponding parser function. | def parse(n):
capabilities = n['capabilities']
if n['platform'].__contains__('IP Phone') or capabilities.__contains__('Phone'):
phone_parse(n)
elif capabilities.__contains__('Router') and capabilities.__contains__('Source-Route-Bridge') or \
capabi... | [
"def _parse_cisco(config):",
"def parse_cdp_neighbors(in_str):\n\n in_line = list(val.strip() for val in in_str.strip().split('\\n') if val.strip().startswith(\"R\") or val.strip().startswith(\"SW\"))\n return {\n (in_line[0][0:in_line[0].find(\">\")], #the first part of the dictionary key, in f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses CUCM export of phones with fields 'Description', 'Device Name', and 'Directory Number 1' | def cucm_export_parse(file):
phones = {}
while True:
try:
with open(file) as phonelist_csv:
for line in phonelist_csv:
if not line.__contains__('Description,Device Name,Directory Number 1'):
info = line.split(',')
... | [
"def merge_phone_discovery_cucm_export(discovered_phones, cucm_parsed_phones):\n for phone in discovered_phones:\n phone_hostname = phone['hostname']\n if phone_hostname in cucm_parsed_phones:\n phone['description'] = cucm_parsed_phones[phone_hostname]['description']\n phone['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a next index for read client. This function implements a default behavior for get a next read client for masterslave setup. Overwrite this function if you want a specific behavior. | def get_next_client_index(self, write=True):
if write or len(self._server) == 1:
return 0
return random.randint(1, len(self._server) - 1) | [
"def readNextIndex(reader: ghidra.app.util.bin.BinaryReader, is32bit: bool) -> long:\n ...",
"def __next_index():\n return redis_store.incr(String.__name__.lower() + '-index')",
"def get_client_index(self):\n return self.client_idx",
"def next_index(self):\n return self._next_index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that parse a connection string. | def parse_connection_string(self, constring):
try:
host, port, db = constring.split(":")
port = port if host == "unix" else int(port)
db = int(db)
return host, port, db
except (ValueError, TypeError):
raise ImproperlyConfigured("Incorrec... | [
"def _parse_connection_string(self, connection_string):\n self.host = '127.0.0.1'\n self.port = 3306\n self.db = None\n self.user = None\n self.pwd = None\n for part in connection_string.split(';'):\n part = part.strip()\n if part != '':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a connection index, returns a new raw redis client/connection instance. Index is used for master/slave setups and indicates that connection string should be used. In normal setups, index is 0. | def connect(self, index=0):
host, port, db = self.parse_connection_string(self._server[index])
return self.connection_factory.connect(host, port, db) | [
"def connection(self, index):\n # Catch bad indexes\n if not 0 <= index < self.ring_size:\n raise ValueError(\n \"There are only %s hosts - you asked for %s!\" % (self.ring_size, index)\n )\n # Make a context manager\n return self.ConnectionContextMan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds delta to the cache version for the supplied key. Returns the new version. | def incr_version(self, key, delta=1, version=None, client=None):
if client is None:
client = self.get_client(write=True)
if version is None:
version = self._backend.version
old_key = self.make_key(key, version)
value = self.get(old_key, version=version... | [
"def incr_version(self, key, delta=1, version=None):\n if version is None:\n version = self.version\n\n old = self.make_key(key, version)\n new = self.make_key(key, version=version + delta)\n\n return self._incr_version(self.client, old, new, delta, version)",
"def incr(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unpickles the given value. | def unpickle(value):
try:
value = int(value)
except (ValueError, TypeError):
value = smart_bytes(value)
value = pickle.loads(value)
return value | [
"def unpickle(data):\n return pickle.loads(data)",
"def _decompressed(value):\n return pickle.loads(bytes(value))",
"def _decode_value(self, value):\n return pickle.loads(value.value) if value else value",
"def deserialize(self, value):\r\n return pickle.loads(value)",
"def reload(va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pickle the given value. | def pickle(self, value):
if isinstance(value, bool) or not isinstance(value, integer_types):
return pickle.dumps(value, self._pickle_version)
return value | [
"def serialize(self, value):\r\n return pickle.dumps(value, protocol=self.protocol)",
"def dump_object(self, value):\n return pickle.dumps(value)",
"def _encode_value(self, value):\n return pickle.dumps(value)",
"def deserialize(self, value):\r\n return pickle.loads(value)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a connection parameters and return a new or cached connection pool for them. Reimplement this method if you want distinct connection pool instance caching behavior. | def get_or_create_connection_pool(self, params):
key = frozenset((k, repr(v)) for (k, v) in params.items())
if key not in self._pools:
self._pools[key] = self.get_connection_pool(params)
return self._pools[key] | [
"def _get_conn_pool(*args, **kwargs):\n from .connection import MySQLConnectionPool\n pool_name = kwargs.setdefault(\"pool_name\", \"mysql_pool\")\n\n if pool_name not in _instances:\n _instances[pool_name] = MySQLConnectionPool(*args, **kwargs)\n pool = _instances[pool_name]\n assert isinstan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a connection parameters, return a new connection pool for them. Overwrite this method if you want a custom behavior on creating connection pool. | def get_connection_pool(self, params):
cp_params = dict(params)
cp_params.update(self.pool_cls_kwargs)
return self.pool_cls(**cp_params) | [
"def get_new_connection(self, conn_params):\n with pool_container.lock:\n # acquire the lock, check whether there exists the pool of current database\n # note: the value of self.alias is the name of current database, one of setting.DATABASES\n if not pool_container.has(self.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load class from path. | def load_class(path):
mod_name, klass_name = path.rsplit('.', 1)
try:
mod = import_module(mod_name)
except AttributeError as e:
raise ImproperlyConfigured('Error importing {0}: "{1}"'.format(mod_name, e))
try:
klass = getattr(mod, klass_name)
except AttributeErr... | [
"def load_class_by_path(taskpath):\n\n return getattr(\n importlib.import_module(\n re.sub(\n r\"\\.[^.]+$\",\n \"\",\n taskpath)),\n re.sub(\n r\"^.*\\.\",\n \"\",\n taskpath))",
"def import_class(path):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests calculating confusion matrix per subpopulation. Tests | def test_confusion_matrix_per_subgroup():
mx1 = np.array([[2, 1, 0], [0, 0, 0], [0, 0, 0]])
mx2 = np.array([[2, 0, 0], [0, 0, 0], [0, 2, 1]])
mx3 = np.array([[2, 0, 1], [0, 2, 0], [1, 0, 1]])
with pytest.warns(UserWarning) as w:
pcmxs, bin_names = fumt.confusion_matrix_per_subgroup(
... | [
"def evaluate_classifications(self):\n test_labels = open('./digitdata/testlabels', 'r')\n self.init_confusion_matrix()\n i = 0\n class_stats = {0:[0,0], 1:[0,0], 2:[0,0], 3:[0,0], 4:[0,0], 5:[0,0], 6:[0,0], 7:[0,0], 8:[0,0], 9:[0,0]}\n total_correct = 0\n num_labels = 1000... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests calculating confusion matrix per indexbased subpopulation. Tests | def test_confusion_matrix_per_subgroup_indexed():
incorrect_shape_error_gt = ('The ground_truth parameter should be a '
'1-dimensional numpy array.')
incorrect_shape_error_p = ('The predictions parameter should be a '
'1-dimensional numpy array.')
... | [
"def test_confusion_matrix_per_subgroup():\n\n mx1 = np.array([[2, 1, 0], [0, 0, 0], [0, 0, 0]])\n mx2 = np.array([[2, 0, 0], [0, 0, 0], [0, 2, 1]])\n mx3 = np.array([[2, 0, 1], [0, 2, 0], [1, 0, 1]])\n\n with pytest.warns(UserWarning) as w:\n pcmxs, bin_names = fumt.confusion_matrix_per_subgroup... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of prizes that will be awarded for this prize. | def num_awarded(self, floor=None):
if self.award_to in ("individual_overall", "floor_overall", "dorm"):
# For overall prizes, it is only possible to award one.
return 1
elif self.award_to in ("floor_dorm", "individual_dorm"):
# For dorm prizes, this is just the number of dorms.
re... | [
"def get_prizes(self):\n return self.prizes.all()",
"def num_pickets(self) -> int:\n return len(self.pickets)",
"def get_num_petals(self):\n return self._num_petals",
"def related_prizes(self):\n return self._related_prizes",
"def num_pauses(self):\r\n objects = self.__get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a ticket from the user if they have one. Throws an exception if they cannot add a ticket. | def add_ticket(self, user):
profile = user.get_profile()
if profile.available_tickets() <= 0:
raise Exception("This user does not have any tickets to allocate.")
ticket = RaffleTicket(raffle_prize=self, user=user)
ticket.save() | [
"def add_user(request, ticket_id):\n if \"user\" in request.POST:\n user = User.objects.get(id=request.POST[\"user\"])\n Ticket.objects.get(id=ticket_id).authorized_users.add(user)\n return HttpResponseRedirect( reverse('tickets.views.show_ticket', kwargs={'ticket_id': ticket_id}) )",
"def cre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes an allocated ticket. | def remove_ticket(self, user):
# Get the first ticket that matches the query.
ticket = RaffleTicket.objects.filter(raffle_prize=self, user=user)[0]
ticket.delete() | [
"def ticket_deleted(self, ticket):\n self.remove_resource_tags(Mock(perm=MockPerm()), ticket)\n if self.use_cache:\n # Invalidate resource cache.\n del self._tagged_resources",
"def ticket_deleted(self, ticket):\n if 'ticket' not in self.sources:\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of tickets allocated to this prize. Takes an optional argument to return the number of tickets allocated by the user. | def allocated_tickets(self, user=None):
query = self.raffleticket_set.filter(raffle_prize=self)
if user:
query = query.filter(user=user)
return query.count() | [
"def num_assigned(self):\n return FlicketTicket.query.filter_by(assigned=self.user).count()",
"def get_total_tickets_count(self):\n return self.tickets.all().count()",
"def get_available_tickets_count(self):\n return self.tickets.filter(reservation__isnull=True).count()",
"def num_pickets... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the transport plan P in regularization path for any given value of lambda | def compute_transport_plan(lam, lambda_list, Pi_list):
if lam <= lambda_list[0]:
Pi_inter = np.zeros(np.shape(Pi_list[-1]))
elif lam >= lambda_list[-1]:
Pi_inter = Pi_list[-1].toarray()
else:
idx = np.where(lambda_list < lam)[0][-1]
lam_k = lambda_list[idx]
lam_k1 = ... | [
"def lambda_cp_func(self):\n self.__lambda_cp = ((float(self.cp_lambda_cp_b) * float(self.cp_c_sf)) + float(self.__lambda_gr) + float(self.__lambda_se) + float(self.cp_lambda_h)) / float(pow(10, 6))",
"def test_PRP(initial):\n return plan_route((initial[0],initial[1]), initial[2],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when the mapper has finished, to allow for any final work to be done. | def finish(self):
logging.info(str(self) + ' Mapper finished.')
if self.next_mapper is not None:
logging.info(str(self) + ' Next: ' + str(self.next_mapper))
self.next_mapper.run()
pass | [
"def finished(self):\n pass",
"def map_finished(self, server_id):\n self.mappers_status[server_id] = True\n for key, value in self.mappers_status.items():\n if not value:\n return\n self._start_reducers()",
"def map_finished(self, node):\n with self.m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes updates and deletes entities in a batch. | def _batch_write(self):
if self.to_put:
db.put(self.to_put)
self.to_put = []
if self.to_delete:
db.delete(self.to_delete)
self.to_delete = [] | [
"def write_batch(self, batch):\n for item in batch:\n self.write_buffer.buffer(item)\n key = self.write_buffer.get_key_from_item(item)\n if self.write_buffer.should_write_buffer(key):\n self._write_current_buffer_for_group_key(key)\n self.increment_w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds Card entities for the given ids, with the given parent. Adds in batches and requeues itself. | def create_cards(card_ids, box_key):
if len(card_ids) == 0:
return
BATCH_SIZE = 20
batch = card_ids[:BATCH_SIZE]
logging.info("Adding cards for %s (%d remaining). Batch: %s"%(box_key,len(card_ids),batch))
for id_tuple in batch:
key = '-'.join([str(p) for p in id_tuple])
card ... | [
"def parent_ids(self, parent_ids):\n self._parent_ids = parent_ids",
"def add_cards(self, lst):\n for card in lst:\n self.enqueue(card)",
"def add(self, fetchables, depth=1):\n if fetchables:\n if isinstance(fetchables, collections.Sequence):\n for fetch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure the incoming dict is a valid rower data frame, so the out coming data is consistent. Check the validity of the incoming dict fields, make sure all the required fields exists, and the value of each key is in the corresponded data type or format. So the data consumers is guaranteed that the out coming data is i... | def _check_dict_validity(self, incoming_dict: dict):
# check key error
# check value error
for key in incoming_dict.keys():
# check invalid key.
if key not in self.all_valid_keys:
raise IncomingRowerDictInvalidKeyError("Incoming rower data dict has unknow... | [
"def validate_required_fields(dataframe):\n\n if dataframe is None:\n raise ValueError(\"It was not provided a valid Dataframe.\")",
"def _validate_inputs(cls, real_data, synthetic_data, metadata=None):\n if set(real_data.columns) != set(synthetic_data.columns):\n raise ValueError('`re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses an HTTP Error from the Google API and returns the error message. | def _get_error_message_from_httperror(err):
json_error = json.loads(str(err.content.decode()))
return json_error.get('error', {}).get('message', '') | [
"def ErrorFromHttpError(error):\n # Handle individual errors based error.status_code here as new API calls\n # are added.\n return UnknownHttpError(error)",
"def _get_httperror(resp):\n status = resp.status\n if status == c.HTTPStatus.NOT_FOUND:\n return pvmex.HttpNotFound(resp)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run the server and wait that it returns | def run(self):
self.rpc_server.serve_forever(0.5) | [
"def run(self):\n self.__rpc_server.run()",
"def serve(self):\n\t\timport thread\n\t\tthread.start_new_thread(self._server_thread, tuple())",
"def run_server(self):\n self.establish_connection()\n while True:\n self.receive_data(self.conn)",
"def run(self):\n server_thre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test if there is something to read on the console | def _check_console_input(self):
if os.name == "nt":
if 0 == ctypes.windll.Kernel32.WaitForSingleObject(self.console_handle, 500):
return True
elif os.name == "posix":
(inputready, abcd, efgh) = select.select([sys.stdin], [], [], 0.5)
if len(i... | [
"def readline_available():\r\n return readline._readline is not None",
"def hastty():\n try:\n return sys.stdin and sys.stdin.isatty()\n except Exception: # pragma: no cover\n return False # i.e. no isatty method?",
"def is_tty_connected() -> bool:\n return sys.stdin.isatty()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read from the console, transfer to the server and write the answer | def run(self):
while self._go.isSet(): #while app is running
if self._check_console_input(): #if something to read on the console
cmd = sys.stdin.readline() #read it
self.inq.put(cmd) #dispatch it tpo the server
response = self.outq.get(timeout=2.... | [
"def mt_interact(self):\n import _thread\n _thread.start_new_thread(self.listener, ())\n while 1:\n line = sys.stdin.readline()\n if not line:\n break\n self.write(line.encode('ascii'))",
"def interact(self):\n print('Ready to interact on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert a tuple to a string | def _tuple_to_str(self, the_tuple):
ret = ""
for item in the_tuple:
ret += (" " + str(item))
return ret[1:] | [
"def _tupstr(tuple_):\n return ', '.join(list(map(str, tuple_)))",
"def tuple_to_str(cls, t):\n if len(t) != 2:\n return None\n\n if t[1] is not None:\n return u'%s/%s' % t\n else:\n return unicode(t[0])",
"def tuple_to_string(letter_word_pair):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute the add_slave command | def _do_add_slave(self, args):
bus_type = args[1]
slave_id = int(args[2])
if bus_type == 'rtu':
self.server._servers[0].add_slave(slave_id)
elif bus_type == 'tcp':
self.server._servers[1].add_slave(slave_id)
return "{0}".format(slave_id) | [
"def add_slave(self, *slaves):\n self.runnables.add(*slaves)\n self.pausables.add(*slaves)\n self.joinables.add(*slaves)",
"def add_slave():\n slaves=read_raw_slaves()\n slaves.append(request.json[0]+'\\n')\n write_slaves(slaves)\n return json.dumps(read_slaves())",
"def attach_slave(name, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute the has_slave command | def _do_has_slave(self, args):
bus_type = args[1]
slave_id = int(args[2])
try:
if bus_type == 'rtu':
self.server._servers[0].get_slave(slave_id)
elif bus_type == 'tcp':
self.server._servers[1].get_slave(slave_id)
except Exce... | [
"def _is_slave():\n return \"--slave\" in sys.argv",
"def slaveConnected(slaveName):",
"def test_slaveof(self):\n self.assertEqual(redismod.slaveof(\"master_host\", \"master_port\"), \"A\")",
"def _is_master():\n return \"--slave\" not in sys.argv",
"def slave_status():\n run_mysql_command(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute the remove_slave command | def _do_remove_slave(self, args):
bus_type = args[1]
slave_id = int(args[2])
if bus_type == 'rtu':
self.server._servers[0].remove_slave(slave_id)
elif bus_type == 'tcp':
self.server._servers[1].remove_slave(slave_id)
return "" | [
"def remove_slave(self, slave_type = SlaveType.PERIPHERAL, slave_index=0):\n self.sgm.remove_slave(slave_index, slave_type)\n return",
"def delete_slave():\n\n slaves=read_raw_slaves()\n matched=True\n while matched:\n matched=False\n for line in slaves:\n if not re.match('... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute the add_block command | def _do_add_block(self, args):
bus_type = args[1]
slave_id = int(args[2])
name = args[3]
block_type = int(args[4])
starting_address = int(args[5])
length = int(args[6])
if bus_type == 'rtu':
slave = self.server._servers[0].get_slave(slave_id)
... | [
"def add(self, block):\n self.blocks.append(block)",
"def add_block(self):\n web_chain_len = len(self.chain)\n self.chain.append(self.current_block)\n for tx in self.current_block.get('transactions'):\n self.utxo[tx.get('sender')] = True;\n self.send2web(web_chain_len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
execute the remove_block command | def _do_remove_block(self, args):
bus_type = args[1]
slave_id = int(args[2])
name = args[3]
if bus_type == 'rtu':
slave = self.server._servers[0].get_slave(slave_id)
elif bus_type == 'tcp':
slave = self.server._servers[1].get_slave(slave_id)
... | [
"def remove_block(self, block):\n raise NotImplementedError()",
"def remove_block(self,blockname):\n\t\tdel self.blocks[blockname]",
"async def remove_block(\n self,\n position: typing.Union[\n typing.Tuple[int, int, int],\n typing.Any,\n ],\n immediate: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |