query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
This function takes the attributes of a Plan and saves them in a tuple | def simplify(worker: AbstractWorker, plan: "Plan") -> tuple:
if not plan.is_built:
raise RuntimeError("A Plan needs to be built before being serialized.")
return (
sy.serde.msgpack.serde._simplify(worker, plan.id),
sy.serde.msgpack.serde._simplify(worker, plan.role),... | [
"def simplify(plan: \"Plan\") -> tuple:\n return (\n tuple(\n plan.readable_plan\n ), # We're not simplifying because readable_plan is already simplified\n sy.serde._simplify(plan.id),\n sy.serde._simplify(plan.arg_ids),\n sy.serde._simpl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function reconstructs a Plan object given its attributes in the form of a tuple. | def detail(worker: AbstractWorker, plan_tuple: tuple) -> "Plan":
(id_, role, include_state, name, tags, description, torchscript, input_types) = plan_tuple
id_ = sy.serde.msgpack.serde._detail(worker, id_)
role = sy.serde.msgpack.serde._detail(worker, role)
name = sy.serde.msgpack.serde... | [
"def simplify(plan: \"Plan\") -> tuple:\n return (\n tuple(\n plan.readable_plan\n ), # We're not simplifying because readable_plan is already simplified\n sy.serde._simplify(plan.id),\n sy.serde._simplify(plan.arg_ids),\n sy.serde._simpl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes the attributes of a Plan and saves them in a Protobuf message | def bufferize(worker: AbstractWorker, plan: "Plan") -> PlanPB:
if not plan.is_built:
raise RuntimeError("A Plan needs to be built before being serialized.")
protobuf_plan = PlanPB()
sy.serde.protobuf.proto.set_protobuf_id(protobuf_plan.id, plan.id)
protobuf_plan.role.CopyF... | [
"def test_plan_serialization(self):\n\n # Construct dict forms of any model objects needed in order to build this model.\n\n feature_model = {} # Feature\n feature_model['title'] = 'testString'\n feature_model['description'] = 'testString'\n\n deployment_model = {} # Deployment\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function reconstructs a Plan object given its attributes in the form of a Protobuf message | def unbufferize(worker: AbstractWorker, protobuf_plan: PlanPB) -> "Plan":
id_ = sy.serde.protobuf.proto.get_protobuf_id(protobuf_plan.id)
role = sy.serde.protobuf.serde._unbufferize(worker, protobuf_plan.role)
name = protobuf_plan.name
tags = set(protobuf_plan.tags) if protobuf_plan.ta... | [
"def bufferize(worker: AbstractWorker, plan: \"Plan\") -> PlanPB:\n if not plan.is_built:\n raise RuntimeError(\"A Plan needs to be built before being serialized.\")\n\n protobuf_plan = PlanPB()\n\n sy.serde.protobuf.proto.set_protobuf_id(protobuf_plan.id, plan.id)\n\n protobu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Injects a service into the endpoint handler One kwarg to inject endpoint self | def set_service(self):
if self.service:
self.service = self.service(
json=self.json,
google_user=self.google_user,
endpoint=self
) | [
"def custom_service_endpoint(self) -> global___Snippet.ClientInitialization.ServiceEndpoint:",
"def endpoint_service(self, endpoint_service: ModelInstanceEndpoint):\n self._endpoint_service = endpoint_service",
"def register_service(self, service):\n return",
"def _add_endpoint(self, endpoint=No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a layer from the ``decoded_data`` to a PIL image. | def extract_layer_image(decoded_data, layer_index):
layers = decoded_data.layer_and_mask_data.layers
layer = layers.layer_records[layer_index]
return _channel_data_to_PIL(
channel_data = layers.channel_image_data[layer_index],
channel_ids = _get_layer_channel_ids(layer),
color_mode ... | [
"def convert_layer_to_pil(layer):\n from PIL import Image\n header = layer._psd._record.header\n if header.color_mode == ColorMode.BITMAP:\n raise NotImplementedError\n width, height = layer.width, layer.height\n channels, alpha = [], None\n for ci, cd in zip(layer._record.channel_info, lay... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a composite (merged) image from the ``decoded_data`` to a PIL image. | def extract_composite_image(decoded_data):
header = decoded_data.header
size = header.width, header.height
if size == (0, 0):
return
channel_ids = _get_header_channel_ids(header)
if channel_ids is None:
warnings.warn("This number of channels (%d) is unsupported for this color mode (... | [
"def extract_layer_image(decoded_data, layer_index):\n layers = decoded_data.layer_and_mask_data.layers\n layer = layers.layer_records[layer_index]\n\n return _channel_data_to_PIL(\n channel_data = layers.channel_image_data[layer_index],\n channel_ids = _get_layer_channel_ids(layer),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return ICC image profile if it exists and was correctly decoded | def get_icc_profile(decoded_data):
# fixme: move this function somewhere?
icc_profiles = [res.data for res in decoded_data.image_resource_blocks
if res.resource_id == ImageResourceID.ICC_PROFILE]
if not icc_profiles:
return None
icc_profile = icc_profiles[0]
if isinstan... | [
"def _apply_icc(image, icc_profile):\n from io import BytesIO\n try:\n from PIL import ImageCms\n except ImportError:\n logger.debug('ICC profile found but not supported. Install little-cms.')\n return image\n\n if image.mode not in ('RGB', ):\n logger.debug('%s ICC profile i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply opacity to an image. | def apply_opacity(im, opacity):
if im.mode == 'RGB':
im.putalpha(opacity)
return im
elif im.mode == 'RGBA':
r, g, b, a = im.split()
opacity_scale = opacity / 255
a = a.point(lambda i: i*opacity_scale)
return Image.merge('RGBA', [r, g, b, a])
else:
rais... | [
"def reduce_opacity(image, opacity):\n assert opacity >= 0 and opacity <= 1\n if image.mode != RGBA:\n image = image.convert(RGBA)\n else:\n image = image.copy()\n alpha = image.split()[3]\n alpha = Imag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str, names of pins | def get_pinnames(self):
return self.pnames | [
"def pins_string_list(self):\n return '[{}, {} and {}]'.format(*self.motor_pins)",
"def __str__(self):\n return '\\n' + self.name + ': ' + self.description + '\\n ' + '\\n '.join(\n [p.__str__() for p in self.pins])",
"def get_pins_name_from_net(self, pin_list, net_name):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test timings. Process all the configuration files in the test_config directory matching timing_.yaml and check the results. | async def test_timings(hass: ha.HomeAssistant, skip_setup):
for fname in glob.glob(test_config_dir + "timing_*.yaml"):
print(f"Processing: {fname}")
config = CONFIG_SCHEMA(load_yaml_config_file(fname))
if ha.DOMAIN in config:
await async_process_ha_core_config(hass, config[ha.D... | [
"def main(cfg: DictConfig):\n benchmark_time(cfg)",
"def test_peformance(self):\n timedeltas = []\n for file in os.listdir(settings.ANALYSIS_REPORT_FOLDER):\n _file = open(os.path.join(settings.ANALYSIS_REPORT_FOLDER, file), \"r\")\n report = json.loads(_file.read())\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Suitable for sorting array length of which is far bigger than alphabet O(n) = R + N where R is alphabet N is len of array Sort is stable | def count_sorting(array):
count = Counter(array)
alphabet = sorted(count.keys())
for letter, next_letter in zip(alphabet, alphabet[1:]):
count[next_letter] += count[letter]
previous = 0
for letter in alphabet:
previous, count[letter] = count[letter], previous
aux = array[:]
... | [
"def bigSorting(unsorted):\n lookup = defaultdict(lambda: [])\n print(lookup)\n for num_string in unsorted:\n lookup[len(num_string)].append(num_string)\n\n results = []\n lengths = list(lookup.keys())\n lengths.sort()\n for length in lengths:\n x = lookup[length]\n x.sort(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts that a check of the given lines with the given local bear either yields or does not yield any results. | def check_validity(self,
local_bear,
lines,
filename=None,
valid=True,
force_linebreaks=True,
create_tempfile=True,
tempfile_kwargs={}):
assert isinsta... | [
"def _check_lines(self, lines: Sequence[str], needed_lines: NeedLines, ignore_spaces: bool = True) -> None:\n if ignore_spaces:\n lines = [vdns.common.compact_spaces(x) for x in lines]\n needed_lines0 = needed_lines\n needed_lines = []\n for line in needed_lines0:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts that a check of the given lines with the given local bear does yield exactly the given results. | def check_results(self,
local_bear,
lines,
results,
filename=None,
check_order=False,
force_linebreaks=True,
create_tempfile=True,
tempfile_kwar... | [
"def check_validity(self,\n local_bear,\n lines,\n filename=None,\n valid=True,\n force_linebreaks=True,\n create_tempfile=True,\n tempfile_kwargs={}):\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a test for a local bear by checking the given valid and invalid | def verify_local_bear(bear,
valid_files,
invalid_files,
filename=None,
settings={},
force_linebreaks=True,
create_tempfile=True,
timeout=None,
t... | [
"def check_validity(self,\n local_bear,\n lines,\n filename=None,\n valid=True,\n force_linebreaks=True,\n create_tempfile=True,\n tempfile_kwargs={}):\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_balancer(b, protocol='HTTPS'), then get_balancer('3130') | def _v1_0_11111_loadbalancers_3130(self, method, url, body, headers):
if method == "PUT":
json_body = json.loads(body)
self.assertDictEqual(json_body, {"protocol": "HTTPS"})
return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
elif method == "GET":
... | [
"def _v1_0_11111_loadbalancers_3133(self, method, url, body, headers):\n if method == \"PUT\":\n json_body = json.loads(body)\n self.assertDictEqual(json_body, {\"algorithm\": \"ROUND_ROBIN\"})\n return (httplib.ACCEPTED, \"\", {}, httplib.responses[httplib.ACCEPTED])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_balancer(b, port=443), then get_balancer('3131') | def _v1_0_11111_loadbalancers_3131(self, method, url, body, headers):
if method == "PUT":
json_body = json.loads(body)
self.assertDictEqual(json_body, {"port": 1337})
return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
elif method == "GET":
... | [
"def network_load_balancer_update(event, context):\n print(\"NLB update Time remaining (MS):\", context.get_remaining_time_in_millis()) \n logger.info('Running network load balancer update')\n fwcontext = lib.get_ssl_context()\n total_fw_az = len(fw_azs)\n\n\n #Search for COMMIT in firewall table\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_balancer(b, algorithm='ROUND_ROBIN'), then get_balancer('3133') | def _v1_0_11111_loadbalancers_3133(self, method, url, body, headers):
if method == "PUT":
json_body = json.loads(body)
self.assertDictEqual(json_body, {"algorithm": "ROUND_ROBIN"})
return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
elif method == "... | [
"def calculate_subnets(total, breakdown):\n sanity_percent = 0 # if this isn't 100% by the end, we got issues.\n subnets = 0\n for nodep, netp in breakdown:\n sanity_percent += nodep\n if (sanity_percent > 100):\n return -1\n subtotal = int(total * .01 * nodep)\n grou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_balancer(b, protocol='IMAPv3'), then get_balancer('3135') | def _v1_0_11111_loadbalancers_3135(self, method, url, body, headers):
if method == "PUT":
json_body = json.loads(body)
self.assertDictEqual(json_body, {"protocol": "IMAPv2"})
return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
elif method == "GET":
... | [
"def _v1_0_11111_loadbalancers_3136(self, method, url, body, headers):\n if method == \"PUT\":\n json_body = json.loads(body)\n self.assertDictEqual(json_body, {\"protocol\": \"IMAPv3\"})\n return (httplib.ACCEPTED, \"\", {}, httplib.responses[httplib.ACCEPTED])\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_balancer(b, protocol='IMAPv3'), then get_balancer('3136') | def _v1_0_11111_loadbalancers_3136(self, method, url, body, headers):
if method == "PUT":
json_body = json.loads(body)
self.assertDictEqual(json_body, {"protocol": "IMAPv3"})
return (httplib.ACCEPTED, "", {}, httplib.responses[httplib.ACCEPTED])
elif method == "GET":
... | [
"def _v1_0_11111_loadbalancers_3135(self, method, url, body, headers):\n if method == \"PUT\":\n json_body = json.loads(body)\n self.assertDictEqual(json_body, {\"protocol\": \"IMAPv2\"})\n return (httplib.ACCEPTED, \"\", {}, httplib.responses[httplib.ACCEPTED])\n elif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Command argument for receiving two options. | async def options(arg):
match = command_pattern.match(arg)
assert match
assert not match.group(1).lower() == match.group(2).lower(), "**The choices cannot be the same.**"
return match.group(1), match.group(2) | [
"def arg2(self):\r\n command_list = self.curr_command.split(\" \")\r\n # return the numeric value\r\n return command_list[2]",
"def RunCommandWithOptions():\n pass",
"def test_short_multiple_modes(self):\n gt = GeneTorrentInstance(self.resourcedir + \"-d xxx -s %s -u xxx\" % (os.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask the bot if he would rather, or have the bot ask you. | async def wouldyourather(message: discord.Message, opt: options=None):
# If there are no options, the bot will ask the questions (if there are any to choose from)
if opt is None:
assert message.channel.id not in sessions, "**A would you rather session is already in progress.**"
sessions.add(mess... | [
"def ask_if_wanna_continue(player_name: str) -> bool:\r\n print(\"You reached one possible end!!!\")\r\n if ask_if_yes(\"Wanna change your fate? \"):\r\n sleep(2)\r\n print(\"Very well then...\")\r\n sleep(2)\r\n return True\r\n else:\r\n if ask_if_yes(f\"{player_name} di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a wouldyourather question with the given options. | async def remove(message: discord.Message, opt: options):
for q in db.data["questions"]:
if q["choices"][0] == opt[0] and q["choices"][1] == opt[1]:
db.data["questions"].remove(q)
db.save()
await client.say(message, "**Entry removed.**")
break
else:
... | [
"def remove_answer(self, answer):\n index = self.find(answer)\n if index is not None:\n del self.answers[index]",
"def removeQuestion(self, search, questionIndex=False):\n if questionIndex == True and\\\n type(search) == int and search < len(self.questions):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a node (which is an integer in this problem) and returns outgoing arcs (always two arcs in this problem) | def outgoing_arcs(self, tail_node):
connections = []
for arc in self.adj_list[tail_node]:
connections.append(Arc(tail_node,arc[0],action = f"{tail_node}->{arc[0]}", cost = arc[1]))
connections.sort(key = lambda x: x[1])
return connections | [
"def outgoing_arcs(self, tail_node):\n return [Arc(tail_node, tail_node-1, action=\"1down\", cost=1),\n Arc(tail_node, tail_node+2, action=\"2up\", cost=1)] #'Arc', 'tail=currentnode, head=nextoption, action=whattodo, cost'",
"def add_arc_from_to(fr, to, net, weight=1):\n a = PetriNet.Ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a sequence (list) of starting nodes. In this problem the seqence always has one element. | def starting_nodes(self):
return self.starting_nodes_ #abstract requires this exists! | [
"def starting_nodes(self):\n return [self.starting_number]",
"def starting_nodes(self):\r\n return self.start_node",
"def getStart(self):\n return(self.graph.roots)",
"def getStartNodes(fn=\"\"):\n print \"File is \" + fn\n reader=csv.reader(open(fn, \"rb\"), delimiter=\";\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine whether a given node (integer) is a goal. | def is_goal(self, node):
# print("is {} in {}".format(node, self.goal_nodes))
if node in self.goal_nodes:
return True | [
"def is_goal(self, node):\r\n return node == self.goal_node",
"def is_goal(self,node):\r\n return node in self.goals",
"def is_goal_node(self, node):\n return node[0] == self.num_rows - 1 and node[1] == self.num_cols - 1",
"def is_goal_node(self, node):\n return node[0] == len(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates the tables. Creates the tables token and val unless they already exist. | def _create_tables(self):
self._c.execute("CREATE TABLE IF NOT EXISTS token ( "
"id INTEGER PRIMARY KEY, "
"name CHAR(50) NOT NULL)")
self._c.execute("CREATE TABLE IF NOT EXISTS val ( "
"id INTEGER PRIMARY KEY, "
... | [
"def txn_createTables(self):\r\n self.db_create_nonce()\r\n self.db_create_assoc()\r\n self.db_create_settings()",
"def create_tables():\n db.create_all()",
"def create_tables():\n\tlog_msg4(\"No hay tablas para el año \" + txt_year + \". Creando\")\n\n\tcreate_table('visited')\n\tcr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select a random image file from the provided directory and return its href. `path` should be relative to MEDIA_ROOT. | def random_img(path):
fullpath = os.path.join(settings.MEDIA_ROOT, path)
filenames = [f for f in os.listdir(fullpath) if is_image_file(f)]
pick = random.choice(filenames)
return posixpath.join(settings.MEDIA_URL, path, pick) | [
"def random_image():\n img_dir = \"./static\"\n img_list = os.listdir(img_dir)\n img_path = os.path.join(img_dir, random.choice(img_list))\n return img_path",
"def getRandomFile(path):\n files = os.listdir(path)\n index = random.randrange(0, len(files))\n return files[index]",
"def getRandomFile(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push retrieved data onto stack and point SP register to top of stack. | def push(self, data):
self.STACK.appendleft(data)
self.SP = self.STACK[0] | [
"def op_push(state):\n # Pointer is u64 and instructions u8\n value = int_from_bytes(state.pop_next_instruction() for _ in range(8))\n state.data_stack.push(value)",
"def push(self, data):\n self.top = Item(data, self.top)",
"def _push_d_to_stack(self) -> None:\n self._write(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup to debug after each step is executed. | def after_step(context, step):
if context.config.userdata.getbool("debug") and step.status == "failed":
spost_mortem(step.exc_traceback) | [
"def debugger_step_over():",
"def setUp(self):\n dbgopt = pytest.config.getoption(\"dbg\")\n stn = '.' + self._testMethodName\n if stn in dbgopt or '.all' in dbgopt:\n pdb.set_trace()\n\n if self._testMethodName in dbgopt or \"all\" in dbgopt:\n self.dbgfunc = pdb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that the class is not an audio file | def __validate_class(self):
if type(self) == AudioFile:
raise ValueError('Cannot be the base-type AudioFile. Must be a song or podcast') | [
"def is_audio_file(self):\n return self.ext is not None",
"def is_valid_audio_file(self, filepath):\n _, filename = filepath.rsplit('/', 1)\n _, ext = filename.rsplit('.', 1)\n try:\n if ext == 'mp3':\n audio = MP3(filepath, ID3=EasyID3)\n elif ext ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current user rating for the audio_file instance | def user_rating(self) -> int:
return self._user_rating | [
"def get_mean_user_rating(self, user_id):\n return self.mean_user_rating[self.mean_user_rating['user_id'] == user_id]['rating'].item()",
"def rating(self):\n return self._rating",
"def getAvgRating(self):\r\n return self.getFieldVal(self.AVG_RATING)",
"def rating(self):\n if self._rati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a formatted string that shows the audio_file name and times played | def display_play_count(self):
play_string = "{} has been played {} time".format(self._title, self._usage.play_count)
if self._usage.play_count > 1 or self._usage.play_count == 0:
play_string += 's'
print(play_string) | [
"def __str__(self):\n\n return \"Sound with \" + str(len(self)) + \" samples.\"",
"def mp3_output_name(self) -> Path:\n filename = f'{self.game_id} Game Audio.mp3'\n return self.game_destination_dir() / filename",
"def get_name(self):\n if self.audio.is_loaded():\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds values to the instance variables of _file_path and _file_name | def __set_file_info(self, path_name):
file_name = os.path.basename(path_name)
file_path = os.path.dirname(path_name)
self._file_path = file_path
self._file_name = file_name | [
"def addFile(self, filePath): \n \n self.filePathDict[filePath] = [0,[]]",
"def __init__(self, file_name):\n self._file_name = file_name",
"def set_file(self, **kwargs):\n if kwargs.keys() == {'path', 'name', 'extension'}:\n self.name = kwargs['name']\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates the file location on audio_file creation | def __validate_location(self):
if not os.path.exists(self._file_path):
raise FileNotFoundError("Directory does not exist")
if not os.path.isfile(self._path_name):
raise FileNotFoundError('File does not exist') | [
"def is_valid_audio_file(self, filepath):\n _, filename = filepath.rsplit('/', 1)\n _, ext = filename.rsplit('.', 1)\n try:\n if ext == 'mp3':\n audio = MP3(filepath, ID3=EasyID3)\n elif ext == 'flac':\n audio = FLAC(filepath)\n eli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the usage stats for this audio_file instance | def update_usage_stats(self):
self._usage.increment_usage_stats() | [
"def __count_usage(self, tags):\n for tag in tags:\n _, count = model.getService('video').find({\n 'tags': [{'$value': tag['_id']}]\n }, returnCount=True)\n tag['usage'] = count\n _, count = model.getService('album').find({\n 'tags': [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns usage stats for the audio_file instance | def get_usage_stats(self) -> UsageStats:
return self._usage | [
"def media_usage(path: str) -> typing.Dict[str, float]:\n stvf = os.statvfs(path)\n free = stvf.f_bavail * stvf.f_frsize\n total = stvf.f_blocks * stvf.f_frsize\n used = (stvf.f_blocks - stvf.f_bfree) * stvf.f_frsize\n\n return {'free': free, 'total': total, 'used': used}",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Part of the Retriever interface returns random popularity for the last 10 years for 30 teams. | def retrieve(team, year):
return random.randint(100,200) | [
"def top_ten_rental() -> None:\n url = movie_api.top_rental_build_url('',10,top_rentals)\n json_result = movie_api.json_response(url)\n print()\n print('Top Rentals by Popularity')\n print('-------------------------')\n print()\n for movie in json_result['movies']:\n print('{} ({})'.form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the expected circuit. If it equals the correct ``IntegerComparator`` we know the circuit is correct. | def test_circuit(self):
num_qubits = 3
strike_price = 0.5
bounds = (0, 2)
ecd = EuropeanCallDeltaObjective(
num_state_qubits=num_qubits, strike_price=strike_price, bounds=bounds
)
# map strike_price to a basis state
x = (strike_price - bounds[0]) / (b... | [
"def test_fixed_value_comparator(self, num_state_qubits, value, geq):\n # build the circuit with the comparator\n comp = IntegerComparator(num_state_qubits, value, geq=geq)\n self.assertComparisonIsCorrect(comp, num_state_qubits, value, geq)",
"def assert_valid_circuit(self, transpiled):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open the pkg_appname csv file(MOB) and load all the pkg name with app name into a dictionary. The key is the pkg name, the value is the | def pkg_appname_file_process(self, file_path):
pkg_app_dict = dict()
with open(file_path, 'r', encoding='utf-8') as pkg_app_file:
reader = csv.reader(pkg_app_file)
for row in reader:
row[0] = row[0].encode('utf-8').decode('utf-8-sig')
pkg_app_dict[... | [
"def apps_information(self):\n with open(self.app_data_path, 'r') as app_csv_file:\n csv_reader = csv.reader(app_csv_file)\n apps = [self.AppInformation(app[0], app[1], app[2], app[3], app[4], app[5]) for app in csv_reader]\n return apps",
"def readApps(userDay, userTime):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert case to YAML. | def _convert_case_to_yaml(vert):
if vert:
yamlfile = os.path.join(os.getcwd(), str(vert).strip())
scripts.generate_case_tmpl(yamlfile) | [
"def to_yaml(self, **kwargs):\n return self._encode(self.dict(), \"yaml\", **kwargs)",
"def to_yaml(self):\n\t\treturn yaml.dump(self.data,default_flow_style=False)",
"def as_yaml(self):\n return yaml.dump(mapping([\n (\"slug\", quoted(self.slug)),\n (\"name\", quoted(self.na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert http.har to YAML. | def _convert_httphar_to_yaml(har):
if har:
temp_dict = ConvertHarToYAML.convert_har_to_ht(har)
ConvertHarToYAML.write_case_to_yaml('', temp_dict) | [
"def _as_yaml(self,res):\n try:\n import yaml\n except:\n print >> sys.stderr, \"You don't seem to have PyYAML installed\"\n return yaml.dump( self._zip_rows( res ))",
"def as_yaml(self):\n return yaml.dump(mapping([\n (\"slug\", self.slug.encode('ascii... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get file case YAML. | def _get_file_yaml(case_file):
temp_list = []
# Get the yaml file name and write to the queue.
if case_file:
# Specify the execution CASE.
fargs = '&#'.join(case_file)
temp_list.append(os.path.join(os.getcwd(), fargs))
cache_dir = os.path.join(gl.loadcasePath, ".am_cache")
... | [
"def _convert_case_to_yaml(vert):\n if vert:\n yamlfile = os.path.join(os.getcwd(), str(vert).strip())\n scripts.generate_case_tmpl(yamlfile)",
"def parse_case(case_file):\n yaml_config = open(case_file)\n config = yaml.load(yaml_config)\n config['model_dir'] = MODEL_ROOT\n return con... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get dirs case YAML. | def _get_dirs_case_yaml(case_dir):
temp_list = []
if case_dir:
for root, dirs, files in os.walk(case_dir):
for f in files:
if 'yaml' in f:
d = os.path.join(os.getcwd(), case_dir)
temp_list.append(os.path.join(d, f))
# 缓存目录
... | [
"def get_rule_dir_yaml(dir_path):\n return os.path.join(dir_path, \"rule.yml\")",
"def test_list_dir_returns_dirs_only(self):\n with self.settings(MIDDLEWARE_CLASSES=self.fix_middleware(), KML_FILE_DIR=self.kml_file_dir):\n user = StaffUserFactory()\n ldv = self.initiate_view(user)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mock multimatic to only handle binary_sensor. | def fixture_only_binary_sensor(mock_manager):
orig_platforms = multimatic.PLATFORMS
multimatic.PLATFORMS = ["binary_sensor"]
yield
multimatic.PLATFORMS = orig_platforms | [
"def test_binary_sensor(self):\n with patch.dict(TYPES, {'BinarySensor': self.mock_type}):\n state = State('binary_sensor.opening', 'on',\n {ATTR_DEVICE_CLASS: 'opening'})\n get_accessory(None, state, 2, {})",
"async def test_binary_sensor(\n hass: HomeAssi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch an observation with a specific ID. | def get_observation(observation_id: str):
pass | [
"def get_obs(db, obs_id):\n with db.transaction() as conn:\n select = db.select([db.obs]).\\\n where(db.obs.c.obs_id == obs_id)\n result = conn.execute(select)\n rows = result.fetchall()\n result.close()\n if len(rows) == 1:\n return rows[0]\n elif len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count the observations within a given geo area that meet the filter, if any, passed in via the request body. | def count_observations_by_geo(geohash: str, filter: Optional[ObservationFilter]):
pass | [
"def count_posts(self, filter: dict) -> int:\n pass",
"def count_filtered(cls, client, filter_) :\n try :\n obj = nshttpprofile()\n option_ = options()\n option_.count = True\n option_.filter = filter_\n response = obj.getfiltered(client, option... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query for observations within a given geohash area that meet the filter, if any, passed in via the request body. | def get_observations_by_geo(geohash: str, filter: Optional[ObservationFilter]):
pass | [
"def count_observations_by_geo(geohash: str, filter: Optional[ObservationFilter]):\n pass",
"def _search_area(self, queryset, search_term):\n\n filtered = queryset.none()\n if search_term.find(\"<>\") > -1:\n area_min, area_max = [float(x) for x in search_term.split(\"<>\")]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the name of each magician in the list. | def show_magicians(magicians):
for magician in magicians:
print(magician.title()) | [
"def show_magicians(magician_names):\n for name in magician_names:\n print(name.title())",
"def show_magicians(magician_names):\r\n for magician in magicians:\r\n print(magician.title())",
"def show_magicians(magician_list):\n\tfor magician in magician_list:\n\t\tprint(magician.title())",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a sandwich with the given items. | def make_sandwich(*items):
print("\nI'll make you a great sandwich:")
for item in items:
print(" ...adding " + item + " to your sandwich.")
print("Your sandwich is ready!") | [
"def make_sandwich(*items):\n print(\"\\nLet's make a sandwich\")\n for item in items:\n print(f\" ...adding {item} to your sandwich.\")\n print(\"Your sandwich is ready!\")",
"def make_sandwich(*items):\r\n print(\"\\nI'll make you a great sandwich:\")\r\n for item in items:\r\n pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save a torch tensor as an image. x is the tensor. x could be in shape of (C, H, W) or (H, W). The values in x must be already regulated in the range of 0255, although internal clipping is applied. Only png file is supported for output. | def save_tensor_image(fn, x):
if ( 3 == len( x.size() ) ):
x = x.permute((1, 2, 0))
# Get the CPU NumPy version.
x = torch.clamp(x, 0, 255)
x = x.cpu().numpy().astype(np.uint8)
# Save the iamge.
cv2.imwrite(fn, x, [cv2.IMWRITE_PNG_COMPRESSION, 0]) | [
"def save_images(self, x, output, name, n=16):\n # make grids and save to logger\n grid_top = vutils.make_grid(x[:n,:,:,:], nrow=n)\n grid_bottom = vutils.make_grid(output[:n,:,:,:], nrow=n)\n grid = torch.cat((grid_top, grid_bottom), 1)\n self.logger.experiment.add_image(name, gr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cache parameter group name to use for the new engine version. This parameter cannot be modified independently. | def cache_parameter_group_name(self) -> Optional[str]:
return pulumi.get(self, "cache_parameter_group_name") | [
"def parameter_group_name(self) -> str:\n return pulumi.get(self, \"parameter_group_name\")",
"def parameter_group_name(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"parameter_group_name\")",
"def parameter_group_name(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
join TargetSizes that have the same length | def compress(self):
known_sizes = dict()
# list to dict to make them unique
for size in self.target_sizes:
if size.length in known_sizes:
known_sizes[size.length] += size.quantity
else:
known_sizes[size.length] = size.quantity
# b... | [
"def _make_sizes_compatible(self, Q, K):\n N, L, H, E = Q.shape\n _, S, _, _ = K.shape\n if L == S:\n return Q, K\n\n if L < S:\n return Q, K[:, :L, :, :]\n\n if L > S:\n return Q, torch.cat([K, K.new_zeros(N, L-S, H, E)], dim=1)",
"def match_siz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of target sizes in job | def __len__(self) -> int:
return sum(target.quantity for target in self.target_sizes) | [
"def num_targets(self) -> int:",
"def train_size(self):",
"def __number_of_jobs__(self):\n # | - __number_of_jobs__\n num_jobs = 0\n\n # Regular jobs\n if self.job_var_lst is not None:\n num_jobs = len(self.job_var_lst)\n\n # Individual dir jobs\n if self.ind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempt to get a handler for target content type, based on the following naming convention. content_type.model_class()._meta.db_table as StudlyCaps + Handler | def get_handler(self, content_name):
import django_userhistory.handlers as handlers
def to_studly(x):
return "".join([token.capitalize() for token in x.split("_")])
handler_class = getattr(handlers,
"%sHandler" % ... | [
"def GetHandler(tab_type):\n return _HANDLERS.get(tab_type)",
"def gettype(self):\r\n\r\n return self.__handler_type",
"def get_handler(cls, handler_type):\n return cls._registry.get(handler_type)",
"def DetermineHandlerModule(request):\n # If we didnt have a server_id specified, use the m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers a handler from django_userhistory.handlers with the target content type. | def register(self, content_type, action):
content_name = content_type.model_class()._meta.db_table
if not content_name in self._registry.keys():
HandlerClass = self.get_handler(content_name)
handler = HandlerClass(content_type, action)
self._registry[content_name] = c... | [
"def get_handler(self, content_name):\n import django_userhistory.handlers as handlers\n \n def to_studly(x):\n return \"\".join([token.capitalize() for token in x.split(\"_\")])\n \n handler_class = getattr(handlers, \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
trilinear interpolation of a list of float indices into an input array | def trilinear_interp(img, indices):
input_array = np.array(img.get_data())
indices = np.array(indices)
x_indices = indices[:,0]
y_indices = indices[:,1]
z_indices = indices[:,2]
# get lower bounds
x0 = x_indices.astype(np.integer)
y0 = y_indices.astype(np.integer)
z0 = z_indice... | [
"def F_bilinear_interp_3d(input, coords):\n x = torch.clamp(coords[:,0], 0, input.size(0)-1.00001)\n x0 = x.floor().long()\n x1 = x0 + 1\n\n y = torch.clamp(coords[:,1], 0, input.size(1)-1.00001)\n y0 = y.floor().long()\n y1 = y0 + 1\n\n z = torch.clamp(coords[:,2], 0, input.size(2)-1.00001)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a list of categories for given word word is assumed to be a noun | def get_synsets_rt(word: str) -> List:
return rt.categories(word) | [
"def wn_category(word):\n cats = ['transport', 'food', 'building', 'animal', 'appliance', 'action', 'clothes', 'utensil', 'body', 'color',\n 'electronics', 'number', 'human']\n cat_synsets = dict(zip(cats, map(wn.synsets, cats)))\n hyper = lambda s: s.hypernyms()\n synsets = wn.synsets(word)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for creating users. | def users_create(): | [
"def createUserViaAPI(self):\n POST_request = self.app.post('/users', data=dict(\n email='anystring',\n password='anystring1',\n first_name='anystring2',\n last_name='anystring3'\n ))\n\n return POST_request",
"def post(self):\r\n return crea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for getting all users. | def get_all_users(): | [
"def all_users():\n\n users = crud.get_users()\n\n return render_template('all_users.html', users=users)",
"def get_user_list(self):\n\n return self._request('/users', method='GET')",
"def fetch_all_users():\n users = find_users()\n return to_response(users, \"No users\")",
"def get_all_use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for deleting an existing user. | def delete_user(): | [
"def test_delete_user(self):\n response = self.client.open(\n '/v0/user/{userUuid}'.format(userUuid='userUuid_example'),\n method='DELETE')\n self.assert200(response,\n 'Response body is : ' + response.data.decode('utf-8'))",
"def delete(self):\n db... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for creating a meal item. | def create_meal(): | [
"def create_item(self, user: User, **kwargs) -> None:",
"async def item_create(item_in: ItemCreate, db: Session = Depends(get_db)):\n return create_item(db=db, item=item_in)",
"def post(id_user):\n return create_meal(id_user, request.json, g.user)",
"def add_item(self, m_id):\r\n \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for getting all meals. | def get_all_meals(): | [
"def get_all_meals():\n\n return MealPlan.get_all()",
"def get_one_meal():",
"def read_all_diaries():\n params = {\n 'page': request.args.get('page', default=1, type=int),\n 'limit': request.args.get('limit', default=5, type=int),\n 'location': request.args.get('location', default=Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for getting a particular meal. | def get_one_meal(): | [
"def get(id_user):\n\n return get_meals(id_user, request, g.user)",
"def test_get_meals(self):\n with self.client:\n self.add_meal(\"fries\", 10000)\n response = self.get_meals()\n data = json.loads(response.data.decode())\n self.assertEqual(response.statu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for updating an existing meal. | def update_meal(): | [
"def put(id_user, id_meal):\n return update_meal(id_user, id_meal, request.json, g.user)",
"def patch(id_user, id_meal):\n return patch_meal(id_user, id_meal, request.json, g.user)",
"def edit_meal(meal_id):\n user = get_user()\n\n if user:\n meal = mongo.db.built_meals.find_one(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for deleting an existing meal. | def delete_meal(): | [
"def delete(id_user, id_meal):\n return delete_meal(id_user, id_meal, g.user)",
"def delete_meal(self): # TODO test\n day = self.meal.day\n day.meals.remove(self.meal)\n self.meal_tree_box.screen.right_panel.update_calculated_day_fields()\n\n self.meal_tree.remove_node(self)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for creating a menu option. | def create_menu(): | [
"def create_menu(self, data):\n tz = timezone(settings.TIME_ZONE)\n local_date = tz.localize(\n datetime.strptime(\n data.pop('date'),\n '%Y-%m-%d'\n )\n )\n data.update(\n {\n 'date': local_date\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for getting all menu options. | def get_all_menu(): | [
"def getMenuItems(object, request):",
"def menus(self):\n return []",
"def menus(self):\r\n return []",
"def get_menu_items():\n\n pass",
"def get_menus(self):\n return self.menus",
"def get_all_options(self): \n return self._options.items()",
"def get_menu_items(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
endpoint for getting a particular menu option. | def get_one_menu_option(): | [
"def get_menu(menu_name):\n\n pass",
"def get_option(self, key):\n return self.options[key]",
"def get_menu_item(menu_item_name):\n\n pass",
"def getOption(self) :\n return self._option",
"def get_menu(self):\n return self.menu",
"def get(self, section, option, type_=six.string_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops the running simulation and starts it again. Arguments are same as those of start_lab | def restart_lab(lab_path, prefix, **kwargs):
stop_lab(lab_path, prefix)
ret = start_lab(lab_path, prefix, **kwargs)
print('\n...done', flush=True)
return ret | [
"def stopSimulation(self):\n self.simulation_running = False",
"def runner_stop():\n RunnerInstance.instance().stop()",
"def restart_simulation_job(job=None):\n pass",
"def stop(self):\n self.scion_sh('stop')",
"def stop(self):\n self.microblaze.reset()",
"def stop(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looks up for an ID relevant to the passed action text in the list of known actions and their ids. | def get_action_id(self, action_text: str) -> int:
return self.templates.actions.index(action_text) # todo unhandled exception when not found | [
"def get_action_id(self, action_text: str) -> int:\n\n actions_tuple = tuple(action_text.split('+'))\n return self.action_tuples2ids[actions_tuple] # todo unhandled exception when not found",
"def findAction(self, actionId): #$NON-NLS-1$\r",
"def _act_id(self, act_str):\n\n # FIXME: instea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate text for the predicted speech action using the pattern provided for the action. The slotfilled state provides info to encapsulate to the pattern. | def _generate_slotfilled_text_for_action(self, action_id: int, slots: dict) -> str:
text = self.templates.templates[action_id].generate_text(slots)
return text | [
"def prep_robot_action(self):\n if self.robot.sensing:\n action_str = \"Action: Sensing...\"\n elif self.robot.moving_forward or self.robot.moving_backward:\n action_str = \"Action: Moving...\"\n else:\n action_str = \"Action: Target reached...\"\n # Prep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that `actual_obj` is the same as `expected_obj` except keys where values are None. | def obj_assert(actual_obj, expected_obj):
# Pytest shortens the diff so we have to produce the diff ourselves
# to workaround this.
# https://github.com/pytest-dev/pytest/issues/2256
# https://github.com/pytest-dev/pytest/issues/3632
# pylint: disable=unidiomatic-typecheck
assert type(actual_obj) == type(ex... | [
"def assertKeysMatch(self, actual_dict, expect_dict):\n self.assertEqual(set(actual_dict.keys()), set(expect_dict.keys()))\n return",
"def assert_dict(self, required, actual):\n for key in required:\n self.assertEquals(required[key], actual[key],\n msg=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns connection widgets to add to connection form | def get_connection_form_widgets():
from flask_appbuilder.fieldwidgets import (
BS3TextFieldWidget,
BS3PasswordFieldWidget,
)
from wtforms import StringField
return {
"extra__ewah_amazon_ads__lwa_client_id": StringField(
"AWS LWA Client... | [
"def connection_form_widgets(self) -> Dict[str, ConnectionFormWidgetInfo]:\n self.initialize_providers_manager()\n return self._connection_form_widgets",
"def get_connection_form_widgets() -> dict:\n from flask_appbuilder.fieldwidgets import BS3TextFieldWidget\n from wtforms import Str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
adults_directory > string, directory of employed_adults_apr2020_jul2020.csv eg '../../src/csv/employed_adults_apr2020_jul2020.csv' covid_pol_directory > string, directory of pol_covid.csv eg '../../src/csv/pol_covid.csv' returns > pandas.DataFrame containing features of intereast | def catch_up(employed_adults_directory, covid_pol_directory):
# load in df
try:
df = pd.read_csv(employed_adults_directory, index_col=0)
except Exception as e:
print(str(e))
print("Please enter the correct directory for employed_adults_apr2020_jul2020.csv")
# create target v... | [
"def download_uci_adult(data_dir: pathlib.Path) \\\n -> Tuple[pd.DataFrame, pd.DataFrame]:\n train_pkl = data_dir / 'train_df.pkl'\n test_pkl = data_dir / 'test_df.pkl'\n\n if data_dir.exists() and len(tuple(data_dir.iterdir())) > 1:\n train_df = pd.read_pickle(train_pkl)\n test_df = p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read size samples starting at start, if resize_if_less is True and less than size samples are read, resize the array to size and fill with zeros | def read(self, start, size, resize_if_less=False):
# number of zeros to add to start and end of the buffer
add_to_start = 0
add_to_end = 0
if start < 0:
# the first FFT window starts centered around zero
if size + start <= 0:
return numpy.zeros... | [
"def sampleArray(sizeOfReducedSample = DEFSIZEOFREDUCEDSAMPLE): \n return np.zeros((sizeOfReducedSample, sizeOfReducedSample))",
"def _preallocate_samples(self):\n self.prealloc_samples_ = []\n for _ in range(self.num_prealloc_samples_):\n self.prealloc_samples_.append(self.sample()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
starting at seek_point read fft_size samples, and calculate the spectral centroid | def spectral_centroid(self, seek_point, spec_range=120.0):
samples = self.read(seek_point - self.fft_size/2, self.fft_size, True)
samples *= self.window
fft = numpy.fft.fft(samples)
spectrum = numpy.abs(fft[:fft.shape[0] / 2 + 1]) / float(self.fft_size) # normalized abs(FFT) b... | [
"def calc_spectral_centroid(song, fs, frame_size=1000):\n # Weighted Average of Frequencies by their Magnitudes for each frame (center of the signal)\n spectral_centroid = np.zeros((int(song.shape[0] / frame_size)))\n ind = 0\n for i in range(spectral_centroid.shape[0]):\n x = song[ind:ind+frame_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read all samples between start_seek and end_seek, then find the minimum and maximum peak in that range. Returns that pair in the order they were found. So if min was found first, it returns (min, max) else the other way around. | def peaks(self, start_seek, end_seek):
# larger blocksizes are faster but take more mem...
# Aha, Watson, a clue, a tradeof!
block_size = 4096
max_index = -1
max_value = -1
min_index = -1
min_value = 1
if end_seek > self.frames:
end_seek ... | [
"def get_max_in_range(snd, start, end):\n\n first = snd.get_sample(start)\n val = abs(first.get_left())\n\n for i in range(start+1, end+1):\n samp = snd.get_sample(i)\n left = abs(samp.get_left())\n if (left > val):\n val = left\n\n return val",
"def peakFind(rawPRI, I... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a list of colors, create a larger list of colors interpolating the first one. If flatten is True a list of numers will be returned. If False, a list of (r,g,b) tuples. num_colors is the number of colors wanted in the final list | def interpolate_colors(colors, flat=False, num_colors=256):
palette = []
for i in range(num_colors):
index = (i * (len(colors) - 1))/(num_colors - 1.0)
index_int = int(index)
alpha = index - float(index_int)
if alpha > 0:
r = (1.0 - alpha) * colors[index_int][0]... | [
"def expand(colors, cutoff=12):\n output = []\n if len(colors) != 7 or cutoff > 14:\n leds_per_color = int(cutoff / len(colors))\n for i in colors:\n output += [i] * leds_per_color\n else:\n for j, i in enumerate(colors):\n output += [i] * (1 + (j % 2 == 1))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draw 2 peaks at x using the spectral_centroid for color | def draw_peaks(self, x, peaks, spectral_centroid):
y1 = self.image_height * 0.5 - peaks[0] * (self.image_height - 4) * 0.5
y2 = self.image_height * 0.5 - peaks[1] * (self.image_height - 4) * 0.5
line_color = self.color_lookup[int(spectral_centroid*255.0)]
if self.previous_y != None... | [
"def test_find_peaks_withnoise(self):\n sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0]\n num_points = 500\n test_data, act_locs = _gen_gaussians_even(sigmas, num_points)\n widths = np.arange(0.1, max(sigmas))\n noise_amp = 0.07\n np.random.seed(18181911)\n test_data += ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
vertical antialiasing at y1 and y2 | def draw_anti_aliased_pixels(self, x, y1, y2, color):
y_max = max(y1, y2)
y_max_int = int(y_max)
alpha = y_max - y_max_int
if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
current_pix = self.pix[x, y_max_int + 1]
r = int((1-alpha)*curren... | [
"def align_yaxis(ax1,v1,ax2,v2):\n _, y1 = ax1.transData.transform((0,v1))\n _, y2 = ax2.transData.transform((0,v2))\n inv = ax2.transData.inverted()\n _, dy = inv.transform((0,0)) - inv.transform((0,y1-y2))\n miny, maxy = ax2.get_ylim()\n ax2.set_ylim(miny+dy,maxy+dy)",
"def align_yaxis(ax1, v1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detecta el cloudfare de un sitio web | def main():
word = 'cloudflare'
url = requests.get("") #aquí va la url del sitio a analizar
cabeceras = dict(url.headers) #convertimos las cabeceras de la respuesta de la peticion a dicionario
verify = False
#print(cabeceras)
for c in cabeceras:
if word in cabeceras[c].lower(): #verifico... | [
"def search_websh(self):\n uploads = \"(.*/uploads?/)\"\n reu = search (uploads, self.site)\n if reu:\n with open(self.commons, \"r\") as wbf:\n for wb in wbf:\n print(\"Request a \" + reu.group(1) + wb[:-1]) if self.verbose else None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute marginal distribution of nodes. Compute marginal distribution of Bayes net nodes by repeatedly applying self transition kernel and storing state counts. | def marginals(self, num_transitions):
counter = marg.MarginalCounter(self.net)
for _ in xrange(num_transitions):
self.transition()
counter.observe(self.state)
return counter.marginals() | [
"def marginal_table(self):\n nodes = list(self.graph.nodes)\n logging.debug(f\"about to calculate marginal table with nodes {nodes}\")\n logging.debug(f\"updating table for node {nodes[-1]}\")\n marginal = self.calc_node_table(nodes.pop())\n logging.debug(f\"current node table:\\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct from a path to a MOS file | def from_file(cls, mos_file_path):
try:
xml = ET.parse(mos_file_path).getroot()
except ET.ParseError as e:
raise MosInvalidXML(e) from e
if cls == MosFile:
return cls._classify(xml)
return cls(xml) | [
"def load(cls, path, format=\"fits\"): # noqa: A002\n path = str(path)\n if format == \"fits\":\n index = mocpy.spatial_moc_from_fits_file(path)\n return cls(cls.__create_key, index)\n if format == \"ascii\":\n index = mocpy.spatial_moc_from_ascii_file(path)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct from an XML string of a MOS document | def from_string(cls, mos_xml_string):
try:
xml = ET.fromstring(mos_xml_string)
except ET.ParseError as e:
raise MosInvalidXML(e) from e
if cls == MosFile:
return cls._classify(xml)
return cls(xml) | [
"def FromString(cls, xml_string):\n from xml.dom.minidom import parseString\n dom = parseString(xml_string)\n return cls(dom)",
"def load(cls, xml_string, mws_access_key=None, mws_secret_key=None, mws_account_id=None, mws_auth_token=None):\n ptn = '\\s+xmlns=\\\".*?\\\"'\n xml_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct from a MOS file in an S3 bucket | def from_s3(cls, bucket_name, mos_file_key):
xml = s3.get_file_contents(bucket_name, mos_file_key)
return cls.from_string(xml) | [
"def from_s3(cls, *, bucket_name, prefix, suffix='.mos.xml', allow_incomplete=False):\n mos_file_keys = s3.get_mos_files(\n bucket_name=bucket_name,\n prefix=prefix,\n suffix=suffix,\n )\n logger.info(\"Making MosCollection from %s S3 files\", len(mos_file_keys)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The XML element of the MOS file | def xml(self):
return self._xml | [
"def get_document_xml():",
"def xml(self):\n raise NotImplementedError('This api does not return xml')",
"def get_xml(self):\n\t\t# get the XML description of the VM\n\t\tvm_xml = self.clonezilla_vm_obj.XMLDesc(0)\n\t\troot = ET.fromstring(vm_xml)\n\t\treturn root",
"def XmlElementName(self) -> str:",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
``RunningOrder`` objects can be merged with other MOS files which | def __add__(self, other):
if self.xml.find('mosromgrmeta') is None or isinstance(other, RunningOrderControl):
return other.merge(self)
raise MosCompletedMergeError("Cannot merge completed MOS file") | [
"def createOrders(self):\n self.ordersDict = {}\n for pstep in self.processingSteps:\n if pstep.orderid not in self.ordersDict:\n self.ordersDict[pstep.orderid] = Order()\n self.ordersDict[pstep.orderid].addProcessingStep(pstep)",
"def create_order(self):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A list of elements found in the story bodies. Each item in the list is either a string (representing a ```` tag) or an | def body(self):
return list(
itertools.chain.from_iterable(story.body for story in self.stories)
) | [
"def getTagList(tags):\n tags = tags[1:len(tags)-1]\n return tags.split('><')",
"def scantags(self, document):\n tags = []\n pos = 0\n while 1:\n match = tagpat.search(document, pos)\n if not match:\n break\n start, end = match.span()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts tag from roStorySend format to a tag to | def _convert_story_send_to_story_tag(self, ss_tag_orig):
# take a copy to preserve the original
ss_tag = copy.deepcopy(ss_tag_orig)
# change <roStorySend> to <story>
ss_tag.tag = 'story'
for item in ss_tag.find('storyBody').findall('storyItem'):
# change <storyItem> t... | [
"def ot2bio_ts(ts_tag_sequence):\n new_ts_sequence = []\n n_tag = len(ts_tag_sequence)\n prev_pos = '$$$'\n for i in range(n_tag):\n cur_ts_tag = ts_tag_sequence[i]\n if cur_ts_tag == 'O':\n new_ts_sequence.append('O')\n cur_pos = 'O'\n else:\n # cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funkcja, która obsługuje zapytanie typu country(country_name);tag(tag). Najpierw wywołuje funkcję country, a następnie wyszukuje w zwracaniej treści zdania ze słowami kluczowymi. | def countryTag(countryName, tag):
string = country(countryName)
output = ""
tag = " " + tag + " "
tag1 = " " + tag + "."
tag2 = " " + tag + ","
listOfSenteces = string.split(".")
for sentence in listOfSenteces:
if sentence.find(tag)>=0 or sentence.find(tag1)>=0 or sentence.find(tag2)>=0:
output = output +... | [
"def country() -> str:",
"def expand_country_name(tag, name, data):\n\tfor each in data:\n\t\tif tag in each['k'] and each['v'][each['k'].index(tag)] == 'IN':\n\t\t\teach['v'][each['k'].index(tag)] = name\n\t\tyield each",
"def country(alpha_2_code: str) -> None:",
"def city_country(city, country):\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute source wavelets for all events. | def compute(self):
wavelet_dict = dict()
self.count_dict = dict()
windows = self.compute_windows()
self.windows = windows
if self.verbose > 0:
print(
'Number of time windows before selection: {}'
.format(len(windows)))
wavelet_... | [
"def compute_source_WFs(self):\n _, self.source_WFs = extract_sources_from_segment_groups( # pylint: disable=W0201\n self.method,\n self.segment_grouper.segment_groups_list,\n self.segment_grouper.segment_STFTs,\n self.segment_grouper.hop_length,\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the clusters into two cluster lists, based on the files they come from. The spectra list in each cluster has been sorted based on the "filename" and "index(spec_id)", to reduce the comparing cost. Cluster with sorted spectra is stored in self.sorted_spectra_dict. | def process_cluster(self, cluster):
if self._ignore_cluster(cluster):
return
self.cluster_lists[self.file_index].append(cluster)
spectra = list(cluster.get_spectra())
def mixed_order( spec ): # for sorting
return (spec.get_title())
spectra.sort(key = mi... | [
"def file_pairing(self, include=None, exclude=None):\n\n # List the file names for both the images and the catalogs\n if isinstance(self._irac_image_dir, list):\n image_files = list(chain.from_iterable(glob.glob(f'{img_dir}/*.fits') for img_dir in self._irac_image_dir))\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the similarity between to cluster. | def calculate_similarity(self, cluster0, cluster1):
def compare_spectrum(spectrum0, spectrum1):
"""
Compare a pair of spectra to decide the
order.
:param: pair of spectra
:return: 0 equal, -1 spectrum0 is less,
1, spectrum0 is bigger.
... | [
"def get_similarity(\n self, cluster1, cluster2,\n annotation=None, models=None, matrix=None, history=None, feature=None\n ):\n\n raise NotImplementedError(\"Method 'get_similarity' must be overriden.\")",
"def compute_clustering_score():\n # TODO: Implement simple clustering\n raise... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare a pair of spectra to decide the order. | def compare_spectrum(spectrum0, spectrum1):
title0 = spectrum0.get_title()
title1 = spectrum1.get_title()
if(title0 < title1):
return -1
elif(title0 > title1):
return 1
else:
return 0 | [
"def compare_models(model1,model2):\n\n # initialisation:\n n_radial = 0\n n_radial_numax = 0\n n_non_radial = 0\n n_non_radial_numax = 0\n result = np.zeros((6+nglb,),dtype=gtype)\n # define frequency interval around numax:\n numax = 0.5*(model1.numax/model1.glb[ifreq_ref] \\\n + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare two cluster lists, get the distribution of the similarities. And build the connection network between clusters. | def compare(self):
len0 = len(self.cluster_lists[0])
len1 = len(self.cluster_lists[1])
longer_index = 0 if len0 >= len1 else 1
shorter_index = 1 if len1 <= len0 else 0
self.stars_length = len(self.cluster_lists[shorter_index])
self.starlets_length = len(self.cluster_list... | [
"def compute_cluster_similarities(emb_clusters1, emb_clusters2, compare, order, clmethod, plot):\n def compute_sim(e, e1, cls, cls1):\n sims = np.empty((20, 20))\n xticks, yticks = [], []\n for i, c in enumerate(cls):\n yticks.append(', '.join(c[1]) + (f' {round(c[3], 5)}' if orde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Only for debug, output the intersted intermediate data. | def output_debug_info(self): | [
"def debug():",
"def _pre_run_model_debug_print(self):\n debug_opt = self.options['debug_print']\n rank = self._problem().comm.rank\n if not debug_opt or debug_opt == ['totals']:\n return\n\n if not MPI or rank == 0:\n header = 'Driver debug print for iter coord: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the graphs, set default namespaces, and add schema information | def initGraphs(self):
self.graph = ConjunctiveGraph()
# Create a separate graph for annotations
self.annotationGraph = ConjunctiveGraph()
self.log.debug('Adding namespaces to graphs')
# Bind namespaces to graphs
for namespace in self.namespaces:
... | [
"def __init__(self):\n self._graph = rdflib.Graph()\n self._namespaces = dict()",
"def graphing_setup(self):\n pass",
"def load_default_schema(self):\n self.schema = preprocess_schema(load_schemaorg())\n self.schemaorg_schema = self.schema\n if \"@context\" in self.sche... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add definition of data cell resource to graph | def addDataCellProperty(self):
if len(self.config.get('dataCell', 'propertyName')) > 0 :
self.dataCellPropertyName = self.config.get('dataCell', 'propertyName')
else :
self.dataCellPropertyName = 'hasValue'
self.graph.add((self.namespaces['tablink'][self.dataCel... | [
"def parseData(self, i,j) :\n \n if self.isEmpty(i,j) and self.config.get('dataCell', 'implicitZeros') == '0':\n return\n\n # Use the fully qualified name of the cell for the resource name\n observation = self.namespaces['scope'][self.source_cell_qname]\n \n # It... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start tablinker for all sheets in workbook | def doLink(self):
self.log.info('Starting TabLinker for all sheets in workbook')
for n in range(self.rb.nsheets) :
self.log.info('Starting with sheet {0}'.format(n))
self.r_sheet = self.rb.sheet_by_index(n)
self.w_sheet = self.wb.get_sheet(n)
... | [
"def assy_tabs(wb, tabs):\n logging.info('creating create jobcard')\n for tab in sorted(tabs, reverse=True):\n logging.info('creating ' + str(tab) + ' worksheet')\n wb.Worksheets('-000-').Copy(After=wb.Worksheets('-000-'))\n wb.Worksheets('-000- (2)').Name = tab\n\n return wb",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |