query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
add all lines to the SQLite database. | def add_all_lines(conn, table_values):
column_list = table_values[0]
column_row = ",".join(column_list)
qmark = "?"
col_count = len(column_list)
for cols in range(1, col_count):
qmark += ", ?"
cols = cols
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS ayasdi_table;")... | [
"def add_to_db(self, loglines):\n self.database = self.database.append(loglines, ignore_index=True)",
"def fdb_add(self, fdb_entries):\n raise NotImplementedError()",
"def commit(self):\n for db in self.values():\n db.commit()",
"def loadToSqlite(self, data):\n conn = sq... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The list of metadata keys and values for the image are returned | def test_list_image_metadata(self):
pass | [
"def _getAllMeta(self):\n try:\n metadata = pyexiv2.ImageMetadata(self.imagePath)\n metadata.read()\n return metadata\n except:\n print 'error reading meta data'\n return None",
"def GetMetadata(IMAGE):\n SPACING = IMAGE.GetSpacing()\n O... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create metadata file for list of CHF patients with study ID and subject ID hf_patients_file CSV file with list of dicoms associated with heart failure patients expects column names 'dicom_id', 'study_id', and 'subject_id' metadata_file CSV file with dicom IDs as rows and a number of metadata fields as columns expects c... | def get_metadata(hf_patients_file, metadata_file, output_file):
# Use 'dicom_id' as names for row indices
hf_patients = pd.read_csv(hf_patients_file, sep=',', index_col="dicom_id")
# Use 'dicom' as name
metadata = pd.read_csv(metadata_file, index_col="dicom", dtype={"StudyDate": str, "StudyTime": str}... | [
"def _write_dicom_metadata_csv(df, metadata_file_suffix=None):\n data_path = os.path.join(os.path.expanduser(\"~\"), \"data_usal\", \"01_raw\")\n os.makedirs(os.path.expanduser(data_path), exist_ok=True)\n if metadata_file_suffix is None:\n dicom_meta_path = os.path.join(data_path, \"dicom_metadata.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the help file | def test_help(self):
help_file = os.path.join(cwd, indir, "rdfc_help")
help_text = StringIO()
with redirect_stdout(help_text):
with self.assertRaises(HelpPrinted):
main(["--help"])
if os.path.exists(help_file):
with open(help_file) as f:
... | [
"def test_help(self):\n help_file = os.path.join(cwd, indir, \"r5json_help\")\n help_text = StringIO()\n with redirect_stdout(help_text):\n with self.assertRaises(HelpPrinted):\n main([\"--help\"])\n if os.path.exists(help_file):\n with open(help_file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns css styles from pygments for syntax highlighting | def get_syntax_css(cls):
from pygments.formatters import HtmlFormatter
return HtmlFormatter().get_style_defs('.highlight') | [
"def highlight_css(ctx: click.Context, style: str) -> None:\n for line in (\n pygments.formatters.HtmlFormatter(style=style).get_style_defs().splitlines()\n ):\n click.echo(f\".highlight {line}\")",
"def highlight_code(code, lexer=None):\n# See this page for help with colouring: http://pygment... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generating a random tensor, passing through the model and saving the picture | async def get_image(self):
# generating
fixed_latent = torch.randn(1, 512, 1, 1, device=self.device)
with torch.no_grad():
# passing through
fake_images = self.model(fixed_latent)
# saving
save_image(fake_images, f'models/FaceGAN_dir/faces/fake.j... | [
"def generate_image(model, test_input, target):\n \"\"\"\n As paper said:\n \"At inference time, we run the generator net in exactly the same manner \n as during the training phase. This differs from the usual protocol in that\n we apply dropout at test time, and we apply batch normalization using th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
split the data by filenames into train, val and test sets | def data_split(folder=CONFIG.data_folder, val_proportion=CONFIG.val_proportion):
files = os.listdir(folder)
train_files, val_files, test_files = list(), list(), list()
period = int(np.round(1 / val_proportion))
corruption = list()
max_H, max_W = 0, 0
for (i, file) in enumerate(files)... | [
"def get_train_val_test_split(root: str, val_file: str, test_file: str):\n \n ####################\n # Labels\n ####################\n\n label_list = [label for label in sorted(os.listdir(root)) if os.path.isdir(os.path.join(root, label)) and label[0] != \"_\"]\n label_map = {idx: label for idx, l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
augmentation on a single image. !! currently type = [0..5] | def augmentation_simple(filename, aug_type, max_H, max_W, folder=CONFIG.data_folder):
image = rgb2grey(mpimg.imread(os.path.join(folder, filename)))
image_augmented = np.ones(shape=(max_H, max_W))
(h, w) = np.shape(image)
stride_0, stride_1 = max_H - h, (max_W - w) // 2
offset = ((aug_type % ... | [
"def augment(self, image):\n pass",
"def augment_img(self, image):\n augment_img = iaa.Sequential([\n #iaa.Crop(keep_size=True, percent=(0.01, 0.05), sample_independently=False),\n #iaa.Affine(rotate=(-10, 10)),\n iaa.Fliplr(0.5)])\n image_aug = augment_img.au... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a Swagger parameter definition to a valid JSONSchema Remove known Swagger fields as well as any custom definitions (starting with "x"). | def clean_schema(schema):
# type: (Dict) -> Dict
return {k: v for k, v in schema.items()
if k not in _SWAGGER_FIELDS and not k.lower().startswith("x-")} | [
"def transform_defn_schema(schema,decl):\n conc = goal_conc(schema)\n decl = goal_conc(decl)\n if not(isinstance(decl,il.Definition) and isinstance(conc,il.Definition)):\n return schema\n declargs = decl.lhs().args\n concargs = conc.lhs().args\n if len(declargs) > len(concargs):\n sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We map paths (typically only the relative part) to a canonical class name. In the event that the path is "/", ROOT_CLASS_NAME will be returned. | def path_to_class_name(path):
# type: (unicode) -> unicode
character_map = {
ord("{"): None,
ord("}"): None,
ord("_"): u"/"
}
sanitised = path.translate(character_map)
class_name = u"".join(
# Uppercase the first letter of each non-empty word, while
# preservi... | [
"def classname(path):\n return os.path.normpath(path).replace(os.sep, '.')",
"def normalize_classnames(self):\n classes = self.get_classes()\n start = common = classes[\"list\"][0]\n for _class in classes[\"map\"].iterkeys():\n if len(_class) < len(common):\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We map paths (typically only the relative part) to a canonical operation name. The operation name is used as the name of the function that must provide the serverside logic. Typically the operation name is provided in the Swagger space via the `operationId` field. This function is used as a fallback mechanism when it i... | def path_to_operation(path, verb):
# type: (unicode, unicode) -> unicode
character_map = {
ord("{"): None,
ord("}"): None,
ord("_"): u"/"
}
if path == u"/":
operation = ROOT_OPERATION
else:
sanitised = path.translate(character_map)
operation = u"_".joi... | [
"def default_operation_name_func(request):\n if getattr(request, 'matched_route', None) is None:\n return request.method\n\n return request.matched_route.name",
"def operation_name(operation, ns):\n verb = operation.value.name\n if ns.object_:\n return \"{}_{}\".format(verb, pluralize(ns... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
JSONSchema definitions may contain references. This function replaces all references with their full definitions. Inplace mods are made. | def resolve_schema_references(self, definition):
# type: (Generator, Dict) -> None
if "$ref" in definition:
schema_reference = definition.pop("$ref")
section, name = schema_reference.split("/")[-2:]
referenced_definition = self.parser.specification[section][name]
... | [
"def resolve_references(self, schema: dict) -> dict:\n ref_url = schema.pop('$ref', '')\n if ref_url:\n identifier, ref = self.resolver.resolve(ref_url)\n schema.update(ref)\n schema['id'] = identifier\n\n for value in schema.values():\n if isinstance... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a `urls.py` file from the given specification. | def generate_urls(self):
# type: (Generator) -> str
relative_urls = [path.replace(self.parser.base_path + "/", "")
for path in self.parser.paths]
entries = {
fixup_parameters(relative_url, self.backend): path_to_class_name(relative_url)
for relati... | [
"def uri_template(app, **kwargs):\n assert len(kwargs) == 1\n\n endpoint = kwargs.keys()[0]\n parameters = kwargs.values()[0]\n\n for url in app.url_map.iter_rules():\n if url.endpoint == endpoint:\n break\n else:\n return ''\n\n ut = url.rule\n\n for param, replacement... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a `schemas.py` file from the given specification. | def generate_schemas(self):
# type: (Generator) -> str
schemas = {}
for name, definition in self.parser.specification.get("definitions",
{}).items():
schema = copy.deepcopy(definition)
self.resolve_schema_refer... | [
"def topology_schema_file():\n return Path(\"src/evengsdk/schemas/lab-schema.json\")",
"def build_schema(self, spec, **kwargs):\n pass",
"def write_schema_files():\n print(\"\\nStarting to generate Provider JSON Schemas...\\n\")\n\n for name, generator in schema_generators().items():\n sc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a `views.py` file from the given specification. | def generate_views(self):
# type: (Generator) -> str
return render_to_string(
self.backend, "views.py", {
"classes": self._classes,
'host': self.parser.specification.get('host'),
'basePath': self.parser.specification.get('basePath'),
... | [
"def create_view(name, fields=''):\n if '/' in name:\n blueprint_name, model_name = name.split('/')\n output_file = 'blueprints/%s/views.py' % blueprint_name\n else:\n model_name = name\n output_file = 'views.py'\n file_exists = os.path.exists(output_file)\n form_data = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a `stubs.py` file from the given specification. | def generate_stubs(self):
# type: (Generator) -> str
return render_to_string(
self.backend, "stubs.py", {
"classes": self._classes,
"module": self.module_name
}) | [
"def _write_module_stub(\n filename: str,\n name: str,\n namespace: Optional[str] = None,\n collection: Optional[str] = None,\n) -> None:\n body = ANSIBLE_MOCKED_MODULE.format(\n name=name, collection=collection, namespace=namespace\n )\n with open(filename, \"w\") as f:\n f.write... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a `utils.py` file from the given specification. | def generate_utils(self):
# type: (Generator) -> str
return render_to_string(
self.backend,
"utils.py",
{
"security_defs": self.security_defs
},
) | [
"def generateModCompat():\n checkDirectory(unificationOptions.defaultPath+unificationOptions.compatPath,unificationOptions.logging)\n generateIE()\n generateJEI()\n generateTiCo()",
"def GenPy(mod,fname):\n f = open(fname, 'w')\n title = \"\"\"#\n# This file is generated automatically\n# Author:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a state, return a sequence of (action, state) pairs reachable from this state. If there are many successors, consider an iterator that yields the successors one at a time, rather than building them all at once. Iterators will work fine within the framework. | def successor(self, state):
successors = []
for move in self.getMoves(state):
a = self.tryMove(move, state)
successors.append([move, a])
return successors | [
"def successorStates(self, state):\r\n\r\n successors = []\r\n\r\n for action in Directions.CARDINAL:\r\n x, y = state\r\n dx, dy = Actions.directionToVector(action)\r\n nextx, nexty = int(x + dx), int(y + dy)\r\n\r\n if (not self.walls[nextx][nexty]):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cancels in progress deletion of VMWare Private Cloud. | def cancel_private_cloud_deletion(
project_id: str, zone: str, cloud_name: str
) -> operation.Operation:
return cancel_private_cloud_deletion_by_full_name(
f"projects/{project_id}/locations/{zone}/privateClouds/{cloud_name}"
) | [
"def cancel(self):\n # terminate background thread\n self.stop.set()\n CoordinationAdaptor.delete_cds(self.url)",
"def quota_destroy(self, context, project_id, resource_name):",
"def deprovision(instance_id):\n api_version = bottle.request.headers.get('x-broker-api-version')\n print(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute command on vm and return dict with results | def run_on_vm(env, os_conn, vm, vm_keypair=None, command='uname',
vm_login="cirros", timeout=3 * 60, vm_password='cubswin:)',
vm_ip=None):
results = []
def execute(expected_exceptions=None):
if not os_conn.server_status_is(vm, 'ACTIVE'):
return False
expe... | [
"def test_004_Process_vmoperation(self):\n\n result = CommandProcessor.Process(\n host=self.host,\n args=['vmoperation', 'FakeVm'])\n\n self.assertEqual(result[0], 'vmoperation')\n self.assertEqual(result[1], self.host.GetVm('FakeVm').powerState)",
"def __kvcmd_results(self, cmd, cm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that all vms can ping each other and public ip | def check_vm_connectivity(env, os_conn, vm_keypair=None, timeout=4 * 60):
servers = os_conn.get_servers()
for server1 in servers:
ips_to_ping = [settings.PUBLIC_TEST_IP]
for server2 in servers:
if server1 == server2:
continue
ips_to_ping += os_conn.get_nov... | [
"def online_check():\n try_first_ips = [\n \"216.58.213.238\", # google\n \"8.8.8.8\", # google\n \"8.8.4.4\", # google\n \"46.228.47.115\", # yahoo\n ]\n last_resort_ips = [ # dns root servers\n \"198.41.0.4\",\n \"192.228.79.201\",\n \"192.33.4.12\",\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to parse affiliation strings Parameter | def parse_affiliation(affiliation):
aff_split = affiliation.split(', ')
if len(aff_split) > 1:
return(aff_split[0], ", ".join(aff_split[1:]))
else:
return(None, aff_split[0]) | [
"def parse_author_affiliation(medline):\n authors = []\n article = medline.find(\"Article\")\n if article is not None:\n author_list = article.find(\"AuthorList\")\n if author_list is not None:\n authors_list = author_list.findall(\"Author\")\n for author in authors_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to parse existing affiliations data from file Parameter | def parse_affiliations(path='affiliations.json'):
geo_dict, affils = atj.get_affiliation_json(path)
return geo_dict, affils | [
"def parse_author_affiliation(medline):\n authors = []\n article = medline.find(\"Article\")\n if article is not None:\n author_list = article.find(\"AuthorList\")\n if author_list is not None:\n authors_list = author_list.findall(\"Author\")\n for author in authors_list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The constructor for the RosIotBridgeActionServer class. This function will initialize this node as an action server. We will also load various paramter values from the ROS parameter server, and start a seprate thread to read the data coming from MQTT client | def __init__(self):
# Initialize the action server
self._as = actionlib.ActionServer('/action_ros_iot',
msgRosIotAction,
self.on_goal,
auto_start = False)
# * self.on_goal - Pointer of the function to be called
# when a goal is received
# * self.on_cancel - Pointer of the f... | [
"def __init__(self):\n self.action_server = actionlib.SimpleActionServer(\"navigate_2D_action\",\n Navigate2DAction, self.navigate_cb)\n\n self.robot_point_sub = rospy.Subscriber(\"robot/point\", Point, self.update_robot_position)\n self.robot_current_point = None\n self.robot_go... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The callback function for when a message is received from MQTT This function publishes the message from MQTT to a ROS topic, and uploads it to google sheet. | def mqtt_sub_callback(self, client, userdata, message):
#def mqtt_sub_callback(self, message):
# Decode the message using UTF-8 and convert it
# to 'string' datatype
payload = str(message.payload.decode("utf-8"))
rospy.loginfo("[BRIDGE] Message Received from MQTT")
# Give the appropiate values to the cont... | [
"def on_message(client, userdata, message): \n print(\"Topic: \" + message.topic + \" Message: \" + message.payload.decode('utf-8'))",
"def callback_custom(self, msg):\n self.topic_custom_value = msg.data",
"def on_publish(client: mqtt.Client, userdata: Any, mid: int) -> None:\n logging.info(f\"Suc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the top authors of all time | def topAuthors():
c = db.cursor()
c.execute("select name, sum(hits) as hits\
from authorhits group by name\
order by hits desc;")
results = c.fetchall()
c.close()
return results | [
"def get_most_popular_authors():\n\tdb = psycopg2.connect(database=DBNAME)\n\tc = db.cursor()\n\tc.execute(\" select t1.name,count(*) as total from authors as t1, articles as t2,log as t3 where t3.path=concat('/article/',t2.slug) and t1.id=t2.author group by t1.name order by total desc limit 3;\")\n\tdata = c.fetch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the given filter's type to SupportedFilterType. This method is necessary because click can only accept a single type for its tuple (which is string in this case). | def _convert_filters_type(
filter: List[Tuple[str, PredicateType, SupportedFilterType]],
schema: StateSchema,
) -> List[Tuple[str, SupportedFilterType]]:
new_filter = []
if dataclasses.is_dataclass(schema):
schema = {field.name: field.type for field in fields(schema)}
else:
schema = ... | [
"def _set_filter_type(filter):\n if filter == 'nat':\n return '-N'\n if filter == 'options':\n return '-O'\n if filter == 'filter':\n return '-R'",
"def filter_type(self) -> str:\n return pulumi.get(self, \"filter_type\")",
"def filter_type(self):\n return self._filte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all placement group information from the cluster. | async def list_placement_groups(self, *, option: ListApiOptions) -> ListApiResponse:
try:
reply = await self._client.get_all_placement_group_info(
timeout=option.timeout
)
except DataSourceUnavailable:
raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARN... | [
"def list_groups(self):\n pass",
"def get_all_groups(self) -> APIResponse:\n return self._get(\"list\")",
"def get_all_groups(self):\n self.cursor.execute(\"select * from groups\")\n self.connection.commit()\n return self.cursor.fetchall()",
"def list_groups(self, **params):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all runtime env information from the cluster. | async def list_runtime_envs(self, *, option: ListApiOptions) -> ListApiResponse:
agent_ids = self._client.get_all_registered_runtime_env_agent_ids()
replies = await asyncio.gather(
*[
self._client.get_runtime_envs_info(node_id, timeout=option.timeout)
for node... | [
"def list_environment() -> List[Environment]:\n _check_active_client()\n return _merlin_client.list_environment() # type: ignore",
"def list(self):\n env_list = []\n for (key, val) in self.env.items():\n env_list.append(\"%s=%s\" % (key, val))\n\n return env_list",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all cluster events from the cluster. | async def list_cluster_events(self, *, option: ListApiOptions) -> ListApiResponse:
result = []
all_events = await self._client.get_all_cluster_events()
for _, events in all_events.items():
for _, event in events.items():
event["time"] = str(datetime.fromtimestamp(int(... | [
"def list_events(self, iteration=None):\n return lapi.list_events(\n self.lasif_root, just_list=True, iteration=iteration, output=True\n )",
"def display_all_evets():\n\n view.print_all_events(events.Event.get_events())",
"def collect_events():\n cmd = OPT.kube_cli + \" get events... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove & Set iptable rules for exposing public IP for enobeb instead of private IP.. | def set_enodebd_iptables_rule():
# Remove & Set iptable rules for exposing public ip
# for enobeb instead of private
cfg = load_service_config('enodebd')
port, interface = cfg['tr069']['port'], cfg['tr069']['interface']
enodebd_public_ip = cfg['tr069']['public_ip']
# IPv4 only as iptables only w... | [
"def iptables_apply():\n\n with settings(warn_only=True):\n run(\"sudo iptables-restore < /etc/iptables.rules\")",
"def set_allowed_ips(self,arg):\n self.mod[\"allowed_ips\"] = []\n if arg.custom is not None:\n for c in arg.custom:\n self.mod[\"allowed_ips\"].inse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a dict into a namedtuple. | def to_namedtuple(d, classname='struct'):
if not isinstance(d, dict):
raise ValueError("Can only convert dicts into namedtuple")
for k,v in d.iteritems():
if isinstance(v, dict):
d[k] = to_namedtuple(v)
return namedtuple(classname, d.keys())(**d) | [
"def convert(dictionary):\n return namedtuple('GenericDict', list(dictionary.keys()))(**dictionary)",
"def toNamedtuple(data, name=\"data\"):\r\n return namedtuple(name, data.keys())(*data.values())",
"def dict2tuple(name,d):\n return namedtuple(name,d.keys())(\n *(dict2tuple(k.upper(),v) if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return index of first clay tile found below current/origin tile and if none are found, return 1. Downward flow is possible (not blocked by clay), if 1 is returned, or an index > (y0 + 1) is returned, otherwise downward flow is blocked. Set wet tiles to '|' along path to clay or if no clay all should be set to '|'. If f... | def flow_down(tiles, x0=0, y0=0, dim=14):
global _flowcnt
yclay = -1
for y in range(1+y0, dim-1):
if(tiles[y][x0] == '#'):
yclay = y
if( yclay < 0 ):
# set all tiles below to '|' and return index of deepest '|'
deepest = dim-1
for y in range(y0, dim-y0-1):
tiles[y][x0] = '|'
... | [
"def flow_left(tiles, x0=0, y0=0, dim=14):\n global _flowcnt\n for xl in range(x0-1, 0, -1):\n if(tiles[y0][xl] == '#'):\n return [xl, y0]\n else:\n tiles[y0][xl] = '|' ; _flowcnt += 1 # flowing left\n if( tiles[y0+1][xl] == '.' ): # stop flowing left and head down\n tiles[y0][xl] = '|... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return index of first clay tile found right of current/origin tile and if none are found, return 1. Rightward flow is possible (not blocked by clay), if 1 is returned, or an index > x+1 is returned, otherwise rightward flow is blocked. Set wet tiles to either '|' along path to clay or if no clay all should be set to '|... | def flow_right(tiles, x0=0, y0=0, dim=14):
global _flowcnt
for xr in range(x0+1, dim-1):
if(tiles[y0][xr] == '#'):
return [xr, y0]
else:
tiles[y0][xr] = '|' ; _flowcnt += 1 # flowing right
if( tiles[y0+1][xr] == '.' ): # flow down -- stop flowing right and flow down
deepest = flow_... | [
"def flow_left(tiles, x0=0, y0=0, dim=14):\n global _flowcnt\n for xl in range(x0-1, 0, -1):\n if(tiles[y0][xl] == '#'):\n return [xl, y0]\n else:\n tiles[y0][xl] = '|' ; _flowcnt += 1 # flowing left\n if( tiles[y0+1][xl] == '.' ): # stop flowing left and head down\n tiles[y0][xl] = '|... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return index of first clay tile found left of current/origin tile and if none are found, return 1. Leftward flow is possible (not blocked by clay), if 1 is returned, or an index < x1 is returned, otherwise leftwardward flow is blocked. Set wet tiles to either '|' or '+' along path to clay or if no clay all should be se... | def flow_left(tiles, x0=0, y0=0, dim=14):
global _flowcnt
for xl in range(x0-1, 0, -1):
if(tiles[y0][xl] == '#'):
return [xl, y0]
else:
tiles[y0][xl] = '|' ; _flowcnt += 1 # flowing left
if( tiles[y0+1][xl] == '.' ): # stop flowing left and head down
tiles[y0][xl] = '|'
de... | [
"def _getLeft(self, list, index) :\n search = list[index:] + list[:index]\n search.reverse() # List reordered to be in the order we want to search\n for x in range(len(search)) :\n if search[x] == 1 :\n return (index - 1 - x) % len(list)\n if DEBUG : print \"no ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Once all the leftrightdownward flow has been established, evaluate the overflow tiles that hold steadystate H2O and reset their respective '|' values to '~'. For eash row of tiles, find areas bounded by clay leftrightbelow, anf if tile(s) are marked as '|', set to '~'. Perhapes simplest to navigate is bottomup, assumim... | def overflow(tiles, xsrc, dim=14):
global _flowcnt
global _wetcnt
blocked = [False for idx in range(0, dim-1)]
for y in range(dim-2, 0, -1):
for x in range(0, dim-1):
if( tiles[y][x] == '|' ):
if( tiles[y+1][x] == '#' or tiles[y+1][x] == '~' ):
tiles[y][x] = '~'
_flowcnt... | [
"def flow_down(tiles, x0=0, y0=0, dim=14):\n global _flowcnt\n yclay = -1\n for y in range(1+y0, dim-1):\n if(tiles[y][x0] == '#'):\n yclay = y\n \n if( yclay < 0 ):\n # set all tiles below to '|' and return index of deepest '|'\n deepest = dim-1\n for y in range(y0, dim-y0-1):\n tiles[y]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Push message into prequeue. Will be added to queue when flushMsgs() is called. This is done to prevent miners that execute later in a step from acting on msgs from miners that executed earlier that step. | def pushMsg(self, msg, delay=0):
self.pre_queue.append([msg, delay]) | [
"def flushMsgs(self):\n\n self.queue = self.pre_queue[:]\n self.pre_queue = []",
"def enqueue (self, session, msg):\n self.__msgq.put((session, msg))",
"def add_queued_msg_to_whitelist(self):\n\n\t\tqueueFileName = self.queue_file(self.config_md5)\n\n\t\t## Create a new AskMessage instanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds all messages from prequeue to queue. | def flushMsgs(self):
self.queue = self.pre_queue[:]
self.pre_queue = [] | [
"def add_to_queue(self, msg):\n print(\"queue size : \", self.q.qsize())\n if self.q.full():\n self.temp_buffer.append(msg)\n else:\n self.q.put(msg)\n if len(self.temp_buffer) > 0:\n self.add_to_queue(self.temp_buffer.pop())",
"def pushMsg(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pops all messages with delay 0 from queue, decrements delay of all other messages in queue. | def popMsg(self):
if not self.queue:
return []
returned_msgs = []
for msg, delay in self.queue:
delay -= 1
if delay < 1:
returned_msgs.append(msg)
else:
self.pushMsg(msg, delay)
self.queue = []
retur... | [
"def clearQueueAll():",
"def flushMsgs(self):\n\n self.queue = self.pre_queue[:]\n self.pre_queue = []",
"def drop_message(self):\n heapq.heappop(self._message_queue)",
"def send_pending_messages(self):\n num_played_frames = self.mem_player.get_num_played_frames()\n\n del_me... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Broadcast tx to all adjacent miners. | def broadcast(self, tx):
for neighbor_id in self.adjacencies:
self.sendMsg(neighbor_id, Message(self.id, Type.BLOCK, tx)) | [
"def broadcast_transactions(self, txs_list):\n for tx in txs_list:\n for node in self.G.nodes(data=False):\n if random.random() < self.pp: # Node is malicious\n self.send_message_to_neighbors(node, tx, inital_message=True)",
"def spreadTransactionToOtherMiners(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send request for a tx with target_hash. Provided so subclasses don't have to know about Message/Type classes. | def sendRequest(self, recipient_id, target_hash):
self.sendMsg(recipient_id, Message(self.id, Type.REQUEST, target_hash)) | [
"def fetch_transaction(self, tx_hash, cb):\r\n data = serialize.ser_hash(tx_hash)\r\n self.send_command('blockchain.fetch_transaction', data, cb)",
"def get_transaction(self, tx_hash):\n raise NotImplementedError()",
"def get_tx(self, tx_hash):\n url = urljoin(self.api_host, f\"/api/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process new tx by adding it to miner's view of blockain and broadcasting tx if appropriate. | def handleNewTx(self, tx, sender_id):
self.seen_tx[tx.hash] = tx
for x in self.processNewTx(tx, sender_id): # ABSTRACT - Process tx.
self.broadcast(x) # Broadcast new or first-time-seen-NON-ORPHAN tx only. | [
"def _on_new_tx(self, key: HathorEvents, args: EventArguments) -> None:\n if self.manager.can_start_mining():\n block_templates = self.get_block_templates()\n if block_templates != self._last_broadcast:\n self.broadcast_notification(method='mining.notify', params=block_te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receive all messages and handle by adding new tx to chain and sending requested tx. | def handleMsgs(self):
force_sheep_check = self.changed_last_step
self.changed_last_step = False
if not self.queue:
return
need_to_check = False
for msg in self.popMsg(): # Receive message(s) from queue.
if msg.type == Type.BLOCK:
new_tx ... | [
"def handleNewTx(self, tx, sender_id):\n\n self.seen_tx[tx.hash] = tx\n for x in self.processNewTx(tx, sender_id): # ABSTRACT - Process tx.\n self.broadcast(x) # Broadcast new or first-time-seen-NON-ORPHAN tx only.",
"async def incoming_chaindata(session: DbSession, tx: ChainTxDb):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a new transaction (simulation rolled protocol's generation probability). | def makeNewTx(self):
new_tx = self.makeTx() # ABSTRACT - Make a new tx.
logging.info("New tx (%d) created by miner %d" % (new_tx.id, self.id))
self.changed_last_step = True
self.handleNewTx(new_tx, self.id)
self.checkAllTx() | [
"def _create_random_transaction():\n return {\n \"source\":_random_account_id(),\n \"target\":_random_account_id(),\n \"amount\":_random_amount(),\n \"currency\":\"EUR\"\n }",
"def create_god_transaction(to_pk):\n\n god_pk, god_sk = signature.generate_keys()\n tx = Transact... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a default kernel configuration for sampling the assignment (clustering) vector. The default kernel is currently a gibbs sampler. | def default_assign_kernel_config(defn):
# XXX(stephentu): model_descriptors should implement
# is_conjugate()
def is_nonconj(x):
return x.name() == 'bbnc'
nonconj_indices = [
idx for idx, x in enumerate(defn.models()) if is_nonconj(x)
]
defn = _validate_definition(defn)
#... | [
"def default_kernel_config(defn):\n return [('beam', {}),\n ('hypers',\n {\n 'alpha_a': 4.0,\n 'alpha_b': 2.0,\n 'gamma_a': 3.0, \n 'gamma_b': 6.0\n }\n )]",
"def default_kernel_confi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a default kernel configuration for sampling the component (feature) model hyperparameters. The default kernel is currently a onedimensional slice sampler. | def default_feature_hp_kernel_config(defn):
defn = _validate_definition(defn)
# hyperparams
hparams = {}
for i, hp in enumerate(defn.hyperpriors()):
if not hp:
continue
# XXX(stephentu): we are arbitrarily picking w=0.1
hparams[i] = {k: (fn, 0.1) for k, fn in hp.iter... | [
"def default_kernel_config(defn):\n # XXX(stephentu): should the default config also include cluster_hp?\n return list(it.chain(\n default_assign_kernel_config(defn),\n default_feature_hp_kernel_config(defn)))",
"def default_kernel_config(defn):\n return [('beam', {}),\n ('hypers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a default kernel configuration for sampling the component (feature) model hyperparameters via gridded gibbs. | def default_grid_feature_hp_kernel_config(defn):
defn = _validate_definition(defn)
config = {}
grid = enumerate(zip(defn.models(), defn.hyperpriors()))
for fi, (model, priors) in grid:
partials = copy.deepcopy(model.default_partial_hypergrid())
if not partials:
continue
... | [
"def default_kernel_config(defn):\n return [('beam', {}),\n ('hypers',\n {\n 'alpha_a': 4.0,\n 'alpha_b': 2.0,\n 'gamma_a': 3.0, \n 'gamma_b': 6.0\n }\n )]",
"def default_kernel_confi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a default kernel configuration suitable for general purpose inference. Currently configures an assignment sampler followed by a component hyperparameter sampler. | def default_kernel_config(defn):
# XXX(stephentu): should the default config also include cluster_hp?
return list(it.chain(
default_assign_kernel_config(defn),
default_feature_hp_kernel_config(defn))) | [
"def default_kernel_config(defn):\n return [('beam', {}),\n ('hypers',\n {\n 'alpha_a': 4.0,\n 'alpha_b': 2.0,\n 'gamma_a': 3.0, \n 'gamma_b': 6.0\n }\n )]",
"def default_assign_kerne... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the specified mixturemodel kernel for `niters`, in a single thread. | def run(self, r, niters=10000):
validator.validate_type(r, rng, param_name='r')
validator.validate_positive(niters, param_name='niters')
model = bind(self._latent, self._view)
for _ in xrange(niters):
for name, config in self._kernel_config:
if name == 'assign... | [
"def keras_multitask(self, args):\n start_time = time.time()\n\n # if self.args.log_metrics:\n # utils.wandb_init_logs(self.config[\"multitask_trainer\"])\n\n embedding_type = self.config[\"multitask_trainer\"][\"embedding_type\"]\n max_len = int(self.config[\"multitask_traine... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate random identity in the range [0,MAX_IDENT) | def rand_ident():
return random.randrange(MAX_IDENT) | [
"def rand_id():\n return str(randrange(9))",
"def genAccountNo():\n from random import randint\n\n accountNumber = randint(0000000000, 9999999999)\n return accountNumber",
"def get_random_id() -> int:\n return uuid.uuid1().int >> 64",
"def generate_id():\n return str(hex(int(time.time() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Go over a list of knodes, and remove knodes that show up more than once. In case of node ident showing more than once, we pick the shorter path. | def remove_knodes_duplicates(knodes):
if len(knodes) == 0:
return knodes
knodes.sort(key=lambda kn:(kn.ident,kn.path_len))
# Resulting array
cur_ident = knodes[0].ident
res = [knodes[0]]
for kn in knodes[1:]:
if kn.ident != cur_ident:
cur_ident = kn.ident
... | [
"def reduction1(g: nx.MultiGraph, k):\n changed = False\n vs = list(nx.nodes_with_selfloops(g))\n for v in vs:\n g.remove_node(v)\n k -= 1\n changed = True\n return k, vs, changed",
"def _augment_keep_nodes_list(keep_node_paths, planned_prune_nodes, planned_keep_nodes):\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the exact location of successor finger f. | def get_finger_succ_loc(self,f):
return (self.ident + 2**f) % MAX_IDENT | [
"def get_finger_pred_loc(self,f):\n return (self.ident - 2**f) % MAX_IDENT",
"def get_best_succ_finger(self,f):\n return min(self.best_finger_succ[f],\\\n key=lambda kn:dist_ident(self.get_finger_succ_loc(f),kn.ident))",
"def get_best_pred_finger(self,f):\n return min(self.be... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the exact location of predecessor finger f. | def get_finger_pred_loc(self,f):
return (self.ident - 2**f) % MAX_IDENT | [
"def get_finger_succ_loc(self,f):\n return (self.ident + 2**f) % MAX_IDENT",
"def locate_predecessor(self, key):\r\n index = self.search(key)\r\n return index-1",
"def get_best_succ_finger(self,f):\n return min(self.best_finger_succ[f],\\\n key=lambda kn:dist_ident(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set knodes to be the neighbours of this Node. | def set_neighbours(self,knodes):
self.neighbours = []
for kn in knodes:
# Make sure we don't have ourselves as a neighbour:
if kn.ident == self.ident:
continue
# A neighbour has a path length 1:
self.neighbours.append(\
... | [
"def define_k_neighbours(self, k_neighbours):\n self.k_neighbours = k_neighbours",
"def updateNodeNeighbors(self) -> None:\n for node in self.grid:\n node.updateNeighbors(self.grid, self.horizontal_nodes, self.vertical_nodes)",
"def rand_neighbours(self):\n # Initialize neighbour... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If any of the nodes in knodes is a better candidate for the f's successor finger, we replace. | def add_known_best_finger_succ(self,f,knodes):
pool = remove_knodes_duplicates(self.best_finger_succ[f] + knodes)
self.best_finger_succ[f] = heapq.nsmallest(self.fk,pool,key=lambda kn:\
(dist_ident(self.get_finger_succ_loc(f),kn.ident),kn.path_len)) | [
"def add_known_best_finger_pred(self,f,knodes):\n pool = remove_knodes_duplicates(self.best_finger_pred[f] + knodes)\n self.best_finger_pred[f] = heapq.nsmallest(self.fk,pool,key=lambda kn:\\\n (dist_ident(kn.ident,self.get_finger_pred_loc(f)),kn.path_len))",
"def update_finger_table(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If any of the nodes in knodes is a better candidate for the f's predecessor finger, we replace. | def add_known_best_finger_pred(self,f,knodes):
pool = remove_knodes_duplicates(self.best_finger_pred[f] + knodes)
self.best_finger_pred[f] = heapq.nsmallest(self.fk,pool,key=lambda kn:\
(dist_ident(kn.ident,self.get_finger_pred_loc(f)),kn.path_len)) | [
"def add_known_best_finger_succ(self,f,knodes):\n pool = remove_knodes_duplicates(self.best_finger_succ[f] + knodes)\n self.best_finger_succ[f] = heapq.nsmallest(self.fk,pool,key=lambda kn:\\\n (dist_ident(self.get_finger_succ_loc(f),kn.ident),kn.path_len))",
"def update_finger_table(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a set of known nodes to self.known . Take the change of path_len into acount. | def add_known_nodes(self,source_path_len,knodes):
# Update the path lengths:
updated_knodes = [kn._replace(path_len=kn.path_len+source_path_len)\
for kn in knodes]
# Make sure the node self.ident is not inside:
updated_knodes = list(filter(lambda kn:kn.ident != self.iden... | [
"def check_with_known(unknown, known):\n\tnew \t= 0\n\tfor seq in unknown:\n\t\tif seq not in known:\n\t\t\tnew += 1\n\tprint 'New alleles:', new",
"def _add_nodes(self):\n\n nodes = self.__create_all_possible_nodes()\n self.add_nodes_from(nodes)",
"def set_neighbours(self,knodes):\n self.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the best successor for finger f. | def get_best_succ_finger(self,f):
return min(self.best_finger_succ[f],\
key=lambda kn:dist_ident(self.get_finger_succ_loc(f),kn.ident)) | [
"def get_best_pred_finger(self,f):\n return min(self.best_finger_pred[f],\\\n key=lambda kn:dist_ident(kn.ident,self.get_finger_pred_loc(f)))",
"def get_finger_succ_loc(self,f):\n return (self.ident + 2**f) % MAX_IDENT",
"def add_known_best_finger_succ(self,f,knodes):\n pool ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the best predecessor for finger f. | def get_best_pred_finger(self,f):
return min(self.best_finger_pred[f],\
key=lambda kn:dist_ident(kn.ident,self.get_finger_pred_loc(f))) | [
"def get_best_succ_finger(self,f):\n return min(self.best_finger_succ[f],\\\n key=lambda kn:dist_ident(self.get_finger_succ_loc(f),kn.ident))",
"def predecessor(self, key):\r\n index = self.locate_predecessor(key)\r\n return self.keys[index] if index >= 0 else None",
"def add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given an index i of a node in self.nodes, create a Knode tuple. Optionally set path_len. | def make_knode(self,i,path_len=0):
return Knode(path_len=path_len,\
ident=self.nodes[i].ident,\
lindex=i) | [
"def _new_node(self):\n self._size += 1\n return self._node_factory()",
"def new_node(name):\n\n return name, []",
"def construct(self, keys: List[int], option: str = 'dense') -> Node:\n keys.sort()\n leaf_distribution = self.get_node_dist(len(keys), NodeType.LEAF, option)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomize immediate neighbours links between the nodes. | def rand_neighbours(self):
# Initialize neighbours sets as empty sets:
nodes_nei = [set() for _ in range(self.num_nodes)]
for i,nd in enumerate(self.nodes):
# Sample a set of indices (Which represent a set of nodes).
# Those nodes will be nd's neighbours:
nod... | [
"def topology_random_connect(self, probability):\n\t\tfor i in range(len(self.sites) - 1):\n\t\t\tfor j in range(i + 1, len(self.sites)):\n\t\t\t\tif not (self.sites[j] in self.sites[i].neighbors):\n\t\t\t\t\tif numpy.random.rand() < probability:\n\t\t\t\t\t\tself.sites[i].neighbors.append(self.sites[j])\n\t\t\t\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ask all known nodes for better known nodes. i is the index of the node in self.nodes. | def iter_node(self,i):
nd = self.nodes[i]
for kn in nd.get_close():
# for kn in nd.get_known():
# for kn in nd.neighbours:
kn_node = self.nodes[kn.lindex]
nd.add_known_nodes(kn.path_len,kn_node.get_close()) | [
"def iter_all(self):\n for i in range(self.num_nodes):\n self.iter_node(i)",
"def get_all_nodes(self):\n pass",
"def neighbors(self, i):\r\n return unique(\r\n j for e in self.nodes[i] for j in self.edges[e]\r\n if (j != i)\r\n )",
"def neighbor_edg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform a full iteration, where all nodes ask other nodes for better nodes. | def iter_all(self):
for i in range(self.num_nodes):
self.iter_node(i) | [
"def algorithm_loop(self):",
"def do_recursions(self):\n for _ in range(self.iterations):\n self.features = self.do_a_recursion()",
"def do_recursions(self):\n for iteration in range(self.iterations):\n self.features = self.do_a_recursion()",
"def run_all_iterations(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify the succ and pred fingers found for all nodes. | def verify_succ_pred_fingers(self):
# Get all nodes (as Knodes), and sort them according to ident:
lnodes = list(map(self.make_knode,range(self.num_nodes)))
lnodes.sort(key=lambda ln:ln.ident)
idents = [ln.ident for ln in lnodes]
for i,ln in enumerate(lnodes):
nd = s... | [
"def verifyNode():\n return verifyReturnNode() and verifyBreakContinueNode() and verifyDefault()",
"def all_nodes_seen( root ):\n if root._Seen:\n a, b = True, True\n if root._Left: a = all_nodes_seen( root._Left )\n if root._Right: b = all_nodes_seen( root._Right )\n return a an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For debugging, iterate over all segments and print the tour distances between them. | def print_all_distances(self):
seg_pairs = [(begin, end) for begin in self.sim.segments
for end in self.sim.segments if begin != end]
for begin, end in seg_pairs:
msg = "{} to {} is {}".format(
begin, end, self.movement_model.shortest_distance(begin, end... | [
"def print_distances(self):\n for this_id, distance in enumerate(self.distances):\n print self.ids[this_id] + ' travelled ' + str(distance) + ' km'",
"def print_distances(self):\n for row in self.grid:\n for cell in row:\n print(f'{cell.distance:02d} ', end=' ')\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the communication delay between any two segments. This is done as per Equation 1 in FLOWER. | def communication_delay(self, begin, end):
duration, path = self.movement_model.shortest_distance(begin, end)
path_clusters = self.count_clusters(path)
segment_speed_pairs = list()
path_index = 0
last_segment = None
for path_cluster in path_clusters:
segment... | [
"def find_delay(signal1, signal2):\r\n if signal1.N != signal2.N:\r\n return print('Signal1 and Signal2 must have the same length')\r\n else:\r\n freqSignal1 = signal1.freqSignal\r\n freqSignal2 = sfft.fft(np.flipud(signal2.timeSignal))\r\n convoluted = np.real(sfft.ifft(freqSignal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge the content of `csv1_path` and `csv2_path` and save the result to `csv_out_path`. After loading the content of `csv1_path` and `csv2_path` to two dataframes, the latter are joined based on the attribute ROW_ID, then the attribute RATIO is calculated as VAR1/VAR2. In case the value of df2.variable2 is 0, the ratio... | def merge(csv1_path, csv2_path, csv_out_path):
df1 = prepare_df(csv1_path, var_name='variable1')
df2 = prepare_df(csv2_path, var_name='variable2')
if df1.shape[0] != df2.shape[0]:
raise MergerError("Dataframes with different number of rows")
df_merge = pd.merge(df1[[ROW_ID, STORE_ID, ADDRESS, ... | [
"def merge_2_csv(\n csv1_path='./train.csv', \n csv2_path='./other_news-v4_aug-from-tbrain.csv', \n save_csv_path='./merge-tbrain-and-aug-from-tbrain.csv'):\n df1 = pd.read_csv(csv1_path, keep_default_na=False)\n df2 = pd.read_csv(csv2_path, keep_default_na=False)\n\n is_from_tbrain = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a private utility function for getBytesIOString to return chr(ord(x)) | def _chr_ord(x):
return chr(ord(x)) | [
"def chb(x):\n if isinstance(x, bytes):\n return x\n else:\n if hasattr(x, \"__int__\") and not isinstance(x, int):\n return bytes(chr(int(x)))\n return bytes(chr(x))",
"def orb(x):\n if isinstance(x, (bytes, str)):\n return ord(x)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return bytesIO.getvalue(), making sure the result is a str. This is necessary because getvalue() returns a bytes object in Python 3. | def getBytesIOString(bytesIO):
if _BytesIOValueIsStr:
# We don't need to convert.
return bytesIO.getvalue()
else:
# Assume value is a Python 3 bytes object. Convert to str.
return "".join(map(_bytesElementToChr, bytesIO.getvalue())) | [
"def _as_str(value):\n\tif isinstance(value, bytes):\n\t\treturn value.decode(\"utf-8\", \"replace\")\n\telif isinstance(value, str):\n\t\treturn value\n\telse:\n\t\traise TypeError(\"expected bytes\")",
"def getvalue(self):\n try:\n buffer_value = self.buffer.getvalue().decode()\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if obj has type str or (in Python 2) unicode. This is necessary because Python 2 has two string types, str and unicode, but Python 3 doesn't have type unicode so we have to be careful to check for type(obj) is unicode. | def typeIsString(obj):
return type(obj) is str or _haveTypeUnicode and type(obj) is unicode | [
"def not_a_string(obj):\n my_type = str(type(obj))\n if is_py3():\n is_str = my_type.find('bytes') < 0 and my_type.find('str') < 0\n return is_str\n\n return my_type.find('str') < 0 and \\\n my_type.find('unicode') < 0",
"def is_unicode(obj):\n if PYTHON3:\n return False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the input has type str (in Python 3) or unicode (in Python 2), then encode it as UTF8 and return an array of integers. If the input is str (in Python 2) then treat it as a "raw" string and just convert each element to int. Otherwise, if the input is not str or unicode, just return the input. This is necessary becaus... | def stringToUtf8Array(input):
if _haveTypeUnicode:
# Assume this is Python 2.
if type(input) is str:
# Convert the raw string to an int array.
return map(ord, input)
elif type(input) is unicode:
# In Python 2, the result of enco... | [
"def bytes2integers(data):\n return list(data)",
"def __convert_string_to_numeric_array(string):\r\n return [int(char) for char in string]",
"def str_to_int_array(str_number):\n return [int(digit) for digit in str_number]",
"def strings_to_int(strings):\n return [ int(num) for num in strings ]",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If value is None or negative, return None, otherwise return float(value). This is used in "setter" methods to ensure the correct type. | def nonNegativeFloatOrNone(value):
return None if value == None or value < 0 else float(value) | [
"def try_float(value: Any) -> Optional[float]:\n try:\n return float(value)\n except (TypeError, ValueError):\n return None",
"def tryFloat(value):\n try:\n return float(value)\n except:\n return value",
"def do_float(value, default=0.0):\r\n try:\r\n return flo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode the input as base64. | def base64Encode(input, addNewlines = False):
base64Str = base64.b64encode(input)
if not type(base64Str) is str:
base64Str = "".join(map(chr, base64Str))
if not addNewlines:
return base64Str
result = ""
i = 0
while i < len(base64Str):... | [
"def f_base64_encode(self):\n return base64.b64encode(self.input)",
"def base64_encode(data):\n return base64.encodestring(data);",
"def encode(data):\n return base64.b64encode(data)",
"def encode_base64(input_bytes: bytes) -> str:\n output_bytes = base64.b64encode(input_bytes)\n output_str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure that the /locations endpoint returns location data | def test_locations(self):
url = reverse("locations", args=[00000])
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(isinstance(response.data, list))
self.assertTrue(response.data) # list not empty
location_data ... | [
"def api_get_locations():\n locations = []\n return jsonify(locations)",
"def test_locations(self):\n response = self.client.get(reverse('manage:locations'))\n eq_(response.status_code, 200)",
"def test_user_location_GET(self):\r\n\r\n with self.client:\r\n u = User.query.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a sqlite3.Row to a string representing JSON | def row_to_json(row: sqlite3.Row) -> str:
d = {}
for key in row.keys():
d[key] = row[key]
return json.dumps(d) | [
"def row_list_to_json(rows: List[sqlite3.Row]) -> str:\n l = []\n for row in rows:\n l.append(row_to_json(row))\n\n return json.dumps(l)",
"def to_json_line(bq_row):\n row = dict()\n for key in bq_row:\n row[key] = bq_row[key]\n\n # default=str converts non JSON serializable object... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a List[sqlite3.Row] to a string representing JSON | def row_list_to_json(rows: List[sqlite3.Row]) -> str:
l = []
for row in rows:
l.append(row_to_json(row))
return json.dumps(l) | [
"def row_to_json(row: sqlite3.Row) -> str:\n d = {}\n for key in row.keys():\n d[key] = row[key]\n\n return json.dumps(d)",
"def convert_to_json(self, rows):\n\t\tjson_list = []\n\t\tfor row in rows:\n\t\t\tjson_record = {}\n\t\t\tjson_record[\"movie_id\"] = row[0]\n\t\t\tjson_record[\"title\"] = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if user's answer is the same as the correct answer, ignoring case | def is_correct_answer(user_answer, correct_answer):
string_correct_answer = str(correct_answer).lower()
string_user_answer = str(user_answer).lower()
return string_user_answer == string_correct_answer
# If you accidentally used the same variable name
# twice in the comparison, for example
# ... | [
"def is_correct(self):\n return self.submission_text.lower() == self.puzzle.answer.lower()",
"def ask_and_evaluate(self):\n\n answer = raw_input(\"{} > \".format(self.question))\n return answer.lower() == self.correct_answer.lower()\n # User's answer doesn't have to match the capitaliz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cuboid route. A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F, sits in the opposite corner. By travelling on the surfaces of the room the shortest "straight line" distance from S to F is 10 and the path is shown on the diagram.  However, there are up to ... | def problem_086(limit,verbose):
# Three routes:
# *------F Sides labeled A, B, C, routes clockwise from S
# | /| R1^2 = (A + C)^2 + B^2
# | / n R2^2 = (B + C)^2 + A^2
# +-----+------+-----F R3^2 = (A + B)^2 + C^2
# | | / | . `|
... | [
"def get_shortest_route_floyd(network, start,destination, excludings=[]):\n\n # On récupère la liste des villes\n list_city = network[1].keys()\n \n # Si la ville de départ ou de fin n'existe pas\n if start not in list_city or destination not in list_city:\n return None\n\n # On retire les villes à exclure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes list of I3 OMKeys and I3 omgeo object and returns the positions of all hit DOMs. | def DOM_positions(omkeys, omgeo):
x_list = []
y_list = []
z_list = []
r_list = []
for omkey in omkeys:
x_list.append(omgeo[omkey].position.x)
y_list.append(omgeo[omkey].position.y)
z_list.append(omgeo[omkey].position.z)
r_list.append(np.sqrt(omgeo[omkey].position.x**2... | [
"def get_goi_hits_coords(fileNames, chrom, pos1, pos2):\n\tprint('getting coords to GOI hits')\n\n\tglobal queryChrom, lPosQuery, rPosQuery # dont like this\n\tgenomePos_laud_db = pd.Series(database_laud['Mutation genome position'])\n\tcells_dict_GOI_coords = {}\n\tqueryChrom = chrom\n\tlPosQuery = pos1\n\trPosQuer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wait for a flag to be raised. Nonasyncio primitives are generally not our worry, but we support them for convenience. | async def wait_flag(
flag: Optional[Flag],
) -> Any:
if flag is None:
return None
elif isinstance(flag, asyncio.Future):
return await flag
elif isinstance(flag, asyncio.Event):
return await flag.wait()
elif isinstance(flag, concurrent.futures.Future):
loop = async... | [
"async def raise_flag(\n flag: Optional[Flag],\n) -> None:\n if flag is None:\n return None\n elif isinstance(flag, asyncio.Future):\n flag.set_result(None)\n elif isinstance(flag, asyncio.Event):\n flag.set()\n elif isinstance(flag, concurrent.futures.Future):\n flag.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raise a flag. Nonasyncio primitives are generally not our worry, but we support them for convenience. | async def raise_flag(
flag: Optional[Flag],
) -> None:
if flag is None:
return None
elif isinstance(flag, asyncio.Future):
flag.set_result(None)
elif isinstance(flag, asyncio.Event):
flag.set()
elif isinstance(flag, concurrent.futures.Future):
flag.set_result(None... | [
"def flag(self, flag: Optional[str], set_raised: bool = True) -> bool:\n\n # If flag is None, do nothing.\n if flag is None:\n return False\n # If we are trying to raise a flag...\n if set_raised:\n # If the flag is not already raised, raise it.\n if flag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize a URI (and return a string) | def normalize_uri(uri):
return normalize_uri_result(uri).unsplit() | [
"def normalize_uri(uri, encoding='utf-8'):\n normalized_reference = URIReference.from_string(uri, encoding).normalize()\n return normalized_reference.unsplit()",
"def normalize_uri(uri):\n if isinstance(uri, str):\n uri = uri.decode('utf-8')\n return uri.strip().replace(u' ', u'_')",
"def nor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalize a URI (And return a URIResult) | def normalize_uri_result(uri):
ref = uri_reference(uri).normalize()
return ref._replace(
authority=normalize_uri_authority(ref),
query=normalize_uri_query(ref),
path=normalize_uri_path(ref),
) | [
"def normalize_uri(uri):\n return normalize_uri_result(uri).unsplit()",
"def normalize_uri(uri, encoding='utf-8'):\n normalized_reference = URIReference.from_string(uri, encoding).normalize()\n return normalized_reference.unsplit()",
"def normalize_uri(uri):\n if isinstance(uri, str):\n uri =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that calls the appropiate developed vtk writer to write the 3d vector field to the desired format. Inputs field Vector field which will be added to the vtk file numpy.array([x,y,z,u,v,w]) path path with name of file where the field will be written. VTKformat Desired VTK format from the developed. | def vF3d_VTK(field,name,VTKformat):
if VTKformat == 'vtu':
vf3d_vtu(field,name)
elif VTKformat == None:
print 'Please select a VTK format'
else:
print 'The selected format has not been developed yet'
return #nothing, since functions output the written VTK file | [
"def WriteVTK(self, filename=None, result=None, fmt=\"binary\", interpolation_degree=10, ProjectionFlags=None):\n\n self.__do_essential_memebers_exist__()\n\n if fmt == \"xml\":\n pass\n elif fmt == \"binary\":\n try:\n from pyevtk.hl import pointsToVTK, lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that wtrites a .vtu file Inputs field Vector field which will be added to the vtk file numpy.array([x,y,z,u,v,w]) name Name of the .vtu field C.Losada de la Lastra 2015 | def vf3d_vtu(field,name):
[X,Y,Z,U,V,W] = field #3d velocity field
#achieve the correct format
Pnts = F3d_2_vtkFromat(N.array([X,Y,Z]))
velF = F3d_2_vtkFromat(N.array([U,V,W]))
#name the vtu file
if name == None:
vtu = 'vf3VTU.vtu'
else:
vtu = name + '.vtu'
... | [
"def vtp(self, f_vtu, f_vtp):\r\n reader = vtk.vtkXMLUnstructuredGridReader()\r\n reader.SetFileName(f_vtu)\r\n reader.Update()\r\n ugrid = reader.GetOutput()\r\n geometryFilter = vtk.vtkGeometryFilter()\r\n geometryFilter.SetInputData(ugrid)\r\n geometryFilter.Updat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that turns a 3d field F3d in [Fx,Fy,Fz] format to a [[fx1,fy1,fz1], ... ,[fxn,fyn,fzn]] fomat Where FX is the zyx array corresponding to the x component of the field and fx1 is the x component of the field at the first point Inputs f3d field which will be converted by the function. C.Losada de la Lastra 2015 | def F3d_2_vtkFromat(F3d):
#asign variables
[Fx,Fy,Fz] = F3d
#generate the output array
F3dVTK = N.array([N.zeros(3) for i in range(len(Fx)*len(Fy[0])*len(Fz[0][0]))])
#loop and rearange
c=0
for k in range(len(Fz)):
for j in range(len(Fz[0])):
for i in range(len(... | [
"def test_3d_tranpose(): \n dic,data = ng.pipe.read_lowmem(\"common_data/3d_pipe/ft/test%03d.ft3\")\n fdic,fdata = ng.pipe.read(\"common_data/3d_pipe/ft/test%03d.ft3\")\n\n assert_array_equal(data.transpose()[0,1,2],fdata.transpose()[0,1,2])\n assert_array_equal(data.transpose((2,0,1))[0,1,2],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method saves a light curve to file. | def saveLightcurve(self, filename):
lfile = open(filename, 'w')
lfile.write("# time \t counts \t countrate \n")
for t,c,cr in zip(self.time, self.counts, self.countrate):
lfile.write(str(t) + "\t" + str(c) + "\t" + str(cr) + "\n")
lfile.close() | [
"def save(self, filename, overwrite=False, verbose=True, msg=''):\n if msg:\n msg = ' \"%s\"' % msg\n save_to_file(\n filename, self, overwrite=overwrite, verbose=verbose,\n showname='curve%s' % msg\n )",
"def saveFile(self,\n event, \n plot):\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test our own custom resource MyTestResource | def test_custom_resource():
data = {
'name': 'Wort wort',
'slug': 'sluggy',
'not_valid': 'nooo'
}
instance = PeopleResource(**data)
# We should have this attribute
assert hasattr(instance, 'name')
# But this one is missing
assert not hasattr(instance, 'another_thing')... | [
"def test_custom_resource_type(self):\n template = Template()\n template.add_resource(MyCustomResource(\"foo\",\n Foo=\"bar\",\n ServiceToken=\"baz\"))\n generated = TemplateGenerator(json.loads(template... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test our custom Hypermedia resource loads correctly | def test_hypermedia_custom_resource():
data = {
'name': 'Wort wort',
'slug': 'sluggy',
'not_valid': 'nooo',
'author': 'http://dev/api/authors/1'
}
instance = HypermediaBlogsResource(**data)
assert hasattr(instance, 'get_authors') | [
"def test_get_media(self):\n pass",
"def test_hypermedia_custom_resource_calling():\n responses.add(responses.GET, 'http://dev/api/authors/1',\n body='''\n {\"id\": \"1\", \"title\": \"blog title\",\n \"slug\": \"blog-title\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test our custom Hypermedia resource handles URls that aren't registered. | def test_hypermedia_custom_resource_non_registered_urls():
data = {
'name': 'Wort wort',
'slug': 'sluggy',
'not_valid': 'nooo',
# This should not appear!
'author': 'http://dev/api/foobar/1'
}
instance = HypermediaBlogsResource(**data)
assert not hasattr(instance, ... | [
"def test_hypermedia_custom_resource():\n data = {\n 'name': 'Wort wort',\n 'slug': 'sluggy',\n 'not_valid': 'nooo',\n 'author': 'http://dev/api/authors/1'\n }\n instance = HypermediaBlogsResource(**data)\n assert hasattr(instance, 'get_authors')",
"def test_urihandler_empt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test our custom Hypermedia resource make HTTP calls correctly | def test_hypermedia_custom_resource_calling():
responses.add(responses.GET, 'http://dev/api/authors/1',
body='''
{"id": "1", "title": "blog title",
"slug": "blog-title",
"content": "This is some content"}''',
status=20... | [
"def test_hypermedia_custom_resource():\n data = {\n 'name': 'Wort wort',\n 'slug': 'sluggy',\n 'not_valid': 'nooo',\n 'author': 'http://dev/api/authors/1'\n }\n instance = HypermediaBlogsResource(**data)\n assert hasattr(instance, 'get_authors')",
"def test_get_media(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get locations using lat and long | def location_search(self, lat: float, lng: float) -> List[Location]:
params = {
"latitude": lat,
"longitude": lng,
# rankToken=c544eea5-726b-4091-a916-a71a35a76474 - self.uuid?
# fb_access_token=EAABwzLixnjYBABK2YBFkT...pKrjju4cijEGYtcbIyCSJ0j4ZD
}
... | [
"def get_all_locations(self):",
"def get_nearby_locations(lat, lon, max_lat=0, max_lon=0, stories_only=False):\n if max_lat == 0:\n min_lat, max_lat = Decimal(lat) - Decimal(0.01), Decimal(lat) + Decimal(0.01)\n else:\n min_lat = Decimal(lat)\n\n if max_lon == 0:\n min_lon, max_lon =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a location using location pk | def location_info(self, location_pk: int) -> Location:
try:
location = self.location_info_a1(location_pk)
except Exception:
# Users do not understand the output of such information and create bug reports
# such this - https://github.com/adw0rd/instagrapi/issues/364
... | [
"def get_location_by_id(self, location_id):",
"def location_info_a1(self, location_pk: int) -> Location:\n data = self.public_a1_request(f\"/explore/locations/{location_pk}/\")\n return extract_location(data['location'])",
"def get_location(id, check_author=True):\n location = get_db().execute(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get chunk of medias for a location and max_id (cursor) by Private Mobile API | def location_medias_v1_chunk(
self, location_pk: int, max_amount: int = 63, tab_key: str = "", max_id: str = None
) -> Tuple[List[Media], str]:
assert tab_key in tab_keys_v1, f'You must specify one of the options for "tab_key" {tab_keys_a1}'
data = {
"_uuid": self.uuid,
... | [
"def location_medias_top_v1(\n self, location_pk: int, amount: int = 21\n ) -> List[Media]:\n return self.location_medias_v1(location_pk, amount, tab_key=\"ranked\")",
"def location_medias_v1(\n self, location_pk: int, amount: int = 63, tab_key: str = \"\"\n ) -> List[Media]:\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get medias for a location by Private Mobile API | def location_medias_v1(
self, location_pk: int, amount: int = 63, tab_key: str = ""
) -> List[Media]:
assert tab_key in tab_keys_v1, f'You must specify one of the options for "tab_key" {tab_keys_a1}'
medias, _ = self.location_medias_v1_chunk(location_pk, amount, tab_key)
if amount:
... | [
"def extract_media_v1(data):\n user = data[\"user\"]\n location = data.get(\"location\")\n if location:\n location = {\"pk\": int(location.get(\"pk\")), \"name\": location.get(\"name\")}\n video_url = \"\"\n if \"video_versions\" in data:\n # Select Best Quality by Resolutiuon\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get top medias for a location | def location_medias_top_v1(
self, location_pk: int, amount: int = 21
) -> List[Media]:
return self.location_medias_v1(location_pk, amount, tab_key="ranked") | [
"def location_medias_top(\n self, location_pk: int, amount: int = 27, sleep: float = 0.5\n ) -> List[Media]:\n try:\n return self.location_medias_top_a1(location_pk, amount, sleep)\n except Exception:\n # Users do not understand the output of such information and create... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get top medias for a location | def location_medias_top(
self, location_pk: int, amount: int = 27, sleep: float = 0.5
) -> List[Media]:
try:
return self.location_medias_top_a1(location_pk, amount, sleep)
except Exception:
# Users do not understand the output of such information and create bug report... | [
"def location_medias_top_v1(\n self, location_pk: int, amount: int = 21\n ) -> List[Media]:\n return self.location_medias_v1(location_pk, amount, tab_key=\"ranked\")",
"def location_medias_recent_v1(\n self, location_pk: int, amount: int = 63\n ) -> List[Media]:\n return self.loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get recent medias for a location | def location_medias_recent_v1(
self, location_pk: int, amount: int = 63
) -> List[Media]:
return self.location_medias_v1(location_pk, amount, tab_key="recent") | [
"def location_medias_recent(\n self, location_pk: int, amount: int = 63, sleep: float = 0.5\n ) -> List[Media]:\n try:\n return self.location_medias_recent_a1(location_pk, amount, sleep)\n except Exception:\n # Users do not understand the output of such information and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get recent medias for a location | def location_medias_recent(
self, location_pk: int, amount: int = 63, sleep: float = 0.5
) -> List[Media]:
try:
return self.location_medias_recent_a1(location_pk, amount, sleep)
except Exception:
# Users do not understand the output of such information and create bug ... | [
"def location_medias_recent_v1(\n self, location_pk: int, amount: int = 63\n ) -> List[Media]:\n return self.location_medias_v1(location_pk, amount, tab_key=\"recent\")",
"def get_recent_media(self):\n medialist = get(self.token,\n '/users/{}/media/recent'.format(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Launch the migration of a snapshot_name between 2 GlanceConnection regions in "streaming" mode If there are multiple the first one is taken | def migration(glance_source: GlanceConnection, glance_destination: GlanceConnection, snapshot_name_source: str,
snapshot_name_destination: str, disk_format: str = "qcow2", container_format: str = "bare"):
try:
snapshot_uuid = get_snapshot_id_from_glance(glance_source, snapshot_name_source)[0]
... | [
"def migration_from_uuid(glance_source: GlanceConnection, glance_destination: GlanceConnection, snapshot_uuid: str,\n snapshot_name_destination: str, disk_format: str = \"qcow2\", container_format: str = \"bare\"):\n data = glance_source.connection.images.data(snapshot_uuid)\n pipe_file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |