query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Set the mask using the numpy image mask. In addition to reading the mask, the 1D indicies into the 3D image are generate and stored | def setMask(self, mask):
try:
self.mask = mask
self.inds = na.nonzero(self.mask.flat)[0]
#print "length of self.inds",len(self.inds)
#print self.inds
self.dim = self.mask.shape[::-1]
#print self.mask.shape
return True
ex... | [
"def test_05_01_mask_of3D(self):\n x=cpi.Image()\n x.image = np.ones((10,10,3))\n self.assertTrue(x.mask.ndim==2)",
"def set_mask(self, mask):\n self.mask = self._image_to_vector(mask)\n\n # PCA needs to be rerun\n self._mark_cache_invalid()",
"def __setMaskArray(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determines if the path points to something Arguments path path to test the existence of, relative to base_dir Return True if the path exists, False, otherwise | def exists(self, path: PathLike): | [
"def pathPresent (\n\n self,\n path = None\n ) :\n\n\n if path is None : return False\n\n path = self.normalizePath( path, normalize = False )\n \n if path is None : return False\n \n result = os.path.exists( path )\n\n return result",
"def pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if a path is a file. Returns false if the path doesn't exists Arguments path path from base_dir to test Returns True if the relative path exists and is a file, false otherwise | def is_file(self, path: PathLike): | [
"def file_exists(file_path: str, is_dir: bool = False) -> bool:\n file_path_expanded = os.path.expanduser(file_path) # type: str\n if is_dir:\n return os.path.isdir(file_path_expanded)\n return os.path.isfile(file_path_expanded)",
"def is_file(path: str) -> bool:\n return _fs().is_file(path)",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if a path is a directory. Returns false if the path doesn't exist Arguments path path from base_dir to test Returns True if the relative path exists and is a directory, false otherwise | def is_dir(self, path: PathLike): | [
"def is_directory(directory_path, path):\n secure_path = remove_upper_level_references(path)\n full_path = Path(directory_path, secure_path)\n if full_path.is_dir():\n return full_path\n return False",
"def is_dir(path: str) -> bool:\n return _fs().is_dir(path)",
"def is_dir(self, path):",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves a file Arguments path file to move dest new name force overwrite destination if it already exists | def move_file(self, path: PathLike, dest: PathLike, force: bool = False): | [
"def move_file(path):\n dst_path = request.args.get('to')\n return files.move_file(path, dst_path)",
"def move_file(file, destination):\n\n if not destination.exists():\n destination.mkdir(parents=True, exist_ok=True)\n shutil.move(file, destination)",
"def moveFile(source, dest):\n try:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends the content of a filelike object to dest Arguments f filelike object to send the data from dest destination file force overwrite dest if it exists | def send_data(self, fp, dest: PathLike, force: bool = False): | [
"def send_file(self, src: PathLike, dest: PathLike, force: bool = False):",
"def copyfileobj(self, fsrc, fdst, length=(16*1024)):\n fsrcRead = fsrc.read\n fdstWrite = fdst.write\n while True:\n buf = fsrcRead(length)\n if not buf:\n break\n fdst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a local file to the filesystem Arguments src local path to send dest destination file force overwrite dest if it exists | def send_file(self, src: PathLike, dest: PathLike, force: bool = False): | [
"def send_data(self, fp, dest: PathLike, force: bool = False):",
"def send_dir(self, src: PathLike, dest: PathLike, force: bool = False):",
"def file_copy(\n self,\n src: str,\n dest: Optional[str] = None,\n file_system: Optional[str] = None,\n peer: Optional[bool] = False,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a local directory to the filesystem Arguments src local path to send dest destination file force overwrite dest if it exists | def send_dir(self, src: PathLike, dest: PathLike, force: bool = False): | [
"def send_file(self, src: PathLike, dest: PathLike, force: bool = False):",
"async def send_dir(self, l_dir: str, r_dest: str) -> None:\n # pause logic\n if not self.running.is_set():\n self.add_to_output(\"Paused...\")\n await self.running.wait()\n\n # tell the user we are ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints summary about the plotting factory, i.e. how many plots and how many datasets per plot. | def info(self):
print(
"""
Factory holds {0} unique plots
""".format(
len(self.plots)
)
)
for i, plot in enumerate(self.plots):
print("\t\tPlot {0} holds {1} unique datasets".format(i, len(plot)))
for j, data... | [
"def make_summary_plots(arf):\n fullresfn = arf.fn+\".png\"\n diagnose.make_composite_summary_plot_psrplot(arf, outfn=fullresfn)\n\n # 6.25 MHz channels\n nchans = arf['bw']/6.25\n preproc = 'C,D,B 128,F %d' % nchans\n if arf['length'] > 60:\n # one minute subintegrations\n preproc +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the metricDataName and stores it in inputDict. @ In, metricDataName, string, the name of the metric data to find in currentInputs @ In, currentInputs, list of inputs to the step. @ Out, metricData, (data, probability) or Distribution | def __getMetricSide(self, metricDataName, currentInputs):
origMetricDataName = metricDataName
metricData = None
if metricDataName.count("|") == 2:
#Split off the data name and if this is input or output.
dataName, inputOrOutput, metricDataName = metricDataName.split("|")
inputOrOutput = [i... | [
"def metric_name(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"metric_name\")",
"def get_input(self, name):\n return self._inputs.get(name)",
"def run(self, inputIn):\n measureList = self.inputToInternal(inputIn)\n outputDict = {}\n assert(len(self.features) == len(measureList))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to convert an input object into the internal format that is understandable by this pp. @ In, currentInputs, list or DataObject, data object or a list of data objects @ Out, measureList, list of (feature, target), the list of the features and targets to measure the distance between | def inputToInternal(self, currentInputs):
if type(currentInputs) != list:
currentInputs = [currentInputs]
hasPointSet = False
hasHistorySet = False
#Check for invalid types
for currentInput in currentInputs:
inputType = None
if hasattr(currentInput, 'type'):
inputType = cur... | [
"def __getMetricSide(self, metricDataName, currentInputs):\n origMetricDataName = metricDataName\n metricData = None\n if metricDataName.count(\"|\") == 2:\n #Split off the data name and if this is input or output.\n dataName, inputOrOutput, metricDataName = metricDataName.split(\"|\")\n inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to place all of the computed data into the output object, (Files or DataObjects) @ In, finishedJob, object, JobHandler object that is in charge of running this postprocessor @ In, output, object, the object where we want to place our computed results @ Out, None | def collectOutput(self, finishedJob, output):
evaluation = finishedJob.getEvaluation()
outputDict = evaluation[1]
# FIXED: writing directly to file is no longer an option!
#if isinstance(output, Files.File):
# availExtens = ['xml']
# outputExtension = output.getExt().lower()
# if outputEx... | [
"def collectOutput(self, finishedJob, output):\n evaluation = finishedJob.getEvaluation()\n\n outputDict ={}\n outputDict['data'] = evaluation[1]\n\n if output.type in ['PointSet']:\n outputDict['dims'] = {}\n for key in outputDict.keys():\n outputDict['dims'][key] = []\n output.lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the method for writing the postprocessor to the metadata within a data object @ In, output, DataObject, instance to write to @ In, outputDictionary, dict, dictionary stores importance ranking outputs @ Out, xml, xmlUtils.StaticXmlElement instance, written data in XML format | def _writeXML(self,output,outputDictionary):
if self.dynamic:
outputInstance = xmlUtils.DynamicXmlElement('MetricPostProcessor', pivotParam=self.pivotParameter)
else:
outputInstance = xmlUtils.StaticXmlElement('MetricPostProcessor')
if self.dynamic:
for key, values in outputDictionary.item... | [
"def _writeXML(self,output,outputDictionary):\n if output.isOpen():\n output.close()\n if self.dynamic:\n outFile = Files.returnInstance('DynamicXMLOutput',self)\n else:\n outFile = Files.returnInstance('StaticXMLOutput',self)\n outFile.initialize(output.getFilename(),self.messageHandler,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method executes the postprocessor action. In this case, it computes all the requested statistical FOMs @ In, inputIn, object, object contained the data to process. (inputToInternal output) @ Out, outputDict, dict, Dictionary containing the results | def run(self, inputIn):
measureList = self.inputToInternal(inputIn)
outputDict = {}
assert(len(self.features) == len(measureList))
for metricInstance in self.metricsDict.values():
metricEngine = MetricDistributor.factory.returnInstance('MetricDistributor', metricInstance)
for cnt in range(le... | [
"def run(self,inputDic):\n if len(inputDic)>1:\n self.raiseAnError(IOError, 'HS2PS Interfaced Post-Processor ' + str(self.name) + ' accepts only one dataObject')\n else:\n inputDic = inputDic[0]\n outputDic={}\n outputDic['metadata'] = copy.deepcopy(inputDic['metadata'])\n outputDic['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds this shifts to the shifts of a Manager | def addShift(self,shift):
self.shifts.append(shift) | [
"def add_work_shift(self, add_name, workHourFrom, workHourTo):\n Log.info(\"Start to add a work shift\")\n self.click(self.add_btn)\n self.input_text(add_name, self.shift_name)\n self.set_combox_value(workHourFrom, self.workHour_from)\n self.set_combox_value(workHourTo, self.workH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds shifts to the shifts of an OtherEmployee | def addShift(self,shift):
self.shifts.append(shift) | [
"def add_work_shift(self, add_name, workHourFrom, workHourTo):\n Log.info(\"Start to add a work shift\")\n self.click(self.add_btn)\n self.input_text(add_name, self.shift_name)\n self.set_combox_value(workHourFrom, self.workHour_from)\n self.set_combox_value(workHourTo, self.workH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
4. Given the true cluster number, run your Lloyd's Kmeans algorithm on the image segmentation.csv dataset, and evaluate the results in terms of the external measurements completed in Part I. | def problem3(dataset_path, n_cluster):
km = KMeans(init="k-mean++", algorithm="lloyds", csv_path=dataset_path, n_clusters=n_cluster, n_init=3, verbose=False)
data = km.fit_predict_from_csv()
# km.show_plot()
ev = ExternalValidator(data)
nmi = ev.normalized_mutual_info()
nri = ev.normalized_ran... | [
"def run_kmeans_experiment(data_set_path, number_of_clusters, learner, fraction_of_data_used=1, data_type=float):\n print(\"Running {0} Experiment with k clusters = {1}\".format(data_set_path, number_of_clusters))\n all_data = CustomCSVReader.read_file(data_set_path, data_type)\n feature_selection_data = a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WikiWrap output correct for a term used as an example | def testTermKnownValuesWikiWrapAsExample(self):
for wikilang, pos, termlang, thisterm, termgender, asexample, \
forlist in self.knownValues:
if pos == 'noun':
aterm = term.Noun(termlang, thisterm, gender=termgender)
if pos == 'verb':
aterm ... | [
"def _HandleWikiWord(self, input_line, match, output_stream):\n if match[0] == \"!\":\n self._formatting_handler.HandleEscapedText(\n input_line,\n output_stream,\n match[1:])\n elif match not in self._wikipages:\n self._formatting_handler.HandleEscapedText(\n inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WikiWrap output correct for a term when used in a list | def testTermKnownValuesWikiWrapForList(self):
for wikilang, pos, termlang, thisterm, termgender, asexample, \
forlist in self.knownValues:
if pos == 'noun':
aterm = term.Noun(termlang, thisterm, gender=termgender)
if pos == 'verb':
aterm = ... | [
"def testTermKnownValuesWikiWrapAsTranslation(self):\n for wikilang, pos, termlang, thisterm, termgender, asexample, \\\n forlist in self.knownValues:\n if pos == 'noun':\n aterm = term.Noun(termlang, thisterm, gender=termgender)\n if pos == 'verb':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WikiWrap output correct for a term when used as a translation | def testTermKnownValuesWikiWrapAsTranslation(self):
for wikilang, pos, termlang, thisterm, termgender, asexample, \
forlist in self.knownValues:
if pos == 'noun':
aterm = term.Noun(termlang, thisterm, gender=termgender)
if pos == 'verb':
at... | [
"def question_new_translate():",
"def _HandleWikiWord(self, input_line, match, output_stream):\n if match[0] == \"!\":\n self._formatting_handler.HandleEscapedText(\n input_line,\n output_stream,\n match[1:])\n elif match not in self._wikipages:\n self._formatting_handle... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
self.term, self.gender and self.number parsed correctly from Wiki format | def testParser(self):
for wikiline, termlang, thisterm, termgender, termnumber in \
self.knownParserValues:
aterm = term.Term(termlang, '', wikiline=wikiline)
self.assertEqual(aterm.getTerm(), thisterm)
self.assertEqual(aterm.getGender(), termgender)
... | [
"def __init__(self):\n self.number_string = \"\"\n self.number_separate_string = \"\"\n self.punctuation_string = \"\"\n self.dic_pb = {}\n self.dic_cha = {}\n self.dic_term = {}",
"def parse_entity(self, term):\n pass",
"def _parse_mw(self, line):\n # Par... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query to count all rows is reasonable. | def test_count_all_rows_query(self):
mock_connector = MagicMock()
database = Database()
database.connect(connector_impl=mock_connector)
connection = mock_connector.connect()
cursor = connection.cursor()
cursor.__iter__.return_value = [(123,)]
num = database.count_all_rows()
self.asser... | [
"def test_countAllCoumns(self):\n self.assertEquals(\n Select([Count(ALL_COLUMNS)], From=self.schema.BOZ).toSQL(),\n SQLFragment(\"select count(*) from BOZ\")\n )",
"def count(self):\n return Env.backend().execute(ir.TableCount(self._tir))",
"def count_rows(self, table... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query to insert/update a row is reasonable. | def test_insert_or_update_query(self):
row = (
'source',
'signal',
'time_type',
'geo_type',
'time_value',
'geo_value',
'value',
'stderr',
'sample_size',
)
mock_connector = MagicMock()
database = Database()
database.connect(connector_impl=mock_co... | [
"def upsert(self, ctx, data, keys = []):\n\n # TODO: Check for AutoIncrement in keys, shall not be used\n\n # If keys\n qfilter = {}\n if (len(keys) > 0):\n for key in keys:\n try:\n qfilter[key] = data[key]\n except KeyError as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query to get rows with stale `direction` is reasonable. | def test_get_rows_with_stale_direction_query(self):
mock_connector = MagicMock()
database = Database()
database.connect(connector_impl=mock_connector)
result = database.get_rows_with_stale_direction()
self.assertIsInstance(result, list)
connection = mock_connector.connect()
cursor = conn... | [
"def test_get_rows_to_compute_direction_query(self):\n\n args = (\n 'source',\n 'signal',\n 'geo_type',\n 'time_value',\n 'geo_value',\n )\n mock_connector = MagicMock()\n database = Database()\n database.connect(connector_impl=mock_connector)\n\n result = database.get_row... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query to get rows needed to compute `direction` is reasonable. | def test_get_rows_to_compute_direction_query(self):
args = (
'source',
'signal',
'geo_type',
'time_value',
'geo_value',
)
mock_connector = MagicMock()
database = Database()
database.connect(connector_impl=mock_connector)
result = database.get_rows_to_compute_direc... | [
"def get_direction_matrix(self) -> int:",
"def getDirections(self):\n return sorted(Directions.objects.filter(recipe__id=self.pk),\n key=lambda x: x.step_number)",
"def trace_directions(self, direction, grid, length=7):\n result = []\n for dx, dy in direction:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query to update a row's `direction` is reasonable. | def test_update_direction_query(self):
args = (
'source',
'signal',
'time_type',
'geo_type',
'time_value',
'geo_value',
'direction',
)
mock_connector = MagicMock()
database = Database()
database.connect(connector_impl=mock_connector)
database.update_di... | [
"def update_player_direction(self,direction):\n pass",
"def update_direction(self, update_data: dict):\n if self.on_update_direction:\n self.on_update_direction(self, update_data)",
"def update_direction(self, ele, direction):\n if direction is not None:\n ele['object'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload the trigger to demisto_client | def upload(self, client: demisto_client):
# return client.import_triggers(file=self.path)
pass | [
"def _add(self):\n path = '/triggers'\n data = self.extract()\n self._dict['trigger_id'] = self.account.adapter.post(path, data)\n self.account.triggers._dict[self._dict['trigger_id']] = self",
"def _update(self):\n path = '/triggers/%s' % self._dict['trigger_id']\n data ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a tip to the TipableVMobject instance, recognising that the endpoints might need to be switched if it's a 'starting tip' or not. | def add_tip(self, tip_length=None, at_start=False):
tip = self.create_tip(tip_length, at_start)
self.reset_endpoints_based_on_tip(tip, at_start)
self.asign_tip_attr(tip, at_start)
self.add(tip)
return self | [
"def add_new_tip():\n\n username = session[\"logged_in_username\"]\n\n state_name= request.args.get(\"state\").title()\n city_name= request.args.get(\"city\").title()\n\n #If user leaves location inputs blank, add None value to database\n #so that, if later user filters by State and leave City blank,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stylises the tip, positions it spacially, and returns the newly instantiated tip to the caller. | def create_tip(self, tip_length=None, at_start=False):
tip = self.get_unpositioned_tip(tip_length)
self.position_tip(tip, at_start)
return tip | [
"def add_tip(self, tip_length=None, at_start=False):\n tip = self.create_tip(tip_length, at_start)\n self.reset_endpoints_based_on_tip(tip, at_start)\n self.asign_tip_attr(tip, at_start)\n self.add(tip)\n return self",
"def createTipFunction(self):\n \n template = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a VGroup (collection of VMobjects) containing the TipableVMObject instance's tips. | def get_tips(self):
result = VGroup()
if hasattr(self, "tip"):
result.add(self.tip)
if hasattr(self, "start_tip"):
result.add(self.start_tip)
return result | [
"def get_tips(self) -> VGroup:\n result = VGroup()\n if hasattr(self, \"tip\"):\n result.add(self.tip)\n if hasattr(self, \"start_tip\"):\n result.add(self.start_tip)\n return result",
"def tips(self):\n if not self._parsed:\n self._parse()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the TipableVMobject instance's (first) tip, otherwise throws an exception. | def get_tip(self):
tips = self.get_tips()
if len(tips) == 0:
raise Exception("tip not found")
else:
return tips[0] | [
"def getTip(self):\n return None",
"def __TipToUseFor(self, vial):\n if not vial.getLabel() in Instrument.__transportTipUsageMap.keys():\n raise InstrumentError (\"%s vial has no designated tip!\" % (vial.getLabel()))\n return (vial.getSector(), Instrument.__transportTipUsageMap[vi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a dictionary of telemetry to the input queue. | def add(self, telemetry):
# Check the telemetry dictionary contains the required fields.
for _field in self.REQUIRED_FIELDS:
if _field not in telemetry:
self.log_error("JSON object missing required field %s" % _field)
return
# Add it to the queue if ... | [
"def add(self, telemetry):\n # Check the telemetry dictionary contains the required fields.\n for _field in self.REQUIRED_FIELDS:\n if _field not in telemetry:\n self.log_error(\"JSON object missing required field %s\" % _field)\n return\n\n # Add it to ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process data from the input queue, and write telemetry to log files. | def process_queue(self):
self.log_info("Started Telemetry Logger Thread.")
while self.input_processing_running:
# Process everything in the queue.
while self.input_queue.qsize() > 0:
try:
_telem = self.input_queue.get_nowait()
... | [
"async def consumer(self):\n while True:\n logging.info(\"Consuming telephony log...\")\n logs = await self.telephonylog_queue.get()\n\n if logs is None:\n logging.info(\n \"Telephony logs empty. Nothing to write...\")\n contin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a telemetry dictionary to a CSV string. | def telemetry_to_string(self, telemetry):
_log_line = "%s,%s,%d,%.5f,%.5f,%.1f,%.1f,%s,%.3f\n" % (
telemetry['datetime'],
telemetry['id'],
telemetry['frame'],
telemetry['lat'],
telemetry['lon'],
telemetry['alt'],
telemetry['temp... | [
"def from_dict_to_csv(dictionary: dict) -> str:\n return \",\".join([f\"{key}:{value}\" for key, value in dictionary.items()])",
"def as_csv(self):\n keys = ['sys_time', 'sys_uptime', 'sys_mem_usage', 'sys_mem_total', 'sys_reboot_cause', 'sys_cpu_usage']\n vals = [self.dict.get(k) for k in keys]\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a packet of telemetry to a log file. | def write_telemetry(self, telemetry):
_id = telemetry['id']
_type = telemetry['type']
# If there is no log open for the current ID check to see if there is an existing (closed) log file, and open it.
if _id not in self.open_logs:
_search_string = os.path.join(self.log_direc... | [
"def log_packet_tx(self, node, event):\n if self.log_packets:\n self.log_file.write(\"{}|{}|{}|{}|{}|{}\\n\".format(event.id,\n event.event_cause if event.event_cause is not None \\\n else -1,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close any open logs that have not had telemetry added in X seconds. | def cleanup_logs(self):
_now = time.time()
for _id in self.open_logs.keys():
try:
if _now > (self.open_logs[_id]['last_time'] + self.FILE_ACTIVITY_TIMEOUT):
# Flush and close the log file, and pop this element from the dictionary.
sel... | [
"def close_logs():\n\tcore.BNCloseLogs()",
"def close_metric_log(self):\n if self.__metric_log_open:\n self._logger.closeMetricLog()\n self.__metric_log_open = False",
"def unload(self):\n for f in self.logs.values():\n f.close()",
"def end_log():\n _log.close... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Average weights from all iterations. | def average_weights(self):
for feat, weight in self.weights.items():
total = self._totals[feat]
total += (self.i - self._tstamps[feat]) * weight
averaged = total / float(self.i)
self.weights[feat] = averaged
return None | [
"def average_weights(w):\n w_avg = copy.deepcopy(w[0])\n for key in w_avg.keys():\n for i in range(1, len(w)):\n w_avg[key] += w[i][key]\n w_avg[key] = torch.div(w_avg[key], len(w))\n return w_avg",
"def average_weights(self, models):\n weights_list = [model.state_dict() f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a DataFrame of factor vectors for this type factor. | def get_factors(self, factor_encoding="one-hot"):
if not self.levels:
df = pd.DataFrame(0, index=range(self.number_elements), columns=[self.type_value])
df.loc[list(self.direct_indices.keys()), [self.type_value]] = 1
return df
levels = list(self.levels.keys()... | [
"def as_df(self):\r\n return pd.DataFrame(self.vectors).set_index(self.words)",
"def to_dataframe(self) -> pd.DataFrame:\n df = pd.DataFrame(data=self.to_numpy())\n df[\"fs\"] = self.dec_fs\n df[\"factors\"] = self.dec_factors\n df[\"increments\"] = self.dec_increments\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count the number of events and multiples in a list. | def _count_level_events(count_list):
if not len(count_list):
return 0, 0, None
number_events = 0
number_multiple = 0
max_multiple = count_list[0]
for index, count in enumerate(count_list):
if count_list[index] > 0:
number_events = n... | [
"def count(self, event_list):\n new_list = self.distinct(event_list)\n count_list = []\n for nl in new_list:\n count_list.append([nl, len(list(filter(lambda x: x.Name == nl, event_list)))])\n return count_list",
"def count_items(a_list):\n count = 0\n for item in a_lis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
{get} /auth/users/scope_dimensions/ 获取用户有权限的维度列表 get_scope_dimensions UserPerm {string} action_id 操作类型,例如 result_table.query_data {string} dimension 维度字段,例如 bk_biz_id {Boolean} [add_tdw] 是否考虑 TDW 标准化结果表 {json} 校验用户对结果表是否有查询数据权限 { | def get_scope_dimensions(self, request):
user_id = get_request_username()
action_id = request.cleaned_params["action_id"]
dimension = request.cleaned_params["dimension"]
# todo 需要换成通用的
valid_actions = ["result_table.query_data", "raw_data.update"]
valid_dimensions = ["bk... | [
"def get_dimensions(self, app_id):\n self.__set_up_auth_cookie()\n return engine_api_dimensions_helper.EngineAPIDimensionsHelper(\n self.__server_address, self.__auth_cookie).get_dimensions(app_id)",
"def dgraph_scopes(self, request):\n pool = Pool(10)\n\n def _build_scope(p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
{post} /auth/users/batch_check/ 批量校验用户与对象权限 batch_check_perm UserPerm {Dict[]} permissions 待鉴权列表 {string} permissions.user_id 待鉴权用户 {string} permissions.action_id 待鉴权功能 {string} permissions.object_id 待鉴权对象,如果不存在绑定对象,则传入 None {boolean} [display_detail] 是否展示鉴权详细结果 {json} 校验用户对结果表是否有查询数据权限 { | def batch_check(self, request):
display_detail = request.cleaned_params.get("display_detail")
pool = Pool(50)
def _check(kwargs):
user_id = kwargs["user_id"]
action_id = kwargs["action_id"]
object_id = kwargs["object_id"]
display_detail = kwargs[... | [
"def bulk_operate(request):\n create_formset_class = formset_factory(BatchAddPermissionsForm, extra=0)\n create_formset = None\n update_formset_class = formset_factory(BatchUpdatePermissionsForm, extra=0)\n update_formset = None\n operate_type = request.GET.get(\"type\")\n if request.method == \"P... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
{post} /auth/users/operation_configs/ 返回用户有权限的功能开关 operation_configs UserPerm {json} SucceesResponse.data [ { | def operation_configs(self, request):
user_id = get_request_username()
configs = OperationConfig.objects.all()
content = []
for config in configs:
if config.users is not None and user_id not in config.user_list:
config.status = OperationStatus.DISABLED
... | [
"def config(\n service: StemmarestPermissionService, args: PermissionArguments\n) -> dict[UserRole, list[PermissionConfig]]:\n base_config = [\n PermissionConfig(\n endpoint_access=EndpointAccess(\n name=\"Allow all\",\n description=\"Allowing full access for no... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
{post} /auth/users/dgraph_scopes/ 批量用户权限范围(dgrpah格式) dgraph_scopes UserPerm {Dict[]} permissions 参数列表 {string} permissions.user_id 用户 {string} permissions.action_id 功能 {string} permissions.variable_name 生成 dgraph 语句的变量名 {string} permissions.metadata_type 元数据类型 {json} 校验用户对结果表是否有查询数据权限 { | def dgraph_scopes(self, request):
pool = Pool(10)
def _build_scope(perm):
user_id = perm["user_id"]
action_id = perm["action_id"]
variable_name = perm["variable_name"]
metadata_type = perm["metadata_type"]
try:
object_class = ... | [
"def refresh_user_permissions(self) -> None:\n\n content = self.power_bi_session.make_request(\n method='post',\n endpoint=self.endpoint\n )\n\n return content",
"def grant_from_json(self, permissions_json):\n permissions = json.loads(permissions_json)\n us... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
{post} /auth/users/handover/ 交接权限 handover_permission UserPerm {String} receiver 被交接人 {json} Response.data { | def handover(self, request):
username = get_request_username()
receiver = request.cleaned_params["receiver"]
num, objects = UserPermission(user_id=username).handover(receiver)
if num > 0:
Stats.add_to_audit_action(
Stats.gene_audit_id(), username, AUDIT_TYPE.... | [
"def _handle_privilege(self, msg: Message):\n for perm in msg[\"privilege\"][\"perms\"]:\n self.granted_privileges[perm[\"access\"]] = perm[\"type\"]\n log.debug(f\"Privileges: {self.granted_privileges}\")\n self.xmpp.event(\"privileges_advertised\")",
"def UserAuthorizationRequest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialises a new object with given word inside a container. | def __init__(self, scene: 'Scene', word: str, container=None, attrs=None) -> None:
if container:
super(Object, self).__init__(scene, container=container)
else:
super(Object, self).__init__(scene)
self.word = word
if attrs:
self.attributes = attrs
... | [
"def from_word(cls, word):\n return cls(word=word.word, definition=word.definition)",
"def __init__(self):\n self._word_dict = {}",
"def __init__(self, tile, word):\n self.tile = tile\n self.word = word",
"def __init__(self, source_word):\n self.source_word = source_word",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the bites.csv file (= stats variable passed in), see example output in the Bite description. Return a list of Bite IDs (int or str values are fine) of the N most complex Bites. | def get_most_complex_bites(N=10, stats=stats):
with open(stats, encoding="utf-8-sig") as f:
bites = list(csv.DictReader(f, delimiter=';'))
pprint(bites)
bites.sort(key=_parse_difficulty, reverse=True)
return [bites[i]['Bite'] for i in range(N)] | [
"def get_most_complex_bites(N=10, stats=stats):\n def get_bite_id(s):\n return s[5:s.index(\".\")]\n\n with open(stats, encoding=\"utf-8-sig\") as csv_file:\n reader = csv.DictReader(csv_file, delimiter=\";\")\n filtered_list = [bite for bite in reader if bite[\"Difficulty\"] != \"None\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an invoice using default currency and language | def test_use_default_language_and_currency(self):
self._invoice_manager.create(
client_id = self._test_client.key().id(),
invoice_no = '2011/44',
invoice_date = date.today(),
... | [
"def gen_invoice():\n invoice_id = gen_id()\n account_id = gen_id()\n invoice_date = datetime(2012, random.choice(range(1,13)), random.choice(range(1,29)))\n\n invoice_item_amounts = [gen_invoice_item(account_id, invoice_id, invoice_date)]\n invoice_amount = sum([i['total_amount'] for i in invoice_it... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an invoice specifying a different language than customer default | def test_set_custom_language(self):
self._invoice_manager.create(
client_id = self._test_client.key().id(),
invoice_no = '2011/26',
invoice_date = date.today(),
... | [
"def test_use_default_language_and_currency(self):\r\n self._invoice_manager.create(\r\n client_id = self._test_client.key().id(), \r\n invoice_no = '2011/44', \r\n invoice_date = date.today(), \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an invoice specifying a different currency than customer default | def test_set_custom_currency(self):
self._invoice_manager.create(
client_id = self._test_client.key().id(),
currency_id = self._test_currency.key().id(),
invoice_no = '2011/26',
... | [
"def create_invoice(self, payment_req_bash_var, amount_msat: int) -> None:\n pass",
"def gen_invoice_item(account_id, invoice_id, invoice_date):\n plans = ['Unlimited', 'Standard']\n billperiods = ['Monthly']\n billperiod_months = {'Monthly': 1, 'Yearly': 12, 'Biyearly':24}\n amounts = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an invoice item to the current invoice and update totals | def _add_invoice_item(self, description, quantity, unit_price):
self._invoice_manager.add_invoice_item(description, quantity, unit_price)
self._sub_total += quantity * unit_price
self._total += quantity * unit_price | [
"def add_item(self, item):\n\n self.contents.append(item)\n self.update_total_items()\n self.update_subtotal()",
"def add_item(self, item):\n item_exists = self.get_item(item.id)\n\n if item_exists:\n item_exists._increment_quantity(item.quantity)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the words from topic file into a dictionary and returns that. | def load_topic_words(topic_file):
f = open(topic_file, 'r')
# Get word/score combinations into a list
lines = f.readlines()
# File is no longer needed
f.close()
topic_dict = {}
# Split all the lines, convert to tuples and then put it into the dict
for (word, score) in map(tuple, map... | [
"def load_words():\n\n print(\"Loading categories from files...\")\n\n w_dict = {}\n for name in FILE_NAMES:\n # inFile: file\n in_file = open(\"data/\" + name + '.txt', 'r')\n # wordlist: list of strings\n wordlist = []\n for line in in_file:\n wordlist.append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the n top scored words from topic_words_dict. | def get_top_n_words(topic_words_dict, n):
score_wordlist = topic_words_dict.items()
score_wordlist.sort(key=lambda x: x[1], reverse=True)
return [word for (word,score) in score_wordlist[:n]] | [
"def get_top_n_words(topic_dict, n=5):\n top_words = []\n for num, data in topic_dict.items():\n sorted_words = {k: v for k, v in sorted(data['words'].items(),\n key=lambda x: x[1],\n reverse=True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters the top n unique words from the word list, sorted by their topic words score. | def filter_top_n_words(topic_words_dict, n, word_list):
# First remove any redundant words in word_list
words = set(word_list)
# Now get the intersection with words, that appear as keys in the dict
topic_words_intersect = set(topic_words_dict.keys()).intersection(words)
# Now get the words with thei... | [
"def get_top_n_words(topic_words_dict, n):\n score_wordlist = topic_words_dict.items()\n score_wordlist.sort(key=lambda x: x[1], reverse=True)\n return [word for (word,score) in score_wordlist[:n]]",
"def get_top_n_words(word_list, n):\n word_counts = get_histogram(word_list)\n\n ordered_by_frequen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
collection is a directory containing textfiles. The first n of those text files will be loaded as sentences. | def load_collection_sentences(collection, n):
files = os.listdir(collection)
files_sentences = []
for f in files:
files_sentences.append(load_file_sentences(collection + "/" + f,f))
n -= 1
if n == 0:
break
return files_sentences | [
"def load_data_sentences(dirname):\n sentence_list = []\n for fname in os.listdir(dirname):\n with open(os.path.join(dirname, fname)) as file:\n #sentence_list.append(gensim.models.word2vec.LineSentence(file))\n sentence_list.append(file)\n return sentence_list",
"def corpusM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the dependency parse of the given sentence. | def dependency_parse_sentence(sentence):
p = Parser()
deps = p.parseToStanfordDependencies(sentence)
# Flatten and organize in the required format
return [(r, gov.text, dep.text) for r, gov, dep in deps.dependencies] | [
"def parse(sentence):\n return nlp(sentence)",
"def parse(sentence, model):\n state = ParseState(sentence)\n while not state.complete:\n transition, deprel = model.predict(state.state())\n state.parse_transition(transition, deprel)\n return state.deps",
"def parse_for_lm(sentence):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of unique words which that appear together with word in the dependency_list. | def get_linked_words(dependency_list, word):
words = set() # Unique words, so first a set
for (rel, gov, dep) in dependency_list:
if gov == word:
words.add(dep)
elif dep == word:
words.add(gov)
return list(words) | [
"def wordset(word_list):\n\n unique_words = []\n\n for word in word_list:\n\n if word not in unique_words:\n unique_words.append(word)\n\n unique_words.sort()\n\n return unique_words",
"def __remove_duplicates(self, word_list: List[str]) -> List[str]:\n\n # here comes the extr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a feature space for a collection. | def create_collection_feature_space(collection_path):
sentences = load_collection_sentences(collection_path, __fape_files_to_load)
return create_feature_space(reduce(lambda x,y: x[0]+y[0], sentences)) | [
"def _feature_collection_from_features(features):\n layer = {\n \"type\": \"FeatureCollection\",\n \"features\": features\n }\n return layer",
"def create_collection(self, collection, scope=CbServer.default_scope):\n collection_spec = SDKClient.get_collection_spec(scope,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
vectorize from solution to hw1. Creates a vector for the given sentence in accordance to the given feature space. | def vectorize(vector_space, sentence):
vector = [0] * len(vector_space)
for word in sentence[0].split():
vector[vector_space[word]] = 1
return vector | [
"def makeFeatureVec(words, model, num_features):\n featureVec = np.zeros((num_features,),dtype=\"float32\")\n num_words = 0.\n index2word_set = set(model.wv.index2word)\n for word in words:\n if word in index2word_set:\n num_words += 1\n featureVec = np.add(featureVec,model[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Vectorizes an entire collection. | def vectorize_collection(feature_space, collection_path):
sentences = load_collection_sentences(collection_path, __fape_files_to_load)
# concatenate all the string lists
sentences = reduce(lambda x,y: x[0]+y[0], sentences)
return zip(sentences, map(vectorize, [feature_space]*len(sentences),\
... | [
"def normalize(self):\n self._vectors = [vector.normalized() for vector in self._vectors]",
"def vectorizer(self) -> object:",
"def vectorize(self, *args, **kwargs):\n kwargs['add_start'] = False\n return super().vectorize(*args, **kwargs)",
"def vectorize(items, cls=None):\n if cls is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes centrality of a given vector regarding the given list of vectors and using the given similarity metric. | def centrality(similarity, vector, vectors):
return 1.0/len(vectors)*sum([similarity(vector,y) for y in vectors\
if y != vector]) | [
"def centrality(vects):\n\n n = len(vects)\n\n # For each vector, find the average similarity to all the other\n # vectors. Use reference equality to avoid comparing with self.\n return [(sum([cosine_sim(vect, vect1)\n for vect1 in vects\n if vect is not vect1])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ranks the sentences from the collection in collection_path by their centrality. | def rank_by_centrality(collection_path, sim_func):
# First get the feature space and vectorize the collection
fs = create_collection_feature_space(collection_path)
vectorized = vectorize_collection(fs, collection_path)
all_vectors = [vector for (sent, vector) in vectorized]
# Compute all centrality ... | [
"def order_ideal(self, gens):",
"def sort_sentiments(source, related_articles):\n #(score, article)\n for article in related_articles:\n score = 0\n return list(related_articles.keys())",
"def _consolidate(self, consolidation_path_list, representative_to_seq_list):\n print('Doing sequence... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a sentence and a list of topic words, returns the number of topic words in the sentence. | def topic_weight(sentence, topic_words):
topic_words = set(topic_words) # slight speedup, lookup in set is faster
topic_weight = 0
for word in sentence.split():
if word in topic_words:
topic_weight += 1
return topic_weight | [
"def get_word_count(text,list_of_words):\n count = 0\n for word in list_of_words: \n count += text.lower().count(word)\n return count",
"def count_words(sentence):\n\tblob = tb.TextBlob(sentence.decode('utf-8','ignore'))\n\tword_list = [w for w in blob.words if '\\'' not in w]\n\treturn len(word_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ranks the collection in collection_path by topic weight, using the topic words found in topic_file. | def rank_by_tweight(collection_path, topic_file):
# First get the sentences and the topic words
ts = load_topic_words(topic_file).keys()
sentences = load_collection_sentences(collection_path, __fape_files_to_load)
# reduce to 1-dimensional list of tuples (sentence, filename)
sentences = reduce(lambd... | [
"def combined_ranking(collection_path, topic_file, sim_func):\n cent_rank = rank_by_centrality(collection_path, sim_func)\n tweight_rank = rank_by_tweight(collection_path, topic_file)\n # Normalize topic weights to have Values in [0,1]\n max_weight = max([w for (x,w) in tweight_rank])\n tweight_rank ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Combines centrality and topic weight ranking into one. | def combined_ranking(collection_path, topic_file, sim_func):
cent_rank = rank_by_centrality(collection_path, sim_func)
tweight_rank = rank_by_tweight(collection_path, topic_file)
# Normalize topic weights to have Values in [0,1]
max_weight = max([w for (x,w) in tweight_rank])
tweight_rank = [(x,(flo... | [
"def rerank_topics(self,topics_commonness,topics_entropy):\n topics_commonness_txt = [x[0] for x in topics_commonness]\n topics_entropy_txt = [x[0] for x in topics_entropy]\n topics_commonness_only = list(set(topics_commonness_txt) - set(topics_entropy_txt))\n topics_entropy_only = list(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a summary of approximately summary_len made from the list of ranked sentences in ranked_sents. | def summarize_ranked_sentences(ranked_sents, summary_len):
summary = []
for (sent, value) in ranked_sents:
summary.append(sent)
summary_len -= len(sent.split())
if summary_len <= 5:
# We stop at n-5 words already, as an effort to avoid being
# really far off.
... | [
"def summarize_ranked_sentences_fixed(ranked_sents, summary_len,\\\n min_sentence_length=None, max_sentence_length=None,\\\n max_similarity=None, sim_func=None):\n summary = []\n # Feature space for ranked sentences, needed for similarity testing:\n fs = create_feature_space(map(lambda x:x[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a summary of approximately summary_len made from the list of ranked sentences in ranked_sents. | def summarize_ranked_sentences_fixed(ranked_sents, summary_len,\
min_sentence_length=None, max_sentence_length=None,\
max_similarity=None, sim_func=None):
summary = []
# Feature space for ranked sentences, needed for similarity testing:
fs = create_feature_space(map(lambda x:x[0], ranked_sen... | [
"def summarize_ranked_sentences(ranked_sents, summary_len):\n summary = []\n for (sent, value) in ranked_sents:\n summary.append(sent)\n summary_len -= len(sent.split())\n if summary_len <= 5:\n # We stop at n-5 words already, as an effort to avoid being\n # really f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to begin a resource claim for a new instance. | def begin_instance_resource_claim(self, context, instance_ref, *args,
**kwargs):
memory_mb = instance_ref['memory_mb']
disk_gb = instance_ref['root_gb'] + instance_ref['ephemeral_gb']
claim = self._do_begin_resource_claim(context, memory_mb, disk_gb,
*args, **kwargs)... | [
"def create_provisioning_claim(templateName=None):\n pass",
"def __init__(__self__,\n resource_name: str,\n args: AuthServerClaimDefaultArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...",
"def create(self):\n raise WufooException(\"Ins... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicate that the compute operation that previously claimed the resources identified by 'claim' has now completed and the resources have been allocated at the virt layer. Calling this keeps the available resource data more accurate and timely than letting the claim timeout elapse and waiting for update_available_resour... | def finish_resource_claim(self, claim):
if self.disabled:
return
if self.claims.pop(claim.claim_id, None):
LOG.info(_("Finishing claim: %s") % claim)
else:
LOG.info(_("Can't find claim %d. It may have been 'finished' "
"twice, or it ha... | [
"def update_available_resource(self, context):\n # ask hypervisor for its view of resource availability &\n # usage:\n resources = self.driver.get_available_resource()\n if not resources:\n # The virt driver does not support this function\n LOG.warn(_(\"Virt driver ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicate that the operation that claimed the resources identified by 'claim_id' has either failed or been aborted and the resources are no longer needed. | def abort_resource_claim(self, context, claim):
if self.disabled:
return
# un-claim the resources:
if self.claims.pop(claim.claim_id, None):
LOG.info(_("Aborting claim: %s") % claim)
values = claim.undo_claim(self.compute_node)
self.compute_node =... | [
"def finish_resource_claim(self, claim):\n if self.disabled:\n return\n\n if self.claims.pop(claim.claim_id, None):\n LOG.info(_(\"Finishing claim: %s\") % claim)\n else:\n LOG.info(_(\"Can't find claim %d. It may have been 'finished' \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Override inmemory calculations of compute node resource usage based on data audited from the hypervisor layer. Add in resource claims in progress to account for operations that have declared a need for resources, but not necessarily retrieved them from the hypervisor layer yet. | def update_available_resource(self, context):
# ask hypervisor for its view of resource availability &
# usage:
resources = self.driver.get_available_resource()
if not resources:
# The virt driver does not support this function
LOG.warn(_("Virt driver does not sup... | [
"def AddResourceUsage(self, status):\n\n if self.user_cpu_usage or self.system_cpu_usage:\n status.cpu_time_used = rdf_client.CpuSeconds(\n user_cpu_time=self.user_cpu_usage.next(),\n system_cpu_time=self.system_cpu_usage.next())\n if self.network_usage:\n status.network_bytes_sent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the compute node in the DB | def _create(self, context, values):
# initialize load stats from existing instances:
compute_node = db.compute_node_create(context, values)
return compute_node | [
"def create_compute_node(context, values):\n return _get_dbdriver_instance().create_compute_node(context, values)",
"def compute_node_create(context, values, session=None):\n if not session:\n session = get_session()\n\n _adjust_compute_node_values_for_utilization(context, values, session)\n wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For each existing instance generate load stats for the compute node record. | def _create_load_stats(self, context, instance=None):
values = {}
if instance:
instances = [instance]
else:
self.stats.clear() # re-generating all, so clear old stats
# grab all instances that are not yet DELETED
filters = {'host': self.host, 'd... | [
"def update_load_metrics(self):\n\n response = self.gcs_client.get_all_resource_usage(timeout=60)\n resources_batch_data = response.resource_usage_data\n log_resource_batch_data_if_desired(resources_batch_data)\n\n # Tell the readonly node provider what nodes to report.\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Persist the compute node updates to the DB | def _update(self, context, values, prune_stats=False):
return db.compute_node_update(context, self.compute_node['id'],
values, prune_stats) | [
"def persist(self):\n neo = self.caller.to_neo()\n client.merge(neo)\n neo.update(self.caller.props)\n client.push(neo)",
"def update_compute_node(context, node_uuid, values):\n return _get_dbdriver_instance().update_compute_node(\n context, node_uuid, values)",
"def save(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test output format for catkin_lint text output | def test_text(self):
result = self._do_output(o.TextOutput(o.Color.Never), self._demo_msgs)
self.assertEqual(result,
"mock: mock.cmake(1): error: short text\n"
"mock: mock.cmake(2): warning: short text\n"
"mock: mock.cmake(3): no... | [
"def test_cli_conversion(self):\n output = main('coloredlogs', '--convert', 'coloredlogs', '--demo', capture=True)\n # Make sure the output is encoded as HTML.\n assert '<span' in output",
"def test_formatter_default(self, capsys):\n f = Formatter(format_='default', output=sys.stdout)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test output format for catkin_lint text output with explanations | def test_explained_text(self):
result = self._do_output(o.ExplainedTextOutput(o.Color.Never), self._demo_msgs)
self.assertEqual(result,
"mock: mock.cmake(1): error: short text\n"
" * long text\n"
" * You can ignore this p... | [
"def test_text(self):\n result = self._do_output(o.TextOutput(o.Color.Never), self._demo_msgs)\n self.assertEqual(result,\n \"mock: mock.cmake(1): error: short text\\n\"\n \"mock: mock.cmake(2): warning: short text\\n\"\n \"mock: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test output format for catkin_lint JSON output | def test_json(self):
result = self._do_output(o.JsonOutput(), self._demo_msgs)
self.assertEqual(result,
'{"errors": ['
'{"id": "MOCK_MSG", "location": {"file": "mock.cmake", "line": 1, "package": "mock"}, "text": "short text"}, '
... | [
"def test_lint_with_json_output(self):\n _lint(\n 'scripts/xsslint/tests/templates',\n template_linters=self.template_linters,\n options={\n 'list_files': False,\n 'verbose': False,\n 'rule_totals': True,\n 'summary_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test output format for catkin_lint XML output | def test_xml(self):
result = self._do_output(o.XmlOutput(), self._demo_msgs)
self.assertEqual(result,
'<catkin_lint xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/fkie/catkin_lint/%(version)s/catkin_lint.xsd... | [
"def test_02_XML(self):\n pass",
"def test_01_Xml(self):\n self.assertEqual(self.m_xml.root.tag, 'PyHouse', 'Invalid XML - not a PyHouse XML config file')\n self.assertEqual(self.m_xml.computer_div.tag, 'ComputerDivision')\n self.assertEqual(self.m_xml.communication_sect.tag, 'Communic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
py2中 raw_input()将所有输入作为字符串看待,并且返回字符串类型 input()只用于数字的输入,返回所输入数字类型 python3中,只存在input()函数,接收任意类型的输入,并且将输入默认为字符串类型处理,返回字符串类型。 | def raw_input():
from past.builtins import raw_input
ri = raw_input()
print("raw_input", type(ri))
i = input()
print("input", type(i)) | [
"def get_input(value=u''):\n input_ = raw_input('%s ' % value)\n if input_:\n return safe_unicode(input_)\n else:\n LOG.debug('No input given')\n return ''",
"def get_input():\n return input().strip()",
"def safeRawInput(in_string = None):\r\n \r\n try:\r\n if in_st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a part to this geometry. | def add_part(self, part_name, part, overwrite=False):
if not part.is_valid:
raise ValueError("Part " + part_name + " is not a valid polygon.")
if (part_name in self.parts) and (not overwrite):
raise ValueError("Attempted to overwrite the part " + part_name + ".")
else:
... | [
"def add_part(self, part):\r\n if part.part_id in self.parts_by_id:\r\n return\r\n \r\n SlTrace.lg(\"add_part: %s\" % part, \"add_part\")\r\n \"\"\" Provide pointers to other entries\r\n in the parts_by_id entry to aid do/undo\r\n \"\"\"\r\n loc_key = part... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the build order restricted to parts. | def part_build_order(self):
priority = []
for geo_item in self.build_order:
if geo_item in self.parts:
priority += [geo_item]
return priority | [
"def part_build_order(self) -> List[str]:\n priority = []\n for geo_item in self.build_order:\n if geo_item in self.parts and isinstance(self.parts[geo_item], Polygon):\n priority += [geo_item]\n return priority",
"def getDoNotOrder(self, components):\n iss = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of vertex coordinates for a part | def part_coord_list(self,part_name):
# Note that in shapely, the first coord is repeated at the end, which we trim off:
coord_list = list(np.array(self.parts[part_name].exterior.coords.xy).T)[:-1]
return coord_list | [
"def coord_list(self, part_name: str) -> List:\n part = self.parts[part_name]\n if isinstance(part, Polygon):\n # Note that in shapely, the first coord is repeated at the end, which we\n # trim off:\n return list(np.array(part.exterior.coords.xy).T)[:-1]\n elif ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of vertex coordinates for an edge. | def edge_coord_list(self,edge_name):
coord_list = list(np.array(self.edges[edge_name].coords.xy).T)[:]
return coord_list | [
"def edge_vertices(edge):\n return [edge.vertex1, edge.vertex2]",
"def edge_coordinates(self, edge, axes=\"xyz\"):\n return self.vertex_coordinates(edge[0], axes=axes), self.vertex_coordinates(edge[1], axes=axes)",
"def node_edge_point(self) -> List[str]:\n return self._node_edge_point",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get mapping of part names to materials. | def get_material_mapping(self):
return {name: self.get_material(name) for name in self.parts.keys()} | [
"def info_materials_polymer_get():\n materials = _material_by_group(974) # 974 == intermediate group\n return materials, 200",
"def collect_materials(self):\n materials = []\n for term in self.terms:\n materials.extend(term.get_materials(join=True))\n\n return materials",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a part from this geometry. | def remove_part(self, part_name, ignore_if_absent=False):
if part_name in self.parts:
del self.parts[part_name]
else:
if not ignore_if_absent:
raise ValueError(
"Attempted to remove the part " + part_name + ", which doesn't exist.")
... | [
"def removeGeometry(self, geometry):\n self.subDivBoxTrees.pop(geometry.guid)",
"def deleteRigPart(self):\n self.setParent(None)\n self.setVisible(False)\n self.deleteLater()",
"def RemoveShape(self, *args):\n return _XCAFDoc.XCAFDoc_ShapeTool_RemoveShape(self, *args)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write geometry to a fcstd file. Returns the fcstd file path. | def write_fcstd(self, file_path=None):
if file_path is None:
file_path = '_'.join([item[0:4].replace(' ', '_') for item in self.build_order]) + '.fcstd'
write_deserialised(self.serial_fcdoc, file_path)
return file_path | [
"def write_geometry_file(prefix, rid, geo):\n GEOMETRY_FILE.write([prefix, rid], geo)",
"def write_mat_file(self):\n mat_dict = {}\n mat_dict['Lx_p'] = self.Lx_p\n mat_dict['Ly_p'] = self.Ly_p\n mat_dict['Lz_p'] = self.Lz_p\n mat_dict['Lo'] = self.obst.get_Lo()\n mat_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
covert ros point cloud to open3d point cloud | def rospc_to_o3dpc(rospc, remove_nans=False):
field_names = [field.name for field in rospc.fields]
is_rgb = 'rgb' in field_names
cloud_array = ros_numpy.point_cloud2.pointcloud2_to_array(rospc)
if remove_nans:
mask = np.isfinite(cloud_array['x']) & np.isfinite(cloud_array['y']) & np.isfinite(clo... | [
"def convertcloud(points):\n pcd = open3d.geometry.PointCloud()\n pcd.points = open3d.utility.Vector3dVector(points)\n return pcd",
"def pc_to_ros_pcl(pc):\n \n from sensor_msgs.msg import PointField\n from std_msgs.msg import Header\n import sensor_msgs.point_cloud2 as pcl2\n \n header = Header()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that filters a point cloud depending of a desired field of view. Resulting point cloud will have horizontal FOV of +fov/2. | def lidar_cloud_filtering(cloud: np.ndarray, fov: float) -> np.ndarray:
min_fov = -(fov/2)*(3.14/180)
max_fov = (fov/2)*(3.14/180)
mask = ((cloud[:,2] > -2.00)
& (np.arctan2(cloud[:,1], cloud[:,0]) > min_fov)
& (np.arctan2(cloud[:,1], cloud[:,0]) < max_fov))
cloud = cloud[mask]
ret... | [
"def fov_setting(points, x, y, z, dist, h_fov, v_fov):\n\n if h_fov[1] == 180 and h_fov[0] == -180 and v_fov[1] == 2.0 and v_fov[0] == -24.9:\n return points\n\n if h_fov[1] == 180 and h_fov[0] == -180:\n return points[in_v_range_points(dist, z, v_fov)]\n elif v_fov[1] == 2.0 and v_fov[0] == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs RANSAC plane segmentation over a point cloud and returns | def ransac_plane_segmentation(cloud: object, thresh: int, n_iter: int) -> Tuple[object, object]:
plane_model, inliers = cloud.segment_plane(
distance_threshold=thresh,
ransac_n=3,
num_iterations=n_iter)
plane_cloud = cloud.select_by_index(inliers)
obstacles_cloud = cloud.select_by_in... | [
"def ransac_plane_estimation (numpy_cloud, threshold, fixed_point=None, w = .9, z = 0.95 ):\r\n\r\n # variables\r\n current_consensus = 0 # keeps track of how many points match the current plane\r\n best_consensus = 0 # shows how many points matched the best plane yet\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs clustering over obstacles in a point cloud applying Open3D implementation of DBSCAN algorithm. | def clustering_dbscan_o3d():
pass | [
"def dbscan(distmat, epsilon, minpoints):\n objs_indices = numpy.arange(distmat.shape[0])\n objs_clusterlabels = numpy.zeros(distmat.shape[0])\n objs_visited = numpy.zeros(distmat.shape[0]).astype(bool)\n\n distmask = (distmat > 0) & (distmat <= epsilon)\n neighbors = [distmask[i].nonzero()[0] for i ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that classify the labels obtained after Open3D clustering with DBSCAN algorithm and returns a list of clusters and other stats. | def classify_clusters_o3d(cloud: object, labels: np.ndarray) -> Tuple[list, list]:
cloud_np = np.asarray(cloud.points)
indices = list(dict.fromkeys(labels))
if (-1 in indices):
indices.remove(-1)
clusters = [[] for i in indices]
for (i, point) in enumerate(cloud_np, start=0):
if (lab... | [
"def classify_k_cluster(labels, datas):\n classify_k_cluster_to_redis(labels=labels, texts=datas)",
"def DBscan_clustering(self,d,s):\r\n print(colored(\"Performing agglomerative clustering\",color = 'yellow', attrs=['bold']))\r\n self.clustering = DBSCAN(eps=d,min_samples=s,metric = 'euclidean')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Request to cancel execution of the given run. | def cancel_run(self, run_id):
raise NotImplementedError() | [
"def cancel(self):\n self.cancelled = True",
"def _cancel(self):\n self.waiter.set_result_if_pending(None)\n \n timer = self.timer\n if (timer is not None):\n self.timer = None\n timer.cancel()",
"def cancel_run(self, run_id: str, reason: Optional[str] = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute a given workflow template for a set of argument values. Returns an unique identifier for the started workflow run. | def execute(self, template, arguments):
raise NotImplementedError() | [
"def execute(self, template, arguments):\n # Before we start creating directories and copying files make sure that\n # there are values for all template parameters (either in the arguments\n # dictionary or set as default values)\n template.validate_arguments(arguments)\n # Create... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load transaction into a list of transactions | def load_transactions(directory):
transactions = []
with open(directory, "r") as infile:
for line in infile:
transaction = line.split()
transactions.append(transaction)
return transactions | [
"def load_transactions(self, address, update=True, verbose=False, **kwargs):\n if self.apikey is None:\n update = False\n if verbose:\n print('load_transactions', address)\n fn = os.path.join(self.cache_dir, address + '.json')\n startblock = None\n transactio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return n number of uniq items | def get_uniq_n(self, num=4):
ret = []
tmp = []
idx = 0
# iterate list, or until 4 items grabbed
#while (idx < len(self.counts)) and (len(tmp) < num):
while True:
print("> x:", idx, tmp, ret)
# done with group, next group
if len(tmp)... | [
"def get_num_unique_items(self):\n return len(self.get_unique_item_ids())",
"def sample_n_unique(sampling_f, n):\n res = []\n while len(res) < n:\n candidate = sampling_f()\n if candidate not in res:\n res.append(candidate)\n return res",
"def number_of_items(self):",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return cost for a set of books | def cost(books):
num_types = len(set(books))
assert num_types < 6, "Discounts indeterminate"
return DISCOUNT_TABLE.get(num_types, 0) * 8 * len(books) * 100 | [
"def compute_bill_11(food):\n assert isinstance(food, (list, tuple, set)), \"{} error enter type\".format(food)\n total = 0\n for item in food:\n try:\n total += prices[item]\n except KeyError as e:\n print(\"The item {} is not in price-list\".format(e))\n return tota... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply transformations to the feedbacks in dataset_dict, if any. | def transform_feedbacks(dataset_dict, image_shape, transforms, *, min_box_size=0):
if "feedback_proposal_boxes" in dataset_dict:
# Transform proposal boxes
proposal_boxes = transforms.apply_box(
BoxMode.convert(
dataset_dict.pop("feedback_proposal_boxes"),
... | [
"def apply_transforms(self, sample: Dict[str, Union[np.ndarray, Any]]) -> Dict[str, Union[np.ndarray, Any]]:\n for transform in self.transforms:\n sample[\"additional_samples\"] = self._get_additional_inputs_for_transform(transform=transform)\n sample = transform(sample=sample)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initalize the Portfolio object with a PositionHandler, an event history, along with cash balance. Make sure the portfolio denomination currency is also set. | def __init__(
self,
start_dt,
starting_cash=0.0,
currency = "USD",
portfolio_id=None,
name=None
):
self.start_dt = start_dt
self.current_dt = start_dt
self.starting_cash = starting_cash
self.currency = currency
self.portfolio_id... | [
"def _initalize_portfolio_with_cash(self):\n self.cash = copy.copy(self.starting_cash)\n\n if self.starting_cash > 0.0:\n self.history.append(\n PortfolioEvent.create_subscription(\n self.current_dt, self.starting_cash, self.starting_cash\n )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initalize the portfolio with a (default) currency Cash Asset with quantity equal to 'starting_cash'. | def _initalize_portfolio_with_cash(self):
self.cash = copy.copy(self.starting_cash)
if self.starting_cash > 0.0:
self.history.append(
PortfolioEvent.create_subscription(
self.current_dt, self.starting_cash, self.starting_cash
)
... | [
"async def init(self, ctx, *amount_and_symbol : str):\n user = ctx.message.author\n portfolio = GetPortfolio(user.id)\n for i in range(0, len(amount_and_symbol),2):\n portfolio.SetOwnedCurrency(amount_and_symbol[i], amount_and_symbol[i+1])\n await self.bot.say('%s\\'s portfolio is now worth $%.2f.'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain the total market value of the portfolio excluding cash. | def total_market_value(self):
return self.pos_handler.total_market_value() | [
"def total_equity(self):\n return self.total_market_value + self.cash",
"def _obtain_broker_portfolio_total_equity(self):\n return self.broker.get_portfolio_total_equity(self.broker_portfolio_id)",
"def total_value(self):\n return self.cash + self.stock_value",
"def market_value(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain the total market value of the portfolio including cash. | def total_equity(self):
return self.total_market_value + self.cash | [
"def total_value(self):\n return self.cash + self.stock_value",
"def total_market_value(self):\n return self.pos_handler.total_market_value()",
"def total_value(self):\n total = 0.0\n for account in self.accounts():\n total += account.available_cash()\n for asse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |