code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchT...
Handle an xray heartbeat batch message from Redis.
Below is the the instruction that describes the task: ### Input: Handle an xray heartbeat batch message from Redis. ### Response: def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRoot...
def _match_maximum_decimal(self, match_key, decimal_value, match): """Matches a minimum decimal value""" if decimal_value is None: raise NullArgument() if match is None: match = True if match: ltegt = '$lte' else: ltegt = '$gt' ...
Matches a minimum decimal value
Below is the the instruction that describes the task: ### Input: Matches a minimum decimal value ### Response: def _match_maximum_decimal(self, match_key, decimal_value, match): """Matches a minimum decimal value""" if decimal_value is None: raise NullArgument() if match is None...
def variables(self, name): """Search for variable by name. Searches scope top down Args: name (string): Search term Returns: Variable object OR False """ if isinstance(name, tuple): name = name[0] if name.startswith('@{'): n...
Search for variable by name. Searches scope top down Args: name (string): Search term Returns: Variable object OR False
Below is the the instruction that describes the task: ### Input: Search for variable by name. Searches scope top down Args: name (string): Search term Returns: Variable object OR False ### Response: def variables(self, name): """Search for variable by name. Searches ...
def reg_incomplete_beta(a, b, x): """ Incomplete beta function; code translated from: Numerical Recipes in C. :param a: a > 0 :param b: b > 0 :param x: 0 <= x <= 1. """ if (x == 0): return 0 elif (x == 1): return 1 else: lbeta = (math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + ...
Incomplete beta function; code translated from: Numerical Recipes in C. :param a: a > 0 :param b: b > 0 :param x: 0 <= x <= 1.
Below is the the instruction that describes the task: ### Input: Incomplete beta function; code translated from: Numerical Recipes in C. :param a: a > 0 :param b: b > 0 :param x: 0 <= x <= 1. ### Response: def reg_incomplete_beta(a, b, x): """ Incomplete beta function; code translated from: Numerical Re...
def add_input(cmd, immediate=False): '''add some command input to be processed''' if immediate: process_stdin(cmd) else: mpstate.input_queue.put(cmd)
add some command input to be processed
Below is the the instruction that describes the task: ### Input: add some command input to be processed ### Response: def add_input(cmd, immediate=False): '''add some command input to be processed''' if immediate: process_stdin(cmd) else: mpstate.input_queue.put(cmd)
def explode(self): """ If the current Line entity consists of multiple line break it up into n Line entities. Returns ---------- exploded: (n,) Line entities """ points = np.column_stack(( self.points, self.points)).ravel()[1:-1].r...
If the current Line entity consists of multiple line break it up into n Line entities. Returns ---------- exploded: (n,) Line entities
Below is the the instruction that describes the task: ### Input: If the current Line entity consists of multiple line break it up into n Line entities. Returns ---------- exploded: (n,) Line entities ### Response: def explode(self): """ If the current Line entity co...
def ingest(event): '''Ingest a finished recording to the Opencast server. ''' # Update status set_service_status(Service.INGEST, ServiceStatus.BUSY) notify.notify('STATUS=Uploading') recording_state(event.uid, 'uploading') update_event_status(event, Status.UPLOADING) # Select ingest ser...
Ingest a finished recording to the Opencast server.
Below is the the instruction that describes the task: ### Input: Ingest a finished recording to the Opencast server. ### Response: def ingest(event): '''Ingest a finished recording to the Opencast server. ''' # Update status set_service_status(Service.INGEST, ServiceStatus.BUSY) notify.notify('...
def set_stderrthreshold(s): """Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised whe...
Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. Raises: ValueError: Raised when s is an invalid value.
Below is the the instruction that describes the task: ### Input: Sets the stderr threshold to the value passed in. Args: s: str|int, valid strings values are case-insensitive 'debug', 'info', 'warning', 'error', and 'fatal'; valid integer values are logging.DEBUG|INFO|WARNING|ERROR|FATAL. ...
def sortkey(x): """Return '001002003' for (colorname, 1, 2, 3)""" k = str(x[1]).zfill(3) + str(x[2]).zfill(3) + str(x[3]).zfill(3) return k
Return '001002003' for (colorname, 1, 2, 3)
Below is the the instruction that describes the task: ### Input: Return '001002003' for (colorname, 1, 2, 3) ### Response: def sortkey(x): """Return '001002003' for (colorname, 1, 2, 3)""" k = str(x[1]).zfill(3) + str(x[2]).zfill(3) + str(x[3]).zfill(3) return k
def ServiceWorker_deliverPushMessage(self, origin, registrationId, data): """ Function path: ServiceWorker.deliverPushMessage Domain: ServiceWorker Method name: deliverPushMessage Parameters: Required arguments: 'origin' (type: string) -> No description 'registrationId' (type: string) -> N...
Function path: ServiceWorker.deliverPushMessage Domain: ServiceWorker Method name: deliverPushMessage Parameters: Required arguments: 'origin' (type: string) -> No description 'registrationId' (type: string) -> No description 'data' (type: string) -> No description No return value.
Below is the the instruction that describes the task: ### Input: Function path: ServiceWorker.deliverPushMessage Domain: ServiceWorker Method name: deliverPushMessage Parameters: Required arguments: 'origin' (type: string) -> No description 'registrationId' (type: string) -> No description...
def sample_mgrid(self, mgrid: np.array) -> np.array: """Sample a mesh-grid array and return the result. The :any:`sample_ogrid` method performs better as there is a lot of overhead when working with large mesh-grids. Args: mgrid (numpy.ndarray): A mesh-grid array of points ...
Sample a mesh-grid array and return the result. The :any:`sample_ogrid` method performs better as there is a lot of overhead when working with large mesh-grids. Args: mgrid (numpy.ndarray): A mesh-grid array of points to sample. A contiguous array of type `numpy.flo...
Below is the the instruction that describes the task: ### Input: Sample a mesh-grid array and return the result. The :any:`sample_ogrid` method performs better as there is a lot of overhead when working with large mesh-grids. Args: mgrid (numpy.ndarray): A mesh-grid array of po...
def _compute_acq_withGradients(self, x): """ Integrated Expected Improvement and its derivative """ means, stds, dmdxs, dsdxs = self.model.predict_withGradients(x) fmins = self.model.get_fmin() f_acqu = None df_acqu = None for m, s, fmin, dmdx, dsdx in zip...
Integrated Expected Improvement and its derivative
Below is the the instruction that describes the task: ### Input: Integrated Expected Improvement and its derivative ### Response: def _compute_acq_withGradients(self, x): """ Integrated Expected Improvement and its derivative """ means, stds, dmdxs, dsdxs = self.model.predict_withGr...
def _decode_v2(value): """ Decode ':' and '$' characters encoded by `_encode`. """ if re.search(r'(?<!\$):', value): raise ValueError("Unescaped ':' in the encoded string") decode_colons = value.replace('$:', ':') if re.search(r'(?<!\$)(\$\$)*\$([^$]|\Z)', decode_colons): raise...
Decode ':' and '$' characters encoded by `_encode`.
Below is the the instruction that describes the task: ### Input: Decode ':' and '$' characters encoded by `_encode`. ### Response: def _decode_v2(value): """ Decode ':' and '$' characters encoded by `_encode`. """ if re.search(r'(?<!\$):', value): raise ValueError("Unescaped ':' in the enco...
def print_usage(actions): """Print the usage information. (Help screen)""" actions = actions.items() actions.sort() print('usage: %s <action> [<options>]' % basename(sys.argv[0])) print(' %s --help' % basename(sys.argv[0])) print() print('actions:') for name, (func, doc, arguments...
Print the usage information. (Help screen)
Below is the the instruction that describes the task: ### Input: Print the usage information. (Help screen) ### Response: def print_usage(actions): """Print the usage information. (Help screen)""" actions = actions.items() actions.sort() print('usage: %s <action> [<options>]' % basename(sys.argv[...
def push(self, buf): """ Push a buffer into the source. """ self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf))
Push a buffer into the source.
Below is the the instruction that describes the task: ### Input: Push a buffer into the source. ### Response: def push(self, buf): """ Push a buffer into the source. """ self._src.emit('push-buffer', Gst.Buffer.new_wrapped(buf))
def get_watermark_for_topic( kafka_client, topic, ): """This method: * refreshes metadata for the kafka client * fetches watermarks :param kafka_client: KafkaToolClient instance :param topic: the topic :returns: dict <topic>: [ConsumerPartitionOffsets] """ # Refresh clie...
This method: * refreshes metadata for the kafka client * fetches watermarks :param kafka_client: KafkaToolClient instance :param topic: the topic :returns: dict <topic>: [ConsumerPartitionOffsets]
Below is the the instruction that describes the task: ### Input: This method: * refreshes metadata for the kafka client * fetches watermarks :param kafka_client: KafkaToolClient instance :param topic: the topic :returns: dict <topic>: [ConsumerPartitionOffsets] ### Response: def get_wa...
def save_task(self): """Transition to save the task and return to ``ASSIGNED`` state.""" task = self.request.activation.task task.status = STATUS.ASSIGNED task.save()
Transition to save the task and return to ``ASSIGNED`` state.
Below is the the instruction that describes the task: ### Input: Transition to save the task and return to ``ASSIGNED`` state. ### Response: def save_task(self): """Transition to save the task and return to ``ASSIGNED`` state.""" task = self.request.activation.task task.status = STATUS.ASSI...
def replace_print(fileobj=sys.stderr): """Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The printer. """ printer = _...
Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The printer.
Below is the the instruction that describes the task: ### Input: Sys.out replacer, by default with stderr. Use it like this: with replace_print_with(fileobj): print "hello" # writes to the file print "done" # prints to stdout Args: fileobj: a file object to replace stdout. Yields: The pri...
def run(self, ipyclient=None, quiet=False, force=False, block=False, ): """ Submits raxml job to run. If no ipyclient object is provided then the function will block until the raxml run is finished. If an ipyclient is provided then the job is se...
Submits raxml job to run. If no ipyclient object is provided then the function will block until the raxml run is finished. If an ipyclient is provided then the job is sent to a remote engine and an asynchronous result object is returned which can be queried or awaited until it finishes. ...
Below is the the instruction that describes the task: ### Input: Submits raxml job to run. If no ipyclient object is provided then the function will block until the raxml run is finished. If an ipyclient is provided then the job is sent to a remote engine and an asynchronous result object ...
def in6_getLocalUniquePrefix(): """ Returns a pseudo-randomly generated Local Unique prefix. Function follows recommandation of Section 3.2.2 of RFC 4193 for prefix generation. """ # Extracted from RFC 1305 (NTP) : # NTP timestamps are represented as a 64-bit unsigned fixed-point number, ...
Returns a pseudo-randomly generated Local Unique prefix. Function follows recommandation of Section 3.2.2 of RFC 4193 for prefix generation.
Below is the the instruction that describes the task: ### Input: Returns a pseudo-randomly generated Local Unique prefix. Function follows recommandation of Section 3.2.2 of RFC 4193 for prefix generation. ### Response: def in6_getLocalUniquePrefix(): """ Returns a pseudo-randomly generated Local U...
def collect_results(rule, max_results=500, result_stream_args=None): """ Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, ...
Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, preferably generated by the `gen_rule_payload` function. max_resu...
Below is the the instruction that describes the task: ### Input: Utility function to quickly get a list of tweets from a ``ResultStream`` without keeping the object around. Requires your args to be configured prior to using. Args: rule (str): valid powertrack rule for your account, preferably ...
def logical_lines(lines): """Merge lines into chunks according to q rules""" if isinstance(lines, string_types): lines = StringIO(lines) buf = [] for line in lines: if buf and not line.startswith(' '): chunk = ''.join(buf).strip() if chunk: yield c...
Merge lines into chunks according to q rules
Below is the the instruction that describes the task: ### Input: Merge lines into chunks according to q rules ### Response: def logical_lines(lines): """Merge lines into chunks according to q rules""" if isinstance(lines, string_types): lines = StringIO(lines) buf = [] for line in lines: ...
def _mine_send(self, tag, data): ''' Send mine data to the master ''' channel = salt.transport.client.ReqChannel.factory(self.opts) data['tok'] = self.tok try: ret = channel.send(data) return ret except SaltReqTimeoutError: log....
Send mine data to the master
Below is the the instruction that describes the task: ### Input: Send mine data to the master ### Response: def _mine_send(self, tag, data): ''' Send mine data to the master ''' channel = salt.transport.client.ReqChannel.factory(self.opts) data['tok'] = self.tok try:...
def dump(self, force=False): """ Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value ...
Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-encoded value
Below is the the instruction that describes the task: ### Input: Encodes the value using DER :param force: If the encoded contents already exist, clear them and regenerate to ensure they are in DER format instead of BER format :return: A byte string of the DER-e...
def _get_style_id_from_style(self, style, style_type): """ Return the id of *style*, or |None| if it is the default style of *style_type*. Raises |ValueError| if style is not of *style_type*. """ if style.type != style_type: raise ValueError( "assigned...
Return the id of *style*, or |None| if it is the default style of *style_type*. Raises |ValueError| if style is not of *style_type*.
Below is the the instruction that describes the task: ### Input: Return the id of *style*, or |None| if it is the default style of *style_type*. Raises |ValueError| if style is not of *style_type*. ### Response: def _get_style_id_from_style(self, style, style_type): """ Return the id of *st...
def alerts(self): """ :rtype: twilio.rest.monitor.v1.alert.AlertList """ if self._alerts is None: self._alerts = AlertList(self) return self._alerts
:rtype: twilio.rest.monitor.v1.alert.AlertList
Below is the the instruction that describes the task: ### Input: :rtype: twilio.rest.monitor.v1.alert.AlertList ### Response: def alerts(self): """ :rtype: twilio.rest.monitor.v1.alert.AlertList """ if self._alerts is None: self._alerts = AlertList(self) return s...
def delete(self): """Remove this resource or collection (recursive). See DAVResource.delete() """ if self.provider.readonly: raise DAVError(HTTP_FORBIDDEN) shutil.rmtree(self._file_path, ignore_errors=False) self.remove_all_properties(True) self.remov...
Remove this resource or collection (recursive). See DAVResource.delete()
Below is the the instruction that describes the task: ### Input: Remove this resource or collection (recursive). See DAVResource.delete() ### Response: def delete(self): """Remove this resource or collection (recursive). See DAVResource.delete() """ if self.provider.readon...
def eq(self, r1, r2): """ True if values of r1 and r2 registers are equal """ if not is_register(r1) or not is_register(r2): return False if self.regs[r1] is None or self.regs[r2] is None: # HINT: This's been never USED?? return False return self.regs[r...
True if values of r1 and r2 registers are equal
Below is the the instruction that describes the task: ### Input: True if values of r1 and r2 registers are equal ### Response: def eq(self, r1, r2): """ True if values of r1 and r2 registers are equal """ if not is_register(r1) or not is_register(r2): return False if se...
def _filter_with_hooks(self, svc_event, listeners): """ Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references """ svc_ref = svc_event.get_se...
Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references
Below is the the instruction that describes the task: ### Input: Filters listeners with EventListenerHooks :param svc_event: ServiceEvent being triggered :param listeners: Listeners to filter :return: A list of listeners with hook references ### Response: def _filter_with_hooks(self, svc_e...
def _prepend_row_index(rows, index): """Add a left-most index column.""" if index is None or index is False: return rows if len(index) != len(rows): print('index=', index) print('rows=', rows) raise ValueError('index must be as long as the number of data rows') rows = [[v...
Add a left-most index column.
Below is the the instruction that describes the task: ### Input: Add a left-most index column. ### Response: def _prepend_row_index(rows, index): """Add a left-most index column.""" if index is None or index is False: return rows if len(index) != len(rows): print('index=', index) ...
def _unpublish(self): """ Process an unpublish action on the related object, returns a boolean if a change is made. Only objects with a current active version will be updated. """ obj = self.content_object actioned = False # Only update if needed if obj....
Process an unpublish action on the related object, returns a boolean if a change is made. Only objects with a current active version will be updated.
Below is the the instruction that describes the task: ### Input: Process an unpublish action on the related object, returns a boolean if a change is made. Only objects with a current active version will be updated. ### Response: def _unpublish(self): """ Process an unpublish action on the ...
def validatePopElement(self, doc, elem, qname): """Pop the element end from the validation stack. """ if doc is None: doc__o = None else: doc__o = doc._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidatePopElement(self._o, doc__o, elem__...
Pop the element end from the validation stack.
Below is the the instruction that describes the task: ### Input: Pop the element end from the validation stack. ### Response: def validatePopElement(self, doc, elem, qname): """Pop the element end from the validation stack. """ if doc is None: doc__o = None else: doc__o = doc._o if ...
def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._target_classes.items(): f.write('{0}.png,{1}\n'.format(k, v))
Saves target classed for all dataset images into given file.
Below is the the instruction that describes the task: ### Input: Saves target classed for all dataset images into given file. ### Response: def save_target_classes(self, filename): """Saves target classed for all dataset images into given file.""" with open(filename, 'w') as f: for k, v in self._targ...
def insertBulkBlock(self): """ API to insert a bulk block :param blockDump: Output of the block dump command :type blockDump: dict """ try: body = request.body.read() indata = cjson.decode(body) if (indata.get("file_parent_list", []) ...
API to insert a bulk block :param blockDump: Output of the block dump command :type blockDump: dict
Below is the the instruction that describes the task: ### Input: API to insert a bulk block :param blockDump: Output of the block dump command :type blockDump: dict ### Response: def insertBulkBlock(self): """ API to insert a bulk block :param blockDump: Output of the bloc...
def create(name, **params): ''' Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverden...
Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create lama salt '*' serverdensity_device.create rich_lama group=lama_...
Below is the the instruction that describes the task: ### Input: Function to create device in Server Density. For more info, see the `API docs`__. .. __: https://apidocs.serverdensity.com/Inventory/Devices/Creating CLI Example: .. code-block:: bash salt '*' serverdensity_device.create la...
def _evaluate(self,R,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTORY: ...
NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTORY: 2017-10-16 - Written - Bovy (UofT)
Below is the the instruction that describes the task: ### Input: NAME: _evaluate PURPOSE: evaluate the potential at R,phi,t INPUT: R - Galactocentric cylindrical radius phi - azimuth t - time OUTPUT: Phi(R,phi,t) HISTO...
def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._abilities( lambda c: c.name != "Smart"), key=lambda c: c.name), start=2): if self._queued_action and cmd ==...
Draw the list of available commands.
Below is the the instruction that describes the task: ### Input: Draw the list of available commands. ### Response: def draw_commands(self, surf): """Draw the list of available commands.""" past_abilities = {act.ability for act in self._past_actions if act.ability} for y, cmd in enumerate(sorted(self._...
def flip(f): """Flip the order of positonal arguments of given function.""" ensure_callable(f) result = lambda *args, **kwargs: f(*reversed(args), **kwargs) functools.update_wrapper(result, f, ('__name__', '__module__')) return result
Flip the order of positonal arguments of given function.
Below is the the instruction that describes the task: ### Input: Flip the order of positonal arguments of given function. ### Response: def flip(f): """Flip the order of positonal arguments of given function.""" ensure_callable(f) result = lambda *args, **kwargs: f(*reversed(args), **kwargs) funct...
def delete_secret(namespace, name, apiserver_url=None, force=True): ''' .. versionadded:: 2016.3.0 Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name. CLI Example: .. code-block:: bash salt '*' k8s.delete_secret namespace_name secret_n...
.. versionadded:: 2016.3.0 Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name. CLI Example: .. code-block:: bash salt '*' k8s.delete_secret namespace_name secret_name salt '*' k8s.delete_secret namespace_name secret_name http://kube-m...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2016.3.0 Delete kubernetes secret in the defined namespace. Namespace is the mandatory parameter as well as name. CLI Example: .. code-block:: bash salt '*' k8s.delete_secret namespace_name secret_name ...
def fcsp_sa_fcsp_auth_proto_auth_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth") fcsp = ET.SubElement(fcsp_sa, "fcsp") auth = ET.SubElement(fcsp, "auth"...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def fcsp_sa_fcsp_auth_proto_auth_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:b...
def getInstalledThemes(self, store): """ Collect themes from all offerings installed on this store, or (if called multiple times) return the previously collected list. """ if not store in self._getInstalledThemesCache: self._getInstalledThemesCache[store] = (self. ...
Collect themes from all offerings installed on this store, or (if called multiple times) return the previously collected list.
Below is the the instruction that describes the task: ### Input: Collect themes from all offerings installed on this store, or (if called multiple times) return the previously collected list. ### Response: def getInstalledThemes(self, store): """ Collect themes from all offerings installed ...
async def insert(self, **kwargs): """ Accepts request object, retrieves data from the one`s body and creates new account. """ if kwargs: # Create autoincrement for account pk = await self.autoincrement() kwargs.update({"id": pk}) # Create account with received data and autoincrement await ...
Accepts request object, retrieves data from the one`s body and creates new account.
Below is the the instruction that describes the task: ### Input: Accepts request object, retrieves data from the one`s body and creates new account. ### Response: async def insert(self, **kwargs): """ Accepts request object, retrieves data from the one`s body and creates new account. """ if kwargs:...
def in_op(self, other): '''checks if self is in other''' if not is_object(other): raise MakeError( 'TypeError', "You can\'t use 'in' operator to search in non-objects") return other.has_property(to_string(self))
checks if self is in other
Below is the the instruction that describes the task: ### Input: checks if self is in other ### Response: def in_op(self, other): '''checks if self is in other''' if not is_object(other): raise MakeError( 'TypeError', "You can\'t use 'in' operator to search in non-objects") ...
def element_count(self): """Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. """ result = conf.lib.clang_getNumElements(self) if result < 0: raise Exception('Type does not have elements.') ...
Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises.
Below is the the instruction that describes the task: ### Input: Retrieve the number of elements in this type. Returns an int. If the Type is not an array or vector, this raises. ### Response: def element_count(self): """Retrieve the number of elements in this type. Returns an in...
def calc_adc_params(self): """ Compute appropriate adc_gain and baseline parameters for adc conversion, given the physical signal and the fmts. Returns ------- adc_gains : list List of calculated `adc_gain` values for each channel. baselines : list ...
Compute appropriate adc_gain and baseline parameters for adc conversion, given the physical signal and the fmts. Returns ------- adc_gains : list List of calculated `adc_gain` values for each channel. baselines : list List of calculated `baseline` values ...
Below is the the instruction that describes the task: ### Input: Compute appropriate adc_gain and baseline parameters for adc conversion, given the physical signal and the fmts. Returns ------- adc_gains : list List of calculated `adc_gain` values for each channel. ...
def get_related_flat(self, content_id, min_strength=None): '''Follow coreference relationships to get full related graph. This differs from ``get_related_coref_relationships`` in that it returns a flat list of all identifiers found through the coreference layer of indirection. ...
Follow coreference relationships to get full related graph. This differs from ``get_related_coref_relationships`` in that it returns a flat list of all identifiers found through the coreference layer of indirection. :rtype: list of identifiers
Below is the the instruction that describes the task: ### Input: Follow coreference relationships to get full related graph. This differs from ``get_related_coref_relationships`` in that it returns a flat list of all identifiers found through the coreference layer of indirection. :...
def create_http_monitor(self, topics, transport_url, transport_token=None, transport_method='PUT', connect_timeout=0, response_timeout=0, batch_size=1, batch_duration=0, compression='none', format_type='json'): """Creates a HTTP Monitor instance in Device Cloud for a given list of to...
Creates a HTTP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDataCore']). :param transport_url: URL of the customer web server. :param transport_token: Credentials for basic authentication in the...
Below is the the instruction that describes the task: ### Input: Creates a HTTP Monitor instance in Device Cloud for a given list of topics :param topics: a string list of topics (e.g. ['DeviceCore[U]', 'FileDataCore']). :param transport_url: URL of the customer web server. ...
def tile(self, bbox, z=0, format=None, clip=True): """Returns a GeoQuerySet intersecting a tile boundary. Arguments: bbox -- tile extent as geometry Keyword args: z -- tile zoom level used as basis for geometry simplification format -- vector tile format as str (pbf, geo...
Returns a GeoQuerySet intersecting a tile boundary. Arguments: bbox -- tile extent as geometry Keyword args: z -- tile zoom level used as basis for geometry simplification format -- vector tile format as str (pbf, geojson) clip -- clip geometries to tile boundary as bool...
Below is the the instruction that describes the task: ### Input: Returns a GeoQuerySet intersecting a tile boundary. Arguments: bbox -- tile extent as geometry Keyword args: z -- tile zoom level used as basis for geometry simplification format -- vector tile format as str (p...
def check_required_fields(self, ignore_fields=list(), allow_no_resources=False): # type: (List[str], bool) -> None """Check that metadata for dataset and its resources is complete. The parameter ignore_fields should be set if required to any fields that should be ignored for the particular opera...
Check that metadata for dataset and its resources is complete. The parameter ignore_fields should be set if required to any fields that should be ignored for the particular operation. Args: ignore_fields (List[str]): Fields to ignore. Default is []. allow_no_resources (bool): Wh...
Below is the the instruction that describes the task: ### Input: Check that metadata for dataset and its resources is complete. The parameter ignore_fields should be set if required to any fields that should be ignored for the particular operation. Args: ignore_fields (List[str]): Field...
def make_session(self): """Authenticate and get the name of assigned SFDC data server""" with connect_lock: if self._sf_session is None: sf_session = requests.Session() # TODO configurable class Salesforce***Auth sf_session.auth = SalesforcePas...
Authenticate and get the name of assigned SFDC data server
Below is the the instruction that describes the task: ### Input: Authenticate and get the name of assigned SFDC data server ### Response: def make_session(self): """Authenticate and get the name of assigned SFDC data server""" with connect_lock: if self._sf_session is None: ...
def _load_params_of(self, effect): """ Called only when a effect has created Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()` """ for param in effect.params: if param.value != param.default: ...
Called only when a effect has created Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()`
Below is the the instruction that describes the task: ### Input: Called only when a effect has created Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()` ### Response: def _load_params_of(self, effect): """ Called only when...
def get_object(self, name, obj): """ :param name: -- string name of backend :param name: str :param obj: -- model object :type obj: django.db.models.Model :return: backend object :rtype: object """ return self[name](obj, **self.opts(name))
:param name: -- string name of backend :param name: str :param obj: -- model object :type obj: django.db.models.Model :return: backend object :rtype: object
Below is the the instruction that describes the task: ### Input: :param name: -- string name of backend :param name: str :param obj: -- model object :type obj: django.db.models.Model :return: backend object :rtype: object ### Response: def get_object(self, name, obj): ...
def run_loop(leds=all_leds): """ Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects """ print('Loop started.\nPress Ctrl+C to break out of the loop.') while 1: try: if switch(): [led.on() for led...
Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects
Below is the the instruction that describes the task: ### Input: Start the loop. :param `leds`: Which LEDs to light up upon switch press. :type `leds`: sequence of LED objects ### Response: def run_loop(leds=all_leds): """ Start the loop. :param `leds`: Which LEDs to light up upon switch pres...
def translate(script): '''translate zipline script into pylivetrader script. ''' tree = ast.parse(script) ZiplineImportVisitor().visit(tree) return astor.to_source(tree)
translate zipline script into pylivetrader script.
Below is the the instruction that describes the task: ### Input: translate zipline script into pylivetrader script. ### Response: def translate(script): '''translate zipline script into pylivetrader script. ''' tree = ast.parse(script) ZiplineImportVisitor().visit(tree) return astor.to_source...
def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): '''Convenience method to configure DisplayDevice properties This calls Set() for all properties that the Disp...
Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API.
Below is the the instruction that describes the task: ### Input: Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. ...
def orient_averaged_adaptive(tm): """Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMat...
Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes. Args: tm: TMatrix (or descendant) instance Returns...
Below is the the instruction that describes the task: ### Input: Compute the T-matrix using variable orientation scatterers. This method uses a very slow adaptive routine and should mainly be used for reference purposes. Uses the set particle orientation PDF, ignoring the alpha and beta attributes....
def create_knowledge_base(project_id, display_name): """Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() proj...
Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base.
Below is the the instruction that describes the task: ### Input: Creates a Knowledge base. Args: project_id: The GCP project linked with the agent. display_name: The display name of the Knowledge base. ### Response: def create_knowledge_base(project_id, display_name): """Creates a Knowledg...
def disable_servicegroup_passive_host_checks(self, servicegroup): """Disable passive host checks for a servicegroup Format of the line that triggers function call:: DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to disable :type s...
Disable passive host checks for a servicegroup Format of the line that triggers function call:: DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to disable :type servicegroup: alignak.objects.servicegroup.Servicegroup :return: None
Below is the the instruction that describes the task: ### Input: Disable passive host checks for a servicegroup Format of the line that triggers function call:: DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;<servicegroup_name> :param servicegroup: servicegroup to disable :type servicegr...
def prepare_environment(work_dir): """ Performs a few maintenance tasks before the Honeypot is run. Copies the data directory, and the config file to the cwd. The config file copied here is overwritten if the __init__ method is called with a configuration URL. :param...
Performs a few maintenance tasks before the Honeypot is run. Copies the data directory, and the config file to the cwd. The config file copied here is overwritten if the __init__ method is called with a configuration URL. :param work_dir: The directory to copy files to.
Below is the the instruction that describes the task: ### Input: Performs a few maintenance tasks before the Honeypot is run. Copies the data directory, and the config file to the cwd. The config file copied here is overwritten if the __init__ method is called with a configuration URL. ...
def get_schedules_for_season(self, season, season_type="REG"): """ Game schedule for a specified season. """ try: season = int(season) if season_type not in ["REG", "PRE", "POST"]: raise ValueError except (ValueError, TypeError): ...
Game schedule for a specified season.
Below is the the instruction that describes the task: ### Input: Game schedule for a specified season. ### Response: def get_schedules_for_season(self, season, season_type="REG"): """ Game schedule for a specified season. """ try: season = int(season) if seas...
def _pwl1_to_poly(self, generators): """ Converts single-block piecewise-linear costs into linear polynomial. """ for g in generators: if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2): g.pwl_to_poly() return generators
Converts single-block piecewise-linear costs into linear polynomial.
Below is the the instruction that describes the task: ### Input: Converts single-block piecewise-linear costs into linear polynomial. ### Response: def _pwl1_to_poly(self, generators): """ Converts single-block piecewise-linear costs into linear polynomial. """ for g in gene...
def ensure_final_value(packageName, arsc, value): """Ensure incoming value is always the value, not the resid androguard will sometimes return the Android "resId" aka Resource ID instead of the actual value. This checks whether the value is actually a resId, then performs the Android Resource look...
Ensure incoming value is always the value, not the resid androguard will sometimes return the Android "resId" aka Resource ID instead of the actual value. This checks whether the value is actually a resId, then performs the Android Resource lookup as needed.
Below is the the instruction that describes the task: ### Input: Ensure incoming value is always the value, not the resid androguard will sometimes return the Android "resId" aka Resource ID instead of the actual value. This checks whether the value is actually a resId, then performs the Android R...
def skip_whitespace(self): """Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype...
Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines are whitespace. @rtype: int
Below is the the instruction that describes the task: ### Input: Consume input until a non-whitespace character is encountered. The non-whitespace character is then ungotten, and the number of whitespace characters consumed is returned. If the tokenizer is in multiline mode, then newlines ...
def output(self, message, color=None): """ A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr...
A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or sys.stderr
Below is the the instruction that describes the task: ### Input: A helper to used like print() or click's secho() tunneling all the outputs to sys.stdout or sys.stderr :param message: (str) :param color: (str) check click.secho() documentation :return: (None) prints to sys.stdout or ...
def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e %= L P = IDENT for i in range(253): if e & 1: P = edwards_add(P=P, Q=Bpow[i]) e //= 2 assert e == 0, e return P
Implements scalarmult(B, e) more efficiently.
Below is the the instruction that describes the task: ### Input: Implements scalarmult(B, e) more efficiently. ### Response: def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e %= L P = IDENT for i in range(253): if e &...
def setup_dotcloud_account(cli): """Gets user/pass for dotcloud, performs auth, and stores keys""" client = RESTClient(endpoint=cli.client.endpoint) client.authenticator = NullAuth() urlmap = client.get('/auth/discovery').item username = cli.prompt('dotCloud email') password = cli.prompt('Passwo...
Gets user/pass for dotcloud, performs auth, and stores keys
Below is the the instruction that describes the task: ### Input: Gets user/pass for dotcloud, performs auth, and stores keys ### Response: def setup_dotcloud_account(cli): """Gets user/pass for dotcloud, performs auth, and stores keys""" client = RESTClient(endpoint=cli.client.endpoint) client.authenti...
def rst_to_obj(cls, file_path=None, text='', columns=None, remove_empty_rows=True, key_on=None, deliminator=' ', eval_cells=True): """ This will convert a rst file or text to a seaborn table :param file_path: str of the path to the file :param text: ...
This will convert a rst file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True will remove empty rows :param key_on: list of str of columns...
Below is the the instruction that describes the task: ### Input: This will convert a rst file or text to a seaborn table :param file_path: str of the path to the file :param text: str of the csv text :param columns: list of str of columns to use :param remove_empty_rows: bool if True...
def end_task(self): ''' Remove the current task from the stack. ''' self.progress(self.task_stack[-1].size) self.task_stack.pop()
Remove the current task from the stack.
Below is the the instruction that describes the task: ### Input: Remove the current task from the stack. ### Response: def end_task(self): ''' Remove the current task from the stack. ''' self.progress(self.task_stack[-1].size) self.task_stack.pop()
def prepare_adiabatic_limit(slh, k=None): """Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The objects ``Y, A, B, F...
Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The objects ``Y, A, B, F, G, N`` necessary to compute the limitin...
Below is the the instruction that describes the task: ### Input: Prepare the adiabatic elimination on an SLH object Args: slh: The SLH object to take the limit for k: The scaling parameter $k \rightarrow \infty$. The default is a positive symbol 'k' Returns: tuple: The ...
def eigenvectors_right_samples(self): r""" Samples of the right eigenvectors of the hidden transition matrix """ res = np.empty((self.nsamples, self.nstates, self.nstates), dtype=config.dtype) for i in range(self.nsamples): res[i, :, :] = self._sampled_hmms[i].eigenvectors_right ...
r""" Samples of the right eigenvectors of the hidden transition matrix
Below is the the instruction that describes the task: ### Input: r""" Samples of the right eigenvectors of the hidden transition matrix ### Response: def eigenvectors_right_samples(self): r""" Samples of the right eigenvectors of the hidden transition matrix """ res = np.empty((self.nsamples, self....
def read_simulation_temps(pathname,NumTemps): """Reads in the various temperatures from each TEMP#/simul.output file by knowing beforehand the total number of temperatures (parameter at top) """ print("--Reading temperatures from %s/..." % pathname) # Initialize return variable temps_from_...
Reads in the various temperatures from each TEMP#/simul.output file by knowing beforehand the total number of temperatures (parameter at top)
Below is the the instruction that describes the task: ### Input: Reads in the various temperatures from each TEMP#/simul.output file by knowing beforehand the total number of temperatures (parameter at top) ### Response: def read_simulation_temps(pathname,NumTemps): """Reads in the various temperatures...
def _example_from_allof(self, prop_spec): """Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict """ example_dict = {} for definition in prop_spec['allOf']: ...
Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict
Below is the the instruction that describes the task: ### Input: Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict ### Response: def _example_from_allof(self, prop_spec): """Get the exam...
def draw_polygon( self, *pts, close_path=True, stroke=None, stroke_width=1, stroke_dash=None, fill=None ) -> None: """Draws the given polygon.""" c = self.c c.saveState() if stroke is not Non...
Draws the given polygon.
Below is the the instruction that describes the task: ### Input: Draws the given polygon. ### Response: def draw_polygon( self, *pts, close_path=True, stroke=None, stroke_width=1, stroke_dash=None, fill=None ) -> None: ...
def server_shutdown(server_state): """ Shut down server subsystems. Remove PID file. """ set_running( False ) # stop API servers rpc_stop(server_state) api_stop(server_state) # stop atlas node server_atlas_shutdown(server_state) # stopping GC gc_stop() # clear PID...
Shut down server subsystems. Remove PID file.
Below is the the instruction that describes the task: ### Input: Shut down server subsystems. Remove PID file. ### Response: def server_shutdown(server_state): """ Shut down server subsystems. Remove PID file. """ set_running( False ) # stop API servers rpc_stop(server_state) a...
def start(self): """Start ZAP authentication""" super().start() self.__poller = zmq.asyncio.Poller() self.__poller.register(self.zap_socket, zmq.POLLIN) self.__task = asyncio.ensure_future(self.__handle_zap())
Start ZAP authentication
Below is the the instruction that describes the task: ### Input: Start ZAP authentication ### Response: def start(self): """Start ZAP authentication""" super().start() self.__poller = zmq.asyncio.Poller() self.__poller.register(self.zap_socket, zmq.POLLIN) self.__task = asyn...
def OnTool(self, event): """Toolbar event handler""" msgtype = self.ids_msgs[event.GetId()] post_command_event(self, msgtype)
Toolbar event handler
Below is the the instruction that describes the task: ### Input: Toolbar event handler ### Response: def OnTool(self, event): """Toolbar event handler""" msgtype = self.ids_msgs[event.GetId()] post_command_event(self, msgtype)
def _replace_scalar(self, scalar): """ Replace scalar name with scalar value """ if not is_arg_scalar(scalar): return scalar name = scalar[1:] return self.get_scalar_value(name)
Replace scalar name with scalar value
Below is the the instruction that describes the task: ### Input: Replace scalar name with scalar value ### Response: def _replace_scalar(self, scalar): """ Replace scalar name with scalar value """ if not is_arg_scalar(scalar): return scalar name = scalar[1:] return self...
def prepare_refresh_body(self, body='', refresh_token=None, scope=None, **kwargs): """Prepare an access token request, using a refresh token. If the authorization server issued a refresh token to the client, the client makes a refresh request to the token endpoint by adding the followin...
Prepare an access token request, using a refresh token. If the authorization server issued a refresh token to the client, the client makes a refresh request to the token endpoint by adding the following parameters using the "application/x-www-form-urlencoded" format in the HTTP request ...
Below is the the instruction that describes the task: ### Input: Prepare an access token request, using a refresh token. If the authorization server issued a refresh token to the client, the client makes a refresh request to the token endpoint by adding the following parameters using the "a...
def _md5_file(fn, block_size=1048576): """Builds the MD5 of a file block by block Args: fn: File path block_size: Size of the blocks to consider (default 1048576) Returns: File MD5 """ h = hashlib.md5() with open(fn) as fp: d = 1 while d: d =...
Builds the MD5 of a file block by block Args: fn: File path block_size: Size of the blocks to consider (default 1048576) Returns: File MD5
Below is the the instruction that describes the task: ### Input: Builds the MD5 of a file block by block Args: fn: File path block_size: Size of the blocks to consider (default 1048576) Returns: File MD5 ### Response: def _md5_file(fn, block_size=1048576): """Builds the MD5 of...
def is_filterbank(filename): """ Open file and confirm if it is a filterbank file or not. """ with open(filename, 'rb') as fh: is_fil = True # Check this is a blimpy file try: keyword, value, idx = read_next_header_keyword(fh) try: assert keyword ...
Open file and confirm if it is a filterbank file or not.
Below is the the instruction that describes the task: ### Input: Open file and confirm if it is a filterbank file or not. ### Response: def is_filterbank(filename): """ Open file and confirm if it is a filterbank file or not. """ with open(filename, 'rb') as fh: is_fil = True # Check this ...
def item(self, key): """Retrieves an Item object for the specified key in this bucket. The item need not exist. Args: key: the key of the item within the bucket. Returns: An Item instance representing the specified key. """ return _item.Item(self._name, key, context=self._context)
Retrieves an Item object for the specified key in this bucket. The item need not exist. Args: key: the key of the item within the bucket. Returns: An Item instance representing the specified key.
Below is the the instruction that describes the task: ### Input: Retrieves an Item object for the specified key in this bucket. The item need not exist. Args: key: the key of the item within the bucket. Returns: An Item instance representing the specified key. ### Response: def item(self,...
def get_all(): ''' Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ''' services = _get_services() ret = set() for service in services: ret.add(service['S...
Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all
Below is the the instruction that describes the task: ### Input: Return all installed services Returns: list: Returns a list of all services on the system. CLI Example: .. code-block:: bash salt '*' service.get_all ### Response: def get_all(): ''' Return all installed servic...
def format(self, tokensource, outfile): """ Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` tuples and write it into ``outfile``. This implementation calculates where it should draw each token on the pixmap, then calculates the required pixmap size and draws ...
Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` tuples and write it into ``outfile``. This implementation calculates where it should draw each token on the pixmap, then calculates the required pixmap size and draws the items.
Below is the the instruction that describes the task: ### Input: Format ``tokensource``, an iterable of ``(tokentype, tokenstring)`` tuples and write it into ``outfile``. This implementation calculates where it should draw each token on the pixmap, then calculates the required pixmap size a...
def Trebble_Bishnoi(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives according to Trebble and Bishnoi (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. ...
r'''Method to calculate `a_alpha` and its first and second derivatives according to Trebble and Bishnoi (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documentation. One coefficient needed. .. math:: ...
Below is the the instruction that describes the task: ### Input: r'''Method to calculate `a_alpha` and its first and second derivatives according to Trebble and Bishnoi (1987) [1]_. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives` for more documen...
def easy_train_and_evaluate(hyper_params, Model=None, create_loss=None, training_data=None, validation_data=None, inline_plotting=False, session_config=None, log_suffix=None, continue_training=False, continue_with_specific_checkpointpa...
Train and evaluate your model without any boilerplate code. 1) Write your data using the starttf.tfrecords.autorecords.write_data method. 2) Create your hyper parameter file containing all required fields and then load it using starttf.utils.hyper_params.load_params method. Minimal Sample Hyper...
Below is the the instruction that describes the task: ### Input: Train and evaluate your model without any boilerplate code. 1) Write your data using the starttf.tfrecords.autorecords.write_data method. 2) Create your hyper parameter file containing all required fields and then load it using startt...
def parse(cls, buff, offset): """ Given a buffer and offset, returns the parsed value and new offset. Calls `parse()` on the given buffer for each sub-part in order and creates a new instance with the results. """ values = {} for name, part in cls.parts: ...
Given a buffer and offset, returns the parsed value and new offset. Calls `parse()` on the given buffer for each sub-part in order and creates a new instance with the results.
Below is the the instruction that describes the task: ### Input: Given a buffer and offset, returns the parsed value and new offset. Calls `parse()` on the given buffer for each sub-part in order and creates a new instance with the results. ### Response: def parse(cls, buff, offset): """ ...
def speakerDiarizationEvaluateScript(folder_name, ldas): ''' This function prints the cluster purity and speaker purity for each WAV file stored in a provided directory (.SEGMENT files are needed as ground-truth) ARGUMENTS: - folder_name: the full path of the folder ...
This function prints the cluster purity and speaker purity for each WAV file stored in a provided directory (.SEGMENT files are needed as ground-truth) ARGUMENTS: - folder_name: the full path of the folder where the WAV and SEGMENT (ground-truth) fi...
Below is the the instruction that describes the task: ### Input: This function prints the cluster purity and speaker purity for each WAV file stored in a provided directory (.SEGMENT files are needed as ground-truth) ARGUMENTS: - folder_name: the full path of the folder wher...
def _is_collinear(self, x, y): """ Checks if first three points are collinear """ pts = np.column_stack([x[:3], y[:3], np.ones(3)]) return np.linalg.det(pts) == 0.0
Checks if first three points are collinear
Below is the the instruction that describes the task: ### Input: Checks if first three points are collinear ### Response: def _is_collinear(self, x, y): """ Checks if first three points are collinear """ pts = np.column_stack([x[:3], y[:3], np.ones(3)]) return np.linalg.det(...
def _unzip(self, src, dst, scene, force_unzip=False): """ Unzip tar files """ self.output("Unzipping %s - It might take some time" % scene, normal=True, arrow=True) try: # check if file is already unzipped, skip if isdir(dst) and not force_unzip: self.out...
Unzip tar files
Below is the the instruction that describes the task: ### Input: Unzip tar files ### Response: def _unzip(self, src, dst, scene, force_unzip=False): """ Unzip tar files """ self.output("Unzipping %s - It might take some time" % scene, normal=True, arrow=True) try: # check if fi...
def process_transform(self, tag_value, resource_set): """ Transform tag value - Collect value from tag - Transform Tag value - Assign new value for key """ self.log.info("Transforming tag value on %s instances" % ( len(resource_set))) key = se...
Transform tag value - Collect value from tag - Transform Tag value - Assign new value for key
Below is the the instruction that describes the task: ### Input: Transform tag value - Collect value from tag - Transform Tag value - Assign new value for key ### Response: def process_transform(self, tag_value, resource_set): """ Transform tag value - Collect valu...
def read_from_buffer(cls, buf, identifier_str=None): """Load the context from a buffer.""" try: return cls._read_from_buffer(buf, identifier_str) except Exception as e: cls._load_error(e, identifier_str)
Load the context from a buffer.
Below is the the instruction that describes the task: ### Input: Load the context from a buffer. ### Response: def read_from_buffer(cls, buf, identifier_str=None): """Load the context from a buffer.""" try: return cls._read_from_buffer(buf, identifier_str) except Exception as e:...
def get_unused_node_id(graph, initial_guess='unknown', _format='{}<%d>'): """ Finds an unused node id in `graph`. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param initial_guess: Initial node id guess. :type initial_guess: str, optional :...
Finds an unused node id in `graph`. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param initial_guess: Initial node id guess. :type initial_guess: str, optional :param _format: Format to generate the new node id if the given is already used...
Below is the the instruction that describes the task: ### Input: Finds an unused node id in `graph`. :param graph: A directed graph. :type graph: networkx.classes.digraph.DiGraph :param initial_guess: Initial node id guess. :type initial_guess: str, optional :param _format: ...
def updateWPText(self): '''Updates the current waypoint and distance to it.''' self.wpText.set_position((self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0.5*self.vertSize/10.0))) self.wpText.set_size(self.fontSize) if type(self.nextWPTime) is str: self.wpText...
Updates the current waypoint and distance to it.
Below is the the instruction that describes the task: ### Input: Updates the current waypoint and distance to it. ### Response: def updateWPText(self): '''Updates the current waypoint and distance to it.''' self.wpText.set_position((self.leftPos+(1.5*self.vertSize/10.0),0.97-(1.5*self.vertSize)+(0...
def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filename in files: queue.put(os.path.join(root, filename))
Add files in a directory to a queue
Below is the the instruction that describes the task: ### Input: Add files in a directory to a queue ### Response: def queue_files(dirpath, queue): """Add files in a directory to a queue""" for root, _, files in os.walk(os.path.abspath(dirpath)): if not files: continue for filen...
def _remove_vlan_from_all_sp_templates(self, handle, vlan_id, ucsm_ip): """Deletes VLAN config from all SP Templates that have it.""" sp_template_info_list = ( CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].sp_template_list.values()) vlan_name = self.make_vlan_name(vlan_id) virtio_port_...
Deletes VLAN config from all SP Templates that have it.
Below is the the instruction that describes the task: ### Input: Deletes VLAN config from all SP Templates that have it. ### Response: def _remove_vlan_from_all_sp_templates(self, handle, vlan_id, ucsm_ip): """Deletes VLAN config from all SP Templates that have it.""" sp_template_info_list = ( ...
def get_notices(self): """ [deprecated] 建議使用方法 `get_notice()` 及 `get_notice_content()` """ result = [] # 取得公布欄訊息列表 for date, title in self.get_notice().items(): content = self.get_notice_content(date) result.append([date, title, content]) #...
[deprecated] 建議使用方法 `get_notice()` 及 `get_notice_content()`
Below is the the instruction that describes the task: ### Input: [deprecated] 建議使用方法 `get_notice()` 及 `get_notice_content()` ### Response: def get_notices(self): """ [deprecated] 建議使用方法 `get_notice()` 及 `get_notice_content()` """ result = [] # 取得公布欄訊息列表 for date, tit...
def listRoleIds(self, *args, **kwargs): """ List Role IDs If no limit is given, the roleIds of all roles are returned. Since this list may become long, callers can use the `limit` and `continuationToken` query arguments to page through the responses. This method gives o...
List Role IDs If no limit is given, the roleIds of all roles are returned. Since this list may become long, callers can use the `limit` and `continuationToken` query arguments to page through the responses. This method gives output: ``v1/list-role-ids-response.json#`` This met...
Below is the the instruction that describes the task: ### Input: List Role IDs If no limit is given, the roleIds of all roles are returned. Since this list may become long, callers can use the `limit` and `continuationToken` query arguments to page through the responses. This metho...
def push_blob(self, filename=None, progress=None, data=None, digest=None, check_exists=True): # pylint: disable=too-many-arguments """ Upload a file to the registry and return its (SHA-256) hash. The registry is con...
Upload a file to the registry and return its (SHA-256) hash. The registry is content-addressable so the file's content (aka blob) can be retrieved later by passing the hash to :meth:`pull_blob`. :param filename: File to upload. :type filename: str :param data: Data to upload i...
Below is the the instruction that describes the task: ### Input: Upload a file to the registry and return its (SHA-256) hash. The registry is content-addressable so the file's content (aka blob) can be retrieved later by passing the hash to :meth:`pull_blob`. :param filename: File to uploa...
def get_notification_commands(self, notifways, n_type, command_name=False): """Get notification commands for object type :param notifways: list of alignak.objects.NotificationWay objects :type notifways: NotificationWays :param n_type: object type (host or service) :type n_type:...
Get notification commands for object type :param notifways: list of alignak.objects.NotificationWay objects :type notifways: NotificationWays :param n_type: object type (host or service) :type n_type: string :param command_name: True to update the inner property with the name of...
Below is the the instruction that describes the task: ### Input: Get notification commands for object type :param notifways: list of alignak.objects.NotificationWay objects :type notifways: NotificationWays :param n_type: object type (host or service) :type n_type: string :p...
def check(self): """ Check if there are records that are ready to start and return them if there are any :return: tuple of WScheduleRecord or None (if there are no tasks to start) """ if self.__next_start is not None: utc_now = utc_datetime() if utc_now >= self.__next_start: result = [] for task...
Check if there are records that are ready to start and return them if there are any :return: tuple of WScheduleRecord or None (if there are no tasks to start)
Below is the the instruction that describes the task: ### Input: Check if there are records that are ready to start and return them if there are any :return: tuple of WScheduleRecord or None (if there are no tasks to start) ### Response: def check(self): """ Check if there are records that are ready to start ...