query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
This API is used to query the list of image sprite generating templates and supports paged queries by filters. | def DescribeImageSpriteTemplates(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("DescribeImageSpriteTemplates", params, headers=headers)
response = json.loads(body)
model = models.DescribeImageSpriteTempla... | [
"def get_trainingimages(self, request, template='trainingimages.html'):\n query_id = request.GET.get('qsid', None)\n if query_id == None:\n raise Http404(\"Query ID not specified. Query does not exist\")\n\n # get query definition dict from query_ses_id\n query = self.visor_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to query the list of VOD domain names. | def DescribeVodDomains(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("DescribeVodDomains", params, headers=headers)
response = json.loads(body)
model = models.DescribeVodDomainsResponse()
mode... | [
"def list_domains(self):\n r = self.make_call('execute/DomainInfo/list_domains')\n if r is None:\n return None\n return r['data']",
"def get_nameservers(cli):\n for domain in cli.args.domain:\n attrs = {\n 'domain': domain,\n 'type': 'nameservers',\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify an adaptive bitrate streaming template. | def ModifyAdaptiveDynamicStreamingTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyAdaptiveDynamicStreamingTemplate", params, headers=headers)
response = json.loads(body)
model = models.Modif... | [
"def setBitrate(self, bitrate):\n try:\n # bypassed by request from Ivan\n if (pu.pxpconfig.IgnoreVideoSettings()):\n dbg.prn(dbg.TDK,\"td -- SetBitrate BYBASSED\")\n return\n \n url = \"http://\"+self.ip+\"/cgi-bin/api.cgi\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify a custom animated image generating template. | def ModifyAnimatedGraphicsTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyAnimatedGraphicsTemplate", params, headers=headers)
response = json.loads(body)
model = models.ModifyAnimatedGraphic... | [
"def generate_image(self) -> None:",
"def animSetCustom():\n return \"TODO\"",
"def create_image(self, obj):\r\n randomize = random.randint(0,3)\r\n if randomize == 0:\r\n image_id = self.canvas.create_image(25, 50, image=obj)\r\n elif randomize == 1:\r\n image_id =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to set the default storage region. A file will be stored in the default region if no region is specified for file upload. | def ModifyDefaultStorageRegion(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyDefaultStorageRegion", params, headers=headers)
response = json.loads(body)
model = models.ModifyDefaultStorageRegionRes... | [
"def set_default_storage_location(cls, storage_location: str) -> None:\n if storage_location:\n storage_dict = {'storage_location': storage_location}\n cls.__save(storage_dict)",
"def get_default_region(self):\r\n return self._default_region",
"def set_region():\n\n region... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify a custom image sprite generating template. | def ModifyImageSpriteTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyImageSpriteTemplate", params, headers=headers)
response = json.loads(body)
model = models.ModifyImageSpriteTemplateRespon... | [
"def create_sprite(self):\n rgb = (84, 170, 232)\n height = 15\n length = 15\n self.sprite = BaseStationSprite(rgb)",
"def get_sprite(self):\n pass",
"def create_sprite(location, image_name, animal_name):\n image = pygame.image.load(image_name)\n image_rect = Rect(locati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify the storage class of media files. | def ModifyMediaStorageClass(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyMediaStorageClass", params, headers=headers)
response = json.loads(body)
model = models.ModifyMediaStorageClassResponse()
... | [
"def change_storage_class(self, new_storage_class, dst_bucket=None,\n validate_dst_bucket=True):\n bucket_name = dst_bucket or self.bucket.name\n if new_storage_class == 'STANDARD':\n return self.copy(bucket_name, self.name,\n reduced_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify a custom moderation template. | def ModifyReviewTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyReviewTemplate", params, headers=headers)
response = json.loads(body)
model = models.ModifyReviewTemplateResponse()
... | [
"def edit_template(self, data: dict) -> None:\n self.add_operation({\n 'op': 'editTemplate',\n 'data': data,\n })",
"def tweak_template_permission(self, tweak_template_permission):\n\n self._tweak_template_permission = tweak_template_permission",
"def _update_template(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify subapplication information, but it is not allowed to modify primary application information. | def ModifySubAppIdInfo(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifySubAppIdInfo", params, headers=headers)
response = json.loads(body)
model = models.ModifySubAppIdInfoResponse()
mode... | [
"def change_subspace(self, cluster_subspace):\n self._subspace = cluster_subspace\n self.update_features()",
"def attach_subarray(self, subarray: \"ctapipe.instrument.SubarrayDescription\"):\n self._subarray = subarray\n self._lookup.attach_subarray(subarray)",
"def update_from_app_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify a custom transcoding template. | def ModifyTranscodeTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyTranscodeTemplate", params, headers=headers)
response = json.loads(body)
model = models.ModifyTranscodeTemplateResponse()
... | [
"def custom_template(self, custom_template):\n\n self._custom_template = custom_template",
"def set_source_template(template):",
"def _update_template(self, content):\r\n t, created = Template.objects.get_or_create(resource=self.resource)\r\n t.content = content\r\n t.save()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify the acceleration region of a domain name on VOD. 1. You can modify acceleration regions of only domain names whose status is `Online`. | def ModifyVodDomainAccelerateConfig(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyVodDomainAccelerateConfig", params, headers=headers)
response = json.loads(body)
model = models.ModifyVodDomainAcce... | [
"def update_region_id(self, region_id, **kwargs):\n return self.netbox_con.patch('/dcim/regions/', region_id, **kwargs)",
"async def update(self, ctx, region: str):\n try:\n riotapi.set_region(region)\n except ValueError:\n embed = discord.Embed(\n title=\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to modify a custom watermarking template. The watermark type cannot be modified. | def ModifyWatermarkTemplate(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("ModifyWatermarkTemplate", params, headers=headers)
response = json.loads(body)
model = models.ModifyWatermarkTemplateResponse()
... | [
"def custom_template(self, custom_template):\n\n self._custom_template = custom_template",
"def WaterMark(waterMark, markRadius=1, markPosition=[250, 10], markSize=1.0):\n txt=a3DText()\n txt.Text = waterMark\n rep=Show();rep.Visibility=0\n RenameSource('WaterMark',txt)\n Transform2=Transfor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This API is used to remove watermarks from a video. | def RemoveWatermark(self, request):
try:
params = request._serialize()
headers = request.headers
body = self.call("RemoveWatermark", params, headers=headers)
response = json.loads(body)
model = models.RemoveWatermarkResponse()
model._deseri... | [
"def remove_marking(markable, marking):\n if not is_marked(markable):\n return\n\n markable.__datamarkings__.remove(marking)",
"def removeVerticalMarker(self, id):\n del self.verticalmarkers[id]",
"def remove_offsets(self, robust=None):\n self.remove_drifts(target_frame_resolution=sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ctor for an SafeEval instance with optional mapping of function names to callables | def __init__(self, allowedCallables: typing.Union[None, typing.Dict[str, typing.Any]] = None):
if allowedCallables is not None:
self.allowedCallables = allowedCallables
else:
self.allowedCallables = dict()
self.nodes: Dict[ast.AST, Callable[[ast.AST, Dict[str, Any]], Any]] = {
ast.Call: self.callNode,
... | [
"def __init__(self, func: Callable[[Any], None]):\n\n if not callable(func):\n raise ValueError('func must be callable')\n\n self._callable = func",
"def __init__(self, columns, func):\n # Ensure that columns is a list.\n self.columns = as_list(columns)\n # Ensure tha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Safely evaluate an expression. If you want to evaluate the expression multiple times with different variables use compile to generate the AST once and call execute for each set of variables. | def safeEval(self, expr: str, names: Dict[str, Any]) -> Any:
return self.execute(self.compile(expr), names) | [
"def evaluate(expr, locals):",
"def safe_eval_custom(expr, globals_dict=None, locals_dict=None, mode=\"eval\", nocopy=False, locals_builtins=False):\n if type(expr) is CodeType:\n raise TypeError(\"safe_eval does not allow direct evaluation of code objects.\")\n\n # prevent altering the globals/local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Warns the user that a forbidden name has been found. | def warn_forbidden_name(forname, inname=None, rename=None):
msg = "found forbidden name {0!r}".format(forname)
if inname is not None:
msg += " in {0!r}".format(inname)
if rename is not None:
msg += ", renaming to {0!r}".format(rename)
warn(msg, RuntimeWarning) | [
"async def _delbadname(self, ctx: commands.Context, badname: str):\n async with self.config.guild(ctx.guild).badnames() as badnames:\n if badname in badnames:\n badnames.remove(badname)\n await ctx.send(f\"{badname} has been removed from the blacklist.\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the rc with values from another mapping. If this rc has if a key is in self, other, and self._updaters, then the updaters value is called to perform the update. This function should return a copy to be safe and not update inplace. | def _update(self, other):
if hasattr(other, '_dict'):
other = other._dict
elif not hasattr(other, 'items'):
other = dict(other)
for k, v in other.items():
if v is NotSpecified:
pass
elif k in self._updaters and k in self:
... | [
"def update(self, other):\n self._map.update(other._map)",
"def update(self, other):\n try:\n it = other.items()\n except AttributeError:\n it = iter(other)\n super().update(map(self._validate_entry, it))",
"def join(self, other):\n self.cache = {**self.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates and possibly converts a value based on its key and the current validators. | def _validate(self, key, value):
validators = self._validators
if key in validators:
validator, convertor = validators[key]
else:
for vld in validators:
if isinstance(vld, str):
continue
m = vld.match(key)
... | [
"def process(self, value):\n if self.value_modifier is not None:\n validator = self.value_modifier\n if inspect.isclass(self.value_modifier):\n validator = validator()\n value = validator.process(value)\n if value not in self.option_keys:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Circumradius of the polygon | def circumradius(self):
return self._circumradius | [
"def get_radius(self):\n return np.degrees(self.bounding_circle[2])",
"def inradius(vertices):\n a = area(vertices)\n s = perimeter(vertices) / 2\n return a / s",
"def circumradius(vertices):\n el = edge_lengths(vertices)\n a = el[0]\n b = el[1]\n c = el[2]\n r = a * b * c / numpy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edge length of individual edge in the polygon | def edge_length(self):
return (2 * self._circumradius * math.sin(math.pi/self._n_edges)) | [
"def edge_lengths(self):\n points = list(self.base_piece.polygon.points())\n NUM = 4\n assert len(points) == NUM\n return [(points[i] - points[(i+1) % NUM]).norm() for i in range(NUM)]",
"def calc_edge_length(edge, layout):\n\n Ax, Ay, Bx, By = edge_to_cartesian(edge,layout)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interior angle value of each angle in the polygon | def interior_angle(self):
return (self._n_edges - 2) * (180/self._n_edges) | [
"def angle_vector(self):\n from math import atan2, pi\n return (atan2(self.y, self.x)) / pi * 180",
"def angle(vertices, i):\n v = edges(vertices)\n u0 = -v[(i + 1) % 3]\n u1 = v[(i + 2) % 3]\n return compute_angle(u0, u1)",
"def _angles_of_a_polygon(num_edges):\n assert num_edges > 2\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modelimplementatie van het heat model | def heat_model(tijdstappen, N2O5_0, N2O4_0, T_0, Ar, Ea, Q, V, rho, Cp, U, A, delta_rH, N2O5_in, N2O4_in, Tin, Tw, returnDataFrame=True):
modeloutput = odeint(model_afgeleiden, [N2O5_0, N2O4_0, T_0], tijdstappen, args=(Ar, Ea, Q, V, rho, Cp, U, A, delta_rH, N2O5_in, N2O4_in, Tin, Tw))
modeloutput = pd.DataFrame... | [
"def heat(self):\r\n return self.m_act * (self.outlet.h - self.cond.h)",
"def heat_func(self):\n return self.Q.val + self.inl[0].m.val_SI * (\n self.outl[0].h.val_SI - self.inl[0].h.val_SI)",
"def visualize_matrice_mi(self):\n ax_heatmap = plt.axes()\n sns.heatmap(self.mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns parser object for Python version 2 or 3 depending on the parameter passed. | def get_python_parser(version, debug_parser):
if version < 3.0:
import uncompyle6.parsers.parse2 as parse2
p = parse2.Python2Parser(debug_parser)
else:
import uncompyle6.parsers.parse3 as parse3
p = parse3.Python3Parser(debug_parser)
p.version = version
return p | [
"def python_parser():\n\n if _has_setup_file():\n parse_fun = _parse_setup_file\n elif _has_pyproject_file():\n raise NotImplementedError(\"Not yet there, but will come!\")\n else:\n return None\n\n # Parse the corresponding file\n software_info = parse_fun()\n software_info.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the header (the first message chunk) for message length. Returns the length and the leftover message chunk. | def parse_header(self, header):
header_separator = self.header_separator.encode()
length, separator, message_chunk = header.partition(header_separator)
try:
return int(length), message_chunk
except ValueError:
return None, None | [
"def _get_chunk(self, header):\n # Read and check header of chunk\n header_chunk = self._file.read(HEADER_LENGTH)\n if header_chunk != header:\n raise RuntimeError(\"The LFP chunk header is invalid.\")\n\n data_pos = None\n sha1 = None\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a socket and starts, binds an address to it, and enables the listen mode. | def start(self, *args, **kwargs):
self.socket = Socket(*args, **kwargs)
self.socket.bind(self.address)
self.socket.listen(1) | [
"def __start_listen_socket(self):\n self.__listen_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.__listen_socket.bind((self.host, self.port))",
"def create_and_bind_socket(self):\r\n try:\r\n self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compiles and executes the received code and returns the output. | def code_output(self, code):
try:
compiled = compile(code, '<inspector-server>', 'single')
except (SyntaxError, OverflowError, ValueError):
return traceback.format_exc(0) # only first entry in the stack
# execute the compiled message and capture the output
with s... | [
"def pythonCode(self):\n return compile(self.pythonString(), \"\", \"exec\")",
"def code(self):\n if self._code is None:\n if self.stale:\n pyfile = self.py_file\n if self.strip_dest_dir and \\\n self.py_file.startswith(self.strip_dest_dir):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shuts down the server (closes the server socket) and deletes namespace. | def shutdown(self):
if self.running:
self.running = False
self.socket.close()
del self.namespace
status(STATUS_SHUTDOWN) | [
"def shutdown(self):\n if self.is_running:\n self.server.server_close()\n self.server.socket.close()\n self.is_running = False",
"def stop(self):\n self.unregister_all_servers()\n self.zeroconf.close()",
"def shutdown(self):\n self._server.shutdown()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens a socket for communicating with the importer from the shell side. Runs a shell after connection is established. | def inspector_shell(host, port, timeout, passphrase):
sock = Socket(timeout=timeout, passphrase=passphrase)
try:
sock.connect((host, port))
# get the file name that runs the server
importer_file = sock.message('code', '__importer_file__')['data']
importer_file = importer_file.str... | [
"def __init__(self, mojo_shell_path, shell_args=None):\n self._tempdir = mkdtemp(prefix='background_shell_')\n self._socket_path = os.path.join(self._tempdir, 'socket')\n self._output_file = TemporaryFile()\n\n shell_command = [mojo_shell_path,\n '--enable-external-applications=' + s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This runs on the inspector's (shell) side. The compiler is used to perform multiline code input. | def code_input():
code = ''
compiled = None
while not compiled:
prompt = PROMPT_INIT if not code else PROMPT_MORE
code += input(prompt) # add a line to the code string
try:
# returns None if the code is valid but not finished
compiled = compile(code, '<inspec... | [
"def run_compiled(filename):\n bytecode = open(filename, 'rb').read()\n codeobject = Deserializer().deserialize_bytecode(bytecode)\n vm = BobVM(output_stream=sys.stdout)\n vm.run(codeobject)",
"def test_cli_compiles_source_file(monkeypatch):\n params = [\"overreact\", \"--compile\", \"data/ethane/B... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads shell history from a file, registers writing at exit | def shell_history():
history_file = os.path.expanduser(SHELL_HISTORY_FILE)
try:
readline.read_history_file(history_file)
except IOError:
pass
atexit.register(readline.write_history_file, history_file) | [
"def readHistory(self):\n\n hist = self.history[self.hposition]\n thist = hist[3]\n if thist is not None:\n hist = thist\n else:\n hist = hist[:3]\n self.string, self.position, self.view = hist\n self.hdirty = False",
"def read_history(fn):\n with... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a server on the importer's side. | def importer_server():
# this behaves strangely for me, so I'm checking the whole stack to make it work for everybody
importer_globals = None
for frame in inspect.stack():
if frame[0].f_globals['__name__'] != __name__:
importer_globals = frame[0].f_globals
break
if not im... | [
"def main() -> None:\n\n start_server()",
"def runserver():\n from web.server import runserver\n runserver()",
"def run_server(server):\n\n server.start()\n server.wait()",
"def runserver():\n load_app().run()",
"def run(self):\n parts = urlparse(HOST_BASE)\n domain, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dict of the top refresh for each source in the queue | def peek(self):
return {
source_name: self._top_refresh(source_name)
for source_name in self.source_to_refresh_queue
} | [
"def refresh_queue(self):\n #print(\"REF Q\")\n now_s = time.time()\n state = self.get_state()\n queue = self.queue = self.get_queue()\n for probe in self.get_probes():\n name = probe['name']\n if not name in queue:\n logger.debug(\"Adding entr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes and returns the top refresh for the given source using its name | def pop(self, source_name):
if source_name not in self.source_to_refresh_queue:
raise EmptyQueueError(source_name)
refresh_id = self.source_to_refresh_queue[source_name].pop(0)
item = self.refresh_ref.pop(refresh_id)
if not self.source_to_refresh_queue[source_name]:
... | [
"def peek(self):\n return {\n source_name: self._top_refresh(source_name)\n for source_name in self.source_to_refresh_queue\n }",
"async def cmd_remove_top(self, ctx, top):\n channel = ctx.channel\n\n if not re.match(r'^-?\\d+$', top):\n await ctx.send(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
coseno = ( V1 V2 ) / ||V1|| x ||V2|| | def coseno(vector1, vector2):
#return float(dot(vector1,vector2) / (math.sqrt(sumarLista(map(cuadrado,vector1))) * math.sqrt(sumarLista(map(cuadrado,vector2))))
return float(dot(vector1,vector2) / (norm(vector1) * norm(vector2))) | [
"def cos_of_angle_between(v1, v2):\n assert len(v1) == len(v2)\n return np.dot(v1, v2)/(np.linalg.norm(v1)*np.linalg.norm(v2))",
"def cosAngle(vector1, vector2=ThreeVector(0, 0, 1)):\n\n return (vector1 ^ vector2) / vector1.norm / vector2.norm",
"def cosine(fingerprint1, fingerprint2):\n return cosi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test thread creation after process attach. | def test_create_after_attach_with_fork(self):
self.build(dictionary=self.getBuildFlags(use_cpp11=False))
self.create_after_attach(use_fork=True) | [
"def start_test(self):\n self.logger.info('Test thread starts')\n self.test_thread.start()",
"def test_create_process(self):\n self.assertIsNotNone(self.pid)",
"def create_test_thread(self):\n return self.create_thread(\n function=test_function,\n name='test',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts the engine, which is in charge of running the all the routines. This method does not return unless there is a fatal erro with the engine. | def start_engine():
global _CONNECTION
global _ENGINE
_ENGINE = RemoteDispatchEngine(_CONNECTION)
engine_results_thread = threading.Thread(
target=_remote_dispatch_engine_result_thread)
engine_results_thread.start()
_ENGINE.start() | [
"def start_engine(self):\n if self.update: # if update specified\n self.start_update() # start the update process\n try:\n # Start the core process\n self.start_core_process()\n except KeyboardInterrupt:\n for process in self.process_pool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It adds inline comment to selected lines based on the file extesion. | def add_inline_comment(area):
comment = TABLE.get(os.path.splitext(area.filename)[1], DEFAULT)
area.replace_ranges('sel', '^ *|^\t*',
lambda data, index0, index1: '%s%s ' % (data, comment))
area.clear_selection()
area.chmode('NORMAL') | [
"def _comment_format(self, path):\n _, extension = os.path.splitext(path)\n return '# {}\\n' if extension == '.py' else '<!-- {} -->'",
"def test_include_filelist_with_full_line_comment(self):\n self.ParseTest([(\"--include-filelist\", \"file\")],\n [(), ('1',), ('1', '1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It removes the inline comments. | def rm_inline_comment(area):
comment = TABLE.get(os.path.splitext(area.filename)[1], DEFAULT)
area.replace_ranges('sel', '^ *%s ?|^\t*%s ?' % (comment, comment),
lambda data, index0, index1: data.replace(
'%s ' % comment, '').replace(comment, ''))
area.clear_selection()
area.chmode('NORMAL... | [
"def remove_commentlines(self):\n\n tmp = self.main.splitlines()\n tmp = list(itertools.filterfalse(re.compile(r\"^\\s*%.*$\").match, tmp))\n self.main = \"\\n\".join(tmp)",
"def remove_inline_comments(_code):\n lines = _code.split('\\n')\n counter = 0\n for i in range(len(lines)):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the u and fvalues at the collocation nodes > corresponds to a single sweep over all nodes | def update_nodes(self):
# get current level and problem description
L = self.level
P = L.prob
# only if the level has been touched before
assert L.status.unlocked
# get number of collocation nodes for easier access
M = self.coll.num_nodes
# initialize ... | [
"def update_nodes(self):\n\n # get current level and problem description\n L = self.level\n P = L.prob\n\n # only if the level has been touched before\n assert L.status.unlocked\n\n # get number of collocation nodes for easier access\n M = self.coll.num_nodes\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
3. Set Dispersion Size | def measureMomentumSpreadSetDispSize(self):
'''Fix Dispersion section needs work!'''
print 'does nothing' | [
"def setSize_0(self, size):",
"def resize(self, size):\r\n self.instance.resize_volume(size)\r\n self.size = size",
"def setSize(self, width, height):",
"def _set_resolution(self, size: (float, float)) -> None:\n self._stream.set(CAP_PROP_FRAME_WIDTH, size[0])\n self._stream.set(CA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
5. Calculate Momentum Spread | def measureMomentumSpreadCalc(self):
#if self.view.checkBox_4_s.isChecked()==True:
self.pSpread = self.func.calcMomSpread(self.Cmagnets,'DIP01',self.Is,self.I) | [
"def measureMomentumSpreadCalc(self):\n #if self.view.checkBox_4_s.isChecked()==True:\n self.beamSigma = self.cam.getSigX(self.C2Vcam)\n self.Is = self.beamSigma/self.Dispersion\n self.pSpread = self.func.calcMomSpread(self.Cmagnets,self.dipole,self.Is,self.data.values['I_rough'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the auth_ims_client_secret of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. | def auth_ims_client_secret(self, auth_ims_client_secret):
self._auth_ims_client_secret = auth_ims_client_secret | [
"def set_oauth_app_info(self, client_id, client_secret, redirect_uri):\n self.client_id = client_id\n self.client_secret = client_secret\n self.redirect_uri = redirect_uri",
"def get_client_secret_authorizer(self):\n client = globus_sdk.ConfidentialAppAuthClient(self.CLIENT_ID, self.CL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the customizer_type of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. | def customizer_type(self, customizer_type):
self._customizer_type = customizer_type | [
"def setCCM_TYPE(self, ccm_type) -> None:\n ...",
"def client_type(self, client_type):\n \n self._client_type = client_type",
"def set_image_type(self, content_type):\n content_types = RedditWallpaperChooser.constants.ACCEPTED_CONTENT_TYPES\n if content_type not in content_typ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the external ip informations for the service | def _process_external_ip(self):
self.infos.external_ip = self._find_external_ip()
self._log_information(key='External IP', value=self.infos.external_ip, ljust=18) | [
"def test_ip_addresses_update(self):\n pass",
"def test_ip_addresses_partial_update(self):\n pass",
"def set_apiip_to_ext(self):\n ip = self.s.get(GET_IP_URL).text.strip()\n # TODO test if ipv4 returned\n return self.set_apiip(ip)",
"def patch(self, request):\n addres... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the name informations for the service | def _process_service_name(self):
self.infos.service_name = self._bind_data(self.configuration['service']['name'])
self.infos.green_infos.stack['Parameters']['ServiceName']['Default'] = self.infos.service_name
self.infos.init_infos.stack['Parameters']['ServiceName']['Default'] = self.infos.servic... | [
"def update_service_definition(service_name):\n data = request.json\n if not data:\n abort(400, 'No data received')\n try:\n services[service_name] = {}\n services[service_name]['name'] = service_name\n services[service_name]['image'] = data['image']\n except KeyError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the version informations for the service | def _process_version(self):
version = 'latest'
if 'version' in self.configuration['service']:
version = str(self.configuration['service']['version'])
self.infos.service_version = version
self.infos.green_infos.stack['Parameters']['Version']['Default'] = self.infos.service_ver... | [
"def _update_info(self):",
"def update_version(self):\n if not hasattr(self, 'versions') and not hasattr(self, 'version_number'):\n self.version_number = 1\n \n if hasattr(self, 'version_number') and self.version_number < 2:\n try:\n if 'short_desc' in sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update the AWS vpc ID informations for the service | def _process_vpc_id(self):
self.infos.vpc_id = self._find_vpc_Id()
self._log_information(key='Vpc ID', value=self.infos.vpc_id, ljust=18) | [
"def modify_vpc_attribute(VpcId=None, EnableDnsSupport=None, EnableDnsHostnames=None):\n pass",
"def updateVpcTable(tableName,data,paGroupName):\n try:\n #VpcCidr is the primary key for VpcTable\n table=dynamodb.Table(tableName)\n item={\n 'VpcId': data['VpcId'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the AWS VPC by environment | def _find_vpc_Id(self):
ec2 = boto3.resource('ec2', region_name=self.infos.region)
client = boto3.client('ec2', region_name=self.infos.region)
ids = map(lambda x: x.id, list(ec2.vpcs.filter(Filters=[])))
for id in ids:
response = client.describe_vpcs(VpcIds=[id])
... | [
"def get_vpc_from_env(self, env):\n vpcs = self.get_all_vpcs(filters=[{\"Name\": \"tag:Environment\", 'Values': [env]}])\n if len(vpcs) == 1:\n return vpcs[0]\n else:\n logger.error(\"Multiple envs found: %s\" % (env,))\n raise ValueError",
"def get_vpc_id(acc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the AWS ECS cluster by name | def _find_cluster(self, clusterName):
client = boto3.client('ecs', region_name=self.infos.region)
response = client.list_clusters()
for arn in response['clusterArns']:
if arn.endswith(clusterName):
return arn
raise ValueError(f'Cluster "{clusterName}" not foun... | [
"def get_cb_cluster_by_name(self, name):\n for cluster in self.clusters:\n if cluster.name == name:\n return cluster\n raise Exception(\"Couchbase Cluster %s does not exist\" % name)",
"def elasticsearch_cluster(self, name, site):\n try:\n endpoint = elast... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the external ip | def _find_external_ip(self):
data = None
try:
data = json.loads(urllib.request.urlopen("https://api.ipify.org?format=json").read())
if 'ip' in data:
return data['ip']
except Exception:
pass
return data | [
"def getPublicIp():\n try:\n data = str(urlopen('http://checkip.dyndns.com/').read())\n #data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\\r\\n'\n externalip = re.compile(r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)').s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Counts the number of vowels in an English word. | def countVowels(word):
# initialize count
count = 0
# loop over letters in word
for letter in word.lower(): # convert word to all lower-case
# increment counter if letter is a vowel
if letter in ('a', 'e', 'i', 'o', 'u'):
count = count + 1
... | [
"def num_vowels(word):\n return sum(char in VOWELS for char in word.lower())",
"def count_vowel(s):\n count = 0\n for i in s:\n\tif i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':\n\t count += 1\n print \"Number of vowels:%d\" %count",
"def count_vowels(s):\r\n\r\n count_vowels = 0\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main function to execute the vowelcounting program. Returns None. | def main():
# program greeting
print('*'*58)
print('Welcome to the vowel-counting program!\n')
print('This program counts the number of vowels in English words.')
print('*'*58)
# get word
word = getWord()
# count vowels
count = countVowels(word)
# di... | [
"def count_vowel(s):\n count = 0\n for i in s:\n\tif i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u':\n\t count += 1\n print \"Number of vowels:%d\" %count",
"def main():\n # set up the program to take in arguments from the command line",
"def test_example_5(self):\n self.assertEq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the severity ranking of an SO term. | def severity(so_term):
try:
return ENSEMBL_SO_SEVERITY_ORDER.index(so_term)
except ValueError:
warnings.warn('Unexpected Sequence Ontology term: %s' % so_term)
# If the SO term is not in ENSEMBL_SO_SEVERITY_ORDER, its severity
# ranking is assumed to be +inf (least severe)
... | [
"def getSeverity(self):\n if not self.lastType:\n return RO.Constants.sevNormal\n return TypeDict[self.lastType][1]",
"def translate_score(self, severity):\n\n if not self.score_stats.has_key(severity):\n self.score_stats[severity] = 1\n else:\n self.sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close the file if it's already open. | def closefile_ifopen(self):
if (self.filep == None):
return
# close file and clear it
self.filep.close()
self.filep = None | [
"def _close_file(self):\n self._iostream.close()\n self._fileobj.close()",
"def close_file():\n lib_close.close_file()",
"def close_file(self):\n self.file_handler.close()",
"def close (self):\r\n\r\n self.file.close ()\r\n self.file = None\r\n self.filename = None... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adjusts the simulation configuration to the current independent variable value. | def configure_simulation(independent_variable_value, input_params, empirical_profile, original_team_size,
configuration_function, simulation_configuration):
return configuration_function(independent_variable_value=independent_variable_value, input_params=input_params,
... | [
"def reset_dynamic_variables(self):\n\n start_ix = 0\n end_ix = self.episode_tracker.episode_time_steps\n self.energy_simulation.cooling_demand[start_ix:end_ix] = self.energy_simulation.cooling_demand_without_control.copy()[start_ix:end_ix]\n self.energy_simulation.heating_demand[start_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test orientation of PNG files | def testOrientation( self ) :
img = Reader.create( "test/IECore/data/png/uvMap.512x256.8bit.png" ).read()
ipe = PrimitiveEvaluator.create( img )
self.assert_( ipe.R() )
self.assert_( ipe.G() )
self.assert_( ipe.B() )
self.failIf ( ipe.A() )
result = ipe.createResult()
colorMap = {
V2i( 0 , 0 )... | [
"def testOrientation( self ) :\n\n\t\timg = Reader.create( \"test/IECore/data/tiff/uvMap.512x256.8bit.tif\" ).read()\n\n\t\tipe = PrimitiveEvaluator.create( img )\n\t\tself.assert_( ipe.R() )\n\t\tself.assert_( ipe.G() )\n\t\tself.assert_( ipe.B() )\n\t\tself.failIf ( ipe.A() )\n\n\t\tresult = ipe.createResult()\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a FITS image file and returns a numpy array | def readFITS(fn,hdr=False):
hdulist=pf.open(fn)
im=hdulist[0].data
hdulist.close()
if hdr:
return im[0,0],getFITSInfo(fn)
else: return im[0,0] | [
"def open_image(infile):\n with fits.open(infile) as f:\n header = f[0].header\n data = f[0].data\n if ((data.ndim == 3 and data.shape[0] != 1) or\n (data.ndim == 4 and data.shape[1] != 1)):\n # NAXIS=3: [FREQ!=1, Y, X]\n # NAXIS=4: [STOKES, FREQ!=1, Y, X]\n raise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read a pickle file, expected format is a NxM numpy array | def readArrayPkl(fn):
fh=open(fn,'rb')
im=pickle.load(fh)
fh.close()
return im | [
"def dem_file_read(self, file_path):\n with open(file_path, 'rb') as handle:\n dem_array_data = pickle.load(handle)\n handle.close()\n return dem_array_data",
"def load_numpy_object_demo(file_name: Path)\\\n -> Union[np.ndarray, np.recarray]:\n return np.load(str(file_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the FITS header for pointing and pixel size information return [RA,DEC], pixel resolution, pixel of [RA,DEC] | def getFITSInfo(fn):
hdulist=pf.open(fn)
hdr=hdulist[0].header
#CTYPE1: RA---[PROJ], projection SIN/TAN/ARC
#CRVAL1: reference RA position in degrees
#CRPIX1: location of reference pixel
#CDELT1: delta RA/pixel size in degrees
#CTYPE2: DEC--[PROJ], projection SIN/TAN/ARC
#CRVAL2: referen... | [
"def get_info_from_header(fits):\n hdr = pyfits.getheader(fits, 1)\n odate = hdr['DATE-OBS']\n obsid = hdr['OBS_ID']\n expo = hdr['EXPOSURE']\n expo = float(expo)\n atemp = re.split('-', odate)\n year = float(atemp[0])\n mon = float(atemp[1])\n fyear = year + mon/12\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write hermite coeffs and meta data to a pickle file | def writeHermiteCoeffs(fn,coeffs,xc,size,beta,norder,pos=[0.,0.,0.,0.],mode='hermite',info=''):
d={ 'coeffs':coeffs,
'mode':mode,
'xc':xc,
'size':size,
'beta':beta,
'norder':norder,
'ra':pos[0],
'dec':pos[1],
'dra':pos[2],
'ddec':pos[2],
... | [
"def writeHessian(self):\n\t\tself.makeHessian()\n\t\tnp.savetxt(\"hessian.dat\",self.H,\"%15.7f\",\" \",\"\\n\")",
"def writeLageurreCoeffs(fn,coeffs,xc,size,beta,norder,pos=[0.,0.,0.,0.],mode='laguerre',info=''):\n d={ 'coeffs':coeffs,\n 'mode':mode,\n 'xc':xc,\n 'size':size,\n 'b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write Lageurre coeffs and meta data to a pickle file | def writeLageurreCoeffs(fn,coeffs,xc,size,beta,norder,pos=[0.,0.,0.,0.],mode='laguerre',info=''):
d={ 'coeffs':coeffs,
'mode':mode,
'xc':xc,
'size':size,
'beta':beta,
'norder':norder,
'ra':pos[0],
'dec':pos[1],
'dra':pos[2],
'ddec':pos[2],
... | [
"def dump(self):\n import pickle as pkl\n \n filename = self.create_output_name(step=self.time_step_count)\n filename = filename.replace('.bin','.pkl')\n file = open(filename, \"wb\")\n pkl.dump(self, file)\n file.close()",
"def pickleModel(self):\n print 'Saving model to file...'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
At present readLageurreCoeffs and readHermiteCoeffs do the same operations | def readCoeffs(fn):
return readHermiteCoeffs(fn) | [
"def _read_coefficients(self):\n coeff = self._read_register(_BME280_REGISTER_DIG_T1, end=24)\n coeff = list(unpack('<HhhHhhhhhhhh', bytearray(coeff)))\n coeff = [float(i) for i in coeff]\n self._temp_calib = coeff[:3]\n self._pressure_calib = coeff[3:]\n\n self._humidity_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that predicted binding value falls within the specified (min,max) range or raise an assertion error. | def check_binding_value(self, value):
assert isinstance(value, (int, float)), \
"Expected float for binding value, got %s : %s" % (
value, type(value))
if self.min_inclusive:
assert value >= self.min_value, \
"Given value (%s) too low (min_value=%... | [
"def _check_bounds(value, varname, minmax=(0, 1)):\n if value < minmax[0] or value > minmax[1]:\n raise AssertionError(f\"{varname} is not in {minmax}\")",
"def _check_bounds(lower_bound: float, upper_bound: float) -> None:\n if lower_bound > upper_bound:\n raise ValueError(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Is the predicted binding value stronger than the given cutoff? | def value_is_binder(self, value, cutoff):
self.check_binding_value(value)
if self.cutoff_is_upper_bound:
return value <= cutoff
else:
return value >= cutoff | [
"def test_broker_weight_cv(self):\n assert abs(self.state.broker_weight_cv - 0.4040) < 1e-4",
"def test_broker_leader_weight_cv(self):\n assert abs(self.state.broker_leader_weight_cv - 1.3030) < 1e-4",
"def spread_to_binary(spread, cutoff):\n return spread > cutoff",
"def has_weight(self) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets current seating chart from the Google Sheet. | def get_seating_chart(self):
seating = {} # keys = periods, values = 2D arrays
service = build('sheets', 'v4', credentials=self.credentials) # Call the Sheets API
sheet = service.spreadsheets()
for period in self.schedules[self.year].keys():
array = [] # Array to hold the... | [
"def _workbook(self):\n return self._chart_part.chart_workbook",
"def spreadsheets(self):\n # Get the list of spreadsheets\n feed = self.gd_client.GetSpreadsheetsFeed()\n self._PrintFeed(feed)\n return feed",
"def get_today_on_duty_name_n_team():\n # print(f'gcp_account_info {json.loads(gc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets class list for each requested period. | def get_class_lists(self):
print('Getting class lists...')
students = {} # key = periods, values = list of names
ss_range = 'Summary!B3:H40' # Spreadsheet range for source sheet.
service = build('sheets', 'v4', credentials=self.credentials) # Call the Sheets API
sheet = servic... | [
"def scrap_classes():\n\n config = load_config()\n session = requests.session()\n\n with session.post('https://myclass.apps.binus.ac.id/Auth/Login', data={\n 'Username': config['login']['username'],\n 'Password': config['login']['password'],\n 'btnSubmit': True\n }) as response:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates seating for the requested periods. | def update(self):
print('Updating seating chart...')
for period in self.periods:
if period in self.class_lists:
new_seating, version = self.new_tables(period)
self.seating_chart[period] = new_seating
# Verify success:
if new_se... | [
"def update_time_period(self, time_period_form):\n pass",
"def write_names(self):\n print('Writing to spreadsheet...')\n service = build('sheets', 'v4', credentials=self.credentials) # Call Google Sheets API.\n\n for period in self.periods:\n if period in self.class_lists:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes updated seating to Google Sheet. | def write_names(self):
print('Writing to spreadsheet...')
service = build('sheets', 'v4', credentials=self.credentials) # Call Google Sheets API.
for period in self.periods:
if period in self.class_lists:
seating_update = self.extend_array(copy.deepcopy(self.seating... | [
"def update_google(season_data, sheet):\n pass",
"def editGoogleSheet(client, data, timeStamp):\r\n\r\n #get the current worksheet\r\n worksheet_feed = client.GetWorksheetsFeed(config.speedsheet_id)\r\n\r\n for d in data:\r\n\r\n #find the sheet name we care about\r\n for entry in workshee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Processes user input to determine which periods need new seating arrangements. | def get_periods(self, user_input):
active_periods = list(self.schedules[self.year].keys())
if user_input == 'all':
periods = active_periods.copy()
print('New Seats: {}'.format(periods))
return periods
choices = list(user_input)
periods = []
for... | [
"def main():\n print('This program takes dates from a file, or user input, and validates that it fits the format:\\n[d/dd]/[0m/m/mm/first 3 characters of month]/[yy/yyy] seperated by /,-, or <space>.\\n')\n op = input('Would you like to read(r) dates file or manually(m) input a date? [r|m|exit]\\n')\n whil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes seating update to storage.json. | def update_storage(self):
print('Updating storage...')
update = self.create_update()
try:
with open('storage.json', 'r+') as storage:
storage_data = json.load(storage)
storage_data["Updates"].append(update)
storage.seek(0)
... | [
"def __write_store__(self):\n store_file = open(os.path.join(os.path.expanduser('~'), Dhop.DHOP_STORE), 'w')\n json_str = json.JSONEncoder().encode(self.store)\n store_file.write(json_str)\n store_file.close()\n return",
"def save(self):\r\n try:\r\n with open(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines appropriate number of tables for a given class size. | def number_of_tables(class_size):
if class_size in [1, 2, 3]:
return 1
if class_size in [4, 5, 6]:
return 2
if class_size in [7, 9]:
return 3
return 4 | [
"def n_tables(self) -> int:\n return self._d",
"def get_table_size(self) -> int:\r\n return self.table_size",
"def db_table_size(self, cls):\r\n with self.__conn.cursor() as cursor:\r\n cursor.execute(\r\n \"select round(bytes/1024/1024,3)|| 'MB'\\n\"\\\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extends array to 4X6. | def extend_array(array):
for row in array:
while len(row) < 6:
row.append('')
while len(array) < 4:
array.append(['', '', '', '', '', ''])
return array | [
"def extend(self):\n new_size = self.size * self.extension_factor\n new_array = [None] * new_size\n new_array[:self.size] = self.array\n self.array = new_array\n self.size = new_size\n # Don't touch self.index",
"def extend_array(array, max_row):\n\n shape = array.shap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return True if btw between a and b | def between(s, btw, a, b):
s = s.replace('::', '') # ignore std::, etc.
ai = s.rfind(a)
bi = s.rfind(b)
btwi = s.rfind(btw)
return True if btwi < bi and btwi > ai else False | [
"def dominates(a, b):\n return np.all(a <= b)",
"def is_between(thetas, lower, upper):\n lower, upper = correct_angle(np.array([lower, upper]))\n if lower <= upper:\n return (lower <= thetas) & (thetas <= upper)\n else: # if upper loops around\n return (upper <= thetas) & (thetas <= low... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prioritizing structural variants in a VCF file annotated with SnpEff. | def main(input_file, output_file=None, genome=None):
vcf = cyvcf2.VCF(input_file or '-')
add_cyvcf2_hdr(vcf, 'SIMPLE_ANN', '.', 'String',
"Simplified structural variant annotation: 'SVTYPE | EFFECT | GENE(s) | TRANSCRIPT | PRIORITY (1-4)'")
add_cyvcf2_hdr(vcf, 'SV_TOP_TIER', '1', 'Integer',
... | [
"def filter_somatic_score(\n input_vcf: str,\n output_vcf: str,\n *,\n tumor_sample_name: str = \"TUMOR\",\n drop_somatic_score: int = 25,\n min_somatic_score: int = 40,\n) -> None:\n logger = Logger.get_logger(\"filter_somatic_score\")\n logger.info(\"Filters SomaticSniper VCF files based o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the annotations for a particular transcript and parse them to find the numbers of the exons that have been deleted | def find_deleted_exons(annotations):
exons = []
gene = ''
for anno_fields in annotations:
_, _, _, g, _, _, _, _, rank, _, _ = anno_fields[:11]
gene = gene or g
try:
exons.append(int(rank.split('/')[0]))
except ValueError:
pass
return exons, gene | [
"def annotate_du_file(xmlfile,results):\n outfile = xmlfile.replace(\".xml\", \"_visasAnnot_temp.xml\")\n tree = ET.parse(IN + xmlfile)\n root = tree.getroot()\n sentID = 0\n for par in root.iter(\"utterance\"):\n for sent in par:\n sentID += 1\n remove_results = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the exon loss simple annotation from the exon dict created in simplify_ann For each transcript with exon losses, find the numbers for each exon and create the annotation | def annotate_exon_loss(exon_loss_anno_by_tid, prioritised_genes):
annos = set()
for transcript, annotations in exon_loss_anno_by_tid.items():
exons, gene = find_deleted_exons(annotations)
exons = list(set(exons))
if len(exons) == 0:
return None
if max(exons) - min(ex... | [
"def write_novel_exon_statistics(self, annotation):\n\n # loop over the novel exon\n for novel_exon in self.confident_novel_exons:\n\n # split the exon\n sp = novel_exon.split(\":\")\n\n # determine splice in reads (all and\n # the ones that fall exactly in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current application id. | def getApplicationId():
return app_identity.get_application_id() | [
"def app_id(self):\n return self._app_id or self._modules['default'].data['application']",
"def id(cls) -> Global:\n return Global.current_application_id()",
"def get_app_id():\n return yaml.safe_load(open(APP_DIR + '/app.yaml'))['application']",
"def applicationId():\n try:\n import cs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the applications email address. | def getApplicationEmail(name):
app_id = getApplicationId()
assert app_id
return "%s@%s.appspotmail.com" % (name, app_id) | [
"def email_address(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"email_address\")",
"def get_email(self):\r\n return self.email",
"def email(self):\n return '{}.{}@email.com'.format(self.first, self.last)",
"def provider_email(self) -> str:\n return pulumi.get(self, \"pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the applications noreply email address. | def getApplicationNoReplyEmail():
return getApplicationEmail('no-reply') | [
"def getApplicationEmail(name):\n app_id = getApplicationId()\n assert app_id\n\n return \"%s@%s.appspotmail.com\" % (name, app_id)",
"def email_address(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"email_address\")",
"def email_reply_to_address(self) -> ConfigNodePropertyString:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Google App Engine "version" of the running instance. | def getAppVersion():
return os.environ.get('CURRENT_VERSION_ID') | [
"def version(self):\n\t\treturn self.query('SELECT VERSION()',1)[0]",
"def get_version() -> str:\n return VERSION",
"def version(self):\n\n return self.__entity[\"version\"]",
"def do_version():\n v = ApiPool.ping.model.Version(\n name=ApiPool().current_server_name,\n version=ApiPoo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Melange part of the GAE version. | def getMelangeVersion():
return getAppVersion().split('.', 1)[0] | [
"def full_version(self):\n return '%d.%d%s @ %d' % (self._version_major, self._version_minor,\n self._beta, self._id)",
"def get_version() -> str:\n return VERSION",
"def getAtmVersion(self):\n _getAtmVersion_result = _str_dc(self._swigobj.getAtmVersion())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if Melange application is running in "debug mode". "Debug mode" is currently enabled if running locally or if the current Melange version is 'devvin'. | def isDebug():
return isLocal() or getMelangeVersion() == 'devvin' | [
"def debuggable(self):\n return self._root.find(\"application\").get(\n \"debuggable\", \"false\") == \"true\"",
"def is_debug(self): # type: () -> bool\n return self._verbosity == DEBUG",
"def debug_enable(self) -> bool:\n return pulumi.get(self, \"debug_enable\")",
"def debu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Imports CSharpExtension into global context. | def add_csharpml_extension():
AddReference("CSharPyMLExtension") | [
"def when_extension_has_loaded(context):\n uitests.vscode.extension.activate_python_extension(context)",
"def given_extension_has_loaded(context):\n uitests.vscode.extension.activate_python_extension(context)",
"def test_import_extension(test_module):\n import_path = 'fake_extension:FakeExtension'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A test to ensure changing the message format is prohibitively annoying | def test_verify_message_format(self):
def message_assert(message):
fields = [('publisher_id', 'publisher_id'),
('event_type', 'event_type'),
('priority', 'WARN'),
('payload', dict(a=3))]
for k, v in fields:
... | [
"def test_reformat_email_4(self):\n email = 'test@examplecom'\n self.assertEqual(self.cmd.reformat_email(email), 'Not available')",
"def test_reformat_email_1(self):\n email = ''\n self.assertEqual(self.cmd.reformat_email(email), 'Not available')",
"def test_reformat_email_2(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines whether point correspondences are in front of both images | def _in_front_of_both_cameras(first_points, second_points, rot, trans):
rot_inv = rot
for first, second in zip(first_points, second_points):
first_z = np.dot(rot[0, :] - second[0] * rot[2, :], trans) / np.dot(
rot[0, :] - second[0] * rot[2, :], second)
first_3d_point = np.array(
... | [
"def is_neighboured (point_1, point_2, size_of_system):\r\n p1 = np.array([point_1%size_of_system, point_1//size_of_system])\r\n p2 = np.array([point_2%size_of_system, point_2//size_of_system])\r\n diff = abs(p1 - p2)\r\n if (diff[0] + diff[1]) == 1:\r\n return True\r\n return False",
"def e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triangulation via LinearLS method | def _linear_ls_triangulation(u1, P1, u2, P2):
# build A matrix for homogeneous equation system Ax=0
# assume X = (x,y,z,1) for Linear-LS method
# which turns it into AX=B system, where A is 4x3, X is 3x1 & B is 4x1
A = np.array([
u1[0] * P1[2, 0] - P1[0, 0], u1[0] * P1[2, 1] - P1[0, 1],
... | [
"def triangulate(self):\n # pre-condition: we should have at least 3 points\n i=0\n lista_t=[]\n assert len(self.points) > 2\n #print self.points[1].x\n gen=group3(len(self.points))\n # print range(math.factorial(len(self.points))/(math.factorial(3)*math.factorial(len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean airports dataset filtering only US airports and discarding data that is not an airport("large_airport", "medium_airport", "small_airport"). Extract iso regions and cast fields as required. | def get_airports_cleansed(self,dfairport):
dfairport.createOrReplaceTempView("Airport")
cl_dfairport=self.spark.sql("""
select a.*,substring(iso_region,-2)state_code from Airport a
where iso_country='US'
and type in ("large_airport", "medium_airport", "small_ai... | [
"def clean_airports(airports_spark, spark_session):\n spark = spark_session\n airports_spark.createOrReplaceTempView('airports')\n \n airports_spark_cleaned = spark.sql(\"\"\"\n SELECT ident, name, municipality as City, SUBSTRING(iso_region, 4, 5) as State, iata_code\n FROM airports\n WHERE iat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean ports dataset to get the port code and state code for only USA | def get_ports_cleansed(self,dfports):
dfports.createOrReplaceTempView("Port")
cl_dfport=self.spark.sql("""
select code as port_code,airport_name,substring_index(airport_name, ',', -1) port_state_code from Port p
""")
return cl_dfport | [
"def get_airports_cleansed(self,dfairport):\n dfairport.createOrReplaceTempView(\"Airport\")\n cl_dfairport=self.spark.sql(\"\"\"\n select a.*,substring(iso_region,-2)state_code from Airport a\n where iso_country='US'\n and type in (\"large_airport\", \"medium_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean countries dataset to add a column as valid/invalid | def get_countries_cleansed(self,dfcountries):
dfcountries.createOrReplaceTempView("Countries")
cl_dfcountries=self.spark.sql("""
select code as country_code,country_name,case when country_name like '%INVALID%' or country_name like '%Collapsed%' or country_name like '%No Country Code%' then... | [
"def preprocess_with_interpolation(training_set):\n \n X = training_set.copy()\n \n X['continent'] = ''\n \n missing = []\n \n for index, row in X.iterrows(): \n \n country = pycountry.countries.get(name = row['Country Name'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Places a token on the board at some given coordinates. 0, 0 is the topleft. `player` is either 'X' or 'O' | def place_token(self, x, y, player):
self.rows[y][x] = player | [
"def place_token(self, x, y, token):\n if x == 0:\n x_letter = 'a'\n elif x == 1:\n x_letter = 'b'\n else:\n x_letter = 'c'\n y_letter = str(y + 1)\n key = x_letter + y_letter\n self.pos_to_token[key] = token",
"def place_token(self, x, y,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Places a token on the board at some given coordinates. 0, 0 is the topleft. `player` is either 'X' or 'O' | def place_token(self, x, y, token):
if x == 0:
x_letter = 'a'
elif x == 1:
x_letter = 'b'
else:
x_letter = 'c'
y_letter = str(y + 1)
key = x_letter + y_letter
self.pos_to_token[key] = token | [
"def place_token(self, x, y, player):\n self.rows[y][x] = player",
"def place_token(self, x, y, token):\n (self._rows[y])[x] = token",
"def placeSymbol(self,posY, posX, player):\n \"\"\"posX and posY are referenced to the board as carthesian values\"\"\"\n print((posY,posX))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request access to public server, returning port and IP address. | def _server():
url = 'https://104.131.128.139/tcp'
headers = {'X-Auth-Key': 'abc', 'X-Auth-Secret': 'abc'}
try:
return requests.get(url, headers=headers, verify=False).json()
except requests.exceptions.ConnectionError:
logging.error('server is unreachable')
... | [
"def page1(self):\n result = request101.GET('/whatIsMyIPAddress')\n return result",
"def page66(self):\n self.token__ = \\\n timestr()\n result = request6601.GET('/whatIsMyIPAddress' +\n '?_=' +\n self.token__)\n return result",
"def check_access(self, uid, host, port):\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Example for fetching each profile that is linked to a Bungie.net account, then finding the data that you last played on each profile. | async def main():
myAccount = await client.get_user("MembershipID") # 4611686018464828555 for example
for profile in myAccount.destinyMemberships:
print("{0}: {1}: {2}".format(profile.displayName, conversionDict[profile.membershipType], profile.membershipId))
myProfile = await client.get_profile... | [
"def get_profiles(remote):\n\n profiles = remote.find_profile({\"name\": \"edu-*-frontend\"})\n my_profiles = []\n \n for profile in profiles:\n my_profiles.append(profile[:(len(profile)-9)])\n\n return my_profiles",
"def fetch_qarnot_profiles():\n global script_dialog\n\n # disable su... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predict the target value for example. Consider each possible value, choose the most likely, by looking at each attribute independently. | def predict(self, example):
possible_values = self.dataset.values[self.dataset.target]
def class_probability(targetval):
return product([self.P(targetval, a, example[a])
for a in self.dataset.inputs]) #removed ',1' from the arglist as product takes a list of vals... | [
"def predict(self, test_example):\r\n\r\n probs = self.features[0].get_probs(test_example[0])\r\n for i, feature in enumerate(test_example):\r\n probs *= self.features[i].get_probs(feature)\r\n total_examples = sum(self.total)\r\n probs *= self.total\r\n return CLASS_LABELS[np.argmax(probs)]",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> _int('5') 5 >>> _int('Abacate') nan | def _int(v):
try:
return int(v)
except Exception:
return float("nan") | [
"def _to_int(string):\n if string == \"\":\n return 0\n return int(string)",
"def conv_int(i):\n return int(i) if i.isdigit() else i",
"def int_conv(string):\n try:\n intstring=int(string)\n except:\n intstring=999\n return intstring",
"def _to_int( self, str ):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> _float('5') 5.0 >>> _float('Abacate') nan | def _float(v):
try:
return float(v)
except Exception:
return float("nan") | [
"def FloatConv(string):\n try:\n v = float(string)\n except ValueError:\n v = numpy.NaN\n return v",
"def nan(self):\r\n\t\treturn float(\"nan\")",
"def _plain_float(value: str) -> float:\n if _plain_float_re.fullmatch(value) is None:\n raise ValueError\n\n return float(value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> _selected("peixe abacate", "peixe") True | def _selected(x, y):
return y in x | [
"def _has_selection(obj: object) -> bool:\n if obj is None or not isinstance(obj, str):\n return False\n return obj.lower() not in [\"\", \"no selection\"]",
"def is_selected(self):\r\n arg_str = p2e._base._util._convert_args_to_string(\"get.object.selected\", \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a skeleton stuffed animal Halloween themed item. | def create(self, has_glow="", **kwargs):
return Skeleton(has_glow, **kwargs) | [
"def generateItem(self, platform):\n blockItem = Block(IMG_PATH_BLOCK, platform.x+platform.w/2-15, platform.y-50, (30, 30))\n healthItem = Health(platform.x+platform.w/2-15, platform.y-50, (30, 30))\n coinItem = Coin(platform.x+platform.w/2-15, platform.y-50, (30, 30))\n self.otherMovabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a ThingSpeakWriter object for manual verification | def write_test():
writer = ThingSpeakWriter(c.L2_M_5A2_WRITE_KEY)
test_date = datetime.now().strftime("%Y-%m-%d")
test_time = datetime.now().strftime("%H:%M:%S")
fields = {c.TEST_FIELD: "{} {}".format(test_date, test_time)}
logging.info('Writing {} {} to {}'.format(test_date, test_time, c.TEST_FI... | [
"def makeTxt():\n print('start')\n model = KeyedVectors.load_word2vec_format('\\\\\\\\smbhome.uscs.susx.ac.uk\\\\ls612\\\\Documents\\\\Dissertation\\\\LSTM-PICO-Detection-master\\\\other_spyder\\\\Extended embeddings\\\\2019-07-19-09-34-51-bigrams_FINAL.bin', binary=True)#, limit = 20 for tests\n model.sav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Proxmox VE API client. | async def get_client(conf):
from proxmoxer import ProxmoxAPI
host = conf[CONF_HOST]
port = conf[CONF_PORT]
user = conf[CONF_USERNAME]
realm = conf[CONF_REALM]
password = conf[CONF_PASSWORD]
verify_ssl = conf[CONF_VERIFY_SSL]
proxmox = ProxmoxAPI(
host, user=user + '@' + realm, pa... | [
"def get_nova_client(session):\n from novaclient import client\n return client.Client('2', session=session)",
"def zeep_client(self) -> ZeepClient:\n if self._zeep_client is None:\n self._zeep_client = Oauth2Request.get_soap_client()\n return self._zeep_client",
"def get_client(ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |