query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Function that calculates the number of active VREs of a UserInfo instance. | def number_of_vres(self, obj):
vres = VreServer.objects.all().filter(user_id=obj.user_id). \
filter(server_status=1).count()
return vres | [
"def count_vouchers():\r\n\tcookie = request.cookies.get(\"token\", None);\r\n\ttoken = Utils.get_token(cookie);\r\n\tif not token:\r\n\t\treturn Utils.make_response({\r\n\t\t\t'status': 'failure',\r\n\t\t\t'reason': 'unauthorized'\r\n\t\t\t}, 403);\r\n\tquery = \"SELECT COUNT(*) AS number_of_vouchers FROM rad_user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Init the debounced entry reloader. | def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
self.hass = hass
self.entry = entry
self.token = self.entry.data.get(CONF_TOKEN)
self._debounced_reload: Debouncer[Coroutine[Any, Any, None]] = Debouncer(
hass,
LOGGER,
cooldown=ENTRY... | [
"def __init__(\n self,\n entry_lifetime: int = constants.DAY_IN_SECONDS,\n ) -> None:\n self._entry_lifetime = datetime.timedelta(seconds=entry_lifetime)\n self._cache: dict[K, CacheEntry[V]] = {}\n self._lock = Lock()\n self._reset_telemetry()",
"def _initialize_cache... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update ssdp locations from discovery cache. | async def _async_update_ssdp_locations(hass: HomeAssistant, entry: ConfigEntry) -> None:
updates = {}
for ssdp_st, key in (
(UPNP_SVC_RENDERING_CONTROL, CONF_SSDP_RENDERING_CONTROL_LOCATION),
(UPNP_SVC_MAIN_TV_AGENT, CONF_SSDP_MAIN_TV_AGENT_LOCATION),
):
for discovery_info in await s... | [
"async def async_step_ssdp(self, discovery_info: SsdpServiceInfo) -> FlowResult:\n url = URL(discovery_info.ssdp_location or \"\")\n if url.host is None or not (\n serial := discovery_info.upnp.get(ATTR_UPNP_SERIAL)\n ):\n return self.async_abort(reason=\"invalid_discovery... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop SamsungTV bridge connection. | async def stop_bridge(event: Event) -> None:
LOGGER.debug("Stopping SamsungTVBridge %s", bridge.host)
await bridge.async_close_remote() | [
"def stop_device(self) -> None:\n if self.connection is not None:\n self.connection.close()\n self.connection = None",
"def disconnect(self):\n\n self.model.status.code *= -1\n\n for i in range(15):\n for service in self.model.sap.connections:\n if not service.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a bridge object and update any missing data in the config entry. | async def _async_create_bridge_with_updated_data(
hass: HomeAssistant, entry: ConfigEntry
) -> SamsungTVBridge:
updated_data: dict[str, str | int] = {}
host: str = entry.data[CONF_HOST]
port: int | None = entry.data.get(CONF_PORT)
method: str | None = entry.data.get(CONF_METHOD)
load_info_attemp... | [
"def update_plugin_config(self):\n conf_dict = {}\n # conf_dict['bridge'] = self.bridge\n conf_dict['bridge_serial'] = self.bridge.get('serialNumber','')\n conf_dict['bridge_user'] = self.bridge.get('username','')\n conf_dict['bridge_ip'] = self.bridge.get('ip','')\n conf_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the locator_number of this SeurShipmentResponse. NumRecogida. Utilizar el id de base de datos | def locator_number(self):
return self._locator_number | [
"def get_numero(self):\r\n return self.__numero",
"def get_number(self):\n\n name_attr = artellapipe.ShotsMgr().config.get('data', 'number_attribute')\n shot_number = self._shot_data.get(name_attr, None)\n if not shot_number:\n LOGGER.warning(\n 'Impossible to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the locator_number of this SeurShipmentResponse. NumRecogida. Utilizar el id de base de datos | def locator_number(self, locator_number):
self._locator_number = locator_number | [
"def locator_number(self):\n return self._locator_number",
"def _set_locator(self, locator):\n pass",
"def setspotnum(self,num):\n self.spotnum = num",
"def movement_number(self, movement_number):\n\n self._movement_number = movement_number",
"def set_number_served(self,customers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the quotation of this SeurShipmentResponse. Tasacion | def quotation(self):
return self._quotation | [
"def getQuotations(self):\n pass",
"def quote_instrument(self) -> 'Instrument':\n return self.exchange_pair.pair.quote",
"def get_quotes(self):\n r = requests.get(self.api_url)\n if r.status_code == 200:\n return r.json()\n else:\n return {\"quotes\": [\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the quotation of this SeurShipmentResponse. Tasacion | def quotation(self, quotation):
self._quotation = quotation | [
"def quotation(self):\n return self._quotation",
"def getQuotations(self):\n pass",
"def quote_instrument(self) -> 'Instrument':\n return self.exchange_pair.pair.quote",
"def quotation(self, generatedEntity, usedEntity, activity=None,\n generation=None, usage=None,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the status_pick_up of this SeurShipmentResponse. | def status_pick_up(self):
return self._status_pick_up | [
"def status_pick_up_code(self):\n return self._status_pick_up_code",
"def status_pick_up(self, status_pick_up):\n allowed_values = [\"Unknown\", \"Ready\", \"Started\", \"Failed\", \"Picked\"]\n if status_pick_up not in allowed_values:\n raise ValueError(\n \"Invalid... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the status_pick_up of this SeurShipmentResponse. | def status_pick_up(self, status_pick_up):
allowed_values = ["Unknown", "Ready", "Started", "Failed", "Picked"]
if status_pick_up not in allowed_values:
raise ValueError(
"Invalid value for `status_pick_up` ({0}), must be one of {1}"
.format(status_pick_up, all... | [
"def status_pick_up_code(self, status_pick_up_code):\n\n self._status_pick_up_code = status_pick_up_code",
"def status_pick_up(self):\n return self._status_pick_up",
"def test_pickmup_set_paket_status_post(self):\n pass",
"def on_set_status(self, status, pokemon, setter, battle):",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the status_pick_up_code of this SeurShipmentResponse. | def status_pick_up_code(self):
return self._status_pick_up_code | [
"def status_pick_up(self):\n return self._status_pick_up",
"def status_pick_up_code(self, status_pick_up_code):\n\n self._status_pick_up_code = status_pick_up_code",
"def status_delivery_code(self):\n return self._status_delivery_code",
"def status_pick_up(self, status_pick_up):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the status_pick_up_code of this SeurShipmentResponse. | def status_pick_up_code(self, status_pick_up_code):
self._status_pick_up_code = status_pick_up_code | [
"def status_pick_up(self, status_pick_up):\n allowed_values = [\"Unknown\", \"Ready\", \"Started\", \"Failed\", \"Picked\"]\n if status_pick_up not in allowed_values:\n raise ValueError(\n \"Invalid value for `status_pick_up` ({0}), must be one of {1}\"\n .form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the status_delivery of this SeurShipmentResponse. | def status_delivery(self):
return self._status_delivery | [
"def status_delivery_code(self):\n return self._status_delivery_code",
"def status_delivery(self, status_delivery):\n allowed_values = [\"Unknown\", \"Ready\", \"Delivered\"]\n if status_delivery not in allowed_values:\n raise ValueError(\n \"Invalid value for `statu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the status_delivery of this SeurShipmentResponse. | def status_delivery(self, status_delivery):
allowed_values = ["Unknown", "Ready", "Delivered"]
if status_delivery not in allowed_values:
raise ValueError(
"Invalid value for `status_delivery` ({0}), must be one of {1}"
.format(status_delivery, allowed_values)
... | [
"def status_delivery_code(self, status_delivery_code):\n\n self._status_delivery_code = status_delivery_code",
"def set_delivery_status(self, commit=False):\n\t\tdelivery_status = None\n\t\tstatus_counts = Counter(\n\t\t\tfrappe.get_all(\"Email Queue\", pluck=\"status\", filters={\"communication\": self.na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the status_delivery_code of this SeurShipmentResponse. | def status_delivery_code(self):
return self._status_delivery_code | [
"def status_delivery(self):\n return self._status_delivery",
"def status_delivery_code(self, status_delivery_code):\n\n self._status_delivery_code = status_delivery_code",
"def get_status_code(self):\n\n return self.last_response.status_code",
"def http_status_code(self):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the status_delivery_code of this SeurShipmentResponse. | def status_delivery_code(self, status_delivery_code):
self._status_delivery_code = status_delivery_code | [
"def status_delivery(self, status_delivery):\n allowed_values = [\"Unknown\", \"Ready\", \"Delivered\"]\n if status_delivery not in allowed_values:\n raise ValueError(\n \"Invalid value for `status_delivery` ({0}), must be one of {1}\"\n .format(status_delivery... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the creation_date of this SeurShipmentResponse. When the item was created | def creation_date(self, creation_date):
self._creation_date = creation_date | [
"def _set_dates(self):\n if self.id is None or self.created_at is None:\n self.created_at = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")",
"def created_at(self, created_at: \"datetime\"):\n self._attrs[\"created_at\"] = created_at",
"def creation_datetime(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get orthologs and PHOGs from database Although this function is titled "Get Ortholog Query Set", what is actually returned is a 6tuple representing the results of that query. The ortholog query set is contained within that 6tuple. | def getOrthologQuerySet(sequence_id, ortholog_type, threshold = 0.0,
orderByTaxonomicDistribution = False):
# If the custom value is the same as one of the default types, use the
# default instead -- as they have been pre-computed. Using the
# default types is faster.
if ortholog_type =... | [
"def _get_orms(self):\n return [orm]",
"def ortho(enable=pythoncom.Empty):\r\n return _base._rsf.ortho(enable)",
"def query_pathway_db_model():\n return tuple([\n (index, DATABASES[str(obj)])\n for index, obj in enumerate(PathwayDatabase.objects.filter(\n database_name__in=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns input dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the image tensors. | def get_batch_size_1_input_images(inputs, b):
b_1_inputs = {}
for field in standard_fields.get_input_image_fields():
if field in inputs:
b_1_inputs[field] = inputs[field][b:b + 1, Ellipsis]
return b_1_inputs | [
"def _crate_input_dictionary(self, tensor_list):\n in_shape = tensor_list[0].get_shape()\n in_dict = dict()\n for i in range(0, self.n_blocks):\n\n if len(tensor_list) == self.n_blocks:\n in_dict['lvl_{0}'.format(i)] = tensor_list[i]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns input dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the point tensors. | def get_batch_size_1_input_points(inputs, b):
b_1_inputs = {}
for field in standard_fields.get_input_point_fields():
if field in inputs:
b_1_inputs[field] = inputs[field][b]
return b_1_inputs | [
"def choose(self):\n if self._flip_first_random_for_beginning and self._start_frames is None:\n ordered_dataset = self._create_dataset(shuffle_files=False)\n # Later flip the first random frame in PPO batch for the true beginning.\n self._start_frames = self._extract_input(\n ordered_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns input dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the voxel tensors. | def get_batch_size_1_input_voxels(inputs, b):
b_1_inputs = {}
for field in standard_fields.get_input_voxel_fields():
if field in inputs:
b_1_inputs[field] = inputs[field][b]
return b_1_inputs | [
"def _crate_input_dictionary(self, tensor_list):\n in_shape = tensor_list[0].get_shape()\n in_dict = dict()\n for i in range(0, self.n_blocks):\n\n if len(tensor_list) == self.n_blocks:\n in_dict['lvl_{0}'.format(i)] = tensor_list[i]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns input dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the object tensors. | def get_batch_size_1_input_objects(inputs, b):
b_1_inputs = {}
for field in standard_fields.get_input_object_fields():
if field in inputs:
b_1_inputs[field] = inputs[field][b]
return b_1_inputs | [
"def _get_input_tensors(dataset, config):\n batch_size = config.hparams.batch_size\n iterator = tf.data.make_one_shot_iterator(dataset)\n (input_sequence, output_sequence, control_sequence,\n sequence_length) = iterator.get_next()\n input_sequence.set_shape(\n [batch_size, None, config.data_converter.inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns output dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the image tensors. | def get_batch_size_1_output_images(outputs, b):
b_1_outputs = {}
for field in standard_fields.get_output_image_fields():
if field in outputs:
b_1_outputs[field] = outputs[field][b:b + 1, Ellipsis]
return b_1_outputs | [
"def generate_images_pred(self, inputs, outputs):\n for scale in self.opt.scales:\n disp = outputs[(\"disp\", scale)]\n if self.opt.v1_multiscale:\n source_scale = scale\n else:\n # without interpolate\n if self.opt.using_v not in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns output dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the point tensors. | def get_batch_size_1_output_points(outputs, b):
b_1_outputs = {}
for field in standard_fields.get_output_point_fields():
if field in outputs and outputs[field] is not None:
b_1_outputs[field] = outputs[field][b]
return b_1_outputs | [
"def choose(self):\n if self._flip_first_random_for_beginning and self._start_frames is None:\n ordered_dataset = self._create_dataset(shuffle_files=False)\n # Later flip the first random frame in PPO batch for the true beginning.\n self._start_frames = self._extract_input(\n ordered_data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns output dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the voxel tensors. | def get_batch_size_1_output_voxels(outputs, b):
b_1_outputs = {}
for field in standard_fields.get_output_voxel_fields():
if field in outputs and outputs[field] is not None:
b_1_outputs[field] = outputs[field][b]
return b_1_outputs | [
"def get_batch_size_1_input_voxels(inputs, b):\n b_1_inputs = {}\n for field in standard_fields.get_input_voxel_fields():\n if field in inputs:\n b_1_inputs[field] = inputs[field][b]\n return b_1_inputs",
"def fake_model_outputs_batch(num_boxes):\n np.random.seed(num_boxes)\n\n outputs = {\n 'pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns output dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the object tensors. | def get_batch_size_1_output_objects(outputs, b):
b_1_outputs = {}
for field in standard_fields.get_output_object_fields():
if field in outputs and outputs[field] is not None:
b_1_outputs[field] = outputs[field][b]
return b_1_outputs | [
"def get_batch_size_1_input_objects(inputs, b):\n b_1_inputs = {}\n for field in standard_fields.get_input_object_fields():\n if field in inputs:\n b_1_inputs[field] = inputs[field][b]\n return b_1_inputs",
"def gather(self, outputs, output_device):\n def _coll_tensor(coll_list, out_tensor):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns output dictionary containing tensors with batch size of 1. Note that this function only applies its example selection to the anchor tensors. | def get_batch_size_1_output_anchors(outputs, b):
b_1_outputs = {}
for field in standard_fields.get_output_anchor_fields():
if field in outputs and outputs[field] is not None:
b_1_outputs[field] = outputs[field][b]
return b_1_outputs | [
"def sample_anchors_and_resample_weights(self) -> Dict[str, torch.Tensor]:\n anchors = {}\n\n for name, param in self.model.mlp.named_parameters():\n # Usually torch weight matrices are initialized by sampling from U[-sqrt(1/k), sqrt(1/k)]\n # Because anchored ensembling requires... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decide the criterion function based on objective criterion function | def _get_criterion_function(self):
if self._objective_function_type == 'wrapper':
return lambda x, y: np.mean(cross_val_score(self._model, x, y, cv=self._folds))
else:
return self._model.get_significance | [
"def __objective_fcn(self, y_true, y_pred, **kwargs):\n obj1 = kwargs['P'](y_true,y_pred) #objective 1\n obj2 = kwargs['ratio_selected_features'] #is objective 2\n \n particle_value = self.obj_function_equation(obj1,obj2, kwargs['alpha'])\n \n return particle_value",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the best features | def best_features(self):
return sorted(self._best_features) | [
"def best_features(self):\n return list()",
"def getBestFeatures(features,labels,features_list):\n from sklearn.feature_selection import SelectKBest,f_classif\n \n selector = SelectKBest(f_classif,10)\n selector.fit(features,labels)\n feature_scores = selector.scores_\n features_selected_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check Oozie API request returns a dict object | def test_oozie_api_request(self, mock_req):
mock_req.return_value = type('obj', (object,), {'status_code' : 200, 'text': json.dumps({
'id': '01234-oozie-oozi-w',
'appName': 'o2-workflow',
'status': 'PREP'
})})
result = application_summary.oozie_api_request('01... | [
"def test_correct_request_returns_valid_dict(self):\n response = self.client.get(get_url())\n data = json.loads(response.content)['packet_data_list']\n\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(data), 10)",
"def test_get_daily_data_req_empty(self):\n o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing Oozie component's action handling for both Coordinator and Workflow | def test_oozie_action_handler(self, spark_job_patch, yarn_job_patch, oozie_api_patch):
#In case of Oozie workflow with a Mapreduce job whose Yarn status's Failed
yarn_job_patch.return_value = {'yarnStatus': 'FAILED', \
'yarnFinalStatus': 'FAILED', 'type': 'MAPREDUCE'}
result = applicatio... | [
"def test_update_workflow_status(self):\n pass",
"def test_case_action(base_store: Store, helpers):\n\n # GIVEN a database with an analysis that was completed but has an active rerun in progress\n analysis = helpers.add_analysis(\n base_store, completed_at=datetime.now(), uploaded_at=datetime.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing Spark API for jobs and stage information | def test_spark_job_handler(self, spark_mock_req):
spark_mock_req.side_effect = [type('obj', (object,), {'status_code' : 200, 'text': json.dumps([
{
'status': 'RUNNING',
'stageIds': [
5,
6
],
'jobI... | [
"def test_get_cloud_job(self):\n pass",
"def test_list_cloud_jobs(self):\n pass",
"def test_wait_for_spark_app_id(sdc_builder, sdc_executor, cluster):\n # STF-1156: STF Does not properly configure Spark Executor for Secured Cluster\n if cluster.hdfs.is_kerberized:\n pytest.skip('Spark... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the sentences split by NLTK and further split them by double newline chars | def split_by_double_newline(sentences, spans):
split_sents = []
split_spans = []
for sent, span in zip(sentences, spans):
doc_begin_index = span[0]
nltk_sent_begin_index = 0
chars = list(sent)
# Find any splits in the sentences
last_char = ""
for nltk_sent_i... | [
"def sep_sentences_to_lines(infile, outfile, sep_paragraphs=True):\n\n with open(infile, 'r') as i:\n text = i.read()\n\n paragraphs = text.split('\\n\\n')\n\n with open(outfile, 'w') as o:\n for par in paragraphs:\n sentences = nltk.sent_tokenize(par)\n for sentence in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new booking with random data | def create_booking(client):
data = BookingDataAttr().random()
res = client.create_booking(data, type_response=AddBookingResponse)
return res.json() | [
"def makeBooking(self, customer, selectedRoom, dateOfArrival, dateOfDepature, \\\n paid):\n dayCount = dateOfDepature - dateOfArrival\n price = dayCount.days * selectedRoom.getPrice()\n\n newBooking = Booking(selectedRoom, dateOfArrival, dateOfDepature, price, paid)\n customer.appendB... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update metameta table with new values | def update_metameta_table(org_id, metameta_id, data):
errors = {}
#key
if not (data.has_key('key') and len(data['key'].strip())):
#TODO validation
errors.update({'key': _('%s field is required.'%('key'))})
return errors
key = data['key'].strip()
#label: if not set, insert k... | [
"def update(self, sql):",
"def update_stat_metameta_table(org_id, metameta_id, state):\n\n update_sql = \"UPDATE metameta SET state='%s', modified_date='%s' WHERE id ='%s' AND org_id='%s';\"%(state, datetime.datetime.utcnow().isoformat(), metameta_id, org_id)\n\n result = Session.execute(update_sql)\n Se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates entries in metameta table for the organisation. value fields are null | def insert_metameta_table(org_id, data):
errors = {}
#key
if not (data.has_key('key') and len(data['key'].strip())):
#TODO validation
errors.update({'key': _('%s field is required.'%('key'))})
return errors
key = data['key'].strip()
#label: if not set, insert key
if data... | [
"def update_metameta_table(org_id, metameta_id, data):\n\n errors = {}\n #key\n if not (data.has_key('key') and len(data['key'].strip())):\n #TODO validation\n errors.update({'key': _('%s field is required.'%('key'))})\n return errors\n key = data['key'].strip()\n\n #label: if no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update stat on metameta table with new status | def update_stat_metameta_table(org_id, metameta_id, state):
update_sql = "UPDATE metameta SET state='%s', modified_date='%s' WHERE id ='%s' AND org_id='%s';"%(state, datetime.datetime.utcnow().isoformat(), metameta_id, org_id)
result = Session.execute(update_sql)
Session.commit() | [
"def job_set_status(self, job, status, setextra=None):\n now = int(time.time())\n cur = self.conn.cursor()\n if setextra:\n cmd = \"update idx set status='%s', date_status=%d, %s where xtcfn = '%s'\" % (\n status, now, setextra, job.fn)\n else:\n cmd ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates entries in metameta options table for the organisation. value fields are null | def insert_metameta_options(org_id, key, option_value):
sql = "INSERT INTO metameta_options(id, org_id, key, option_value, modified_date) VALUES ('%s', '%s', '%s', '%s', '%s');"%(str(uuid.uuid4()), org_id, key, option_value, datetime.datetime.utcnow().isoformat())
result = Session.execute(sql)
Session.comm... | [
"def insert_metameta_table(org_id, data):\n errors = {}\n #key\n if not (data.has_key('key') and len(data['key'].strip())):\n #TODO validation\n errors.update({'key': _('%s field is required.'%('key'))})\n return errors\n key = data['key'].strip()\n\n #label: if not set, insert k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if org has any entries in metameta table (it won't if no defaults have been set before) | def org_has_defaults(org_id, key=None, metameta_id=None):
sql = "SELECT 1 FROM metameta WHERE org_id = '" + org_id + "'"
if key is not None:
sql = sql + " AND key = '" + key +"'"
if metameta_id is not None:
sql = sql + " AND id <> '" + metameta_id +"'"
sql = sql + " LIMIT 1;"
result ... | [
"def is_defined(self, lexema):\n return lexema in self.tabla and len(self.tabla[lexema].keys()) != 0",
"def missing_meta( self, dataset, check = [], skip = [] ):\n if check:\n to_check = [ ( to_check, dataset.metadata.get( to_check ) ) for to_check in check ]\n else:\n t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes a naive datetime.datetime in a given time zone aware. | def _make_aware(value, timezone):
if hasattr(timezone, 'localize'):
# available for pytz time zones
return timezone.localize(value, is_dst=None)
else:
# may be wrong around DST changes
return value.replace(tzinfo=timezone) | [
"def smart_default_tz(datetime_value):\n if timezone.is_naive(datetime_value):\n datetime_value = timezone.make_aware(datetime_value, timezone=timezone.get_default_timezone())\n return timezone.localtime(datetime_value, timezone.get_default_timezone())",
"def test_aware_within_no_tz_return_aware(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create Trajectory from GeoDataFrame or DataFrame. | def __init__(
self,
df,
traj_id,
obj_id=None,
t=None,
x=None,
y=None,
crs="epsg:4326",
parent=None,
): # noqa: E501
if len(df) < 2:
raise ValueError("The input DataFrame must have at least two rows.")
if not isinsta... | [
"def __init__(\n self,\n data,\n latitude=LATITUDE,\n longitude=LONGITUDE,\n datetime=DATETIME,\n traj_id=TRAJ_ID,\n local_label=LOCAL_LABEL\n ):\n\n super()\n\n if isinstance(data, dict):\n data = pd.DataFrame.from_dict(data)\n eli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a copy of the trajectory. Returns Trajectory | def copy(self):
return Trajectory(self.df.copy(), self.id, parent=self.parent) | [
"def get_trajectory(self):\n return self.trajectory;",
"def get_trajectory(self):\n start_point = [0.3, 0, 0.295]\n end_point = [0.5, -0.2, 0.295] \n\n milestones = np.array([start_point, end_point])\n self.num_waypoints = np.size(milestones, 0)\n\n return trajectory.Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of the speed column Returns string | def get_speed_column_name(self):
if hasattr(self, "speed_col_name"):
return self.speed_col_name
else:
return SPEED_COL_NAME | [
"def get_distance_column_name(self):\n if hasattr(self, \"distance_col_name\"):\n return self.distance_col_name\n else:\n return DISTANCE_COL_NAME",
"def name (self):\n return self._column;",
"def get_direction_column_name(self):\n if hasattr(self, \"direction_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of the distance column Returns string | def get_distance_column_name(self):
if hasattr(self, "distance_col_name"):
return self.distance_col_name
else:
return DISTANCE_COL_NAME | [
"def get_direction_column_name(self):\n if hasattr(self, \"direction_col_name\"):\n return self.direction_col_name\n else:\n return DIRECTION_COL_NAME",
"def name (self):\n return self._column;",
"def get_speed_column_name(self):\n if hasattr(self, \"speed_col_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of the direction column Returns string | def get_direction_column_name(self):
if hasattr(self, "direction_col_name"):
return self.direction_col_name
else:
return DIRECTION_COL_NAME | [
"def name (self):\n return self._column;",
"def get_distance_column_name(self):\n if hasattr(self, \"distance_col_name\"):\n return self.distance_col_name\n else:\n return DISTANCE_COL_NAME",
"def _get_column_name(self, column):\n return column",
"def directio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrun name of the angular difference column Returns string | def get_angular_difference_column_name(self):
if hasattr(self, "angular_difference_col_name"):
return self.angular_difference_col_name
else:
return ANGULAR_DIFFERENCE_COL_NAME | [
"def _get_column_name(self, column):\n return column",
"def new_column_name(self) -> str:\n return pulumi.get(self, \"new_column_name\")",
"def test_CompDataFrames_col_diff(self):\n f2=self.b.col_diff(self.c3)\n self.assertEqual(f2[0], \"Cour_H Beam1X-East\", \"Dont read the right va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of the timedelta column Returns string | def get_timedelta_column_name(self):
if hasattr(self, "timedelta_col_name"):
return self.timedelta_col_name
else:
return TIMEDELTA_COL_NAME | [
"def timedelta(td):\n return format_timedelta(td)",
"def get_speed_column_name(self):\n if hasattr(self, \"speed_col_name\"):\n return self.speed_col_name\n else:\n return SPEED_COL_NAME",
"def name (self):\n return self._column;",
"def new_column_name(self) -> st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return name of the geometry column Returns string | def get_geom_column_name(self):
return self.df.geometry.name | [
"def geometry_column_name(df): \n try:\n geom_col = df.geometry.name\n except AttributeError:\n geom_col = 'geometry'\n return geom_col",
"def geom_name(self) -> str:\n if self.get_attrs(\"geom_name\") not in self._obj.dims:\n self.set_spatial_dims()\n if \"geom_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the WKT string of the trajectory LineStringM representation. Returns string WKT of trajectory as LineStringM | def to_linestringm_wkt(self):
# Shapely only supports x, y, z. Therefore, this is a bit hacky!
coords = ""
for index, row in self.df.iterrows():
pt = row[self.get_geom_column_name()]
t = to_unixtime(index)
coords += "{} {} {}, ".format(pt.x, pt.y, t)
w... | [
"def as_linestring(self):\n if self._geography.getType() == Geography.LSVAL:\n return LineStringWrapper(self._geography.get_lsVal())\n raise InvalidValueTypeException(\n \"expect LineString type, but is \" + self._get_type_name()\n )",
"def transform_linestring(orig_geoj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a GeoDataFrame with one row containing the trajectory as a single LineString. Returns GeoDataFrame | def to_traj_gdf(self, wkt=False):
properties = {
TRAJ_ID_COL_NAME: self.id,
"start_t": self.get_start_time(),
"end_t": self.get_end_time(),
"geometry": self.to_linestring(),
"length": self.get_length(),
"direction": self.get_direction(),
... | [
"def _to_line_df(self):\n line_df = self.df.copy()\n line_df[\"prev_pt\"] = line_df.geometry.shift()\n line_df[\"t\"] = self.df.index\n line_df[\"prev_t\"] = line_df[\"t\"].shift()\n line_df[\"line\"] = line_df.apply(self._connect_prev_pt_and_geometry, axis=1)\n return line... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the trajectory's start location. Returns shapely Point Trajectory start location | def get_start_location(self):
return self.df.geometry.iloc[0] | [
"def start_coord(self):\n return self.lat_s, self.lon_s",
"def curr_curve_start_xyt(self):\n if self._curr_curve_start_index is None:\n return None\n else:\n return self._recent_near_coords[self._curr_curve_start_index]",
"def getLocalStartingPoint(self) -> \"SbVec3f\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the trajectory's end location. Returns shapely Point Trajectory end location | def get_end_location(self):
return self.df.geometry.iloc[-1] | [
"def end_coord(self):\n return self.lat_e, self.lon_e",
"def _get_end(self) -> Point:\n amount = self.amount * self.magnitude\n\n movement = [0, 0]\n if self.axis == \"x\":\n movement[0] = amount\n else:\n movement[1] = amount\n\n return cast(Point, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the trajectory's bounding box. Returns tuple Bounding box values (minx, miny, maxx, maxy) | def get_bbox(self):
return tuple(self.df.total_bounds.tolist()) # (minx, miny, maxx, maxy) | [
"def boundingBox(self):\n xpos = self.xpos\n\n minXY = np.array([xpos - self.box_width / 2, self._bpdata.min * 0.95])\n maxXY = np.array([xpos + self.box_width / 2, self._bpdata.max * 1.05])\n return minXY, maxXY",
"def bbox(self) -> Tuple[Tuple[float, float], Tuple[float, float]]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return row of the trajectory's DataFrame at time t. | def get_row_at(self, t, method="nearest"):
try:
return self.df.loc[t]
except KeyError:
index = self.df.index.sort_values().drop_duplicates()
idx = index.get_indexer([t], method=method)[0]
return self.df.iloc[idx] | [
"def get_trajectory(self, tid):\n return self.data[self.tidToIdx[tid]]",
"def _get_instantaneos_values(self):\n self._shift_data(datetime.now())\n current_row = self.data[self.data.index <= datetime.now()]\n if len(current_row) > 0:\n current_row = current_row.ix[-1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return LineString of segment between times t1 and t2. | def get_linestring_between(self, t1, t2, method="interpolated"):
if method not in ["interpolated", "within"]:
raise ValueError(
"Invalid split method {}. Must be one of [interpolated, within]".format(
method
)
)
if method == "in... | [
"def get_segment_between(self, t1, t2):\n segment = Trajectory(self.df[t1:t2], \"{}_{}\".format(self.id, t1), parent=self)\n if not segment.is_valid():\n raise RuntimeError(\n \"Failed to extract valid trajectory segment between {} and {}\".format(\n t1, t2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return Trajectory segment between times t1 and t2. | def get_segment_between(self, t1, t2):
segment = Trajectory(self.df[t1:t2], "{}_{}".format(self.id, t1), parent=self)
if not segment.is_valid():
raise RuntimeError(
"Failed to extract valid trajectory segment between {} and {}".format(
t1, t2
... | [
"def time_segment(self, start, end):\n if start < 0:\n start = self.time.min() + abs(start)\n if end < 0:\n end = self.time.max() - abs(end)\n this_t = np.array([t for t in self.time if start < t <= end])\n this_rate = np.array([r for t, r in zip(self.time, self.rat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the length of the trajectory. Length is calculated using CRS units, except if the CRS is geographic | def get_length(self):
pt_tuples = [(pt.y, pt.x) for pt in self.df.geometry.tolist()]
if self.is_latlon:
return geodesic(*pt_tuples).m
else: # The following distance will be in CRS units that might not be meters!
return LineString(pt_tuples).length | [
"def ST_Length(geos):\n return arctern.ST_Length(geos)",
"def length(self):\n act_loc = self.thin_face.parent_thin.parent_lattice.z_line\n myo_loc = self.thick_face.get_axial_location(-1)\n ls = self.parent_lattice.lattice_spacing\n length = np.sqrt( (act_loc-myo_loc)**2 + ls**2 )\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the direction of the trajectory. The direction is calculated between the trajectory's start and end location. Direction values are in degrees, starting North turning clockwise. Returns float Direction of the trajectory in degrees | def get_direction(self):
pt0 = self.get_start_location()
pt1 = self.get_end_location()
if self.is_latlon:
return calculate_initial_compass_bearing(pt0, pt1)
else:
return azimuth(pt0, pt1) | [
"def get_theta_direction(self):\n return self._direction.get_matrix()[0, 0]",
"def motor_direction(self):\n self.write_line('MOTOR:DIRECTION?')\n direction = int(self.read_line())\n return direction",
"def direction(self, r):\n d = r - self.position\n return d / np.lina... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the sampling interval of the trajectory. The sampling interval is computed as the median time difference between consecutive rows in the trajectory's DataFrame. Returns datetime.timedelta Sampling interval | def get_sampling_interval(self):
if hasattr(self, "timedelta_col_name"):
if self.timedelta_col_name in self.df.columns:
return self.df[self.timedelta_col_name].median()
return self._get_df_with_timedelta()[TIMEDELTA_COL_NAME].median() | [
"def _calculate_startend_sample(delta, starttime, plot_start, plot_end):\n beg_sample = int(-1*starttime/delta + plot_start/delta)\n end_sample = int(-1*starttime/delta + plot_end/delta)\n return beg_sample, end_sample",
"def window_bins(mili_seconds, sample_rate):\n return sample_rate * mili_seconds ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add trajectory id column and values to the trajectory's DataFrame. | def add_traj_id(self, overwrite=False):
if TRAJ_ID_COL_NAME in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already contains a {TRAJ_ID_COL_NAME} column! "
f"Use overwrite=True to overwrite exiting values."
)
self.df[TRAJ_ID_... | [
"def append_person(self, id, frame, traj, vel=None):\n\n if id in self.data.p.to_list():\n raise IndexError(\"Person ID already exists.\")\n\n l = traj.shape[0]\n\n if vel is None:\n vel = np.empty((l, 2))\n\n data = np.hstack((np.ones((l,1))*id, frame.reshape((l,1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add direction column and values to the trajectory's DataFrame. The direction is calculated between consecutive locations. Direction values are in degrees, starting North turning clockwise. Values are [0, 360). | def add_direction(self, overwrite=False, name=DIRECTION_COL_NAME):
self.direction_col_name = name
if self.direction_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.direction_col_name}! "
"Use ove... | [
"def calc_direction(price_data):\n price_data['1d-direction'][0] = np.nan\n price_data['2d-direction'][0: 2] = [np.nan for x in price_data['2d-direction'][0: 2]]\n price_data['5d-direction'][0: 5] = [np.nan for x in price_data['5d-direction'][0: 5]]\n\n price_data['1d-logreturn'] = price_data['1d-logret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add angular difference to the trajectory's DataFrame. Angular difference is calculated as the absolute smaller angle between direction for points along the trajectory. Values are [0, 180.0] | def add_angular_difference(
self,
overwrite=False,
name=ANGULAR_DIFFERENCE_COL_NAME,
):
self.angular_difference_col_name = name
if self.angular_difference_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a... | [
"def angular_difference(self):\n\t\treturn math.atan2(self.goal[1]-self.pos.position.y, self.goal[0]-self.pos.position.x) - self.theta",
"def angle_traveled(self):\n diff = self.cur_odom.theta-self.prev_odom.theta\n # If there is a big jump, then it must have crossed the -180/180 \n # bounda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add speed column and values to the trajectory's DataFrame. Speed is calculated as CRS units per second, except if the CRS is | def add_speed(self, overwrite=False, name=SPEED_COL_NAME):
self.speed_col_name = name
if self.speed_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.speed_col_name}! "
f"Use overwrite=True to over... | [
"def speed_data(self):\n time_s = self.t / 1000\n speed = np.gradient(self.y, time_s)\n\n MODEL_ORDER = 2\n coeffs = np.polyfit(self.t, speed, MODEL_ORDER)\n\n poly = np.poly1d(coeffs)\n speed_polyfit = [poly(x) for x in self.t]\n\n return (self.t, speed, speed_polyf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add timedelta column and values to the trajectory's DataFrame. Timedelta is calculated as the time difference between the current and the previous row. Values are instances of datetime.timedelta. | def add_timedelta(self, overwrite=False, name=TIMEDELTA_COL_NAME):
self.timedelta_col_name = name
if self.timedelta_col_name in self.df.columns and not overwrite:
raise RuntimeError(
f"Trajectory already has a column named {self.timedelta_col_name}! "
f"Use ov... | [
"def add_timedelta(series: Series, **kwargs) -> Series:\n return series.map(lambda d: d + timedelta(**kwargs))",
"def add_deltas_to_summary(df):\n\n # file dates for deltas (except the first one).\n dtfs = df.index.get_level_values('Date_file').unique().sort_values()[1:]\n # create new columns\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether the trajectory intersects the given polygon. | def intersects(self, polygon):
return intersects(self, polygon) | [
"def is_on_polygon(x, y, polygon, bounds=None):\n if _is_a_vertex_of_polygon(x, y, polygon):\n return True\n\n if bounds is None:\n minx, maxx = float('+inf'), float('-inf')\n miny, maxy = minx, maxx\n for point in polygon:\n minx = min(minx, point[0])\n miny ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Hausdorff distance to the other geometric object (based on shapely | def hausdorff_distance(self, other):
if self.is_latlon:
message = (
f"Hausdorff distance is computed using Euclidean geometry but "
f"the trajectory coordinate system is {self.crs}."
)
warnings.warn(message, UserWarning)
if type(other) ... | [
"def hausdorff(A,B):\n D = cdist(A,B,'sqeuclidean')\n fhd = np.max(np.min(D,axis=0))\n rhd = np.max(np.min(D,axis=1))\n return np.sqrt(max(fhd,rhd))",
"def distance(self, other):\n return great_circle_distance(self.centroid, other.centroid)",
"def get_distance(a, b):\n return math.sqrt((a.x - ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return trajectory segments clipped by the given polygon. By default, the trajectory's line representation is clipped by the polygon. If pointbased=True, the trajectory's point representation is used instead, leading to shorter segments. | def clip(self, polygon, point_based=False):
from .trajectory_collection import TrajectoryCollection
segments = clip(self, polygon, point_based)
return TrajectoryCollection(segments) | [
"def slicePolygon(bounding_polygon, poly_line):\n\n p1 = poly_line[0]\n ray1 = GeometryTools.lineToRay(poly_line[1], poly_line[0])\n intersection1 = GeometryTools.rayPolygonIntersections(p1, ray1, bounding_polygon)[0] # assume convex\n\n p2 = poly_line[-1]\n ray2 = GeometryTools.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the trajectory segments that intersects the given feature. Feature attributes are appended to the trajectory's DataFrame. By default, the trajectory's line representation is clipped by the polygon. If pointbased=True, the trajectory's point representation is used instead, leading to shorter segments. | def intersection(self, feature, point_based=False):
from .trajectory_collection import TrajectoryCollection
segments = intersection(self, feature, point_based)
return TrajectoryCollection(segments) | [
"def line_segment(\n geojson: Union[LineString, Polygon, MultiLineString, MultiPolygon, Feature]\n) -> FeatureCollection:\n if not geojson:\n raise Exception(\"geojson is required!!!\")\n\n results: List[Feature] = []\n\n def callback_flatten_each(feature, feature_index, multi_feature_index):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shift column by the specified offset in seconds. | def apply_offset_seconds(self, column, offset):
self.df[column] = self.df[column].shift(offset, freq="1s") | [
"def offset_time(timestamp):\n return timestamp % COLUMN_HEIGHT",
"def shift_time(ds):\n pass",
"def shift(self, dt):\n self.times += dt",
"def shift_timestamp(ts: pd.Timestamp, offset: int) -> pd.Timestamp:\n return _shift_timestamp_helper(ts, ts.freq, offset)",
"def shift(self, dt):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shift column by the specified offset in minutes. | def apply_offset_minutes(self, column, offset):
self.df[column] = self.df[column].shift(offset, freq="1min") | [
"def offset_time(timestamp):\n return timestamp % COLUMN_HEIGHT",
"def shift(self, offset):\n new_origin = offset\n delta = (new_origin - self.origin)\n self.origin = new_origin\n for peak in self.peaklist:\n peak.mz += delta\n return self",
"def shiftScheduleOff... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert trajectory data GeoDataFrame of points to GeoDataFrame of lines that connect consecutive points. Returns | def _to_line_df(self):
line_df = self.df.copy()
line_df["prev_pt"] = line_df.geometry.shift()
line_df["t"] = self.df.index
line_df["prev_t"] = line_df["t"].shift()
line_df["line"] = line_df.apply(self._connect_prev_pt_and_geometry, axis=1)
return line_df.set_geometry("lin... | [
"def line_merger(self):\n line = self.polyline.unary_union\n geom = [line]\n Multiline_string = gpd.GeoDataFrame(crs=\"EPSG:4326\", geometry=geom)\n explode = Multiline_string.explode()\n multiLineGeom = ops.linemerge(explode.unary_union)\n gdf = gpd.GeoDataFrame(geometry=[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_get_instance_name is a helper method which returns the name of the instance the volume will be attached to. It is stubbed and shoul be implemented by inheriting classes. | def _get_instance_name(self):
pass | [
"def _get_volume_name(self):\n pass",
"def _get_instance_name(self):\n return self._heat_resource.properties[\"instance_uuid\"]",
"def instance_identifier(self) -> str:\n ...",
"def instance_name(self):\r\n return _base._rsf.block_instance_name(self._block_instance._rhino_id)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_get_volume_name is a helper method which returns the name of the volume to be attached. It is stubbed and should be implemented by inheriting classes. | def _get_volume_name(self):
pass | [
"def _get_volume_name(self):\n return self._heat_resource.properties[\"volume_id\"]",
"def volumeBind(influence=\"string\", name=\"string\"):\n pass",
"def _to_volume(self, element, name=None):\r\n volId = findtext(element=element, xpath='volumeId',\r\n namespace=NAMESPA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
update_context goes ahead and add the necessary volume declaration to the required instance. | def update_context(self):
super(BaseVolumeAttachmentTranslator, self).update_context()
volume_name = self._get_volume_name()
res = self._context.get_arm_resource({
"type": "Microsoft.Compute/virtualMachines",
"name": "[variables('vmName_%s')]" % self._get_instance_name... | [
"def volume(ctx, *args, **kwargs):",
"def attach_volume(self, context, connection_info, instance, mountpoint,\n disk_bus=None, device_type=None, encryption=None):\n instance_name = instance['name']\n if instance_name not in self.__mounts:\n self.__mounts[instance_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_get_volume_name returns the name of the Cinder volume referred to by the attachment. | def _get_volume_name(self):
return self._heat_resource.properties["volume_id"] | [
"def _get_volume_name(self):\n pass",
"def docker_volume_name(self) -> str:\n return os.environ.get(\n 'DATA_VOLUME_NAME',\n f\"{self.docker_container_name}-vol\"\n )",
"def volume_get_root_name(self):\n return self.request( \"volume-get-root-name\", {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_get_instance_name returns the name of the Nova server referred to by the attachment. | def _get_instance_name(self):
return self._heat_resource.properties["instance_uuid"] | [
"def _get_instance_name(self):\n pass",
"def _get_instance_name(self):\n return self._heat_resource.properties[\"InstanceId\"]",
"def instance_name(self):\n return self.name[0].lower() + self.name[1:]",
"def managed_instance_name(self) -> Optional[pulumi.Input[str]]:\n return pulum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
_get_instance_name returns the name of the EC2 instance referred to by the attachment. | def _get_instance_name(self):
return self._heat_resource.properties["InstanceId"] | [
"def _get_instance_name(self):\n return self._heat_resource.properties[\"instance_uuid\"]",
"def _get_instance_name(self):\n pass",
"def get_instance_name(instance, regexp):\n instancename = ''\n try:\n p = re.compile(regexp, re.I)\n try:\n for t in instance[\"Tags\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
addTypeBranch does not only add the given type, but also the whole branch. this means it also adds all parents, all children and their children to the type tree. | def add_type_branch(self, type_name, type_dict):
inserted = self.recursive_insert(type_name, type_dict)
for_inserted = True
if inserted:
for key in type_dict.keys():
if type_dict[key] == type_name:
for_inserted = for_inserted & self.add_type_branch... | [
"def add_branch(self, tree):\n# print 'ADDING BRANCH', tree\n self._insert_branch(None, tree)\n self._cleanup_branches()",
"def addBranch(self, branch):\n if self._isLeaf:\n return false\n else:\n self._branches.append(branch)\n self._branches[-1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
recursiveInsert needs a typeName and a typeDict and inserts the type with it's parents into the tree. | def recursive_insert(self, type_name, type_dict):
inserted = False
if type_name in type_dict:
parent = type_dict[type_name]
if self.is_in_tree(parent):
inserted = self.insert(type_name, parent)
else:
inserted = self.recursive_insert(par... | [
"def add_type_branch(self, type_name, type_dict):\n inserted = self.recursive_insert(type_name, type_dict)\n for_inserted = True\n if inserted:\n for key in type_dict.keys():\n if type_dict[key] == type_name:\n for_inserted = for_inserted & self.add_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
insert takes a typeName and a parentName, and inserts it into the tree. insert does not work, if the parent is not in the tree yet. | def insert(self, type_name, parent_name):
inserted = self.is_in_tree(type_name)
if (not type_name is None) & (not inserted):
inserted = self.__insert(type_name, parent_name)
return inserted | [
"def __insert(self, type_name, parent_name):\n inserted = False\n if parent_name == self.type_name:\n self.children.append(TypeTree(type_name))\n inserted = True\n else:\n for child in self.children:\n inserted = child.__insert(type_name, parent_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__insert takes a typeName and a parentName, and inserts the typeName as child of the parentName into the tree. | def __insert(self, type_name, parent_name):
inserted = False
if parent_name == self.type_name:
self.children.append(TypeTree(type_name))
inserted = True
else:
for child in self.children:
inserted = child.__insert(type_name, parent_name)
... | [
"def insert(self, type_name, parent_name):\n inserted = self.is_in_tree(type_name)\n if (not type_name is None) & (not inserted):\n inserted = self.__insert(type_name, parent_name)\n return inserted",
"def __insert(self, parent, line):\n # print(\"Insert(): \" + line)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a string in pddl notation representing the typetree. | def get_as_pddl_string(self):
as_string = ""
if self.children:
for child in self.children:
as_string = as_string + child.type_name + " "
as_string = as_string + "- " + self.type_name + "\r\n"
for child in self.children:
child_string = c... | [
"def to_tikz(mpt):\n\n def recursive_translation(node):\n \"\"\" Recursively turn list to str \"\"\"\n if node.leaf:\n return node.content\n pos = recursive_translation(node.pos)\n neg = recursive_translation(node.neg)\n return \"[.{} {} {} ]\".format(node.content, p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
isInTree searchs the typeTree for a specific type, and returns true, if the tree contains the type. unfortunately the tree is not sorted, and has a complexity of O(n) | def is_in_tree(self, type_to_search):
return self.get_sub_tree(type_to_search) is not None | [
"def foundIn(pattern, tree):\n ans = False\n if tree == pattern :\n ans = True\n elif isinstance(tree, list) :\n for subtree in tree :\n ans = ans or foundIn(pattern, subtree)\n else :\n ans = False\n return ans",
"def is_in_tree(self, value):\n \n if se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_sub_tree get_sub_tree gets a type, and returns the subtree, with the type as root. | def get_sub_tree(self, type_to_search):
sub_tree = None
if self.type_name == type_to_search:
sub_tree = self
else:
for child in self.children:
sub_tree = child.get_sub_tree(type_to_search)
if sub_tree is not None:
break... | [
"def get_sub(self, annotation_type: str) -> Optional[SubAnnotation]:\n for sub in self.subs:\n if sub.annotation_type == annotation_type:\n return sub\n return None",
"def _fetch_subtree(cursor, type_tree=None):\n\n if type_tree is None:\n type_tree = _determine_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get_parent_of receives a type name, and searchs in the tree for it's parent. | def get_parent_of(self, type_name):
parent = None
# look, if this node the parent
for child in self.children:
if type_name == child.type_name:
parent = self.type_name
break
# search in child nodes for parent
if parent is None:
... | [
"def get_parent_of_type(self, t):\n try:\n if self.content_type.name == t:\n return self\n else:\n return self.get_parent().specific.get_parent_of_type(t)\n except (AttributeError):\n return None",
"def get_parent_type(khoros_object, ide... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Probar que el html no sea valido | def test_html_is_not_valid(self):
url = ""
single_date = date(2019, 3, 4)
coins = {}
with patch.object(
BCRASMLScraper,
'fetch_content',
return_value=' '
):
scraper = BCRASMLScraper(url, coins, intermediate_panel_path=None, use_int... | [
"def and_has_html(self, html: str):\n pass",
"def validate(self):\n\n for line in self.htmlstring.split(\"\\n\"):\n if re.search(r\"<(\\\"[^\\\"]*\\\"|'[^']*'|[^'\\\">])*>\",line):\n print(\"Valid html string!\")\n else:\n print(\"Invalid html stri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
log_i provides a decorator for logging | def log_i(func):
def log_wrapper(*args, **kwargs):
"""send function call to kivy log"""
log_entry = "{}()".format(func.__name__)
kivy.logger.Logger.info(log_entry)
return func(*args, **kwargs)
return log_wrapper | [
"def log_decorator(func):\n\t\t@functools.wraps(func)\n\t\tdef log_wrapper(*args, **kwargs):\n\t\t\t\"\"\"Prints info before and after start of the function\"\"\"\t\t\n\t\t\tdebug_string = \"Start of {}\".format(func.__name__)\n\n\t\t\tlogger.log(logging.DEBUG, debug_string)\n\n\t\t\tresult = func(*args, **kwargs)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
log_exception writes the given exception and optional message to kivy log | def log_exception(error, message):
log_entry = "{}:\n{}".format(str(error), str(message))
kivy.logger.Logger.error(log_entry) | [
"def logException(self,message):\n self.wLogger.exception(message)",
"def _log_exception():\n exc = traceback.format_exception(*sys.exc_info())\n rospy.logerr(\"\".join(exc))",
"def log_die(self, fmt, *args, exception=None, exc_arg=\"\", end=os.linesep): \n self.log(fmt, *args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getter for weather gui | def get_weather_screen(self):
return self.get_screen("screen_weather") | [
"def get_today_weather(self):\n return self.data['weather1']",
"def update_weather(self):\r\n global weather\r\n global draw_wthr\r\n weather = getWeather();\r\n draw_wthr = True;\r\n self._weather.config(text = weather)",
"def current_weather(self):\n\t\tobservation = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ask the screenmanager to show weather gui screen | def show_weather_gui_screen(self):
self.screenmanager.transition.direction = "left"
self.screenmanager.show_weather_screen()
kivy.clock.Clock.schedule_once(self.show, DELAY_OPEN_SCREENSAVER_SEC) | [
"def check_current_screen(self, _):\n assert self.screenmanager\n\n hour = datetime.datetime.now().hour\n if hour in HOURS_SHOW_WEATHER_DEFAULT:\n self.screenmanager.show_weather_screen()\n else:\n self.screenmanager.show_slideshow()",
"def get_weather_screen(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
make sure the screenmanager shows the slideshow | def show(self, _):
self.screenmanager.show_slideshow() | [
"def show_slide_show_screen(self):\n self.screenmanager.transition.direction = \"right\"\n self.screenmanager.show_slideshow()",
"def check_current_screen(self, _):\n assert self.screenmanager\n\n hour = datetime.datetime.now().hour\n if hour in HOURS_SHOW_WEATHER_DEFAULT:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add directory to take images from | def add_directory(self, local_dir):
self.images.add_directory(os.path.abspath(local_dir)) | [
"def make_image_list(image_dir):",
"def create_image_directory():\n if not os.path.exists(\"Images\"):\n os.makedirs(\"Images\")",
"def createImages():\n if not isdir(\"images\"):\n mkdir(\"images\")",
"def make_image_directory():\n directory = '/Users/jon/PycharmProjects/Cleveland_VAE/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update displayed time, parameter is required for kivy.clock | def update_clock(self, _):
self.clock = utils.get_time_human_readable() | [
"def update(self, dt):\n\t\tif self.running:\n\t\t\tself.time += 1\n\t\t\tm, s = divmod(self.time, 60)\n\t\t\tself.label.text = '%02d:%02d' % (m, s)",
"def update():\n seconds = 0 if self.start_time == 0 else round(time.time() - self.start_time)\n hours = seconds // 3600\n seconds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ask the screenmanager to show slideshow screen | def show_slide_show_screen(self):
self.screenmanager.transition.direction = "right"
self.screenmanager.show_slideshow() | [
"def show(self, _):\n self.screenmanager.show_slideshow()",
"def showStartScreen(self):\n self.current_screen = self.start_screen\n self.game_over = False",
"def check_current_screen(self, _):\n assert self.screenmanager\n\n hour = datetime.datetime.now().hour\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
spawn thread to obtain weather data and update ui when finished parameter is required for kivy.clock | def update_weather_async(self, _):
threading.Thread(target=self.update_weather).start() | [
"def update_weather(self):\n try:\n self.weather_data = self.app.get_weather_data()\n except openweather.RetrieveWeatherDataException as error:\n log_exception(error, \"could not download data\")\n return\n except weatherdata.ParseWeatherDataException as error:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
download weather data and trigger ui update | def update_weather(self):
try:
self.weather_data = self.app.get_weather_data()
except openweather.RetrieveWeatherDataException as error:
log_exception(error, "could not download data")
return
except weatherdata.ParseWeatherDataException as error:
l... | [
"def update_weather_async(self, _):\n threading.Thread(target=self.update_weather).start()",
"def _download_data(self):\n self.raw_data = requests.get(self.api_address).json()\n self.age = datetime.now()",
"def change_weather(data):\n \n print(\"change requested\")\n set_weather()"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update displayed time, parameter is required for kivy.clock | def update_clock(self, _):
self.clock = utils.get_time_human_readable() | [
"def update(self, dt):\n\t\tif self.running:\n\t\t\tself.time += 1\n\t\t\tm, s = divmod(self.time, 60)\n\t\t\tself.label.text = '%02d:%02d' % (m, s)",
"def update():\n seconds = 0 if self.start_time == 0 else round(time.time() - self.start_time)\n hours = seconds // 3600\n seconds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build app, connect screens and schedule updates | def build(self):
self.load_kv("resources/gui_weatherstation.kv")
self.screenmanager = self.root
# init screens
weather_gui = self.screenmanager.get_weather_screen()
weather_gui.screenmanager = self.screenmanager
weather_gui.app = self
slideshow = self.screenmana... | [
"def initiate_schedule():\r\n root = tk.Tk()\r\n page = interface.Window(root)\r\n root.mainloop()",
"def update_app():\n pull_project()\n restart_app()",
"def h_app_show(self, *_):\n if self.window is None:\n self.window=self.ui_window_class(self.glade_file)\n self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check which screen to show | def check_current_screen(self, _):
assert self.screenmanager
hour = datetime.datetime.now().hour
if hour in HOURS_SHOW_WEATHER_DEFAULT:
self.screenmanager.show_weather_screen()
else:
self.screenmanager.show_slideshow() | [
"def checkScreen(self):\r\n if not window.screen == self.screen:\r\n window.setScreen(self.screen)",
"def showStartScreen(self):\n self.current_screen = self.start_screen\n self.game_over = False",
"def is_onscreen(self):\n x,y = self.loc\n w,h = get_screen_siz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |