query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Converts a date into a single number matching that returned by the sqlite julianday function | def JulianDay(ADate):
C.execute('''SELECT julianday(?)''', (ADate,))
return C.fetchall()[0][0] | [
"def _get_dateNumber(self):\n return self.year * 10000 + self.month * 100 + self.day",
"def get_num_date(date):\n day = date[0]\n month = date[1]\n year = date[2]\n days_index = 10000 * year + 100 * month + day\n return days_index",
"def get_date(date):\n return date",
"def get_date_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a behaviour tree from a list of routines and a plan | def makeTree(plan, initialState):
#The initial node of the behaviour tree
tree = Sequence("Tree")
#Added the routines from the black board
tree.add_child(global_vars.black_board.makeRoutines())
#The node of the plan
planTask = Sequence("Plan")
#Initialize the first place where the robot starts
lastPlace = g... | [
"def plan(modules):\n logging.info(\"\"\"Creating execution plan for %s module(s)\"\"\", \", \".join(modules))\n run_scripts(type='plan', selection=modules)",
"def build_plan(self):\n assert False, \"Not implemented.\"",
"def gen_planrun(cwd,caldir,planflags):\n planflagstr = \"\"\n for k in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs the robot Initializes all the variables needed for the application, calls for a plan, makes the behaviour tree and runs it. | def runRobot(): | [
"def run():\n\n e = Environment() # create environment (also adds some dummy traffic)\n a = e.create_agent(QLearningAgent) # create agent\n e.set_primary_agent(a, enforce_deadline=True) # set agent to track\n # Now simulate it\n sim = Simulator(e, update_delay=0.00001) # reduce update_delay t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shutdown function for rospy Cancels all the goals given to move_base, stops the robot | def shutdown():
rospy.loginfo("Stopping the robot...")
global_vars.move_base.cancel_all_goals()
global_vars.cmd_vel_pub.publish(Twist())
rospy.sleep(1) | [
"def shutdown(self):\n\t\trospy.loginfo(\"Stopping the robot...\")\n\t\tself.cmd_vel.publish(Twist())\n\t\trospy.sleep(1)",
"def stopRobot():\n\tglobal pub_stop_vel_\n\t\n\tstop_vel = Twist()\n\tstop_vel.linear.x = 0\n\tstop_vel.linear.y = 0\n\tstop_vel.angular.z = 0\n\n\tpub_stop_vel_.publish(stop_vel)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the string representation of this cache item. | def __str__(self):
return 'CacheItem: [{key}-{value}]'.format(key=self._key, value=self._value) | [
"def __str__(self):\n return super(AbstractItemStorage, self).__str__()",
"def toString(self):\n return self.__str__()",
"def __repr__(self):\n return str(self._queue_items)",
"def __str__(self):\n self.semaphore_lock.acquire()\n string_representation = \"\"\n for key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the cached value. it is intended to be overridden in subclasses. | def _get_cached_value(self, value):
return value | [
"def _get_cached_value(self, value):\n\n if self._refreshable is True and self.is_expired is False:\n self.refresh()\n\n return deepcopy(value)",
"def get(self, key):\n return self.cache_data.get(key, None)",
"def cacheme( self ) :\n dofunc = lambda : self\n cache... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
prepares value to be cached. it is intended to be overridden in subclasses. | def _prepare_cache(self, value):
return value | [
"def _get_cached_value(self, value):\n\n return value",
"def _get_cached_value(self, value):\n\n if self._refreshable is True and self.is_expired is False:\n self.refresh()\n\n return deepcopy(value)",
"def set_cache(self, val):\n pass",
"def cache_per_page_value(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the cached value. | def _get_cached_value(self, value):
if self._refreshable is True and self.is_expired is False:
self.refresh()
return deepcopy(value) | [
"def _get_cached_value(self, value):\n\n return value",
"def get(self, key):\n return self.cache_data.get(key, None)",
"def get(self, key):\n # Initialize key variables\n result = self.cache.get(key)\n\n # Return\n return result",
"def _get_cached(self, environ, ident... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the administrator adds a new pathology | def save_new_pathology(self, request, pathology_name, zone,
vegetable_oil, essential_oil1,
essential_oil2, essential_oil3):
if Pathology.objects.filter(name=pathology_name).exists():
messages.error(request, "la pathologie existe")
... | [
"def add_warehouse():\n check_admin()\n\n verify_module_access('Warehouses')\n verify_view_access('add_warehouse')\n user_sections = fetch_sections() \n\n add_warehouse = True\n\n form = WarehouseForm()\n form.locations.choices = [(l.id,l.name) for l in Location.query.order_by('id')]\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the test run status name given the outcome and marginal args. | def _measurement_outcome_to_test_run_status_name(outcome: measurements.Outcome,
marginal: bool) -> str:
return ('MARGINAL_PASS'
if marginal else MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[outcome]) | [
"def _test_run_status_name_to_measurement_outcome_and_marginal(\n name: str) -> Tuple[measurements.Outcome, bool]:\n return TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME[name], 'MARGINAL' in name",
"def get_test_outcome(outcome):\n return PYTEST_TO_TESTRAIL_STATUS[outcome]",
"def outcome_string(outcome):\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the outcome and marginal args given the test run status name. | def _test_run_status_name_to_measurement_outcome_and_marginal(
name: str) -> Tuple[measurements.Outcome, bool]:
return TEST_RUN_STATUS_NAME_TO_MEASUREMENT_OUTCOME[name], 'MARGINAL' in name | [
"def _measurement_outcome_to_test_run_status_name(outcome: measurements.Outcome,\n marginal: bool) -> str:\n return ('MARGINAL_PASS'\n if marginal else MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[outcome])",
"def status(self,*args):\n print_(\"TEST\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Populate dict of units by code iff UNITS_BY_CODE is empty. | def _lazy_load_units_by_code():
if UNITS_BY_CODE:
# already populated
return
for unit in units.UNITS_BY_NAME.values():
UNITS_BY_CODE[unit.code] = unit | [
"def generate_array_code_units(code_units: Dict[str, Any]) -> Dict[str, Any]:\n _units = dict()\n _array_quantities = array_quantities()\n for arr, unit in _array_quantities.items():\n _units[arr] = _get_code_unit(unit, code_units)\n return _units",
"def get_unit_map(self):\n units = dic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an OpenHTF TestRecord to an MfgEvent proto. Most fields are copied over directly and some are pulled out of metadata (listed below). Multidimensional measurements are stored only in the JSON dump of the record. | def mfg_event_from_test_record(
record: htf_test_record.TestRecord,
attachment_cache: Optional[AttachmentCacheT] = None,
) -> mfg_event_pb2.MfgEvent:
mfg_event = mfg_event_pb2.MfgEvent()
_populate_basic_data(mfg_event, record)
_attach_record_as_json(mfg_event, record)
_attach_argv(mfg_event)
_attach_... | [
"def _populate_basic_data(mfg_event: mfg_event_pb2.MfgEvent,\n record: htf_test_record.TestRecord) -> None:\n # TODO(openhtf-team):\n # * Missing in proto: set run name from metadata.\n # * `part_tags` field on proto is unused\n # * `timings` field on proto is unused.\n # * Hand... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies data from the OpenHTF TestRecord to the MfgEvent proto. | def _populate_basic_data(mfg_event: mfg_event_pb2.MfgEvent,
record: htf_test_record.TestRecord) -> None:
# TODO(openhtf-team):
# * Missing in proto: set run name from metadata.
# * `part_tags` field on proto is unused
# * `timings` field on proto is unused.
# * Handle arbitrar... | [
"def _copy_attachment(self, name, data, mimetype, mfg_event):\n attachment = mfg_event.attachment.add()\n attachment.name = name\n attachment.value_binary = data\n if mimetype in test_runs_converter.MIMETYPE_MAP:\n attachment.type = test_runs_converter.MIMETYPE_MAP[mimetype]\n elif mimetype == t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach a copy of the record as JSON so we have an unmangled copy. | def _attach_record_as_json(mfg_event, record):
attachment = mfg_event.attachment.add()
attachment.name = TEST_RECORD_ATTACHMENT_NAME
test_record_dict = htf_data.convert_to_base_types(record)
attachment.value_binary = _convert_object_to_json(test_record_dict)
attachment.type = test_runs_pb2.TEXT_UTF8 | [
"def encode_record(record):\n return json.dumps(record)",
"def to_json(self, record: Mapping[str, Any]) -> str:\n return self.json_lib.dumps(record, cls=ObjectEncoder)",
"def serialize_to_json(self, record, pretty=False):\n return self._json_serializer.to_json(record)",
"def mutate_json_recor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes the names of phase measurement and attachments unique. This function will make the names of measurements and attachments unique. It modifies the input all_phases. | def phase_uniquizer(all_phases):
measurement_name_maker = UniqueNameMaker(
itertools.chain.from_iterable(
phase.measurements.keys() for phase in all_phases
if phase.measurements))
attachment_names = list(itertools.chain.from_iterable(
phase.attachments.keys() for phase in all_phases)... | [
"def _make_names_unique(animations):\n counts = {}\n for a in animations:\n c = counts.get(a['name'], 0) + 1\n counts[a['name']] = c\n if c > 1:\n a['name'] += '_' + str(c - 1)\n\n dupes = set(k for k, v in counts.items() if v > 1)\n for a in animations:\n if a['na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a multidim measurement to an `openhtf.test_record.Attachment`. | def multidim_measurement_to_attachment(name, measurement):
dimensions = list(measurement.dimensions)
if measurement.units:
dimensions.append(
measurements.Dimension.from_unit_descriptor(measurement.units))
dims = []
for d in dimensions:
if d.suffix is None:
suffix = u''
else:
s... | [
"def attachment_to_multidim_measurement(attachment, name=None):\n data = json.loads(attachment.data)\n\n name = name or data.get('name')\n # attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code'\n attachment_dims = data.get('dimensions', [])\n # attachment_value is a list of lists [[t1, x1,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts each multidim measurements into attachments for all phases.. | def convert_multidim_measurements(all_phases):
# Combine actual attachments with attachments we make from multi-dim
# measurements.
attachment_names = list(itertools.chain.from_iterable(
phase.attachments.keys() for phase in all_phases))
attachment_names.extend(itertools.chain.from_iterable([
'multi... | [
"def attachment_to_multidim_measurement(attachment, name=None):\n data = json.loads(attachment.data)\n\n name = name or data.get('name')\n # attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code'\n attachment_dims = data.get('dimensions', [])\n # attachment_value is a list of lists [[t1, x1,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copy unidimensional measurements to the MfgEvent. | def _copy_unidimensional_measurement(self, phase, name, measurement,
mfg_event):
mfg_measurement = mfg_event.measurement.add()
# Copy basic measurement fields.
mfg_measurement.name = name
if measurement.docstring:
mfg_measurement.description = measurement.do... | [
"def process_event(self, evt):\n det_data = {}\n for det, thisDetDict in zip(self.dets, self.targetVarsXtc):\n try:\n det.getData(evt)\n det.processFuncs()\n thisDetDataDict = getUserData(det)\n img = None\n for key ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies attachments into the MfgEvent from the configured phases. If partial uploads are in use (indicated by configuring this class instance with an Attachments cache), this function will exit early if the total attachment data size exceeds a reasonable threshold to avoid the 2 GB serialized proto limit. | def copy_attachments(self, mfg_event: mfg_event_pb2.MfgEvent) -> bool:
value_copied_attachment_sizes = []
skipped_attachment_names = []
for phase in self._phases:
for name, attachment in sorted(phase.attachments.items()):
size = attachment.size
attachment_cache_key = AttachmentCacheKey... | [
"def Produce(self, events):\n with file_utils.TempDirectory(dir=self.attachments_tmp_dir) as tmp_dir:\n try:\n # Step 1: Copy attachments.\n source_paths = []\n for event in events:\n for att_id, att_path in event.attachments.items():\n source_paths.append(att_path)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Copies an attachment to mfg_event. | def _copy_attachment(self, name, data, mimetype, mfg_event):
attachment = mfg_event.attachment.add()
attachment.name = name
attachment.value_binary = data
if mimetype in test_runs_converter.MIMETYPE_MAP:
attachment.type = test_runs_converter.MIMETYPE_MAP[mimetype]
elif mimetype == test_runs_pb... | [
"def copy_attachments(self, xform):\n existing_names = {a.name for a in self.attachments_list}\n self.attachments_list.extend(\n Attachment(meta.name, meta, meta.content_type, meta.properties)\n for meta in xform.attachments.values()\n if meta.name not in existing_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the original test_record saved as an attachment on a mfg_event. | def test_record_from_mfg_event(mfg_event):
for attachment in mfg_event.attachment:
if attachment.name == TEST_RECORD_ATTACHMENT_NAME:
return json.loads(attachment.value_binary)
raise ValueError('Could not find test record JSON in the given MfgEvent.') | [
"def _attach_record_as_json(mfg_event, record):\n attachment = mfg_event.attachment.add()\n attachment.name = TEST_RECORD_ATTACHMENT_NAME\n test_record_dict = htf_data.convert_to_base_types(record)\n attachment.value_binary = _convert_object_to_json(test_record_dict)\n attachment.type = test_runs_pb2.TEXT_UTF8... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert an OpenHTF test record attachment to a multidim measurement. This is a best effort attempt to reverse, as some data is lost in converting from a multidim to an attachment. | def attachment_to_multidim_measurement(attachment, name=None):
data = json.loads(attachment.data)
name = name or data.get('name')
# attachment_dimn are a list of dicts with keys 'uom_suffix' and 'uom_code'
attachment_dims = data.get('dimensions', [])
# attachment_value is a list of lists [[t1, x1, y1, f1], [... | [
"def test_reversibleish(self):\n mdim = self.create_multi_dim_measurement()\n\n attachment = mfg_event_converter.multidim_measurement_to_attachment(\n name='test_measurement_multidim', measurement=mdim)\n\n reversed_mdim = mfg_event_converter.attachment_to_multidim_measurement(\n attachment)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a new DMA object. Uses the Default configuration parameters to initialize a DMA. After initialization, the DMA is reset and the interrupts are disabled for DMA. | def __init__(self, address, direction=DMA_FROM_DEV,attr_dict= None):
self.buf = None
self.direction = direction
self.bufLength = None
self.phyAddress = address
self.DMAengine = ffi.new("XAxiDma *")
self.DMAinstance = ffi.new("XAxiDma_Config *")
self.Configuration ... | [
"def _wait_for_dma_init(self):\n self.reg.wait_set(types.IXGBE_RDRXCTL, types.IXGBE_RDRXCTL_DMAIDONE)",
"def init(self, parameters, agent_parameters):\n pass",
"def initialize(self):\n self.logger.debug('Dummy Generic Serial Controller device initialized')\n self._empty_buffer()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Destructor for DMA object. Frees the internal buffer and Resets the DMA. | def __del__(self):
if self.buf != None and self.buf != ffi.NULL:
self.free_buf()
libdma.XAxiDma_Reset(self.DMAengine) | [
"def __del__(self):\n self.ds = None\n self.destroy_array()",
"def __del__( self ):\n mkl.DftiFreeDescriptor( ctypes.byref(self.descriptor) )",
"def __del__(self):\n #self.myCModule.free_array(self.arrayRef)\n pass",
"def _clear(self):\n self._buffer = None\n #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transfer data using DMA (Nonblocking). Used to initiate transfer of data between a physically contiguous buffer and PL. The buffer should be allocated using `create_buf` before this call. The `num_bytes` should be less than buffer size and `DMA_TRANSFER_LIMIT_BYTES`. | def transfer(self,num_bytes,direction=DMA_FROM_DEV):
if num_bytes > self.bufLength:
raise RuntimeError("Buffer size smaller than the transfer size")
if num_bytes > DMA_TRANSFER_LIMIT_BYTES:
raise RuntimeError("DMA transfer size > {}".format(
DM... | [
"def setup_buffer(self):\n ## Validate ##\n assert self.ChanReady and self.ModeReady, \"The Mode & Channels must be configured before Buffer!\"\n assert len(self.Segments) > 0, \"No Segments defined! Nothing to put in Buffer.\"\n\n ## Gather Information from Board ##\n num_chan = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Free the memory buffer associated with this object. Use this to free a previously allocated memory buffer. This is specially useful for reallocations. | def free_buf(self):
if self.buf == None or self.buf == ffi.NULL:
return
libxlnk.cma_free(self.buf) | [
"def release_memory(self):\n # remove outdated buffer\n while not self.__receive_buffer.empty():\n self.__receive_buffer.get()",
"def buffer_destroy(self):\n try:\n assert self.buf is not None, \"wtf\"\n assert self.size is not None, \"wtf\"\n asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Block till DMA is busy or a timeout occurs. Default value of timeout is 10 seconds. | def wait(self, wait_timeout=10):
if self._TransferInitiated == 0:
return
Error = "DMA wait timed out."
with timeout(seconds = wait_timeout, error_message = Error):
while True:
if libdma.XAxiDma_Busy(self.DMAengine,self.direction) == 0:
... | [
"def wait_done(self, timeout: float = 10, sleep_time: float = 0.005) -> None:\n self._generator.wait_done(timeout=timeout, sleep_time=sleep_time)",
"def _wait_for_dma_init(self):\n self.reg.wait_set(types.IXGBE_RDRXCTL, types.IXGBE_RDRXCTL_DMAIDONE)",
"def wait_done(self, timeout: float = 10, slee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a CFFI pointer to object's internal buffer. This can be accessed like a regular array in python. | def get_buf(self, data_type = "void"):
if self.buf is not None:
return ffi.cast(data_type + "*", self.buf)
else:
raise RuntimeError("Buffer not created.") | [
"def CPointer(self):\n buf = ctypes.create_string_buffer(self.Pack())\n # Store the C buffer in the object so it doesn't get garbage collected.\n super(CStruct, self).__setattr__(\"_buffer\", buf)\n return ctypes.addressof(self._buffer)",
"def get_buffer(self) -> ctypes.Array:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reconfigure and Reinitialize the DMA IP. Uses a user provided dict to reinitialize the DMA. This method also frees the internal buffer associated with current object. The keys in `attr_dict` should exactly match the ones used in default config. All the keys are not required. The default configuration is defined in dma.... | def configure(self, attr_dict=None):
self.free_buf()
self.__init__(self.phyAddress,self.direction,attr_dict) | [
"def __init__(self, address, direction=DMA_FROM_DEV,attr_dict= None):\n self.buf = None\n self.direction = direction\n self.bufLength = None\n self.phyAddress = address\n self.DMAengine = ffi.new(\"XAxiDma *\")\n self.DMAinstance = ffi.new(\"XAxiDma_Config *\")\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve $ref and $merge in obj, using servicedef for remote references. This function takes an input object which is a dictionary, and evaluates $merge / $ref only if they are present at the root of the object. If need_copy is True, a modifyable shallow copy is returned. | def _eval_shallow(servicedef, obj, need_copy=False):
# _eval_shallow() resolves $ref and $merge to their values in
# source and with_. This is a *shallow* evaluation in that embedded
# $ref or $merge at deeper levels are *not* resolved.
#
# For example, the following will be resolved:
# { $... | [
"def maybe_resolve(object, resolve):\n if isinstance(object, dict) and object.get('$ref'):\n return resolve(object['$ref'])\n return object",
"def ref(obj):\n try:\n return obj['$ref']\n except (KeyError, TypeError):\n return None",
"def get_extended_reference(self, ref: Referen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a new dict from source with with_ as a jsonmergepatch. | def json_merge_patch(servicedef, source, with_):
if isinstance(source, list) or isinstance(with_, list):
return with_
if not isinstance(source, dict):
raise TypeError('source must be a dict, got %s' % (type(source)))
if not isinstance(with_, dict):
raise TypeError('with_ must be a... | [
"def _merge_sources(dest: Dict[str, Any], source: ConfigSource) -> Dict[str, Any]:\n for key, val in source.items():\n if isinstance(val, dict):\n if key in dest:\n dest[key] = _merge_sources(dest[key], val)\n else:\n dest[key] = val.copy()\n else... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the couch database. | def get_db():
# this is a bit of a hack, since it assumes all the models talk to the same
# db. that said a lot of our code relies on that assumption.
# this import is here because of annoying dependencies
return Database(settings.COUCH_DATABASE) | [
"def get_db(self):\n return self._db",
"def database():\n return _databases[_active_db]",
"def get_db():\n db = load()\n return db",
"def db(self) -> DB:\n return DB.get_db()",
"def log_db():\n return pymongo.MongoClient(SCITRAN_PERSISTENT_DB_LOG_URI).get_database()",
"def _get_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The number of nodes to force an update/read in bigcouch to make sure we have a quorum. Should typically be the number of copies of a doc that end up in the cluster. | def bigcouch_quorum_count():
return (3 if not hasattr(settings, 'BIGCOUCH_QUORUM_COUNT')
else settings.BIGCOUCH_QUORUM_COUNT) | [
"def node_count(self) -> int:\n return pulumi.get(self, \"node_count\")",
"def zookeeper_node_size(self) -> Optional[Any]:\n return pulumi.get(self, \"zookeeper_node_size\")",
"def phoenix_node_count(self) -> int:\n return pulumi.get(self, \"phoenix_node_count\")",
"def number_of_nodes(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function for safely applying a change to a couch doc. For getting around ResourceConflict errors that stem from the distributed cloudant nodes | def apply_update(doc, update_fn, max_tries=5):
tries = 0
while tries < max_tries:
try:
update_fn(doc)
doc.save()
return doc
except ResourceConflict:
doc = doc.__class__.get(doc._id)
tries+=1
raise ResourceConflict("Document update confl... | [
"def update_document(self):\n pass",
"def test_update_document(self):\n pass",
"def document_update(index_name, doc_type, doc_id, doc=None, new=None):\n if doc:\n resp = es.index(index=index_name, doc_type=doc_type,\n id=doc_id, body=doc)\n print(resp)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register views location in the project. location must be a folder containinng the views you want to publish. | def views(self, location, publish=False):
self.package.add_views(location)
# register views into project
self.application.make("view").add_namespaced_location(
self.package.name, self.package.views
)
if publish:
location_abs_path = self.package._build_pat... | [
"def register_view( self, target, view ):\n skins = getToolByName( target, 'portal_skins', None )\n write = self.stream.write\n\n if skins._getOb( view, None ) is not None:\n write( \"Failed to register view '%s' (already exists)\\n\" % view )\n return view\n\n foun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check that the function returns 6 arrays | def test_returns_6(self):
print("Testing that get_region_data returns 6 arrays")
test = get_region_data(self.wmo_boxes, self.float_name, self.config,
self.index, self.pres)
self.assertTrue(test.__len__() == 6, "Should return 6 arrays") | [
"def test_check_compatible_correct_output():\n output = check_compatible(1, 5, 12, 13, np.array([5, 6]), np.array([6,8]), np.array([7, 8]))\n assert (np.all(output))",
"def _check_input(data):\n T = len(data)\n data = np.array(data)\n dim = data[0].size if not np.isscalar(data[0]) else 1\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that, if only bad indices are given, an exception is raised | def test_raise_exception_bad_indices(self):
print("Testing exception is raised if indices are bad")
with self.assertRaises(Exception) as no_index:
get_region_data(self.wmo_boxes, self.float_name, self.config,
[], self.pres)
self.assertTrue('NO DATA FOUND... | [
"def check_valid_index(index:int,message:str):\n if index<0:\n raise Exception(message)",
"def _validate_indexes(self, row, col):\n if min(row, col) < 0 or max(row, col) >= self._n:\n raise IndexError(\n \"Incorrect position (%d, %d) in grid of size %d\" % (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export merged data to CSV format. | def _export(merged_data, export_config, csv_writer):
print('writing merged data to CSV file')
columns = export_config.columns
csv_writer.writerow(column.name for column in columns)
for item in merged_data:
nutrients_by_name = {
nutrient['nutrient']['id']: nutrient['amount']
... | [
"def write_csv(self, outfile=sys.stdout):\n csv_out =csv.writer(outfile)\n csv_out.writerow(self.column_names)\n for d in self.data:\n csv_out.writerow(d)",
"def exportCSV(self, datasets='ALL', filename=None, sep=','):\n import csv\n if filename != None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read and check the `pyproject.toml` or `flit.ini` file with data about the package. | def read_pkg_ini(path: Path):
if path.suffix == '.toml':
with path.open() as f:
d = toml.load(f)
res = prep_toml_config(d, path)
else:
# Treat all other extensions as the older flit.ini format
cp = _read_pkg_ini(path)
res = _validate_config(cp, path)
if v... | [
"def main() -> int:\n version: str | None = None\n\n if (path_pyproject := Path(\"pyproject.toml\")).is_file():\n with open(path_pyproject, \"rb\") as fp:\n data = tomllib.load(fp)\n\n try:\n version = data[\"project\"][\"version\"]\n except KeyError:\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flatten nested entrypoints dicts. Entry points group names can include dots. But dots in TOML make nested | def flatten_entrypoints(ep):
def _flatten(d, prefix):
d1 = {}
for k, v in d.items():
if isinstance(v, dict):
yield from _flatten(v, prefix+'.'+k)
else:
d1[k] = v
if d1:
yield prefix, d1
res = {}
for k, v in ep.item... | [
"def flatten(self):\r\n newdict = dict()\r\n def recurse_flatten(prefix, dd):\r\n for k, v in dd.iteritems():\r\n newkey = prefix + '.' + k if len(prefix) > 0 else k\r\n if isinstance(v, DotDict):\r\n recurse_flatten(newkey, v)\r\n else:\r\n newdict[newkey] = v\r\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process & verify the metadata from a config file Pull out the module name we're packaging. Read descriptionfile and check that it's valid rst Convert dashes in key names to underscores (e.g. homepage in config > home_page in metadata) | def _prep_metadata(md_sect, path):
if not set(md_sect).issuperset(metadata_required_fields):
missing = metadata_required_fields - set(md_sect)
raise ConfigError("Required fields missing: " + '\n'.join(missing))
module = md_sect.get('module')
if not module.isidentifier():
raise Confi... | [
"def validate_pack_readme_and_pack_description(self):\n pack_meta_file_content = self._read_file_content(self.pack_meta_file)\n metadata = json.loads(pack_meta_file_content)\n metadata_description = metadata.get(PACK_METADATA_DESC, '').lower().strip()\n if not self._check_if_file_is_empt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup editing data using a regular cohort setup Setup a WikiCohort that will span to all users that we have in the project. | def setUp(self):
DatabaseTest.setUp(self)
self.common_cohort_4()
self.create_wiki_cohort()
self.cohort_service = CohortService()
self.wiki_cohort = self.cohort_service.get(
self.session, self.owner_user_id, by_id=self.basic_wiki_cohort.id
)
# This shou... | [
"def setUp(self):\n super().setUp()\n\n # create course with cohorts\n self.manual_cohort_name = \"ManualCohort1\"\n self.auto_cohort_name = \"AutoCohort1\"\n self.course_fixture = CourseFixture(**self.course_info).install()\n self.setup_cohort_config(self.course_fixture, a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve pages created metric for wiki cohort for project 'wiki' Results of tests should be identical as if we used cohort number 4 | def test_pages_created_happy_case(self):
metric = PagesCreated(
namespaces=[301, 302, 303],
start_date='2013-06-19 00:00:00',
end_date='2013-08-21 00:00:00'
)
results = metric(self.user_ids, self.mwSession)
assert_equal(results[self.editors[0].user_id... | [
"def test_user_can_get_web_analysis_list_for_their_own_web_analysis(self):\n self.client.force_login(self.user)\n\n page_content_length = 42\n web_analysis1 = self.factory.create_web_analysis(\n self.user,\n 'Sitemap: https://www.foobar.com/sitemaps/ User-agent: *',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve pages created metric for wiki cohort for project 'wiki' Results should include the additional users created by `self.common_cohort_4(cohort=False)` | def test_pages_created_extra_users(self):
self.common_cohort_4(cohort=False)
metric = PagesCreated(
namespaces=[301, 302, 303],
start_date='2013-06-19 00:00:00',
end_date='2013-08-21 00:00:00'
)
results = metric(self.user_ids, self.mwSession)
... | [
"def get_all_wikis(self, project=None):\n route_values = {}\n if project is not None:\n route_values['project'] = self._serialize.url('project', project, 'str')\n response = self._send(http_method='GET',\n location_id='288d122c-dbd4-451d-aa5f-7dbbba070728... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input. | def generate_proto(source):
output = source.replace(".proto", "_pb2.py")
if not os.path.exists(output) or (
os.path.exists(source) and os.path.getmtime(source) > os.path.getmtime(output)
):
print("Generating %s..." % output)
if not os.path.exists(source):
sys.stderr.wr... | [
"def MakeProto():\n # Start running from one directory above the directory which is found by\n # this scripts's location as __file__.\n cwd = os.path.dirname(os.path.abspath(__file__))\n\n # Find all the .proto files.\n protos_to_compile = []\n for (root, _, files) in os.walk(cwd):\n for filename in files:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add alias to an idol/group (Underscores are spaces) | async def addalias(self, ctx, alias, mem_id: int, mode="idol"):
alias = alias.replace("_", " ")
if mode.lower() in ["idol", "member", "members", "idols"]:
obj = await self.ex.u_group_members.get_member(mem_id)
name = f"{obj.full_name} ({obj.stage_name}) [{obj.id}]"
elif m... | [
"def addAlias(self, alias, node):",
"def add_group(group):",
"async def addtagalias(\n self, ctx: context.CustomContext, *, tag: Fuzzy[CollaboratorOfTag]\n ):\n\n p = config.BOT_PREFIX\n\n alias = await ctx.input(\n f\"{config.USER_INTERACTION_REQUIRED} Reply with the new alia... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The role to give a user when they first join the server. Use command without role to delete the welcome role set to the guild. | async def welcomerole(self, ctx, role: discord.Role = None):
if not ctx.guild: # command must not be used in DMs.
return await ctx.send(await self.ex.get_msg(ctx, "general", "no_dm"))
guild = self.ex.cache.welcome_roles.get(ctx.guild)
# if the user wants to delete the role.
... | [
"async def userrole(self, ctx, *, role=None):\n server = ctx.message.guild\n\n if not role:\n result = await self.bot.db.config.find_one({'_id': str(server.id)})\n if result and result.get('user_role'):\n await ctx.send(f'The user role restricts which users are abl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a welcome message or disable welcome in the current channel. Use %user where they should be mentioned. Use %guild_name if the server name should be added. | async def welcome(self, ctx, *, message=None):
try:
channel_id = ctx.channel.id
guild_id = ctx.guild.id
server_prefix = await self.ex.get_server_prefix(ctx)
server = self.ex.cache.welcome_messages.get(guild_id)
welcome_new_users = f"> This server will ... | [
"async def setwelcome(self, ctx, *, message = None):\n\n isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator\n if not isAdmin:\n checkAdmin = self.settings.getServerStat(ctx.message.guild, \"AdminArray\")\n for role in ctx.message.author.roles:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unmute a user that is already muted. | async def unmute(self, ctx, user: discord.Member = None):
try:
if not user:
return await ctx.send(f"> **<@{ctx.author.id}>, Please specify a user to unmute.**")
if user.id == ctx.author.id:
return await ctx.send(f"> **<@{ctx.author.id}>, You cannot unmute ... | [
"async def unmute(self, ctx, user: Redeemed):\n if member == None or member == ctx.message.author:\n await ctx.send(\"You cannot unmute yourself!\")\n return \n await user.remove_roles(discord.utils.get(ctx.guild.roles, name=\"Muted\"))\n await ctx.send(f\"{user.mention}... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the server prefix. If prefix was forgotten, type this command with the default prefix. | async def setprefix(self, ctx, *, prefix=bot_prefix):
prefix = prefix.lower()
current_server_prefix = await self.ex.get_server_prefix(ctx.guild.id)
if len(prefix) > 8:
await ctx.send("> **Your prefix can not be more than 8 characters.**")
else:
# Default prefix '%... | [
"async def prefix(self, ctx: discord.ext.commands.context.Context, *, prefix='-'):\n async with asyncio.Lock():\n data = json_helper.read_json(\"prefixes\")\n data[str(ctx.message.guild.id)] = prefix\n json_helper.write_json(\"prefixes\", data)\n await ctx.send(embed=d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes Current Channel a temporary channel deleting messages after a certain time period (greater than 1 minute). If delay is 1, it will remove the channel. | async def tempchannel(self, ctx, delay=-1):
channel_id = ctx.channel.id
try:
if delay == -1:
await self.ex.conn.execute("DELETE FROM general.TempChannels WHERE chanID = $1", channel_id)
self.ex.cache.temp_channels[channel_id] = None
return awai... | [
"def _delete_after(delay: int, message: Message):\n time.sleep(delay)\n message.delete()\n logger.debug(f'Message {message.message_id} in {message.chat.type} chat {message.chat.id} deleted:\\n{message.text}')\n return",
"async def channel_(self, ctx, number=10):\n number = number if number <= 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable or Enable the ability to play games in a text channel. | async def togglegames(self, ctx, *, channel: discord.TextChannel = None):
channel = channel or ctx.channel
user = await self.ex.get_user(ctx.author.id)
if not channel:
log.console(f"Could not find text channel. -> User: {user.id} - Moderator.togglegames")
msg = await self... | [
"async def tc_enable(self, ctx):\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(True)\n await ctx.send(_(\"Private text channels enabled.\"))",
"async def tc_disable(self, ctx):\n await self.config.guild(ctx.guild).private_textchannels_enabled.set(False)\n await ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine the minimum clock period of a given synchronous network graph | def clock_period(graph):
G0 = graph.copy()
for i, j in graph.edges():
if graph.edge[i][j]['weight'] != 0:
G0.remove_edge(i,j)
sorted_nodes = nx.topological_sort(G0)
delta = [0 for node in sorted_nodes]
for node in sorted_nodes:
in_edges = G0.in_edges(node)
d = gra... | [
"def negotiatedminimumtransmitinterval(self) :\n\t\ttry :\n\t\t\treturn self._negotiatedminimumtransmitinterval\n\t\texcept Exception as e:\n\t\t\traise e",
"def DRFindMinimalEdge(self, flow, edge_lst):\n\t\tarr_time = flow[3]\n\t\tend_time = flow[3] + flow[4]\n\t\tmin_cum_size = float('inf')\n\t\tmin_edge = (-1,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests the ability to parse list (phase) of list (measurements) of tensors into list (expert_id) of lists (phase) of list (measurements) where each value in this List[List[List[int]]] is ID of the active cluster center | def test_partition_to_list_of_ids():
flock_size = 3 # and num_cc = 4
# measurement 0 in phase 0 (output of the flock at the time step 0)
meas_0 = [1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1]
# measurement 1 in phase 0 (flock output at time step 1)
meas_1 = [0, 0, 1, 0,
... | [
"def split(input_legs, tensor_list, leg_list, ent_list, cutoff):\n # find tensor common to all input legs\n input_inds = [set([leg_list.index(legs) for legs in leg_list\n if legs.__contains__(qs)]) for qs in input_legs]\n ind = list(set.intersection(*input_inds))[0]\n svd_ten = tensor_list[ind] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
upgrades the kernel image in all nodes. | def upgrade_kernel(**kwargs):
execute("upgrade_kernel_node", env.host_string, **kwargs) | [
"def upgrade_kernel():\n execute(\"upgrade_kernel_node\", env.host_string)",
"def refresh_kernels() -> None:\n ...",
"def refresh_kernelspecs() -> None:\n ...",
"def upgrade_old_nodes(self):\n self.check_release_requirements()\n\n self.show_step(1, initialize=True)\n self.env.rev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches through the specified JSON string looking for HA state enumerations. | def _get_ha_state_from_json(string_json):
json_data = json.loads(string_json)
jmx_beans = json_data["beans"]
# look for NameNodeStatus-State first
for jmx_bean in jmx_beans:
if "name" not in jmx_bean:
continue
jmx_bean_name = jmx_bean["name"]
if jmx_bean_name == "Hadoop:service=NameNode,nam... | [
"def states():\n # Query all abbreviations by state\n States = engine.execute(\"SELECT * FROM states\").fetchall()\n \n return jsonify({'States': [dict(row) for row in States]})",
"def _match_states(payload):\n log.debug(f'Find handler from payload: {payload}')\n handlers = items[\"states\"]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts to correctly coerce a value to an integer. For the case of an integer or a float, this will essentially either NOOP or return a truncated value. If the parameter is a string, then it will first attempt to be coerced from a integer, and failing that, a float. | def _coerce_to_integer(value):
try:
return int(value)
except ValueError:
return int(float(value)) | [
"def try_int_cast(value):\n try: \n return int(value)\n except:\n return value",
"def sanitize_int(value):\n if isinstance(value, str):\n try:\n return int(value)\n except ValueError:\n return None\n elif isinstance(value, int):\n return value",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update background via colorpicker. | def update_background(self):
color = QColorDialog().getColor()
self.model.set('Look', 'background', str(color.name(QColor.HexRgb)))
self.model.announce_update() | [
"def onPickBg(self):\n self.pickColor('bg') # this is too easy?",
"def change_bg():\r\n self.parent.config(bg=\"light green\")\r\n self.TimeLabel.config(bg=\"light green\")\r\n self.AveragesLabel.config(bg=\"light green\")\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads data to an 'artificial' history bank on NCBI's servers. Returns a WebEnv and a query_key | def use_epost(self, accession_numbers, webenv):
if self.terminated is True:
raise ProgramDone
url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi"
post_params = {"db": self.database,
"api_key": self.api_key}
if webenv is not None:
... | [
"def request_history(self):\n\n # Api() will have set this field to the timestamp of the last\n # known candle, so we only request data since this time\n # since = self.history_last_candle\n\n def history_thread():\n \"\"\"request trading history\"\"\"\n\n querystri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if any sequences did not download correctlly. If discrepancies between the downloaded sequences and the Accesions are found, a new missing sequences list is generated and an attempt is made to fetch the missing sequences. | def missing_checker(self):
self.verification_attempt += 1
if self.verification_attempt >= 6:
self.finish(False, "After 5 failed attempts to verify the download,"
" it is apparent that some accession numbers cannot be "
"matched to the FASTA tit... | [
"def on_missing_sequence(self, messages):\n community = messages[0].community\n sources = defaultdict(lambda: defaultdict(set))\n\n if __debug__: dprint(\"received \", len(messages), \" missing-sequence message for community \", community.database_id)\n\n # we know that there are buggy c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of accn numbers, posts it to NCBI to generate an 'artificial' history (webenv and query_key). This avoids download by | def artificial_history(self, accns):
if self.terminated is True:
raise ProgramDone
count = len(accns)
# Split the accn list into a list of 200 accns strings
accn_strs = self.splitter(list(accns), self.batch_size, "s")
batches = [200 * x for x in range(0, len(accn_st... | [
"def use_epost(self, accession_numbers, webenv):\n if self.terminated is True:\n raise ProgramDone\n url = \"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/epost.fcgi\"\n post_params = {\"db\": self.database,\n \"api_key\": self.api_key}\n if webenv is not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits a "list to split" (lts) into a list of lists with length 'size' and returns it. If 'res' == 's', return a list of strings instead (with list elements joined by ',') | def splitter(self, lts, size, res="l"):
if res == "l":
new_list = [lts[i:i + size] for i in range(0, len(lts), size)]
elif res == "s":
new_list = [",".join(lts[i:i + size])
for i in range(0, len(lts), size)]
return new_list | [
"def repair_size_list(self, str_val):\n return [word for word in str_val[2:-2].split('\\', \\'')]",
"def reduce_list_size(li):\n size = sys.getsizeof(li)\n keep = li\n toss = []\n n = len(li)\n decrement_by = max(n / 10, 10)\n while (size >= MAX_SIZE) and (n > 0):\n n -= decrement_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Here we extract the quantum energies (Hartree) from Gaussian outputs | def collect_quantum_energies(quantum_outputs):
#here we will cycle throught the outputs in order to detect SCF enery
input_files = glob.glob(quantum_outputs)
dict_energy = {}
#now cycle through all the output gaussian files
for f in input_files:
#to be sure we take the last indexes
p... | [
"def ReadGaussian():\n # LICHEM calculates this as the optimization energy - self energy.\n # Self energy of the charges = {f} a.u.\n self_line = \" Self energy of the charges\"\n # SCF Done: E({s}) = {f} A.U. after {d} cycles\n SCF_line = \" SCF Done:\"\n with open('LICHM_GaussEnergy_0.log') as ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Here we extract the molecular mechanics (amber) energies by using Paramfit as evaluator | def collect_amber_energies(top,crd):
input_files = glob.glob(crd)
dict_energy = {}
for f in input_files:
phi =int( f.split("/")[-2]) # to be more consistent, we know that in -2 there's phi
psi =int( f.split("/")[-1].split(".crd")[0].split("structure_")[1])
#first fix phi and psi val... | [
"def _param_energies(p: BeatModelParams) -> Tuple[float, float]:\n return sample.sample.modal_energy(p[:2], p[4:6])",
"def ensemble_average_energy(self):",
"def get_energies(data, cencol, save_path = None, eltname = '', **kwargs):\n # element id\n try:\n kalpha = emission[eltname]['ka1']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls all interaction between user and program, handles program menu and user inputs. It should repeat displaying menu and asking for input until that moment. You should create new functions and call them from main whenever it can make the code cleaner | def main():
is_program_working = True
while is_program_working:
display.print_program_menu(MAIN_MENU)
try:
choose_option()
except ValueError as err:
display.print_command_result(str(err)) | [
"def run():\n show_greeting()\n show_menu()\n show_prompt()\n while True:\n # Get user's selection\n choice = get_selection().lower()\n # Check validity of user's choice. Will be True or False\n if check_input(choice):\n show_confirmation(choice)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test MSc thesis skipping. | def test_non_thesis(non_thesis):
assert non_thesis is None | [
"def test_should_skip(self):\n pass",
"def test_skips(self):\n log.info(\"executing ExampleTestCase.test_skips\")",
"def test_all_by_study(self):\n pass",
"def test_choose_a_lesson_of_dificulty_hard():",
"def test_text_found_in_single_slide(collected_seg_motif):\n slide_not_found... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check connection and download file trough ftp. !!! Overwrites existing file if not told otherwise | def get_file(self):
while not (self.is_connection_working()):
print('Connection is not working. Reason should be printed above. Sleeping 5 minutes and retrying.')
time.sleep(300)
i = 0
while True:
if i >= 3:
print('Looks like file {} is really ... | [
"def _download_file(self, filename, out_filename):\n self.update_progress('Downloading: ' + filename)\n if not os.path.exists(self.local_dir):\n os.mkdir(self.local_dir)\n ftp = FTP(self.ftp_host, 'anonymous', 'gcb-contact@duke.edu')\n ftp.cwd(self.get_ftp_dir())\n with... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Group miler names into threes. Yields a generator. | def _miler_grouper(iterable):
length = len(iterable) + 1
if length == 3:
yield [each.text for each in iterable]
for i in range(3, length, 3):
previous = i - 3
group = iterable[previous: i]
yield [each.text for each in group] | [
"def make_groups() -> Iterable[list[Token]]:\n group: list[Token] = []\n for token in tokens:\n if token.name == \"comma\":\n if group:\n yield group\n group = []\n else:\n group.appen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the system to dark mode or not. | def _set_dark_mode(dark_mode: bool):
cmd = ["osascript", "-l", "JavaScript", "-e"]
if dark_mode:
cmd += ["Application('System Events').appearancePreferences.darkMode = true"]
else:
cmd += ["Application('System Events').appearancePreferences.darkMode = false"]
subprocess.run(cmd) | [
"def darkLightSwitch(self):\n\n if self._lightMode:\n self.configureFramesToDark()\n self.configureWidgetsToDark()\n self._lightMode = False\n\n else:\n self.configureFramesToLight()\n self.configureWidgetsToLight()\n self._lightMode = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes a function at regular intervals while the condition is false and the amount of attempts < maxAttempts. | def wait_until(condition, delay, max_attempts):
attempt = 0
while not condition() and attempt < max_attempts:
attempt += 1
time.sleep(delay)
if attempt >= max_attempts:
raise Exception("Condition is still False after {} attempts.".format(max_attempts)) | [
"def _check_with_retries(\n condition: Callable[[], bool],\n max_attempts: int = 3,\n delay_seconds: int = 5,\n) -> bool:\n attempts = 0\n while True:\n if condition():\n return True\n attempts += 1\n if attempts >= max_attempts:\n return False\n slee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies the bridge layer to the final encoder hidden states. The input to the ``forward`` is expected to have already been reshaped for initializing the decoder. | def forward(self, hidden: Union[torch.Tensor, Tuple[torch.Tensor, ...]]) -> Union[torch.Tensor, Tuple[torch.Tensor, ...]]:
# First, map the non-tuple version to a 1-tuple for easier processing.
# We will undo this at the end
if not isinstance(hidden, tuple):
hidden = (hidden,)
... | [
"def forward(self, trg_embed, encoder_hidden, encoder_final, \n src_mask, trg_mask, hidden=None, max_len=None):\n \n # the maximum number of steps to unroll the RNN\n #print(\"czw src mask\", src_mask.size())\n #print(\"czw trg embed\", trg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cook up a mock for the Response with specific arguments. | def response():
def inner(ret_code, ret_value):
"""Set up response with the given parameters.
:param ret_code: Return code for the response
:param ret_value: Return value for the response
:return: Mocked Responce object with the given parameters
"""
with mo... | [
"def __init__(self, response: Mock) -> None:\n self.response = response",
"def mocked_requests_get():\n\n class MockResponse:\n def __init__(self, _content, _status):\n self.content = _content\n self.status_code = _status\n\n def content(self):\n return sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepare instance of the RPClient for testing. | def rp_client():
client = RPClient('http://endpoint', 'project', 'api_key')
client.session = mock.Mock()
return client | [
"def prepare(self):\n # The default implementation takes care of local compilation of the client, if needed. Be sure to call it.\n client.prepare(self)\n # TODO: Add any additional preparations if needed. You're not likely to need those, though.",
"def __init__(self, client, use_stubs=True):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
First identify strongly connected components, then perform a topological sort on these components. | def robust_topological_sort(graph):
components = strongly_connected_components(graph)
node_component = { }
for component in components:
for node in component:
node_component[node] = component
component_graph = { }
for component in components:
component_grap... | [
"def _topological_sort(self):\n self._reset_topological_order()\n\n def is_connected(src, dst):\n \"\"\"Judge two node whether are connected.\"\"\"\n for precursor in dst.precursor_nodes:\n if src == precursor.split(\":\")[0]:\n return 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter method for enable, mapped from YANG variable /openflow_global/openflow/enable (container) | def _set_enable(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=enable.enable, is_container='container', presence=False, yang_name="enable", rest_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, e... | [
"def _set_enable(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name=\"enable\", rest_name=\"enable\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter method for default_behavior, mapped from YANG variable /openflow_global/openflow/default_behavior (container) | def _set_default_behavior(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=default_behavior.default_behavior, is_container='container', presence=False, yang_name="default-behavior", rest_name="default-behavior", parent=self, path_helper=self._path_helper, e... | [
"def declare_default_behavior(self, default_behavior):\n self.default_behavior = default_behavior\n return default_behavior",
"def removeDefaultBehavior(self, behavior):\n if not self.proxy:\n self.proxy = self.session.service(\"ALBehaviorManager\")\n return self.proxy.remov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setter method for controller, mapped from YANG variable /openflow_global/openflow/controller (list) | def _set_controller(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("controller_name",controller.controller, yang_name="controller", rest_name="controller", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, y... | [
"def setController(self,controller):\n root = self.frames['root']\n robot = controller.robot()\n robot.setConfig(controller.getCommandedConfig())\n for i in range(robot.numLinks()):\n p = robot.link(i).getParent()\n if p >= 0:\n Fp = self.frames[robot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the default value for `option`, if any, and remove entry. | def pop_default(self, option: str) -> Optional[Any]:
index = self._get_index(option)
assert index is not None
value = self._options[index]
del self._options[index]
default = value[1] if isinstance(value, tuple) else None
return default | [
"async def _opt_default(self, ctx, option):\n try:\n guild_options = self.database.get_guild_options(ctx.guild.id)\n setattr(guild_options, option, None)\n self.database.save_item(guild_options)\n await ctx.send(f\"Option {option} set to default\")\n except ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of options. | def __len__(self) -> int:
return len(self._options) | [
"def num_options(self) -> int:\n return len(self._optlst)",
"def size(self) -> int:\n sz = 1\n for option in self.options:\n # Each option can be applied or not.\n sz *= len(option) + 1\n return sz",
"def __len__(self):\n return len(self._opts) + len(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return string representation of options. | def __repr__(self) -> str:
return repr(self._options) | [
"def __options_str(self, oneline=True):\n concat = ' ' if oneline else '\\n'\n return concat.join(\n ['-{} {}'.format(k, v) for k, v in self.options.items()])",
"def _format_options(self, options):\n\n return ''.join((' ' + '{0}={1}'.format(k, v) for k, v in options.iteritems()))",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add standard, named arguments to the `ArgumentParser`. Standard argument is given, but can be overwritten as a tuple. | def with_standard_arguments(
self, *args: Union[str, Tuple[str, Any]]
) -> "ArgumentParser":
remaining = Options(*args)
for argument, options in copy.deepcopy(
self.standard_arguments
).items():
if remaining.contains(argument):
options["defaul... | [
"def parser_add_arguments(parser: ArgumentParser):",
"def add_args(parser, args):\n for arg in args:\n parser.add_argument('--' + arg, **global_args_dict[arg])\n return parser",
"def add_argument(parser, *args, **kwargs):\n if \"help\" in kwargs:\n default = kwargs.get(\"default\")\n if de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach info of bought products to payload Order lines that contain bought products are retrieved through order | def payload_add_products(self, payload: dict, order: Order, language: str):
order_lines: [OrderLine] = OrderLine.objects.filter(order=order.id)
items: [dict] = []
area = resolve_area(order)
# Additional product orders doesn't have berth product
if hasattr(order, "product") and ... | [
"def _serialize_order_and_product_data(order_data:dict):\n\n placed_orders = []\n ordered_products = []\n\n for order in order_data:\n if order[\"financial_status\"] not in COMPLETE_ORDER_STATUSES:\n continue\n \n items = []\n products = []\n for item in order[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach customer data to payload | def payload_add_customer(self, payload: dict, order: Order):
if hasattr(order, "lease") and order.lease.application:
application = order.lease.application
payload.update(
{
"email": application.email.strip(),
"customer": {
... | [
"def data_load(payload):\r\n customer = Customer(0,\r\n payload['username'],\r\n payload['password'],\r\n payload['firstname'],\r\n payload['lastname'],\r\n payload['address'],\r\n payload['phone'],\r\n payload['email'],\r\n payload['active'],\r\n pa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate that refund notify payload authcode matches | def check_new_refund_authcode(self, request: HttpRequest):
return self.check_authcode_params(
request,
(
"RETURN_CODE",
"REFUND_ID",
),
) | [
"def validate_receipt(self, receipt_id):",
"def verify_payload():\n return True",
"def test_handle_notify_request_payment_failed(bambora_provider_base_config, order):\n order.order_number = \"abc123\"\n order.status = OrderStatus.PAID\n order.save()\n refund = OrderRefundFactory(\n ord... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle the asynchronous part of payform response Arrives some time after user has completed the payment flow or stopped it abruptly. Skips changing order status if it has been previously set. Although, according to Bambora's documentation, there are some cases where payment status might change from failed to successful... | def handle_notify_request(self):
request = self.request
logger.debug("Handling Bambora notify request, params: {}.".format(request.GET))
order_number, _timestamp = request.GET.get("ORDER_NUMBER", "-").split("-")
try:
order = Order.objects.get(order_number=order_number)
... | [
"def awaiting_payment(self):",
"async def process_payment_status(order_id, payment_id, calls=3):\n await asyncio.sleep(10)\n if await is_paid(payment_id):\n await db.orders.update({'order_id': order_id, 'status': 'PAID'})\n return True\n if calls:\n loop.create_task(process_payment_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redirect back to UI after a successful payment This should be used after a successful payment instead of the standard Django redirect. | def ui_redirect_success(self, order: Order = None) -> HttpResponse:
ui_return_url = self.extract_ui_return_url()
if ui_return_url:
return self._redirect_to_ui(
ui_return_url, "success", order, path="/payment-result"
)
else:
return HttpResponse(... | [
"def ui_redirect_success(self, order: Order = None) -> HttpResponse:\n ui_return_url = self.extract_ui_return_url()\n if ui_return_url:\n return self._redirect_to_ui(ui_return_url, \"success\", order)\n else:\n return HttpResponse(\n content=\"Payment succes... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Redirect back to UI after a failed payment This should be used after a failed payment instead of the standard Django redirect. | def ui_redirect_failure(self, order: Order = None) -> HttpResponse:
ui_return_url = self.extract_ui_return_url()
if ui_return_url:
return self._redirect_to_ui(
ui_return_url, "failure", order, path="/payment-result"
)
else:
return HttpResponseS... | [
"def ui_redirect_failure(self, order: Order = None) -> HttpResponse:\n ui_return_url = self.extract_ui_return_url()\n if ui_return_url:\n return self._redirect_to_ui(ui_return_url, \"failure\", order)\n else:\n return HttpResponseServerError(\n content=\"Pay... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check a given subject contains some template variables | def check_template_variables(subject, vars):
for var in vars:
expect(subject).to(match(r'\{\{cookiecutter\.' + var + '\}\}')) | [
"def __validateTemplateVariables(self, vars):\n for requiredVarName in self.varNames():\n if requiredVarName not in vars:\n raise VariableNotFoundError(\n 'Could not find a value for the variable {0}'.format(\n requiredVarName\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse how the different variant callers have performed | def parse_callers(variant):
callers = {
'gatk': None,
'freebayes': None,
'samtools': None,
'mutect': None,
'pindel': None,
}
raw_info = variant.INFO.get('set')
if raw_info:
info = raw_info.split('-')
for call in info:
if call == 'Filter... | [
"def _handleVariant():\n signature_strategy = dbus_signatures(\n max_codes=5,\n min_complete_types=1,\n max_complete_types=1,\n blacklist=\"h\"\n )\n return signature_strategy.flatmap(\n lambda x: strategies.tuple... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Random page returns a Page type. | def test_random_page_returns_page(mock_requests_get: Mock) -> None:
page = wikipedia.get_random_page()
assert isinstance(page, wikipedia.Page) | [
"def get_random_page() -> Dict:\n name = random.choice(wiki_data[\"names\"])\n return get_page_from_name(name)",
"def get_random_page(lang=\"ru\"):\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\twikipedia.set_lang(lang)\n\t\t\t\tres = wikipedia.random(pages=1)\n\t\t\t\treturn wikipedia.page(res)\n\t\t\texcept wikipe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new deployment resource pool using v1beta1 API. | def CreateBeta(self,
location_ref,
deployment_resource_pool_id,
autoscaling_metric_specs=None,
accelerator_dict=None,
min_replica_count=None,
max_replica_count=None,
machine_type=None):
machine_sp... | [
"def _create(\n cls,\n api_client: deployment_resource_pool_service_client_v1beta1.DeploymentResourcePoolServiceClient,\n deployment_resource_pool_id: str,\n project: Optional[str] = None,\n location: Optional[str] = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a deployment resource pool using v1beta1 API. | def DeleteBeta(self, deployment_resource_pool_ref):
req = self.messages.AiplatformProjectsLocationsDeploymentResourcePoolsDeleteRequest(
name=deployment_resource_pool_ref.RelativeName())
operation = self.client.projects_locations_deploymentResourcePools.Delete(
req)
return operation | [
"def pool_delete(self, pool_id):\n return self._get('pools/{0}.json'.format(pool_id), method='DELETE',\n auth=True)",
"def ex_destroy_pool(self, pool):\n destroy_request = ET.Element(\"deletePool\", {\"xmlns\": TYPES_URN, \"id\": pool.id})\n\n result = self.connection.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes a deployment resource pool using v1beta1 API. | def DescribeBeta(self, deployment_resource_pool_ref):
req = self.messages.AiplatformProjectsLocationsDeploymentResourcePoolsGetRequest(
name=deployment_resource_pool_ref.RelativeName())
response = self.client.projects_locations_deploymentResourcePools.Get(req)
return response | [
"def describe_identity_pool(self, identity_pool_id):\n params = {'IdentityPoolId': identity_pool_id, }\n return self.make_request(action='DescribeIdentityPool',\n body=json.dumps(params))",
"def resource_pool(self) -> Optional[pulumi.Input[str]]:\n return pulum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lists deployment resource pools using v1beta1 API. | def ListBeta(self, location_ref):
req = self.messages.AiplatformProjectsLocationsDeploymentResourcePoolsListRequest(
parent=location_ref.RelativeName())
return list_pager.YieldFromList(
self.client.projects_locations_deploymentResourcePools,
req,
field='deploymentResourcePools',... | [
"def list(\n cls,\n filter: Optional[str] = None,\n order_by: Optional[str] = None,\n project: Optional[str] = None,\n location: Optional[str] = None,\n credentials: Optional[auth_credentials.Credentials] = None,\n ) -> List[\"models.DeploymentResourcePool\"]:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries deployed models sharing a specified deployment resource pool using v1beta1 API. | def QueryDeployedModelsBeta(self, deployment_resource_pool_ref):
req = self.messages.AiplatformProjectsLocationsDeploymentResourcePoolsQueryDeployedModelsRequest(
deploymentResourcePool=deployment_resource_pool_ref.RelativeName())
response = self.client.projects_locations_deploymentResourcePools.QueryD... | [
"def show_pool(self, pool, **_params):\r\n return self.get(self.pool_path % (pool), params=_params)",
"def get_shared_model(self, model_name):\n if model_name in self.pool:\n return self.pool[model_name]\n\n raise NoModelFoundError(\"No model by the name %s found\", model_name)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send stream instructions to streamer servers in the form of HTTP POST requests. The streamer_0 is dedicated to the Twitter sample API, so we don't send any keywords or language to track | def stream():
while True:
try:
r = requests.post("http://streamer_0:5000/stream", json={})
break
except requests.exceptions.ConnectionError:
logging.error("Could not connect to server streamer_0, retrying")
time.sleep(2)
continue
loggin... | [
"def streaming_request(self) -> global___Snippet.SimpleRequestInitialization:",
"def server_streaming(self) -> global___Snippet.ServerStreaming:",
"def first_streaming_request(self) -> global___Snippet.SimpleRequestInitialization:",
"def post_to_twitter(worker_responses):\n for worker_response in worker_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The start time of the backup task each day. The time is displayed in UTC and denoted by Z. | def backup_time(self) -> str:
return pulumi.get(self, "backup_time") | [
"def getBackupStartTime() : \n \n # If the cron file has not been created, create it with the default time.\n if not os.path.exists(CRON_FILE) :\n setBackupStartTime(datetime.time(20,00))\n\n # Parse the cron time format.\n timeItems = smartbox.system.readFromFile(CRON_FILE).split(\"\\n\")[1].split()\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The ID of the data center for the backup in the cluster. | def data_center_id(self) -> str:
return pulumi.get(self, "data_center_id") | [
"def datacenter_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"datacenter_id\")",
"def datacenter(self) -> str:\n return pulumi.get(self, \"datacenter\")",
"def cluster_id(self) -> str:\n return pulumi.get(self, \"cluster_id\")",
"def cluster_id(self):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The name of the Cassandra cluster. | def cluster_name(self) -> str:
return pulumi.get(self, "cluster_name") | [
"def cluster_name(self):\n return self._cluster_name",
"def cluster_name(self):\n node = self.get_node()\n try:\n return node.oget(\"cluster\", \"name\").lower()\n except Exception as exc:\n pass\n name = \"default\"\n from cluster import ClusterSvc\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |