code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def wait_for_election_success(cls): """Await this function if your cluster must have a leader""" if cls.leader is None: cls.leader_future = asyncio.Future(loop=cls.loop) await cls.leader_future
Await this function if your cluster must have a leader
Below is the the instruction that describes the task: ### Input: Await this function if your cluster must have a leader ### Response: async def wait_for_election_success(cls): """Await this function if your cluster must have a leader""" if cls.leader is None: cls.leader_future = asyncio...
def alias_repository(self, repository_id, alias_id): """Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to an...
Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer to another repository, it is reassigned to the given reposito...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to a ``Repository`` for the purpose of creating compatibility. The primary ``Id`` of the ``Repository`` is determined by the provider. The new ``Id`` is an alias to the primary ``Id``. If the alias is a pointer ...
def get_managed_policies(group, **conn): """Get a list of the managed policy names that are attached to the group.""" managed_policies = list_attached_group_managed_policies(group['GroupName'], **conn) managed_policy_names = [] for policy in managed_policies: managed_policy_names.append(policy...
Get a list of the managed policy names that are attached to the group.
Below is the the instruction that describes the task: ### Input: Get a list of the managed policy names that are attached to the group. ### Response: def get_managed_policies(group, **conn): """Get a list of the managed policy names that are attached to the group.""" managed_policies = list_attached_group_...
def delete(self, template_id, session): '''taobao.delivery.template.delete 删除运费模板 根据用户指定的模板ID删除指定的模板''' request = TOPRequest('taobao.delivery.template.delete') request['template_id'] = template_id self.create(self.execute(request, session), fields=['complete', ]) ...
taobao.delivery.template.delete 删除运费模板 根据用户指定的模板ID删除指定的模板
Below is the the instruction that describes the task: ### Input: taobao.delivery.template.delete 删除运费模板 根据用户指定的模板ID删除指定的模板 ### Response: def delete(self, template_id, session): '''taobao.delivery.template.delete 删除运费模板 根据用户指定的模板ID删除指定的模板''' request = TOPRequest('ta...
def set_parent(self, new_site): """ Set self.site as either an empty string, or with a new Site. """ if new_site: if not isinstance(new_site, Site): raise Exception self.site = new_site self.propagate_data() return new_site
Set self.site as either an empty string, or with a new Site.
Below is the the instruction that describes the task: ### Input: Set self.site as either an empty string, or with a new Site. ### Response: def set_parent(self, new_site): """ Set self.site as either an empty string, or with a new Site. """ if new_site: if not isinstance...
def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ col_labels = self.df.columns blank_item = pd.Series({}, index=col_labels, name=label) # use .loc to add in place (append won't do that) self....
Add a blank row with only an index value to self.df. This is done inplace.
Below is the the instruction that describes the task: ### Input: Add a blank row with only an index value to self.df. This is done inplace. ### Response: def add_blank_row(self, label): """ Add a blank row with only an index value to self.df. This is done inplace. """ ...
def hierarchy_cycles(rdf, fix=False): """Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive. """ top_concepts = so...
Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive.
Below is the the instruction that describes the task: ### Input: Check if the graph contains skos:broader cycles and optionally break these. :param Graph rdf: An rdflib.graph.Graph object. :param bool fix: Fix the problem by removing any skos:broader that overlaps with skos:broaderTransitive. ### R...
def temp_directory(*args, **kwargs): """ Context manager returns a path created by mkdtemp and cleans it up afterwards. """ path = tempfile.mkdtemp(*args, **kwargs) try: yield path finally: shutil.rmtree(path)
Context manager returns a path created by mkdtemp and cleans it up afterwards.
Below is the the instruction that describes the task: ### Input: Context manager returns a path created by mkdtemp and cleans it up afterwards. ### Response: def temp_directory(*args, **kwargs): """ Context manager returns a path created by mkdtemp and cleans it up afterwards. """ path = tempfile....
def as_url(cls, api=None, name_prefix='', url_prefix=''): """ Generate url for resource. :return RegexURLPattern: Django URL """ url_prefix = url_prefix and "%s/" % url_prefix name_prefix = name_prefix and "%s-" % name_prefix url_regex = '^%s%s/?$' % ( url_...
Generate url for resource. :return RegexURLPattern: Django URL
Below is the the instruction that describes the task: ### Input: Generate url for resource. :return RegexURLPattern: Django URL ### Response: def as_url(cls, api=None, name_prefix='', url_prefix=''): """ Generate url for resource. :return RegexURLPattern: Django URL """ u...
def parse_range_list(ranges): """Split a string like 2,3-5,8,9-11 into a list of integers. This is intended to ease adding command-line options for dealing with affinity. """ if not ranges: return [] parts = ranges.split(',') out = [] for part in parts: fields = part.split('-...
Split a string like 2,3-5,8,9-11 into a list of integers. This is intended to ease adding command-line options for dealing with affinity.
Below is the the instruction that describes the task: ### Input: Split a string like 2,3-5,8,9-11 into a list of integers. This is intended to ease adding command-line options for dealing with affinity. ### Response: def parse_range_list(ranges): """Split a string like 2,3-5,8,9-11 into a list of integers....
def set_host(ip, alias): ''' Set the host entry in the hosts file for the given ip, this will overwrite any previous entry for the given ip .. versionchanged:: 2016.3.0 If ``alias`` does not include any host names (it is the empty string or contains only whitespace), all entries for the...
Set the host entry in the hosts file for the given ip, this will overwrite any previous entry for the given ip .. versionchanged:: 2016.3.0 If ``alias`` does not include any host names (it is the empty string or contains only whitespace), all entries for the given IP address are removed...
Below is the the instruction that describes the task: ### Input: Set the host entry in the hosts file for the given ip, this will overwrite any previous entry for the given ip .. versionchanged:: 2016.3.0 If ``alias`` does not include any host names (it is the empty string or contains only ...
def init_with_context(self, context): """ Initialize the menu. """ # Apply the include/exclude patterns: listitems = self._visible_models(context['request']) # Convert to a similar data structure like the dashboard icons have. # This allows sorting the items iden...
Initialize the menu.
Below is the the instruction that describes the task: ### Input: Initialize the menu. ### Response: def init_with_context(self, context): """ Initialize the menu. """ # Apply the include/exclude patterns: listitems = self._visible_models(context['request']) # Conver...
def optimize(exp_rets, covs): """ Return parameters for portfolio optimization. Parameters ---------- exp_rets : ndarray Vector of expected returns for each investment.. covs : ndarray Covariance matrix for the given investments. Returns --------- a : ndarray ...
Return parameters for portfolio optimization. Parameters ---------- exp_rets : ndarray Vector of expected returns for each investment.. covs : ndarray Covariance matrix for the given investments. Returns --------- a : ndarray The first vector (to be combined with ta...
Below is the the instruction that describes the task: ### Input: Return parameters for portfolio optimization. Parameters ---------- exp_rets : ndarray Vector of expected returns for each investment.. covs : ndarray Covariance matrix for the given investments. Returns -----...
def _ite(f, g, h): """Return node that results from recursively applying ITE(f, g, h).""" # ITE(f, 1, 0) = f if g is BDDNODEONE and h is BDDNODEZERO: return f # ITE(f, 0, 1) = f' elif g is BDDNODEZERO and h is BDDNODEONE: return _neg(f) # ITE(1, g, h) = g elif f is BDDNODEONE...
Return node that results from recursively applying ITE(f, g, h).
Below is the the instruction that describes the task: ### Input: Return node that results from recursively applying ITE(f, g, h). ### Response: def _ite(f, g, h): """Return node that results from recursively applying ITE(f, g, h).""" # ITE(f, 1, 0) = f if g is BDDNODEONE and h is BDDNODEZERO: r...
def replace_csi_driver(self, name, body, **kwargs): """ replace the specified CSIDriver This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_csi_driver(name, body, async_req=True) ...
replace the specified CSIDriver This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_csi_driver(name, body, async_req=True) >>> result = thread.get() :param async_req bool :para...
Below is the the instruction that describes the task: ### Input: replace the specified CSIDriver This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_csi_driver(name, body, async_req=True) >...
def load_manuf(filename): """Load manuf file from Wireshark. param: - filename: the file to load the manuf file from""" manufdb = ManufDA(_name=filename) with open(filename, "rb") as fdesc: for line in fdesc: try: line = line.strip() if not line o...
Load manuf file from Wireshark. param: - filename: the file to load the manuf file from
Below is the the instruction that describes the task: ### Input: Load manuf file from Wireshark. param: - filename: the file to load the manuf file from ### Response: def load_manuf(filename): """Load manuf file from Wireshark. param: - filename: the file to load the manuf file from""" ma...
def get_bytes_from_blob(val) -> bytes: """ 不同数据库从blob拿出的数据有所差别,有的是memoryview有的是bytes """ if isinstance(val, bytes): return val elif isinstance(val, memoryview): return val.tobytes() else: raise TypeError('invalid type for get bytes')
不同数据库从blob拿出的数据有所差别,有的是memoryview有的是bytes
Below is the the instruction that describes the task: ### Input: 不同数据库从blob拿出的数据有所差别,有的是memoryview有的是bytes ### Response: def get_bytes_from_blob(val) -> bytes: """ 不同数据库从blob拿出的数据有所差别,有的是memoryview有的是bytes """ if isinstance(val, bytes): return val elif isinstance(val, memoryview): retur...
def parent(self, resource): """Set parent resource :param resource: parent resource :type resource: Resource :raises ResourceNotFound: resource not found on the API """ resource.check() self['parent_type'] = resource.type self['parent_uuid'] = resource.u...
Set parent resource :param resource: parent resource :type resource: Resource :raises ResourceNotFound: resource not found on the API
Below is the the instruction that describes the task: ### Input: Set parent resource :param resource: parent resource :type resource: Resource :raises ResourceNotFound: resource not found on the API ### Response: def parent(self, resource): """Set parent resource :param r...
def _copy(master_fd, master_read=_read, stdin_read=_read): """Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)""" fds = [master_fd, STDIN_FILENO] while True: rfds, wfds, xfds = select(fds, [], []) ...
Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read)
Below is the the instruction that describes the task: ### Input: Parent copy loop. Copies pty master -> standard output (master_read) standard input -> pty master (stdin_read) ### Response: def _copy(master_fd, master_read=_read, stdin_read=_read): """Parent copy loop. Copi...
def _generate_examples(self, label_images): """Generate example for each image in the dict.""" for label, image_paths in label_images.items(): for image_path in image_paths: yield { "image": image_path, "label": label, }
Generate example for each image in the dict.
Below is the the instruction that describes the task: ### Input: Generate example for each image in the dict. ### Response: def _generate_examples(self, label_images): """Generate example for each image in the dict.""" for label, image_paths in label_images.items(): for image_path in image_paths: ...
def bind_license(self, license_item_id=None): """ Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None """ params = {'license_item_id': license_...
Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None
Below is the the instruction that describes the task: ### Input: Auto bind license, uses dynamic if POS is not found :param str license_item_id: license id :raises LicenseError: binding license failed, possibly no licenses :return: None ### Response: def bind_license(self, license_item_id=...
def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__self_class__) p.text(',') p.breakable() p.pretty(obj.__self__) p.end_group(8, '>')
The pprint for the super type.
Below is the the instruction that describes the task: ### Input: The pprint for the super type. ### Response: def _super_pprint(obj, p, cycle): """The pprint for the super type.""" p.begin_group(8, '<super: ') p.pretty(obj.__self_class__) p.text(',') p.breakable() p.pretty(obj.__self__) ...
def encrypt(self, sa, esp, key): """ Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: the secret key used for encryption @return: a valid ESP packet...
Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: the secret key used for encryption @return: a valid ESP packet encrypted with this algorithm
Below is the the instruction that describes the task: ### Input: Encrypt an ESP packet @param sa: the SecurityAssociation associated with the ESP packet. @param esp: an unencrypted _ESPPlain packet with valid padding @param key: the secret key used for encryption @return: a ...
def get_status(self, response, finished=False): """Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`""" for line in response.split("\n"): if line.strip() in self.status_mapping: return s...
Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status`
Below is the the instruction that describes the task: ### Input: Given the stdout from the command returned by :meth:`cmd_status`, return one of the status code defined in :mod:`clusterjob.status` ### Response: def get_status(self, response, finished=False): """Given the stdout from the command ret...
def reduce_chunk(func, array): """Reduce with `func`, chunk by chunk, the passed pytable `array`. """ res = [] for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]): res.append(func(array[..., slice])) return func(res)
Reduce with `func`, chunk by chunk, the passed pytable `array`.
Below is the the instruction that describes the task: ### Input: Reduce with `func`, chunk by chunk, the passed pytable `array`. ### Response: def reduce_chunk(func, array): """Reduce with `func`, chunk by chunk, the passed pytable `array`. """ res = [] for slice in iter_chunk_slice(array.shape[-1]...
def parse(readDataInstance): """ Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new L{DosHeader} object...
Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new L{DosHeader} object.
Below is the the instruction that describes the task: ### Input: Returns a new L{DosHeader} object. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} object with data to be parsed as a L{DosHeader} object. @rtype: L{DosHeader} @return: A new...
def accept(self): """Method invoked when OK button is clicked.""" output_path = self.output_path_line_edit.text() if not output_path: display_warning_message_box( self, tr('Empty Output Path'), tr('Output path can not be empty')) ...
Method invoked when OK button is clicked.
Below is the the instruction that describes the task: ### Input: Method invoked when OK button is clicked. ### Response: def accept(self): """Method invoked when OK button is clicked.""" output_path = self.output_path_line_edit.text() if not output_path: display_warning_message_...
def copyto(self, other): """Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray``...
Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`` is a context, a new ``NDArray`` will be first created on th...
Below is the the instruction that describes the task: ### Input: Copies the value of this array to another array. If ``other`` is a ``NDArray`` object, then ``other.shape`` and ``self.shape`` should be the same. This function copies the value from ``self`` to ``other``. If ``other`...
def insert(self, inst): """Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert """ ...
Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert
Below is the the instruction that describes the task: ### Input: Insert a vdata or a vgroup in the vgroup. Args:: inst vdata or vgroup instance to add Returns:: index of the inserted vdata or vgroup (0 based) C library equivalent : Vinsert ### Response: def insert(...
def eval_master(self, opts, timeout=60, safe=True, failed=False, failback=False): ''' Evaluates and returns a tuple of the current master address and the pub_channel. In standard mode, just creat...
Evaluates and returns a tuple of the current master address and the pub_channel. In standard mode, just creates a pub_channel with the given master address. With master_type=func evaluates the current master address from the given module and then creates a pub_channel. With master_typ...
Below is the the instruction that describes the task: ### Input: Evaluates and returns a tuple of the current master address and the pub_channel. In standard mode, just creates a pub_channel with the given master address. With master_type=func evaluates the current master address from the given ...
def swo_supported_speeds(self, cpu_speed, num_speeds=3): """Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (...
Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the n...
Below is the the instruction that describes the task: ### Input: Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed ...
def payment_end(self, account, wallet): """ End a payment session. Marks the account as available for use in a payment session. :param account: Account to mark available :type account: str :param wallet: Wallet to end payment session for :type wallet: str ...
End a payment session. Marks the account as available for use in a payment session. :param account: Account to mark available :type account: str :param wallet: Wallet to end payment session for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rp...
Below is the the instruction that describes the task: ### Input: End a payment session. Marks the account as available for use in a payment session. :param account: Account to mark available :type account: str :param wallet: Wallet to end payment session for :type wallet: ...
def wait(self): ''' Waits for the current application to idle or window update event occurs. Usage: d.wait.idle(timeout=1000) d.wait.update(timeout=1000, package_name="com.android.settings") ''' @param_to_property(action=["idle", "update"]) def _wait(actio...
Waits for the current application to idle or window update event occurs. Usage: d.wait.idle(timeout=1000) d.wait.update(timeout=1000, package_name="com.android.settings")
Below is the the instruction that describes the task: ### Input: Waits for the current application to idle or window update event occurs. Usage: d.wait.idle(timeout=1000) d.wait.update(timeout=1000, package_name="com.android.settings") ### Response: def wait(self): ''' Waits...
def close(self): """ Closes the connection to the bridge. """ self.is_closed = True self.is_ready = False self._command_queue.put(None)
Closes the connection to the bridge.
Below is the the instruction that describes the task: ### Input: Closes the connection to the bridge. ### Response: def close(self): """ Closes the connection to the bridge. """ self.is_closed = True self.is_ready = False self._command_queue.put(None)
def section(self, section): """Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining """ if not isinstance(self._container, ConfigUpdater): raise ValueError("Sections can only be...
Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining
Below is the the instruction that describes the task: ### Input: Creates a section block Args: section (str or :class:`Section`): name of section or object Returns: self for chaining ### Response: def section(self, section): """Creates a section block Args...
def merge_insert(ins_chunks, doc): """ doc is the already-handled document (as a list of text chunks); here we add <ins>ins_chunks</ins> to the end of that. """ # Though we don't throw away unbalanced_start or unbalanced_end # (we assume there is accompanying markup later or earlier in the # docume...
doc is the already-handled document (as a list of text chunks); here we add <ins>ins_chunks</ins> to the end of that.
Below is the the instruction that describes the task: ### Input: doc is the already-handled document (as a list of text chunks); here we add <ins>ins_chunks</ins> to the end of that. ### Response: def merge_insert(ins_chunks, doc): """ doc is the already-handled document (as a list of text chunks); her...
def parse_devices(self, json): """Parse result from API.""" result = [] for json_device in json: license_plate = json_device['EquipmentHeader']['SerialNumber'] device = Device(self, license_plate) device.update_from_json(json_device) result.appen...
Parse result from API.
Below is the the instruction that describes the task: ### Input: Parse result from API. ### Response: def parse_devices(self, json): """Parse result from API.""" result = [] for json_device in json: license_plate = json_device['EquipmentHeader']['SerialNumber'] dev...
def generate(env): """Add Builders and construction variables for Borland ilink to an Environment.""" SCons.Tool.createSharedLibBuilder(env) SCons.Tool.createProgBuilder(env) env['LINK'] = '$CC' env['LINKFLAGS'] = SCons.Util.CLVar('') env['LINKCOM'] = '$LINK -q $LINKFLAGS -e$TA...
Add Builders and construction variables for Borland ilink to an Environment.
Below is the the instruction that describes the task: ### Input: Add Builders and construction variables for Borland ilink to an Environment. ### Response: def generate(env): """Add Builders and construction variables for Borland ilink to an Environment.""" SCons.Tool.createSharedLibBuilder(env) ...
def forward(self, inputs, begin_state=None): # pylint: disable=arguments-differ """Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, b...
Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` when `layout` is "TNC". begin_state : list init...
Below is the the instruction that describes the task: ### Input: Defines the forward computation. Arguments can be either :py:class:`NDArray` or :py:class:`Symbol`. Parameters ----------- inputs : NDArray input tensor with shape `(sequence_length, batch_size)` ...
def get_as_nullable_boolean(self, key): """ Converts map element into a boolean or returns None if conversion is not possible :param key: an index of element to get. :return: boolean value of the element or None if conversion is not supported. """ value = self.get(key) ...
Converts map element into a boolean or returns None if conversion is not possible :param key: an index of element to get. :return: boolean value of the element or None if conversion is not supported.
Below is the the instruction that describes the task: ### Input: Converts map element into a boolean or returns None if conversion is not possible :param key: an index of element to get. :return: boolean value of the element or None if conversion is not supported. ### Response: def get_as_nullabl...
def get(self): """ Reloads the measurements from the backing store. :return: 200 if success. """ try: self._measurementController.reloadCompletedMeasurements() return None, 200 except: logger.exception("Failed to reload measurements") ...
Reloads the measurements from the backing store. :return: 200 if success.
Below is the the instruction that describes the task: ### Input: Reloads the measurements from the backing store. :return: 200 if success. ### Response: def get(self): """ Reloads the measurements from the backing store. :return: 200 if success. """ try: ...
def login(self, username=None, password=None, **kwargs): """Login to a reddit site. **DEPRECATED**. Will be removed in a future version of PRAW. https://www.reddit.com/comments/2ujhkr/ https://www.reddit.com/comments/37e2mv/ Look for username first in parameter, then praw.ini ...
Login to a reddit site. **DEPRECATED**. Will be removed in a future version of PRAW. https://www.reddit.com/comments/2ujhkr/ https://www.reddit.com/comments/37e2mv/ Look for username first in parameter, then praw.ini and finally if both were empty get it from stdin. Look for p...
Below is the the instruction that describes the task: ### Input: Login to a reddit site. **DEPRECATED**. Will be removed in a future version of PRAW. https://www.reddit.com/comments/2ujhkr/ https://www.reddit.com/comments/37e2mv/ Look for username first in parameter, then praw.ini...
def c_module_relocs(self): """Build relocation for the module variable.""" if self.opts.no_structs or self.opts.windll: return '', '' x86 = reloc_var( self.name, self._c_struct_names()[1], self.opts.reloc_delta, self._c_uses_pointer() ) ...
Build relocation for the module variable.
Below is the the instruction that describes the task: ### Input: Build relocation for the module variable. ### Response: def c_module_relocs(self): """Build relocation for the module variable.""" if self.opts.no_structs or self.opts.windll: return '', '' x86 = reloc_var( ...
def finalize(self, process_row = None): """ Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done simply in the belief th...
Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done simply in the belief that it might assist in constructing well balanc...
Below is the the instruction that describes the task: ### Input: Restore the LigolwSegmentList objects to the XML tables in preparation for output. All segments from all segment lists are inserted into the tables in time order, but this is NOT behaviour external applications should rely on. This is done si...
def _negotiateHandler(self, request): """ Negotiate a handler based on the content types acceptable to the client. :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes` :return: Pair of a resource and the content type. """ accept = _parseAccept(request.re...
Negotiate a handler based on the content types acceptable to the client. :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes` :return: Pair of a resource and the content type.
Below is the the instruction that describes the task: ### Input: Negotiate a handler based on the content types acceptable to the client. :rtype: 2-`tuple` of `twisted.web.iweb.IResource` and `bytes` :return: Pair of a resource and the content type. ### Response: def _negotiateHandler(self...
def filter_with_schema(self, model=None, context=None): """ Perform model filtering with schema """ if model is None or self.schema is None: return self._schema.filter( model=model, context=context if self.use_context else None )
Perform model filtering with schema
Below is the the instruction that describes the task: ### Input: Perform model filtering with schema ### Response: def filter_with_schema(self, model=None, context=None): """ Perform model filtering with schema """ if model is None or self.schema is None: return self._schema.fi...
def get_bnum(opts, minions, quiet): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(minions) try: if '%' in opts['batch']: res = partition(float(opts['batch'].strip('%'))) if res < 1: return int(math...
Return the active number of minions to maintain
Below is the the instruction that describes the task: ### Input: Return the active number of minions to maintain ### Response: def get_bnum(opts, minions, quiet): ''' Return the active number of minions to maintain ''' partition = lambda x: float(x) / 100.0 * len(minions) try: if '%' in...
def sendSomeData(self, howMany): """ Send some DATA commands to my peer(s) to relay some data. @param howMany: an int, the number of chunks to send out. """ # print 'sending some data', howMany if self.transport is None: return peer = self.transport.g...
Send some DATA commands to my peer(s) to relay some data. @param howMany: an int, the number of chunks to send out.
Below is the the instruction that describes the task: ### Input: Send some DATA commands to my peer(s) to relay some data. @param howMany: an int, the number of chunks to send out. ### Response: def sendSomeData(self, howMany): """ Send some DATA commands to my peer(s) to relay some data. ...
def install_virtualenv(parser_args): """ Installs virtual environment """ python_version = '.'.join(str(v) for v in sys.version_info[:2]) sys.stdout.write('Installing Python {0} virtualenv into {1} \n'.format(python_version, VE_ROOT)) if sys.version_info < (3, 3): install_virtualenv_p2(VE_ROOT, ...
Installs virtual environment
Below is the the instruction that describes the task: ### Input: Installs virtual environment ### Response: def install_virtualenv(parser_args): """ Installs virtual environment """ python_version = '.'.join(str(v) for v in sys.version_info[:2]) sys.stdout.write('Installing Python {0} virtualenv into {...
def get_groups(self, condition=None, page_size=1000): """Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them ...
Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them for group in dc.devicecore.get_groups(): print ...
Below is the the instruction that describes the task: ### Input: Return an iterator over all groups in this device cloud account Optionally, a condition can be specified to limit the number of groups returned. Examples:: # Get all groups and print information about them ...
def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
Close the application and all installed plugins.
Below is the the instruction that describes the task: ### Input: Close the application and all installed plugins. ### Response: def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self....
def add_path_object(self, *args): """ Add custom path objects :type: path_object: static_bundle.paths.AbstractPath """ for obj in args: obj.bundle = self self.files.append(obj)
Add custom path objects :type: path_object: static_bundle.paths.AbstractPath
Below is the the instruction that describes the task: ### Input: Add custom path objects :type: path_object: static_bundle.paths.AbstractPath ### Response: def add_path_object(self, *args): """ Add custom path objects :type: path_object: static_bundle.paths.AbstractPath ""...
def part_search(self, part_query): ''' handles the part lookup/search for the given part query part_query: part string to search as product name outputs result on stdout ''' limit = 100 results = self._e.parts_search(q=part_query, ...
handles the part lookup/search for the given part query part_query: part string to search as product name outputs result on stdout
Below is the the instruction that describes the task: ### Input: handles the part lookup/search for the given part query part_query: part string to search as product name outputs result on stdout ### Response: def part_search(self, part_query): ''' handles the part lookup/search f...
def parse_gcs_url(gsurl): """ Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob. """ parsed_url = urlparse(gsurl) if not parsed_url.netloc: raise AirflowException('Please provide a bucket name...
Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob.
Below is the the instruction that describes the task: ### Input: Given a Google Cloud Storage URL (gs://<bucket>/<blob>), returns a tuple containing the corresponding bucket and blob. ### Response: def parse_gcs_url(gsurl): """ Given a Google Cloud Storage URL (gs://<bucket>/<blob>), return...
def read_data(self, **kwargs): ''' Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data attribute. ...
Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data attribute.
Below is the the instruction that describes the task: ### Input: Read the datafile specified in Sample.datafile and return the resulting object. Does NOT assign the data to self.data It's advised not to use this method, but instead to access the data through the FCMeasurement.data a...
def _allocate_channel(self): """ Allocate a new AMQP channel. Raises: NoFreeChannels: If this connection has reached its maximum number of channels. """ try: channel = yield self.channel() except pika.exceptions.NoFreeChannels: raise N...
Allocate a new AMQP channel. Raises: NoFreeChannels: If this connection has reached its maximum number of channels.
Below is the the instruction that describes the task: ### Input: Allocate a new AMQP channel. Raises: NoFreeChannels: If this connection has reached its maximum number of channels. ### Response: def _allocate_channel(self): """ Allocate a new AMQP channel. Raises: ...
def clear_history(vcs): """Clear (committed) test run history from this project. Args: vcs (easyci.vcs.base.Vcs) """ evidence_path = _get_committed_history_path(vcs) if os.path.exists(evidence_path): os.remove(evidence_path)
Clear (committed) test run history from this project. Args: vcs (easyci.vcs.base.Vcs)
Below is the the instruction that describes the task: ### Input: Clear (committed) test run history from this project. Args: vcs (easyci.vcs.base.Vcs) ### Response: def clear_history(vcs): """Clear (committed) test run history from this project. Args: vcs (easyci.vcs.base.Vcs) """...
def __write_data(self, idx): """ Write out the measurement tables found in paleoData and chronData :return: """ pair = self.noaa_data_sorted["Data"][idx] # Run once for each pair (paleo+chron) of tables that was gathered earlier. # for idx, pair in enumerate(self....
Write out the measurement tables found in paleoData and chronData :return:
Below is the the instruction that describes the task: ### Input: Write out the measurement tables found in paleoData and chronData :return: ### Response: def __write_data(self, idx): """ Write out the measurement tables found in paleoData and chronData :return: """ p...
def parse_port(port_obj, owner): '''Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. ...
Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a Component object or None. @return The created port object.
Below is the the instruction that describes the task: ### Input: Create a port object of the correct type. The correct port object type is chosen based on the port.port_type property of port_obj. @param port_obj The CORBA PortService object to wrap. @param owner The owner of this port. Should be a...
def get_bundle_for_cn(cn, relation_name=None): """Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict. """ entries = get_requests_for_lo...
Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict.
Below is the the instruction that describes the task: ### Input: Extract certificates for the given cn. :param cn: str Canonical Name on certificate. :param relation_name: str Relation to check for certificates down. :returns: Dictionary of certificate data, :rtype: dict. ### Response: def get_bun...
def check_hints(self, ds): ''' Checks for potentially mislabeled metadata and makes suggestions for how to correct :param netCDF4.Dataset ds: An open netCDF dataset :rtype: list :return: List of results ''' ret_val = [] ret_val.extend(self._check_hint_bo...
Checks for potentially mislabeled metadata and makes suggestions for how to correct :param netCDF4.Dataset ds: An open netCDF dataset :rtype: list :return: List of results
Below is the the instruction that describes the task: ### Input: Checks for potentially mislabeled metadata and makes suggestions for how to correct :param netCDF4.Dataset ds: An open netCDF dataset :rtype: list :return: List of results ### Response: def check_hints(self, ds): ''' ...
def preparse(output_format): """ Do any special processing of a template, and return the result. """ try: return templating.preparse(output_format, lambda path: os.path.join(config.config_dir, "templates", path)) except ImportError as exc: if "tempita" in str(exc): raise erro...
Do any special processing of a template, and return the result.
Below is the the instruction that describes the task: ### Input: Do any special processing of a template, and return the result. ### Response: def preparse(output_format): """ Do any special processing of a template, and return the result. """ try: return templating.preparse(output_format, lamb...
def gen(sc, asset, expire): ''' Database population function. What we are doing here is trying to interpret the output of plugin ID 20811 and use that information to help populate the database with individualized entries of the software that is installed on the host. This information will late...
Database population function. What we are doing here is trying to interpret the output of plugin ID 20811 and use that information to help populate the database with individualized entries of the software that is installed on the host. This information will later be used to build the report.
Below is the the instruction that describes the task: ### Input: Database population function. What we are doing here is trying to interpret the output of plugin ID 20811 and use that information to help populate the database with individualized entries of the software that is installed on the host. T...
def recognize( self, config, audio, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Performs synchronous speech recognition: receive results after all audio has been sent and...
Performs synchronous speech recognition: receive results after all audio has been sent and processed. Example: >>> from google.cloud import speech_v1p1beta1 >>> from google.cloud.speech_v1p1beta1 import enums >>> >>> client = speech_v1p1beta1.SpeechClient...
Below is the the instruction that describes the task: ### Input: Performs synchronous speech recognition: receive results after all audio has been sent and processed. Example: >>> from google.cloud import speech_v1p1beta1 >>> from google.cloud.speech_v1p1beta1 import enums ...
def get_options(self, section='default', opt_keys=None, vars=None): """ Get all options for a section. If ``opt_keys`` is given return only options with those keys. """ vars = vars if vars else self.default_vars conf = self.parser opts = {} if opt_keys is...
Get all options for a section. If ``opt_keys`` is given return only options with those keys.
Below is the the instruction that describes the task: ### Input: Get all options for a section. If ``opt_keys`` is given return only options with those keys. ### Response: def get_options(self, section='default', opt_keys=None, vars=None): """ Get all options for a section. If ``opt_keys`...
def set_executing(on: bool): """ Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing ...
Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread should be annotated as executing a step file.
Below is the the instruction that describes the task: ### Input: Toggle whether or not the current thread is executing a step file. This will only apply when the current thread is a CauldronThread. This function has no effect when run on a Main thread. :param on: Whether or not the thread shoul...
def redshift(distance, **kwargs): r"""Returns the redshift associated with the given luminosity distance. If the requested cosmology is one of the pre-defined ones in :py:attr:`astropy.cosmology.parameters.available`, :py:class:`DistToZ` is used to provide a fast interpolation. This takes a few seconds...
r"""Returns the redshift associated with the given luminosity distance. If the requested cosmology is one of the pre-defined ones in :py:attr:`astropy.cosmology.parameters.available`, :py:class:`DistToZ` is used to provide a fast interpolation. This takes a few seconds to setup on the first call. ...
Below is the the instruction that describes the task: ### Input: r"""Returns the redshift associated with the given luminosity distance. If the requested cosmology is one of the pre-defined ones in :py:attr:`astropy.cosmology.parameters.available`, :py:class:`DistToZ` is used to provide a fast interpol...
def ListMappedNetworkDrives(): ''' On Windows, returns a list of mapped network drives :return: tuple(string, string, bool) For each mapped netword drive, return 3 values tuple: - the local drive - the remote path- - True if the mapping is enabled (warning: not r...
On Windows, returns a list of mapped network drives :return: tuple(string, string, bool) For each mapped netword drive, return 3 values tuple: - the local drive - the remote path- - True if the mapping is enabled (warning: not reliable)
Below is the the instruction that describes the task: ### Input: On Windows, returns a list of mapped network drives :return: tuple(string, string, bool) For each mapped netword drive, return 3 values tuple: - the local drive - the remote path- - True if the mapping ...
def birthdays_subcommand(vcard_list, parsable): """Print birthday contact table. :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t...
Print birthday contact table. :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by tabulator (\t) :type parsable: bool :returns: None :rtyp...
Below is the the instruction that describes the task: ### Input: Print birthday contact table. :param vcard_list: the vcards to search for matching entries which should be printed :type vcard_list: list of carddav_object.CarddavObject :param parsable: machine readable output: columns devided by...
def up(self): """Moves the layer up in the stacking order. """ i = self.index() if i != None: del self.canvas.layers[i] i = min(len(self.canvas.layers), i+1) self.canvas.layers.insert(i, self)
Moves the layer up in the stacking order.
Below is the the instruction that describes the task: ### Input: Moves the layer up in the stacking order. ### Response: def up(self): """Moves the layer up in the stacking order. """ i = self.index() if i != None: del self.canvas.layers[i] ...
def _get_license_description(license_code): """ Gets the body for a license based on a license code """ req = requests.get("{base_url}/licenses/{license_code}".format( base_url=BASE_URL, license_code=license_code), headers=_HEADERS) if req.status_code == requests.codes.ok: s = req.json()["body"] se...
Gets the body for a license based on a license code
Below is the the instruction that describes the task: ### Input: Gets the body for a license based on a license code ### Response: def _get_license_description(license_code): """ Gets the body for a license based on a license code """ req = requests.get("{base_url}/licenses/{license_code}".format( base_u...
def safe_split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]: """ Split long text :param text: :param length: :return: """ # TODO: More informative description temp_text = text parts = [] while temp_text: if len(temp_text) > length: t...
Split long text :param text: :param length: :return:
Below is the the instruction that describes the task: ### Input: Split long text :param text: :param length: :return: ### Response: def safe_split_text(text: str, length: int = MAX_MESSAGE_LENGTH) -> typing.List[str]: """ Split long text :param text: :param length: :return: ""...
def iter_get( self, name=None, group=None, index=None, raster=None, samples_only=False, raw=False, ): """ iterator over a channel This is usefull in case of large files with a small number of channels. If the *raster* keyword argument...
iterator over a channel This is usefull in case of large files with a small number of channels. If the *raster* keyword argument is not *None* the output is interpolated accordingly Parameters ---------- name : string name of channel group : int ...
Below is the the instruction that describes the task: ### Input: iterator over a channel This is usefull in case of large files with a small number of channels. If the *raster* keyword argument is not *None* the output is interpolated accordingly Parameters ---------- ...
def enabled(name): ''' Ensure an Apache conf is enabled. name Name of the Apache conf ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} is_enabled = __salt__['apache.check_conf_enabled'](name) if not is_enabled: if __opts__['test']: msg = 'A...
Ensure an Apache conf is enabled. name Name of the Apache conf
Below is the the instruction that describes the task: ### Input: Ensure an Apache conf is enabled. name Name of the Apache conf ### Response: def enabled(name): ''' Ensure an Apache conf is enabled. name Name of the Apache conf ''' ret = {'name': name, 'result': True, 'com...
def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. """ replace = {} # Fast path for resetting all attributes. if not attrs or attrs == (0, ): self.cursor.attrs = self.default_char ...
Set display attributes. :param list attrs: a list of display attributes to set.
Below is the the instruction that describes the task: ### Input: Set display attributes. :param list attrs: a list of display attributes to set. ### Response: def select_graphic_rendition(self, *attrs): """Set display attributes. :param list attrs: a list of display attributes to set. ...
def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky is not None else nn.ReLU(inplace=inplace)
Return a relu activation, maybe `leaky` and `inplace`.
Below is the the instruction that describes the task: ### Input: Return a relu activation, maybe `leaky` and `inplace`. ### Response: def relu(inplace:bool=False, leaky:float=None): "Return a relu activation, maybe `leaky` and `inplace`." return nn.LeakyReLU(inplace=inplace, negative_slope=leaky) if leaky ...
def resume_reading(self): """ Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading. """ # Clear the read pause status self._recv_paused = False ...
Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading.
Below is the the instruction that describes the task: ### Input: Called by the client protocol to resume the receiving end. The protocol's ``frame_received()`` method will be called once again if some data is available for reading. ### Response: def resume_reading(self): """ Called ...
def write_byte_data(self, address, register, value): """ SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr...
SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr [A] Comm [A] S Addr Rd [A] [Data] NA P Functionality flag: I...
Below is the the instruction that describes the task: ### Input: SMBus Read Byte: i2c_smbus_read_byte_data() ============================================ This reads a single byte from a device, from a designated register. The register is specified through the Comm byte. S Addr Wr ...
def read_scans(sdmfile, bdfdir=''): """ Use sdmpy to get all scans and info needed for rtpipe as dict """ sdm = getsdm(sdmfile, bdfdir=bdfdir) scandict = {} skippedscans = [] for scan in sdm.scans(): scannum = int(scan.idx) scandict[scannum] = {} intentstr = ' '.join(scan....
Use sdmpy to get all scans and info needed for rtpipe as dict
Below is the the instruction that describes the task: ### Input: Use sdmpy to get all scans and info needed for rtpipe as dict ### Response: def read_scans(sdmfile, bdfdir=''): """ Use sdmpy to get all scans and info needed for rtpipe as dict """ sdm = getsdm(sdmfile, bdfdir=bdfdir) scandict = {} ...
def figure( key=None, width=400, height=500, lighting=True, controls=True, controls_vr=False, controls_light=False, debug=False, **kwargs ): """Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this fi...
Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this figure :param int width: pixel width of WebGL canvas :param int height: .. height .. :param bool lighting: use lighting or not :param bool controls: show controls or not...
Below is the the instruction that describes the task: ### Input: Create a new figure if no key is given, or return the figure associated with key. :param key: Python object that identifies this figure :param int width: pixel width of WebGL canvas :param int height: .. height .. :param bool lightin...
def execute(self, offset=0, **query): """ Executes a query. Additional query parameters can be passed as keyword arguments. Returns: The request parameters and the raw query response. """ _params = self._build_query(**query) self._page_offset = offset _p...
Executes a query. Additional query parameters can be passed as keyword arguments. Returns: The request parameters and the raw query response.
Below is the the instruction that describes the task: ### Input: Executes a query. Additional query parameters can be passed as keyword arguments. Returns: The request parameters and the raw query response. ### Response: def execute(self, offset=0, **query): """ Executes a query. A...
def pokeStorable(self, storable, objname, obj, container, visited=None, _stack=None, **kwargs): """ Arguments: storable (StorableHandler): storable instance. objname (any): record reference. obj (any): object to be serialized. container (any): containe...
Arguments: storable (StorableHandler): storable instance. objname (any): record reference. obj (any): object to be serialized. container (any): container. visited (dict): map of the previously serialized objects that are passed by referenc...
Below is the the instruction that describes the task: ### Input: Arguments: storable (StorableHandler): storable instance. objname (any): record reference. obj (any): object to be serialized. container (any): container. visited (dict): map of the prev...
def SLIT_DIFFRACTION(x,g): """ Instrumental (slit) function. """ y = zeros(len(x)) index_zero = x==0 index_nonzero = ~index_zero dk_ = pi/g x_ = dk_*x[index_nonzero] w_ = sin(x_) r_ = w_**2/x_**2 y[index_zero] = 1 y[index_nonzero] = r_/g return y
Instrumental (slit) function.
Below is the the instruction that describes the task: ### Input: Instrumental (slit) function. ### Response: def SLIT_DIFFRACTION(x,g): """ Instrumental (slit) function. """ y = zeros(len(x)) index_zero = x==0 index_nonzero = ~index_zero dk_ = pi/g x_ = dk_*x[index_nonzero] w_ =...
def mounts(): ''' Return a list of current MooseFS mounts CLI Example: .. code-block:: bash salt '*' moosefs.mounts ''' cmd = 'mount' ret = {} out = __salt__['cmd.run_all'](cmd) output = out['stdout'].splitlines() for line in output: if not line: c...
Return a list of current MooseFS mounts CLI Example: .. code-block:: bash salt '*' moosefs.mounts
Below is the the instruction that describes the task: ### Input: Return a list of current MooseFS mounts CLI Example: .. code-block:: bash salt '*' moosefs.mounts ### Response: def mounts(): ''' Return a list of current MooseFS mounts CLI Example: .. code-block:: bash ...
def between(self, time_): """ Compare if the parameter HH:MM is in the time range. """ hour = int(time_[0:2]) minute = int(time_[3:5]) return not ( hour < self.h1 or hour > self.h2 or (hour == self.h1 and minute < self.m1) or (hour == s...
Compare if the parameter HH:MM is in the time range.
Below is the the instruction that describes the task: ### Input: Compare if the parameter HH:MM is in the time range. ### Response: def between(self, time_): """ Compare if the parameter HH:MM is in the time range. """ hour = int(time_[0:2]) minute = int(time_[3:5]) ...
def export_agg_losses_ebr(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ if 'ruptures' not in dstore: logging.warning('There are no ruptures in the datastore') return [] name, ext = export.keyfunc(ekey) agg_los...
:param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object
Below is the the instruction that describes the task: ### Input: :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object ### Response: def export_agg_losses_ebr(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore ob...
def close(self): """Stop monitoring and close connection.""" _LOGGER.debug("Closing...") self.closed = True if self.connected: self._writer.close()
Stop monitoring and close connection.
Below is the the instruction that describes the task: ### Input: Stop monitoring and close connection. ### Response: def close(self): """Stop monitoring and close connection.""" _LOGGER.debug("Closing...") self.closed = True if self.connected: self._writer.close()
def delete(self, url_path, data=None): """Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. ...
Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e.g. "/packages/id/<object ID>") Raises: ...
Below is the the instruction that describes the task: ### Input: Delete an object from the JSS. In general, it is better to use a higher level interface for deleting objects, namely, using a JSSObject's delete method. Args: url_path: String API endpoint path to DEL, with ID (e....
def _normalize_json_search_response(self, json): """ Normalizes a JSON search response so that PB and HTTP have the same return value """ result = {} if 'facet_counts' in json: result['facet_counts'] = json[u'facet_counts'] if 'grouped' in json: ...
Normalizes a JSON search response so that PB and HTTP have the same return value
Below is the the instruction that describes the task: ### Input: Normalizes a JSON search response so that PB and HTTP have the same return value ### Response: def _normalize_json_search_response(self, json): """ Normalizes a JSON search response so that PB and HTTP have the same re...
def convert_to_group_ids(groups, vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None): ''' Given a list of security groups and a vpc_id, convert_to_group_ids will convert all list items in the given list to security group ids. CLI example:: salt...
Given a list of security groups and a vpc_id, convert_to_group_ids will convert all list items in the given list to security group ids. CLI example:: salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h
Below is the the instruction that describes the task: ### Input: Given a list of security groups and a vpc_id, convert_to_group_ids will convert all list items in the given list to security group ids. CLI example:: salt myminion boto_secgroup.convert_to_group_ids mysecgroup vpc-89yhh7h ### Respons...
def updateState(self, slicedArray, rtiInfo, separateFields): """ Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents. """ self.beginResetModel() try: # The sliced array can be a maske...
Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents.
Below is the the instruction that describes the task: ### Input: Sets the slicedArray and rtiInfo and other members. This will reset the model. Will be called from the tableInspector._drawContents. ### Response: def updateState(self, slicedArray, rtiInfo, separateFields): """ Sets the slicedAr...
def turbulent_Sieder_Tate(Re, Pr, mu=None, mu_w=None): r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [1]_ and supposedly [2]_. .. math:: Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14} Parameters ---------- Re : float ...
r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [1]_ and supposedly [2]_. .. math:: Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14} Parameters ---------- Re : float Reynolds number, [-] Pr : float Prandtl number...
Below is the the instruction that describes the task: ### Input: r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [1]_ and supposedly [2]_. .. math:: Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14} Parameters ---------- Re : flo...
def infect(cls, graph, key, default_scope=None): """ Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding """ f...
Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding
Below is the the instruction that describes the task: ### Input: Forcibly convert an entry-point based factory to a ScopedFactory. Must be invoked before resolving the entry point. :raises AlreadyBoundError: for non entry-points; these should be declared with @scoped_binding ### Response: def inf...
def pair_tree_creator(meta_id): """Splits string into a pairtree path.""" chunks = [] for x in range(0, len(meta_id)): if x % 2: continue if (len(meta_id) - 1) == x: chunk = meta_id[x] else: chunk = meta_id[x: x + 2] chunks.append(chunk) ...
Splits string into a pairtree path.
Below is the the instruction that describes the task: ### Input: Splits string into a pairtree path. ### Response: def pair_tree_creator(meta_id): """Splits string into a pairtree path.""" chunks = [] for x in range(0, len(meta_id)): if x % 2: continue if (len(meta_id) - 1) ...
def _create_job_details(self, key, job_config, logfile, status): """Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular jo...
Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular job logfile : str Name of the associated log file ...
Below is the the instruction that describes the task: ### Input: Create a `JobDetails` for a single job Parameters ---------- key : str Key used to identify this particular job job_config : dict Dictionary with arguements passed to this particular job ...
def _psd_mask(x): """Computes whether each square matrix in the input is positive semi-definite. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. Returns: mask: A floating-point `Tensor` of shape `[B1, ... Bn]`. Each scalar is 1 if the corresponding matrix was PSD, otherwise 0. ...
Computes whether each square matrix in the input is positive semi-definite. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. Returns: mask: A floating-point `Tensor` of shape `[B1, ... Bn]`. Each scalar is 1 if the corresponding matrix was PSD, otherwise 0.
Below is the the instruction that describes the task: ### Input: Computes whether each square matrix in the input is positive semi-definite. Args: x: A floating-point `Tensor` of shape `[B1, ..., Bn, M, M]`. Returns: mask: A floating-point `Tensor` of shape `[B1, ... Bn]`. Each scalar is 1 if t...
def _update_handlers(self): """Update `_handler_map` after `handlers` have been modified.""" handler_map = defaultdict(list) for i, obj in enumerate(self.handlers): for dummy, handler in inspect.getmembers(obj, callable): if not hasattr(handler, "_pyxmpp_event...
Update `_handler_map` after `handlers` have been modified.
Below is the the instruction that describes the task: ### Input: Update `_handler_map` after `handlers` have been modified. ### Response: def _update_handlers(self): """Update `_handler_map` after `handlers` have been modified.""" handler_map = defaultdict(list) for i, obj i...
def ssh_sa_ssh_client_mac(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services") ssh = ET.SubElement(ssh_sa, "ssh") client = ET.SubElement(ssh, "client") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ssh_sa_ssh_client_mac(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-ser...
def set_canvas_properties(self, canvas, x_title=None, y_title=None, x_lim=None, y_lim=None, x_labels=True, y_labels=True): """! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title ...
! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title for X axis, if 'None', then nothing is displayed. @param[in] y_title (string): Title for Y axis, if 'None', then nothing is di...
Below is the the instruction that describes the task: ### Input: ! @brief Set properties for specified canvas. @param[in] canvas (uint): Index of canvas whose properties should changed. @param[in] x_title (string): Title for X axis, if 'None', then nothing is displayed. @param[...
def iso_name_converter(iso): ''' Converts the name of the given isotope (input), e.g., 'N-14' to 14N as used later to compare w/ grain database. ''' sp = iso.split('-') output = sp[1] + sp[0] return output.lower()
Converts the name of the given isotope (input), e.g., 'N-14' to 14N as used later to compare w/ grain database.
Below is the the instruction that describes the task: ### Input: Converts the name of the given isotope (input), e.g., 'N-14' to 14N as used later to compare w/ grain database. ### Response: def iso_name_converter(iso): ''' Converts the name of the given isotope (input), e.g., 'N-14' to 14N as used...