query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Build a command to create a new volume based on the required type and the current system state. Uses build_create_or_expand_volume_command to do most of the work. Returns a dict with the command, the node list, the dataset list and a count that will be used by the caller to create the appropriate datasets, etc.. vol_in... | def build_create_volume_command(vol_name, vol_type, ondisk_storage, repl_count, transport, si):
return_dict = None
try:
# Now build the command based on parameters provided
cmd = 'gluster volume create %s ' % vol_name
if 'replicate' in vol_type.lower():
cmd = cmd + ' replica... | [
"def build_create_or_expand_volume_command(cmd, si, anl, vol_type, ondisk_storage, repl_count, vol_name):\n\n return_dict = {}\n try:\n node_list = []\n\n if (not si) or (not vol_type) or (not ondisk_storage) or (not vol_name):\n raise Exception('Required parameter not passed')\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start or stop a gluster volume. Returns a dict with the result and the xml root. vol_name The name of the volume op Either 'start' or 'stop' | def volume_stop_or_start(vol_name, op):
return_dict = None
try:
cmd = 'gluster --mode=script volume %s %s --xml' % (op, vol_name)
return_dict, err = xml_parse.run_gluster_command(cmd)
if err:
raise Exception(err)
except Exception, e:
return None, 'Error stopping/... | [
"def started(name):\n ret = {\"name\": name, \"changes\": {}, \"comment\": \"\", \"result\": False}\n\n volinfo = __salt__[\"glusterfs.info\"]()\n if name not in volinfo:\n ret[\"result\"] = False\n ret[\"comment\"] = \"Volume {} does not exist\".format(name)\n return ret\n\n if int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing defined partial syn from Mariadb to Snowflake | def test_defined_partial_sync_mariadb_to_sf(self):
from_value_weight = 5
from_value_address = 400
# run-tap command
assertions.assert_run_tap_success(
self.tap_id, self.target_id, ['fastsync', 'singer']
)
# partial sync
source_records_weight = self... | [
"def test_tableSyntaxFromSchemaSyntaxCompare(self):\n self.assertEquals(self.schema.FOO, self.schema.FOO)\n self.assertNotEquals(self.schema.FOO, self.schema.BOZ)",
"def test_synonym(self): \n pass",
"def test_get_sql_scd2_updated_ins_cms(self):\n for mode in ['database_table', '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
save story post to database check for duplicates | def save(self, *args, **kwargs):
if not self.post_id:
self.created = timezone.now()
dup = StoryPost.objects.filter(title=self.title)
if len(dup) > 0:
# objects with the same slug exist -> duplicate!
nos = str(len(dup))
# append ... | [
"def save(self):\n dupID = articleQa.isDuplicate(self)\n if not self.isValid():\n print(\"Article from source: \" + self.source + \"feed: \" + self.feed + \" was invalid\")\n elif dupID is not None: # we just update the content because this is a duplicate of something\n db... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts old classifier in Classifiers dir to the 6.0.0 classifier convention. Splits the classifier of 5_9_9 to 6_0_0 classifier and 6_0_0 mapper if exists. | def convert_dir(self) -> int:
old_classifiers: List[Classifier] = self.get_entities_by_entity_type(
self.pack.classifiers, FileType.OLD_CLASSIFIER
)
intersection_fields = self.get_classifiers_schema_intersection_fields()
for old_classifier in old_classifiers:
self... | [
"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 i in range(len(_class)):\n if _class[i] != common[i]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receives classifier of format 5_9_9. Builds mapper of format 6_0_0 and above, if mapping exists in the old classifier. | def create_mapper_from_old_classifier(self, old_classifier: Classifier) -> None:
classifier_name_and_id = self.extract_classifier_name(old_classifier)
mapping = old_classifier.get("mapping")
if not classifier_name_and_id or not mapping:
return
mapper = dict(
id=f"... | [
"def _set_mapper(self, classification_dict):\n d = {class_code: class_index for class_index, class_code in enumerate(classification_dict.keys())}\n # Here we update the dict so that code 65 remains unchanged.\n # Indeed, 65 is reserved for noise/artefacts points, that will be deleted by transfo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the new path for mapper or classifier of 6_0_0 format | def calculate_new_path(self, old_classifier_brand: str, is_mapper: bool) -> str:
fixed_brand_name = self.entity_separators_to_underscore(old_classifier_brand)
if is_mapper:
fixed_brand_name = f"mapper-incoming-{fixed_brand_name}"
new_path_suffix = f"classifier-{fixed_brand_name}.json... | [
"def calculateNewPath(self):\r\n\r\n\t\tnodeDict = self.simulationHandle.getMap().getNodeDict()\r\n\t\tdistDict = self.simulationHandle.getMap().getDistDict()\r\n\r\n\t\tself.pathToGoal = pathfinder.findPath(self.currentNode, self.goalNode, nodeDict, distDict)",
"def calculate_path(self):\n\n mid_states = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get raw text message , use rgx exp to match date formate and retun the date time | def getTransactionDate(self,message):
#matches date time example (2016-04-11:10:14:29) formate
date = re.findall(Analyzer.rgxDateTime,message.lower())
if len(date)>0:
date = datetime.datetime.strptime(date[0], "%Y-%m-%d:%H:%M")
return date.strftime('%Y-%b-%d %H:... | [
"def get_date(text):\n match = re.search(r\"\\[(.+?)\\]\", text)\n if match:\n match_string = match.group()\n else:\n match_string = \"\"\n # print(\"{}\".format(match_string))\n # match should now be a combination of the date and time, we just want the date portion...\n date_string ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get raw text message , use rgx exp to match card formate and retun the creadit card details | def getCardNumber(self,message):
card = re.findall(Analyzer.rgxCard,message.lower())
return card[0] | [
"def getTextForCards(card_db, cards):\n comment_text = ''\n for card in cards:\n log.info('getting text for %s', card)\n # Find cards containing the match\n for name, cardText in card_db.items():\n if len(card) > 2 and name.startswith(card):\n comment_text += car... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get raw text message , use rgx exp to match amount formate and retun the transaction amount involved in (spent/recived/payment) | def getTransactionAmount(self,message):
amount = re.findall(Analyzer.rgxAmount,message.lower())
return amount[0].capitalize() | [
"def test_spacy_extracts_amount():\n string = ('Major Precious Metals Announces C$10,000,000 Non-Brokered'\n ' Private Placement')\n assert(helpers.extract_money(string) == \"10,000,000\")",
"def on_text_message(self, update, context):\n chat_id = update.effective_chat.id\n log.in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return sms recived time | def getSmsRecivedDate(self,timestamp):
#convert millisec to sec
timestamp = timestamp/1000
date = datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%b-%d %H:%M %p')
return date | [
"def LogMessageRespondTime(self):\n \n \n if dict(self.Response['texts']['items'][0]).has_key('delivered') == True:\n \n # Get the Message deliverable time \n self.MessageDeliveredTime = str(self.Response['texts']['items'][0]['delivered'])\n LoadR... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main execution scheduler. A thread pool handles concurrent monitoring of the targets specified in the `config` attribute. The thread pool allocates as many workers as targets in the `config` attribute, rounded to the next ten. Each thread monitors a single target. | def run(self):
self.logger.info("Starting execution loop...")
with ThreadPoolExecutor(
max_workers=len(self.config) + 10 - (len(self.config) % 10)
) as executor:
for target in self.config:
executor.submit(self.monitor, target)
executor.shutdown... | [
"def pooling(lconf, poolsize=10):\n pool = Pool(poolsize)\n pool.map(worker, lconf)",
"def run(cls, targetfunc, thname, loop, interval, arglist=[]):\n\n th = threading.Thread(target=cls._thread_runner_, args=(targetfunc, thname, interval, arglist))\n th.setDaemon(True)\n cls.running_thr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Busy monitoring loop. Implements an infinite loop to monitor a target. During each iteration of the run loop a target gets queried and the result is published to the kafka topic specified in the `topic` attribute. A busy wait loop pauses execution in 1 second intervals until the next scheduled check time. The nature of... | def monitor(self, target):
while self.RUNNING:
check_time = datetime.now()
next_check = check_time + timedelta(seconds=target["frequency"])
try:
self.produce(
get(target["url"], timeout=target["frequency"] - 0.5),
targe... | [
"async def main_loop(self):\n while True:\n # Generate random new temperature\n self.current_temp = self.sensor.get_temperature()\n # Publish the new tempe\n await self.publish_to(self.my_topic[0], self.current_temp)\n # GO to sleep and give CPU time to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cache_man from .cacheManager import RedisPandas as RedisPandasCacheManager | def __init__(self, cache_man=None):
# manager of redis-pandas caching
self.cache_man = cache_man
super().__init__() | [
"def setup_redis_cache_connection():\n\tglobal cache\n\n\tif not cache:\n\t\tfrom frappe.utils.redis_wrapper import RedisWrapper\n\n\t\tcache = RedisWrapper.from_url(conf.get(\"redis_cache\"))",
"def pymod_cache():\n pymod.cache.cache = Singleton(pymod.cache.factory)",
"def enable_cache(self, **kwargs: Dict[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get lending history from Poloniex. If begin or end is not specified, its most extreme value is assumed. | def getLendingHistory(self,
begin = None,
end = None):
# TODO: implement a local cache
raw = handleBeginEndCall(begin, end, self.api.returnLendingHistory)
return ensure.listOf(raw=raw, path="lendingHistory",
ensurer=partial(ensure.dictOf, ensureRest=ensure... | [
"def get_lending_purchase_history(self, **params):\n return self._request_margin_api('get', 'lending/union/purchaseRecord', signed=True, data=params)",
"def get_lending_interest_history(self, **params):\n return self._request_margin_api('get', 'lending/union/interestHistory', signed=True, data=param... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get active loans on Poloniex. If begin or end is not specified, its most extreme value is assumed. Returns a dict where the key "provided" has all the loans the user has provided and the key "used" has all the loans that the user is using on margin. | def getActiveLoans(self,
begin = None,
end = None):
raw = handleBeginEndCall(begin, end, self.api.returnActiveLoans)
typeActiveLoanList = partial(ensure.listOf,
ensurer=partial(ensure.dictOf, ensureRest=ensure.fail,
ensurers={
... | [
"async def loans(ctx, scope: str = 'all'):\n\tif await auth_check(ctx) and await channel_check(ctx):\n\t\tres = []\n\t\tif scope == 'all':\n\t\t\tres = cursor.execute(\"SELECT * FROM loans\").fetchall()\n\t\tif scope == 'returned':\n\t\t\tres = cursor.execute(\"SELECT * FROM loans WHERE returned IS TRUE\").fetchall... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
That custom action allows an admin (or an automated task) to notify a users who will attend the retreat with an existing automated email preconfigured (AutomaticEmail). | def execute_automatic_email(self, request, pk=None):
try:
retreat = Retreat.objects.get(pk=pk)
except Exception:
response_data = {
'detail': "Retreat not found"
}
return Response(response_data, status=status.HTTP_400_BAD_REQUEST)
t... | [
"def send_created_email(self):\n if settings.NOTIFY_NEW_REG:\n to = settings.NOTIFY_NEW_REG\n message = \"\"\"\\\nGreetings,<br><br>\n\nA new vehicle registration has been submitted by %s.<br><br>\n\nGo here to view or edit the request: <br>\n<a href=\"%s\">%s</a>\n<br><br>\nSincerely,<... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
That custom action allows an admin (or automated task) to notify users who has attended the retreat. | def recap(self, request, pk=None):
retreat = self.get_object()
# This is a hard-coded limitation to allow anonymous users to call
# the function.
time_limit = retreat.end_time - timedelta(days=1)
if timezone.now() < time_limit:
response_data = {
'detai... | [
"def send_reminder(self):\n pass",
"def task_rescheduled_notify(name, attempts, last_error, date_time, task_name, task_params):\n body = loader.render_to_string(\n 'notification/email/notify_rescheduled_task.html', {\n 'name': name,\n 'attempts': attempts,\n 'last... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This viewset should return the request user's wait_queue except if the currently authenticated user is an admin (is_staff). | def get_queryset(self):
if self.request.user.is_staff:
return WaitQueue.objects.all()
return WaitQueue.objects.filter(user=self.request.user) | [
"def is_on_waiting_list(self):\n if self.user is None:\n return False\n if unicode(self.user._id) in self.barcamp.event.waiting_list:\n return True\n return False",
"def get_queryset(self):\n return Task.objects.filter(user=self.request.user)",
"def get_queryset... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In larger samples, older tweets have a slight advantage. Is there a way to incorporate age into score bearing in mind that tweets receive most engagement directly proximate to the time they are posted? | def alt_score(objects):
scores = {}
for tweet in objects:
data = tweet._json
raw_time = datetime.strptime(
data['created_at'],
'%a %b %d %H:%M:%S +0000 %Y'
)
age = ((datetime.utcnow() - raw_time).seconds / 60) + 1
rt = data[... | [
"def analyze_tweets():",
"def generate_tweet_scores(data):\n max_rt = 0\n max_likes = 0\n rt = {}\n likes = {}\n for i in data:\n max_rt = max(data[i][\"retweet_count\"], max_rt)\n max_likes = max(data[i][\"favorite_count\"], max_likes)\n rt[i] = data[i][\"retweet_count\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return sorted list 'l' using the merge sort method. | def merge_sort(l: list) -> list:
# Trap for lists with one or fewer elements.
if len(l) <= 1:
return l[:]
# Divide the list into 2
mid = len(l) // 2
first = l[mid:]
second = l[:mid]
# Recursively sort smaller lists and merge the two resulting lists.
left = merge_sort(... | [
"def mergesort(L: list) -> None:",
"def merge_sort(lst):",
"def sortlist(self, l):\n l = list(l)\n l.sort()\n return l",
"def merge_sort(li):\n if not li or len(li) == 1:\n return li\n if len(li) == 2:\n return [li[0], li[1]] if li[0] < li[1] else [li[1], li[0]]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a list of contours up, in order to break erroneous connections | def splitContours(contours):
split_contours = []
for contour in contours:
c = contour.reshape(-1, 2)
line_segments = splitLine(c)
for seg in line_segments:
# Turn it back to its original shape, so we can add it back to contours
new_contour = seg.reshape(-1,1,2)
... | [
"def __filter_contours(input_contours, min_area, min_perimeter, min_width, max_width,\n min_height, max_height, solidity, max_vertex_count, min_vertex_count,\n min_ratio, max_ratio):\n output = []\n for contour in input_contours:\n x,y,w,h = cv2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a line on horizontal or vertical segments | def splitLine(line):
# Find a point where our line changes direction
l = np.copy(line)
change = l[2:] - l[:-2]
# Create breaks where derivative equals 0
break_indicies = np.unique(np.where(change == 0)[0])
line_segments = []
while break_indicies.size > 0:
i = break_indicies[0]
... | [
"def split_line(line):\n halves = cut(line, distance=line.length/2)\n logging.debug(halves)\n return halves",
"def split_line(line, sizer, surface_width):\n splits = []\n queue = [line]\n while len(queue) > 0:\n current = queue.pop(0)\n line_width, _ = sizer(current)\n if li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a blob generator. | def blob_generator(self):
for blob in self.data:
yield blob | [
"def makeBlob(*args):\n return _yarp.Value_makeBlob(*args)",
"def create_blob(self, blob_key, data):\n return self.blobstore_stub.CreateBlob(blob_key, data)",
"def CreateBlob(self, blob_key, blob):\n self._blobs[blobstore.BlobKey(unicode(blob_key))] = blob",
"def new_blob(self, blob_name):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load Panoptic CMU dataset calibrations from HD cameras, convert in to a is_msgs.camera_pb2.CameraCalibration protobuf. | def load_calibrations_pb(calibrations_file, referencial=9999, cameras=None):
with open(calibrations_file, 'r') as f:
calibrations = json.load(f)['cameras']
calibrations = list(filter(lambda d: d['type'] == 'hd', calibrations))
calibrations_pb = {}
for calibration in calibrations:
calib... | [
"def get_calibration_data(self):\n\n try:\n self.cam_matrix = np.load('./calibration_parameters/Cameramatrix.npy')\n self.dist_coefs = np.load('./calibration_parameters/DistortionCoeffs.npy')\n except:\n print(\"Couldn't load calibration data. Starting calibration...\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample a `task_state` from the set of `n_tasks` tasks. `task_state` contains all the information that the environment needs to switch to any other task. The subclasses, extending this class, should ensure that the task seed is set (by calling `seed(int)`) before invoking this method (for reproducibility). It can be don... | def sample_task_state(self) -> TaskStateType:
self.assert_task_seed_is_set()
if not self._are_tasks_set:
self.tasks = [self.env.sample_task_state() for _ in range(self.n_tasks)]
self._are_tasks_set = True
# The assert statement (at the start of the function) ensures that... | [
"def sample_tasks(self, num_tasks):\n wid = int(pow(self.num_states,0.5))\n transitions = self.np_random.dirichlet(np.ones(self.num_states),\n size=(num_tasks, self.num_states, self.num_actions))\n rewards_mean = self.np_random.normal(1.0, 1.0,\n size=(num_tasks, self.num_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sample a new task_state from the set of `n_tasks` tasks and set the environment to that `task_state`. | def reset_task_state(self) -> None:
self.set_task_state(task_state=self.sample_task_state()) | [
"def sample_task_state(self) -> TaskStateType:\n self.assert_task_seed_is_set()\n if not self._are_tasks_set:\n self.tasks = [self.env.sample_task_state() for _ in range(self.n_tasks)]\n self._are_tasks_set = True\n\n # The assert statement (at the start of the function) e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test StudyEventRecord include_option is a boolean, when False only required params are included, when True both required and optional params are included | def make_instance(self, include_optional):
# model = rcc.models.study_event_record.StudyEventRecord() # noqa: E501
if include_optional :
return StudyEventRecord(
participant_id = '0',
participant_screening_number = '0',
participant_status = ... | [
"def _asert_fields_set(option_metadata):\n vampytest.assert_instance(option_metadata, ApplicationCommandOptionMetadataSubCommand)\n \n vampytest.assert_instance(option_metadata.options, tuple, nullable = True)\n vampytest.assert_instance(option_metadata.default, bool)",
"def test_partner_optional_fiel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify the escalate cronjob escalates the right questions. | def test_escalate_questions_cron(self, submit_ticket):
questions_to_escalate = [
# Questions over 24 hours old without an answer.
question(
created=datetime.now() - timedelta(hours=24, minutes=10),
save=True),
question(
created... | [
"def escalate_questions():\n if settings.STAGE:\n return\n # Get all the questions that need attention and haven't been escalated.\n qs = Question.objects.needs_attention().exclude(\n tags__slug__in=[config.ESCALATE_TAG_NAME])\n\n # Exclude certain products.\n qs = qs.exclude(product__s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert GARMIN GPX extensions to DaimlerGPXExtensions | def _convert_wpt_extension(ext_el, wpt_out, ns, link_href,
map_category, map_icon, ignore_tags):
gpxx = "{%s}" % (ns["gpxx"],)
gpxd = "{%s}" % (ns["gpxd"],)
gxx_wp_ext = ext_el.find(gpxx + "WaypointExtension")
if gxx_wp_ext is None:
logging.warning("gpx:wpt has no GA... | [
"def extension_to_format(self, extension):",
"def format_to_extension(self, format):",
"def convert_poi(input, output, map_category=(), map_icon=(), ignore_tags=()):\n\n # some tools write v2, others v3. Use RegExp to find which\n rx = re.compile(\"xmlns:([^= ]+) *=['\\\"]([^'\\\"]+/GpxExtensions/[^'\\\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursive copy tags in GPX namespace, trims text elements | def _copy_gpx_tags(el, out):
if not el.tag.startswith("{http://www.topografix.com/GPX/1/1}"):
return
out_el = ET.Element(el.tag, attrib=el.attrib)
if el.text:
t = el.text.strip()
if t:
out_el.text = t
for c in el:
_copy_gpx_tags(c, out_el)
if el.tail:
... | [
"def strip_tags(tree_or_element, *tag_names): # real signature unknown; restored from __doc__\n pass",
"def strip_elements(tree_or_element, *tag_names, with_tail=True): # real signature unknown; restored from __doc__\n pass",
"def convert_poi(input, output, map_category=(), map_icon=(), ignore_tags=()):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert PoI from GARMIN to MercedesBenz GPX extensions. | def convert_poi(input, output, map_category=(), map_icon=(), ignore_tags=()):
# some tools write v2, others v3. Use RegExp to find which
rx = re.compile("xmlns:([^= ]+) *=['\"]([^'\"]+/GpxExtensions/[^'\"]+)")
m = None
for line in input:
m = rx.search(line)
if m:
break
... | [
"def _convert_wpt_extension(ext_el, wpt_out, ns, link_href,\n map_category, map_icon, ignore_tags):\n\n gpxx = \"{%s}\" % (ns[\"gpxx\"],)\n gpxd = \"{%s}\" % (ns[\"gpxd\"],)\n\n gxx_wp_ext = ext_el.find(gpxx + \"WaypointExtension\")\n if gxx_wp_ext is None:\n logging.war... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derive the desired score numbers from summarized COCOeval. | def _derive_coco_results(self, coco_eval, iou_type, class_names=None):
metrics = {
"bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
"segm": ["AP", "AP50", "AP75", "APs", "APm", "APl"],
"keypoints": ["AP", "AP50", "AP75", "APm", "APl"],
}[iou_type]
if coc... | [
"def compute_scores():\n\n prediction_table = load_predictions(\"all\")\n\n # ROC AUC scores\n roc_aucs = compute_score(prediction_table, roc_auc_score)\n roc_aucs = roc_aucs.round(4)\n save_evaluation(roc_aucs, \"roc_auc\")\n\n # Brier loss scores\n brier_losses = compute_score(prediction_tabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a small table using the keys of small_dict as headers. This is only suitable for small dictionaries. | def create_small_table(small_dict):
keys, values = tuple(zip(*small_dict.items()))
table = tabulate(
[values],
headers=keys,
tablefmt="pipe",
floatfmt=".3f",
stralign="center",
numalign="center",
)
return table | [
"def show_me(main_dict, keys, headers, meta=set()): \n rows = []\n for key in keys:\n if key not in main_dict:\n row = [key] + ['NA' for _ in range(len(headers)-1)]\n rows.append(row)\n continue\n \n the_object = main_dict[key]\n row = [getattr(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a function func for all i in a iterator list. | def process_list(_func, iterator, *args, **kwargs):
return [_func(i, *args, **kwargs) for i in iterator] | [
"def apply(items: Iterable, func: Callable):\n for item in items:\n func(item)",
"def each(self, func):\n\n for i in self._:\n func(i)\n return self",
"def for_each(fn: t.Callable[[T], t.Any], items: t.Iterable[T]) -> None:\n for i in items:\n fn(i)",
"def foreach(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scan and replace {key} values in a dictionary by dictionary['key'] value. | def batch_key_replace(dictionary, key=None):
if key is None:
for i in dictionary.keys():
batch_key_replace(dictionary, i)
return
if isinstance(dictionary[key], (six.string_types)):
for i in dictionary.keys():
if '{'+i+'}' in dictionary[key]:
logge... | [
"def recursiveSearchReplace(x, s, r):\n for k, v in x.items():\n if type(v) is dict:\n recursiveSearchReplace(v, s, r)\n else:\n if v == s:\n x[k] = r",
"def multiple_replace(dict, text): \n\n # Create a regular expression from the dictionary keys\n regex =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Daily prices are correctly returned. | def test_list_daily_prices(self):
from grand_exchanger.resources.graph import Graph
price_history = Graph(
daily={
datetime(2020, 7, 26, 0, 0): 120,
datetime(2020, 7, 25, 0, 0): 110,
datetime(2020, 7, 27, 0, 0): 100,
},
... | [
"def get_prices(self):\n pass",
"def get_daily_currencies():\n try:\n response = requests.get(DAILY_URL)\n if response.status_code == 200:\n return parse_cbr_currency_base_daily(response.text)\n abort(503)\n except:\n abort(503)",
"def with_dov(self, dov: Date... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Daily average prices are correctly returned. | def test_list_average_prices(self):
from grand_exchanger.resources.graph import Graph
price_history = Graph(
daily={},
average={
datetime(2020, 7, 26, 0, 0): 100,
datetime(2020, 7, 27, 0, 0): 104,
datetime(2020, 7, 25, 0, 0): 110,
... | [
"def average_monthly_price(self):\n currency_data_list = self.currency_data\n unique_list_of_dates = set(map(lambda x: x[\"date\"][0:7], currency_data_list))\n\n currency_date_list = []\n for i in unique_list_of_dates:\n dict_dates = {\"date\": i,\n \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test renaming columns in a data frame with duplicate column names. | def test_rename_columns(dupcols):
# Rename the first column
d1 = rename(dupcols, columns='Name', names='Person')
assert d1.columns[0] == 'Person'
assert dupcols.columns[0] == 'Name'
assert d1.columns[1] == 'A'
assert d1.columns[2] == 'A'
for col in d1.columns:
assert isinstance(col, ... | [
"def check_for_identical_column_names(\n df_1: pd.DataFrame, df_2: pd.DataFrame\n) -> bool:\n return list(df_1.columns) == list(df_2.columns)",
"def test_duplicated_column_names(suffix: str) -> None:\n path = rsc / duplicated_column_names_file\n df = read_ods(path.with_suffix(suffix), 1)\n\n assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
based on multiclass column stratify_column return stratified df | def simple_stratify(df, statify_column, seed=0, ratios=None, verbose=False):
if ratios == "original":
return df
else:
np.random.seed(seed)
vc = df[statify_column].value_counts()
masks = [(df[statify_column] == v) for v in vc.index]
sizes = list(vc)
if not isinstan... | [
"def to_binary_classification_task(df, class_col_name, minority_label, merged_label=\"rest\"):\n unique_class_labels = set(df[class_col_name].tolist())\n unique_class_labels.remove(minority_label)\n labels_to_merge = dict((label, merged_label) for label in unique_class_labels)\n df[class_col_name] = df[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
importances, stds, covariate_columns are all lists of the same length | def plot_importances(
importances,
stds,
covariate_columns,
fname=None,
title_prefix=None,
show=False,
ax=None,
topn=None,
sort_them=False,
title=None,
colors_dict=None,
keep_order=True,
):
sns.set_style("whitegrid")
# if not ax:
# fig = plt.figure(figsi... | [
"def numeric_features(data_list):\n mean = np.mean(data_list)\n min = np.min(data_list)\n max = np.max(data_list)\n variance = np.var(data_list)\n cv = np.var(data_list)/mean\n unique = len(set(data_list))\n return np.array([mean, min, max, variance,cv, unique/len(data_list)])",
"def get_feat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the first iterated number greater than cap | def advent_3b(cap):
for x in iter_nums():
if x > cap:
return x | [
"def lower_bound(stock):\n counter=0\n for i in stock_price(stock):\n if i <= support(stock):\n counter+=1\n return counter",
"def count_above(iterable, limit):\n return 0",
"def first_element_greater_than(list, number):\n for i in range(len(list)):\n if list[i] >... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the value at (x, y) in the cache, or return 0 | def get_or_zero(x, y):
coord = (x, y)
if coord in saved:
return saved[coord]
else:
return 0 | [
"def getVal(x, y, M):\n if (x, y) in M.keys():\n return M[(x, y)]\n elif (y, x) in M.keys():\n return M[(y, x)]\n else:\n return 0\n pass",
"def get_tile_from_cache(self, x, y):\n\n if not self.map.is_on_map(x, y):\n return Tile.EMPTY\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines a generator which goes through and outputs all coordinates in order | def iter_coords():
yield (0, 0)
incr = 0
x = 1
y = 0
while True:
incr += 2
top = y + incr - 1
bot = y - 1
left = x - incr
right = x
yield (x, y)
while y < top:
y += 1
yield (x, y)
while x > left:
... | [
"def iter_outputs(self):\n\n x, y, z = self.coords\n\n for dx, dy, dz in ((-1, 0, 0), (1, 0, 0), (0, 0, -1), (0, 0, 1),\n (0, -1, 0), (0, 1, 0)):\n yield x + dx, y + dy, z + dz",
"def coord_iter(self):\n for row in range(self.width):\n for col in range(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check all the known values for coordinates to see if the function works | def test_get_coords(self):
known_values = {
1: (0, 0),
2: (1, 0),
3: (1, 1),
4: (0, 1),
5: (-1, 1),
6: (-1, 0),
7: (-1, -1),
8: (0, -1),
9: (1, -1),
10: (2, -1),
11: (2, 0),
... | [
"def test_always_have_coordinates(self):\n pass",
"def _validate_coordinates(self):\n return",
"def test_are_coordinates_valid_invalid(self):\n board = [[student_submission.WATER for i in range(5)] for i in range(5)]\n self.assertFalse(student_submission.are_coordinates_valid(board, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we're traversing things in the right order | def test_traversal(self):
expected = [
(0, 0),
(1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1),
(2, -1), (2, 0), (2, 1), (2, 2), (1, 2), (0, 2), (-1, 2), (-2, 2),
(-2, 1), (-2, 0), (-2, -1), (-2, -2), (-1, -2), (0, -2), (1, -2), (2, -2),
... | [
"def test_pre_order_traversal(our_bsts):\n bpo = []\n for i in our_bsts[0].pre_order():\n bpo.append(i)\n assert bpo == our_bsts[4]",
"def _check_if_ordering_is_correct(self, ordering):\r\n if self._known_dependencies == {}:\r\n self._complete_dependencies()\r\n items_alre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert data in MongoDB and then check if MongoDB Oplog origin captures changes in data from MongoDB correctly. | def test_mongodb_oplog_origin(sdc_builder, sdc_executor, mongodb):
pipeline_builder = sdc_builder.get_pipeline_builder()
pipeline_builder.add_error_stage('Discard')
time_now = int(time.time())
mongodb_oplog = pipeline_builder.add_stage('MongoDB Oplog')
database_name = get_random_string(ascii_letter... | [
"def test_mongodb_inserts(self):\n self.render_config_template(\n mongodb_ports=[27017]\n )\n self.run_packetbeat(pcap=\"mongodb_inserts.pcap\",\n debug_selectors=[\"mongodb\"])\n\n objs = self.read_output()\n o = objs[1]\n assert o[\"t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create 3 simple documents consists with BSON Binary data type in MongoDB and confirm that MongoDB origin reads them. | def test_mongodb_origin_simple_with_BSONBinary(sdc_builder, sdc_executor, mongodb):
ORIG_BINARY_DOCS = [
{'data': binary.Binary(b'Binary Data Flute')},
{'data': binary.Binary(b'Binary Data Oboe')},
{'data': binary.Binary(b'Binary Data Violin')}
]
pipeline_builder = sdc_builder.get_... | [
"def test_create_empty_document(self):\n empty_doc = self.db.new_document()\n self.assertEqual(self.db[empty_doc['_id']], empty_doc)\n self.assertEqual(self.db.get(empty_doc['_id']), empty_doc)\n self.assertEqual(self.db.get(empty_doc['_id'], remote=True), empty_doc)\n self.assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send simple text into MongoDB destination from Dev Raw Data Source and confirm that MongoDB correctly received them using PyMongo. | def test_mongodb_destination(sdc_builder, sdc_executor, mongodb):
pipeline_builder = sdc_builder.get_pipeline_builder()
pipeline_builder.add_error_stage('Discard')
dev_raw_data_source = pipeline_builder.add_stage('Dev Raw Data Source')
dev_raw_data_source.set_attributes(data_format='TEXT', raw_data='\n... | [
"def MongoSave(message):\n client = pymongo.MongoClient(\"localhost\",27017)\n db = client.PortfolioTracker\n db.AllPortfolios.save(message)#this must be a dictionary for proper insertion http://docs.python.org/2/tutorial/datastructures.html#dictionaries",
"def test_mongodb_origin_simple_with_BSONBinary(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a imgLoader object initiated with the ra dec above | def L_radec():
return sdssimgLoader(ra=ra , dec=dec, dir_obj=dir_obj, img_width=img_width, img_height=img_height) | [
"def L_radec_64pix():\n\treturn sdssimgLoader(ra=ra , dec=dec, dir_obj=dir_obj, img_width=64, img_height=64)",
"def __init__(self, img_loader, gt_loader, den_map_loader=None):\n if (gt_loader is None) == (den_map_loader is None):\n raise ValueError(\"One and only one loader for target must be se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a imgLoader object initiated with the ra dec above of img size 6464 | def L_radec_64pix():
return sdssimgLoader(ra=ra , dec=dec, dir_obj=dir_obj, img_width=64, img_height=64) | [
"def L_radec():\n\treturn sdssimgLoader(ra=ra , dec=dec, dir_obj=dir_obj, img_width=img_width, img_height=img_height)",
"def image_loader(image):\n image = loader(image).float()\n image = Variable(image, requires_grad=True)\n image = image.unsqueeze(\n 0) # this is for VGG, may no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test that when overwrite=True make_stamp() always call download_stamp() whether file exists or not | def test_make_stamps_overwriteTrue(L_radec):
L = L_radec
band = 'r'
overwrite = True
file = dir_obj+'stamp-{0}.fits'.format(band)
if os.path.isfile(file):
os.remove(file)
# when file does not exist it creates stamp
assert not os.path.isfile(file)
L.make_stamps(overwrite=overwrite)
assert os.path.isfile(f... | [
"def test_make_stamps_overwriteFalse(L_radec):\n\tL = L_radec\n\n\toverwrite = False\n\n \tfor band in L.bands:\n\t\tfile = dir_obj+'stamp-{0}.fits'.format(band)\n\n\t\tif os.path.isfile(file):\n\t\t\tos.remove(file)\n\t\topen(file, 'w').close()\n\t\tassert os.stat(file).st_size == 0\n\n\t# when file exists it shou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test that when overwrite=False make_stamp() does not update file | def test_make_stamps_overwriteFalse(L_radec):
L = L_radec
overwrite = False
for band in L.bands:
file = dir_obj+'stamp-{0}.fits'.format(band)
if os.path.isfile(file):
os.remove(file)
open(file, 'w').close()
assert os.stat(file).st_size == 0
# when file exists it should not update file
L.make_stamps... | [
"def test_make_stamps_overwriteTrue(L_radec):\n\tL = L_radec\n\n\tband = 'r'\n\toverwrite = True\n\n\tfile = dir_obj+'stamp-{0}.fits'.format(band)\n\n\tif os.path.isfile(file):\n\t\tos.remove(file)\n\n\t# when file does not exist it creates stamp\n\tassert not os.path.isfile(file)\n\tL.make_stamps(overwrite=overwri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates the pipeline service client. | def __init__(
self,
*,
credentials: ga_credentials.Credentials = None,
transport: Union[str, PipelineServiceTransport] = "grpc_asyncio",
client_options: ClientOptions = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
self._... | [
"def create_client(self) -> None:\n self._client = discovery.build('ml', 'v1')",
"def create_client(self) -> None:\n self._client = gapic.JobServiceClient(\n client_options=dict(api_endpoint=self._region +\n _VERTEX_ENDPOINT_SUFFIX))",
"def create_client(self) -> None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Lists TrainingPipelines in a Location. | async def list_training_pipelines(
self,
request: pipeline_service.ListTrainingPipelinesRequest = None,
*,
parent: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListTrai... | [
"def list(cls):\n pipelines = []\n _pipeline_data = cls._api_get_pipelines()\n for pipeline in _pipeline_data:\n _tmp_pipe = cls.load(pipeline, unknown=EXCLUDE)\n _tmp_pipe.update_fed_status()\n pipelines.append(_tmp_pipe)\n return pipelines",
"def list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Cancels a TrainingPipeline. Starts asynchronous cancellation on the TrainingPipeline. The server makes a best effort to cancel the pipeline, but success is not guaranteed. Clients can use [PipelineService.GetTrainingPipeline][google.cloud.aiplatform.v1beta1.PipelineService.GetTrainingPipeline] or other methods to c... | async def cancel_training_pipeline(
self,
request: pipeline_service.CancelTrainingPipelineRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
#... | [
"def cancel(self) -> None:\n self.api_client.cancel_pipeline_job(name=self.resource_name)",
"async def cancel_pipeline_job(\n self,\n request: pipeline_service.CancelPipelineJobRequest = None,\n *,\n name: str = None,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Cancels a PipelineJob. Starts asynchronous cancellation on the PipelineJob. The server makes a best effort to cancel the pipeline, but success is not guaranteed. Clients can use [PipelineService.GetPipelineJob][google.cloud.aiplatform.v1beta1.PipelineService.GetPipelineJob] or other methods to check whether the can... | async def cancel_pipeline_job(
self,
request: pipeline_service.CancelPipelineJobRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
# Create or... | [
"def cancel(self) -> None:\n self.api_client.cancel_pipeline_job(name=self.resource_name)",
"def cancel_job(self):\n r = self.s.post(self.base_address + '/api/job', json={'command': 'cancel'})\n if r.status_code != 204:\n raise Exception(\"Error: {code} - {content}\".format(code=r.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a textual coverage report of all covergroups | def get_coverage_report(details=False)->str:
model = get_coverage_report_model()
out = StringIO()
formatter = TextCoverageReportFormatter(model, out)
formatter.details = details
formatter.report()
return out.getvalue() | [
"def coverage_report(self):\n verbose = '--quiet' not in sys.argv\n self.cov.stop()\n if verbose:\n log.info(\"\\nCoverage Report:\")\n try:\n include = ['%s*' % package for package in self.packages]\n omit = ['*tests*']\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a coverage report model of all covergroups | def get_coverage_report_model()->CoverageReport:
covergroups = CoverageRegistry.inst().covergroup_types()
db = MemFactory.create()
save_visitor = CoverageSaveVisitor(db)
now = datetime.now
save_visitor.save(TestData(
UCIS_TESTSTATUS_OK,
"UCIS:simulator",
ucis.ucis_Ti... | [
"def get_project_test_coverage(self) -> None:\n print_statistics = {}\n total_number_columns = 0\n number_columns_without_tests = 0\n\n for model_name in self.dbt_tests.keys():\n columns = self.dbt_tests[model_name]\n\n model_number_columns = 0\n model_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a coverage report to the console | def report_coverage(fp=None, details=False):
if fp is None:
fp = sys.stdout
fp.write(get_coverage_report(details)) | [
"def coverage_report(self):\n verbose = '--quiet' not in sys.argv\n self.cov.stop()\n if verbose:\n log.info(\"\\nCoverage Report:\")\n try:\n include = ['%s*' % package for package in self.packages]\n omit = ['*tests*']\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a dataframe with tags to influx, with time_precision=s. | def write_to_influx(df, tags, host, port, user, password, db_name, batch_size=10000, time_precision='s'):
logger.debug("Write DataFrame with Tags {}, with length: {}".format(tags, len(df)))
client = DataFrameClient(host, port, user, password, db_name)
if not client.write_points(df, db_name, tags, time_preci... | [
"def prepare_for_influxdb(df):\n df = df.drop(columns=\"landkreis\", errors=\"ignore\") # prevent name collision in get_ags()\n df = get_ags(df)\n df[\"time\"] = df.apply(lambda x: 1000000000*int(datetime.timestamp((pd.to_datetime(x[\"timestamp\"])))), 1)\n df[\"measurement\"] = \"hystreet\"\n df[\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the signature of this CancelClaimRequest. | def signature(self, signature: object):
self._signature = signature | [
"def signature(self, signature):\n\n self._signature = signature",
"def signature_required(self, signature_required):\n\n self._signature_required = signature_required",
"def setSignature(self, signature):\n self._signature.set(Sha256WithRsaSignature() if signature == None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the claim_id of this CancelClaimRequest. | def claim_id(self) -> str:
return self._claim_id | [
"def participant(self) -> AllOfCancelClaimRequestParticipant:\n return self._participant",
"def claim(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"claim\")",
"def crm_id(self):\n return self._crm_id",
"def cancellation_code(self) -> int:\n return self._cancellation_code"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the claim_id of this CancelClaimRequest. | def claim_id(self, claim_id: str):
if claim_id is None:
raise ValueError("Invalid value for `claim_id`, must not be `None`") # noqa: E501
self._claim_id = claim_id | [
"def abort_resource_claim(self, context, claim):\n if self.disabled:\n return\n\n # un-claim the resources:\n if self.claims.pop(claim.claim_id, None):\n LOG.info(_(\"Aborting claim: %s\") % claim)\n values = claim.undo_claim(self.compute_node)\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the participant of this CancelClaimRequest. | def participant(self) -> AllOfCancelClaimRequestParticipant:
return self._participant | [
"def participant(self) -> AllOfAcknowledgeClaimRequestParticipant:\n return self._participant",
"def participant(self):\n return self._participant",
"def participant(self, participant: AllOfCancelClaimRequestParticipant):\n if participant is None:\n raise ValueError(\"Invalid val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the participant of this CancelClaimRequest. | def participant(self, participant: AllOfCancelClaimRequestParticipant):
if participant is None:
raise ValueError("Invalid value for `participant`, must not be `None`") # noqa: E501
self._participant = participant | [
"def participant(self) -> AllOfCancelClaimRequestParticipant:\n return self._participant",
"def participant(self, participant: AllOfAcknowledgeClaimRequestParticipant):\n if participant is None:\n raise ValueError(\"Invalid value for `participant`, must not be `None`\") # noqa: E501\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the reason of this CancelClaimRequest. | def reason(self) -> ConfirmClaimRequestpropertiesReason:
return self._reason | [
"def cancel_reason(self):\n return self._dict.get('cancel_reason')",
"def cancel_reason(self) -> str:\n return self._cancel_reason",
"def reason(self) -> str:\n return self._reason",
"def reason_code(self):\n return self._reason_code",
"def rejection_reason(self):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the reason of this CancelClaimRequest. | def reason(self, reason: ConfirmClaimRequestpropertiesReason):
if reason is None:
raise ValueError("Invalid value for `reason`, must not be `None`") # noqa: E501
self._reason = reason | [
"def reason(self) -> ConfirmClaimRequestpropertiesReason:\n return self._reason",
"def reason(self, reason):\n\n self._reason = reason",
"def cancel_reason(self) -> str:\n return self._cancel_reason",
"def reason(self, reason):\n allowed_values = [\"CLIENT_ORDER\", \"TRADE_CLOSE\",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
子类中没有调用父类的方法也可以称为方法重写。当父类的方法不符合子类的实物的行为时,都可对其进行重写, 可在子类中定义一个这样的方法,即它与要重写的父类方法同名。这种子类包含与父类同名的方法的现象被称为方 法重写,也被称为方法覆盖。可以说子类重写了父类的方法,也可以说子类覆盖了父类的方法。 不显示调用当前类的父类的时候就不能调用父类的方法 | def eat(self):
# 在新的基类中有和父类一样的方法的时候叫重写父类方法/重载父类方法,可以说重写的方法不调用父类的方法的话就不会包含
# 父类中被重写方法的功能
print("什么都喜欢吃") | [
"def monkey_patch(cls, new_func, method, parent, methodtype=\"\", repatch=False, source=None):\r\n assert not parent or inspect.isclass(parent) or inspect.ismodule(parent)\r\n with Trace_rlock:\r\n if not parent:\r\n parent = getattr(method, cls.patch_parent_attr, None)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A contrived instance of the Swarm class at a certain timestep | def swarm():
attrs_at_t = {
"position": np.array([[5, 5, 5], [3, 3, 3], [1, 1, 1]]),
"velocity": np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]]),
"current_cost": np.array([2, 2, 2]),
"pbest_cost": np.array([1, 2, 3]),
"pbest_pos": np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),
... | [
"def setup_run(self, target_time):",
"def time_step():\n return TimeStep()",
"def __init__(self, lr_schedule, warmup_steps):\n super(WarmupDecaySchedule, self).__init__()\n self._lr_schedule = lr_schedule\n self._warmup_steps = warmup_steps",
"def __call__(self, plane, loop, step, *args, **kwargs):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lazyinitialize and return the map '__inits'. | def _get_inits(self):
# Fast-path already loaded
if self.__inits is not None:
return self.__inits
# Initialize the dictionary
self.__inits = dict()
# Populate this dictionary with PyTorch's initialization functions
for name in dir(torch.nn.init):
if len(name) == 0 or name[0] == "_": ... | [
"def _new_empty_basic_map(self):\n return OrderedDict()",
"def __init__(self):\n self.map = dict()\n self.ids = list()",
"def initialize(cls):\n if len(cls.mapping) == 0:\n cls.mapping[\"noop\"] = cls(Transform.identity, Combiner.noop)\n cls.mapping[\"sigmoid\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getter for the immutable configuration. | def config(self):
return self._config | [
"def get_config(self) -> Configuration:\n return self.config",
"def get_config(self):\n return self.full_config",
"def get_config(self):\n\n # make sure that the config reflects the state of the underlying logic\n self.logic_to_config()\n # and then return the config struct.\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve the given keywordarguments with the associated default value. | def _resolve_defaults(self, **kwargs):
res = list()
for name, value in kwargs.items():
if value is None:
value = self.default(name)
if value is None:
raise RuntimeError(f"Missing default {name}")
res.append(value)
return res | [
"def resolver(parameters: List[str], defaults: Optional[Mapping]=None):\n defaults = defaults or {}\n def resolve(*args, **kwargs):\n resolved = dict(zip(parameters, args)) # resolved positionals\n remaining = set(parameters) - set(resolved)\n resolved.update({\n p: kwargs.get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get (optionally make each parameter's gradient) a reference to the flat gradient. | def get_gradient(self):
# Fast path
if self._gradient is not None:
return self._gradient
# Flatten (make if necessary)
gradient = tools.flatten(tools.grads_of(self._model.parameters()))
self._gradient = gradient
return gradient | [
"def get_gradient_function(self):\n return self._rewrite_forward_and_call_backward",
"def get_gradient(self):\n return self.gradient",
"def _get_gradient_function(self):\n return self._delayed_rewrite_functions._rewrite_forward_and_call_backward # pylint: disable=protected-access",
"def get_grad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate loss at the current parameters, with a batch of the given dataset. | def loss(self, dataset=None, loss=None, training=None):
# Recover the defaults, if missing
dataset, loss = self._resolve_defaults(trainset=dataset, loss=loss)
# Sample the train batch
inputs, targets = dataset.sample(self._config)
# Guess whether computation is for training, if necessary
if trai... | [
"def eval_loss(self, input_dataset, target_dataset):\n\t\t#######################################################################\n\t\t# ** START OF YOUR CODE **\n\t\t#######################################################################\n\t\tprediction = self.network.forward(input_dataset)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the parameters using the given gradient, and the given optimizer. | def update(self, gradient, optimizer=None, relink=None):
# Recover the defaults, if missing
optimizer = self._resolve_defaults(optimizer=optimizer)[0]
# Set the gradient
self.set_gradient(gradient, relink=(self._config.relink if relink is None else relink))
# Perform the update step
optimizer.st... | [
"def update_parameters(parameters, grads, learning_rate = 1.2):\n # Retrieve each parameter from the dictionary \"parameters\"\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = parameters['W1']\n b1 = parameters['b1']\n W2 = parameters['W2']\n b2 = parameters['b2']\n ### END CODE HERE ###\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the revision number of the documentation helper | def getRevisionNumber(self):
return self.getDocumentedObject().getRevision() | [
"def revision_id(self):",
"def revision(self) -> Optional[int]:\n return pulumi.get(self, \"revision\")",
"def api_revision(self) -> Optional[str]:\n return pulumi.get(self, \"api_revision\")",
"def get_document_revision(draft):\n rev = draft.Properties.Item[\"ProjectInformation\"][\"Revision... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the building_state of the documentation helper | def getBuildingState(self):
return self.getDocumentedObject().getBuildingState() | [
"def test_docstring_State(self):\n self.assertIsNotNone(State.__doc__)",
"def build_info(self):\n return self._build_info",
"def buildable(self):\n return self._info['buildable']",
"def getDoc(self):\r\n return self.__doc__",
"def current_buildfile(self):\r\n return self._active_b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the installation_state of the documentation helper | def getInstallationState(self):
return self.getDocumentedObject().getInstallationState() | [
"def get_installation_status(self):\n if self.installation_status:\n version_str = self._get_version_string()\n status = f\"Installed (Version {version_str})\"\n else:\n status = \"Not installed\"\n return status",
"def _determine_installation_status(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of maintainers of the business template | def getMaintainerList(self):
return self.getDocumentedObject().getMaintainerList() | [
"def maintainers(path):\n pkg = catkin_pkg.package.parse_package(path)\n for m in pkg.maintainers:\n yield m.name, m.email",
"def maintainers():\r\n\r\n return FeedsAlchemy.db_all_maintainers()",
"def getProjectMaintainers(self, project):\n tree = ElementTree.fromstring(''.join(core.show_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of dependencies of the business template | def getDependencyList(self):
return self.getDocumentedObject().getDependencyList() | [
"def depend_list(self):\n return self._depend_list",
"def dependencies(self):\n if self._isDependent():\n return [self.ref.brick]\n else:\n return []",
"def dependencies(self):\n return self._deps",
"def dependencies(self):\n return self.config.get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves a dummy tokenized corpus to file and reads it | def test_unlabeled_corpus_saving(self):
original_corpus = [["Yo", "soy", "una", "oración", "gramatical", ",",
"regocíjense", "en", "mi", "glória", "."],
["Yo", "ungrammatical", "es", "oración", ","
"tú", "presumido", "elitista", ... | [
"def fit_to_corpus(self):\n print(\"creating the corpus object ... \")\n self.word_count=Counter()\n with open(self.corpus_path,encoding='utf-8') as f: #read the file\n data = tf.compat.as_str(f.read()).replace(\"\\n\",\" \").split(' ')\n\n\n self.word_count.update(data)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves corpus to file as G or unG and loads with reader | def test_labeled_corpus_saving(self):
original_corpus = [["Yo", "soy", "una", "oración", "gramatical", ",",
"regocíjense", "en", "mi", "glória", "."],
["Yo", "ungrammatical", "es", "oración", ","
"tú", "presumido", "elitista", ".... | [
"def save(file, corpus):\n with open(file, 'w') as f_out:\n f_out.write(corpus)",
"def test_unlabeled_corpus_saving(self):\n\n original_corpus = [[\"Yo\", \"soy\", \"una\", \"oración\", \"gramatical\", \",\",\n \"regocíjense\", \"en\", \"mi\", \"glória\", \".\"],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print query plans by running EXPLAIN on the queries. This also checks for distribution styles which cause a performance penalty. When the query plan consists of multiple query plans (which means, there will be temporary tables created), warn about that as well. A query plan has multiple subqueries when the query plan h... | def explain_queries(dsn: dict, relations: List[RelationDescription]) -> None:
transforms = [relation for relation in relations if relation.sql_file_name is not None]
if not transforms:
logger.info("No transformations were selected")
return
queries_with_temps = 0
counter: Dict[str, int] ... | [
"def printQueries(cls, out: TextIO = stdout) -> None:\n queries = (\n (getattr(cls.query, name).text, name)\n for name in sorted(vars(cls.query))\n )\n\n with createDB(None, cls.loadSchema()) as db:\n for line in explainQueryPlans(db, queries):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
restore packages required by tests | def restore(c):
c.run('pip install -r tests/requirements.txt') | [
"def tearDown(self):\n builtins.__import__ = self.original_imports",
"def test_reinstall_packages():\n\tassert packaging.install_packages(pkgs) == None",
"def test_remove_all(self):\n self.policy.add_package(\"test2.pkg\")\n self.policy.remove_all_packages()\n self.assertEqual(self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronously run function func in a separate thread. Any args and kwargs supplied for this function are directly passed | async def to_thread(func, *args, **kwargs):
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context()
func_call = functools.partial(ctx.run, func, *args, **kwargs)
return await loop.run_in_executor(None, func_call) | [
"async def to_thread(func, *args, **kwargs):\n loop = events.get_running_loop()\n ctx = contextvars.copy_context()\n func_call = functools.partial(ctx.run, func, *args, **kwargs)\n return await loop.run_in_executor(None, func_call)",
"async def run_async(self, func, *args):\n return await self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test reading of selections | def test_read_selection():
# test one channel for each selection
ch_names = ['MEG 2211', 'MEG 0223', 'MEG 1312', 'MEG 0412', 'MEG 1043',
'MEG 2042', 'MEG 2032', 'MEG 0522', 'MEG 1031']
sel_names = ['Vertex', 'Left-temporal', 'Right-temporal', 'Left-parietal',
'Right-parietal... | [
"def _test_sel_pres(self, sel, i):\n return self.__sel_pres(sel, i)",
"def test_boolean_and_selection(self):\n\n # The selection loop:\n sel = list(mol_res_spin.residue_loop(\"#Ap4Aase:4 & :Pro\"))\n\n # Test:\n self.assertEqual(len(sel), 1)\n for res in sel:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the RAID level and enforce restrictions based on it. | def level(self, value):
self._level = mdraid.RAID_levels.raidLevel(value) # pylint: disable=attribute-defined-outside-init | [
"async def setpermlevel(self, ctx, perm_level: int, *, role: discord.Role):\n if perm_level < 0:\n raise commands.BadArgument(f'{perm_level} is below 0')\n\n if perm_level == 0:\n await self.bot.db.update_guild_config(ctx.guild.id, {'$pull': {'perm_levels': {'role_id': str(role.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether or not a bitmap should be created on the array. If the the array is sufficiently small, a bitmap yields no benefit. If the array has no redundancy, a bitmap is just pointless. | def createBitmap(self):
return self.level.has_redundancy and self.size >= 1000 and self.format.type != "swap" | [
"def boolean(operation, bitmaps):\n\n maxX, maxY = size = bitmaps[0].size()\n result = bitmap(size)\n for x in range(maxX):\n for y in range(maxY):\n pixel = bitmaps[0].get(x,y)\n for b in bitmaps[1:]:\n pixel = apply(operation, (pixel, b.get(x,y)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the superblock size for a member of an array, given the total available memory for this array and raid level. | def getSuperBlockSize(self, raw_array_size):
return mdraid.get_raid_superblock_size(raw_array_size,
version=self.metadataVersion) | [
"def sub_block_size(self):\n if not self.sub_block_count or not self.parent_block_size:\n return None\n return self.parent_block_size / np.array(self.sub_block_count)",
"def _child_size(self) -> int:\n return round(self.size / 2.0)",
"def read_size_info(self):\n for part i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This array's mdadm.conf entry. | def mdadmConfEntry(self):
if self.memberDevices is None or not self.mdadmFormatUUID:
raise errors.DeviceError("array is not fully defined", self.name)
# containers and the sets within must only have a UUID= parameter
if self.type == "mdcontainer" or self.type == "mdbiosraidarray":
... | [
"def _config_md(self):\n self.cntrl[\"imin\"] = 0\n self.cntrl[\"ntx\"] = 1\n self.cntrl[\"irest\"] = 0\n self.cntrl[\"maxcyc\"] = 0\n self.cntrl[\"ncyc\"] = 0\n self.cntrl[\"dt\"] = 0.002\n self.cntrl[\"nstlim\"] = 5000\n self.cntrl[\"ntpr\"] = 500\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Total number of devices in the array, including spares. | def totalDevices(self):
if not self.exists:
return self._totalDevices
else:
return len(self.parents) | [
"def get_number_devices(self):\n return len(self.__devices_list)",
"def get_number_of_devices(self):\n return self.drt_manager.get_number_of_devices()",
"def get_number_of_devices(self):\n return self.num_of_devices",
"def get_count():\n _check_init()\n return _pypm.CountDevices()",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the array is running in degraded mode. | def degraded(self):
rc = False
degraded_file = "%s/md/degraded" % self.sysfsPath
if os.access(degraded_file, os.R_OK):
val = open(degraded_file).read().strip()
if val == "1":
rc = True
return rc | [
"def cluster_is_degraded(self):\n return self._cluster_is_degraded",
"def is_on(self) -> bool:\n return self._raid[\"degraded\"]",
"def run_degraded(self):\n return self._run_degraded",
"def is_degraded(graph: BELGraph, node: BaseEntity) -> bool:\n return has_edge_modifier(graph, node,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns this array's members. If the array is a BIOS RAID array then its unique parent is a container and its actual member devices are the container's parents. | def members(self):
if self.type == "mdbiosraidarray":
members = self.parents[0].parents
else:
members = self.parents
return list(members) | [
"def get_members(self):\n return sorted([x[\"patient\"] for x in self.pedigree])",
"def members(self) -> \"List[str]\":\n return self._attrs.get(\"members\")",
"def members(self):\n\t\tcount = ctypes.c_ulonglong()\n\t\tmembers = core.BNGetStructureMembers(self.handle, count)\n\t\tresult = []\n\t\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An MDRaidArrayDevice is complete if it has at least as many component devices as its count of active devices. | def complete(self):
return (self.memberDevices <= len(self.members)) or not self.exists | [
"def has_devices(self):\n return len(self.__devices_list) > 0",
"def is_full(self):\n return self.list_length >= len(self.the_array)",
"def validate_device_components(self):\n model_catalog = IModelCatalogTool(dmd)\n failed_devices = []\n object_implements_query = Eq('objectIm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove any stale LVM metadata that preexisted in a new array's ondisk footprint. | def removeStaleLVM():
log.debug("waiting 5s for activation of stale lvm on new md array %s", self.path)
time.sleep(5)
udev.settle()
try:
pv_info = lvm.pvinfo(device=self.path)[self.path]
except (errors.LVMError, KeyError) as e:
... | [
"def cleanup_keep_in_memory(self) -> None:\n first_key = self.first_key_in_memory\n if first_key is None:\n return\n cutoff_point = self.stop_entry - self.span_to_keep_in_memory\n for index, row in enumerate(self.data_in_memory):\n ts, value = row\n if ts... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update an image's total likes when a user likes it. users_like is a ManyToManyField so we send a m2m_changed signal to this receiver function. It updates the total_likes field for an image instance when that image's like count changes. Saying "(m2m_changed...)" connects this users_like_changed receiver function to the ... | def users_like_changed(sender, instance, **kwargs):
instance.total_likes = instance.users_like.count()
instance.save() | [
"def update_likes(self):\n self.nb_likes = self.likes.count()\n self.save()",
"def on_deleted_like(sender, instance: dillo.models.mixins.Likes, **kwargs):\n if not instance.content_object:\n return\n target_user = instance.content_object.user\n profile_likes_count_decrease(target_use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates vehicle's last date and duration if it exists in the database, creates a new vehicle if it doesn't. Updates vehicle's price/seller/mileage if a change is found from the existing price/seller. | def update_vehicle(vehicle, marketplace):
api = PscraperAPI()
seller_id = get_seller_id(vehicle, api)
if seller_id == -1:
return
# Post to history table
api.history_post(**{
'vin': vehicle[VIN],
'price': vehicle[PRICE],
'seller': seller_id,
'date': CURR_DATE... | [
"def update_vehicle_db_entry(cur, ulog, log_id, vehicle_name):\n\n vehicle_data = DBVehicleData()\n if 'sys_uuid' in ulog.msg_info_dict:\n vehicle_data.uuid = escape(ulog.msg_info_dict['sys_uuid'])\n\n if vehicle_name == '':\n cur.execute('select Name '\n 'from ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a seller id (primary_key). Search for existing seller by address. If not found creates a new seller and returns its id. Requires `seller` to have `streetAddress`, `city` and `state`. If any are missing returns 1. | def get_seller_id(vehicle, api):
seller = vehicle[SELLER]
try:
address = ADDRESS_FORMAT.format(seller[STREET_ADDRESS], seller[CITY], seller[STATE])
except KeyError:
send_slack_message(text=f'Address error for seller: {seller} and vehicle: {vehicle}')
return -1
# Search for exist... | [
"def seller_id(self) -> Any:\n return pulumi.get(self, \"seller_id\")",
"def seller(self):\n if \"seller\" in self._prop_dict:\n return self._prop_dict[\"seller\"]\n else:\n return None",
"def get_book(cls, book_title, book_id):\n return Bestseller.get_or_none((... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Context manager for applying `options` to `camera` | def _applied_camera_options(options, panel, camera):
from maya import cmds
old_options = None
if options is not None:
options = _parse_options(options)
old_options = dict()
for opt in options:
try:
old_options[opt] = cmds.getAttr(camera + "." + opt)
... | [
"def createCameraOptions(self):\n\t\tcamera = mc.optionMenuGrp(\"cameraPresets\", query=True, value=True)\n\t\trig = mc.checkBox(\"createRig\", query=True, value=True)\n\t\tphysical = mc.checkBox(\"physicalCam\", query=True, value=True)\n\n\t\t#print camera, rig, physical\n\t\tself.createCamera(camera, rig, physica... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |