code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def parse_component_reference(self, node): """ Parses <ComponentReference> @param node: Node containing the <ComponentTypeRef> element @type node: xml.etree.Element """ if 'name' in node.lattrib: name = node.lattrib['name'] else: self.rai...
Parses <ComponentReference> @param node: Node containing the <ComponentTypeRef> element @type node: xml.etree.Element
Below is the the instruction that describes the task: ### Input: Parses <ComponentReference> @param node: Node containing the <ComponentTypeRef> element @type node: xml.etree.Element ### Response: def parse_component_reference(self, node): """ Parses <ComponentReference> @...
def parse_bool(s, default=False): """ Return the boolean value of an English string or default if it can't be determined. """ if s is None: return default return TRUTH.get(s.lower(), default)
Return the boolean value of an English string or default if it can't be determined.
Below is the the instruction that describes the task: ### Input: Return the boolean value of an English string or default if it can't be determined. ### Response: def parse_bool(s, default=False): """ Return the boolean value of an English string or default if it can't be determined. """ if...
def add_training_sample(self, text=u'', lang=''): """ Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text. """ self.tr...
Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text.
Below is the the instruction that describes the task: ### Input: Initial step for adding new sample to training data. You need to call `save_training_samples()` afterwards. :param text: Sample text to be added. :param lang: Language label for the input text. ### Response: def a...
def expand_ssh_proxy_command(command, user, addr, port=22): """ Expand spacial digraphs ``%h``, ``%p``, and ``%r``. Return a copy of `command` with the following string substitutions applied: * ``%h`` is replaced by *addr* * ``%p`` is replaced by *port* * ``%r`` is replaced by *user* *...
Expand spacial digraphs ``%h``, ``%p``, and ``%r``. Return a copy of `command` with the following string substitutions applied: * ``%h`` is replaced by *addr* * ``%p`` is replaced by *port* * ``%r`` is replaced by *user* * ``%%`` is replaced by ``%``. See also: man page ``ssh_config``, se...
Below is the the instruction that describes the task: ### Input: Expand spacial digraphs ``%h``, ``%p``, and ``%r``. Return a copy of `command` with the following string substitutions applied: * ``%h`` is replaced by *addr* * ``%p`` is replaced by *port* * ``%r`` is replaced by *user* * ``...
def visit_importfrom(self, node): """visit astroid.ImportFrom and catch modules for package diagram """ if self.pkgdiagram: self.pkgdiagram.add_from_depend(node, node.modname)
visit astroid.ImportFrom and catch modules for package diagram
Below is the the instruction that describes the task: ### Input: visit astroid.ImportFrom and catch modules for package diagram ### Response: def visit_importfrom(self, node): """visit astroid.ImportFrom and catch modules for package diagram """ if self.pkgdiagram: self.pkgdia...
def pythonize(self, val): """Convert value into a list:: * split value (or each element if value is a list) on coma char * strip split values :param val: value to convert :type val: str :return: list corresponding to value :rtype: list """ if isi...
Convert value into a list:: * split value (or each element if value is a list) on coma char * strip split values :param val: value to convert :type val: str :return: list corresponding to value :rtype: list
Below is the the instruction that describes the task: ### Input: Convert value into a list:: * split value (or each element if value is a list) on coma char * strip split values :param val: value to convert :type val: str :return: list corresponding to value :rtype:...
def p_systemcall(self, p): 'systemcall : DOLLER ID LPAREN sysargs RPAREN' p[0] = SystemCall(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
systemcall : DOLLER ID LPAREN sysargs RPAREN
Below is the the instruction that describes the task: ### Input: systemcall : DOLLER ID LPAREN sysargs RPAREN ### Response: def p_systemcall(self, p): 'systemcall : DOLLER ID LPAREN sysargs RPAREN' p[0] = SystemCall(p[2], p[4], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
def _get_instance(self): """Retrieve instance matching instance_id.""" resource = self._connect() try: instance = resource.Instance(self.running_instance_id) except Exception: raise EC2CloudException( 'Instance with ID: {instance_id} not found.'.f...
Retrieve instance matching instance_id.
Below is the the instruction that describes the task: ### Input: Retrieve instance matching instance_id. ### Response: def _get_instance(self): """Retrieve instance matching instance_id.""" resource = self._connect() try: instance = resource.Instance(self.running_instance_id) ...
def getSpec(cls): """ Return the Spec for ApicalTMPairRegion """ spec = { "description": ApicalTMPairRegion.__doc__, "singleNodeOnly": True, "inputs": { "activeColumns": { "description": ("An array of 0's and 1's representing the active " "m...
Return the Spec for ApicalTMPairRegion
Below is the the instruction that describes the task: ### Input: Return the Spec for ApicalTMPairRegion ### Response: def getSpec(cls): """ Return the Spec for ApicalTMPairRegion """ spec = { "description": ApicalTMPairRegion.__doc__, "singleNodeOnly": True, "inputs": { "...
def cpu_count(logical=True): """Return system CPU count """ if logical: from multiprocessing import cpu_count ncpu=cpu_count() else: import psutil ncpu=psutil.cpu_count(logical=False) return ncpu
Return system CPU count
Below is the the instruction that describes the task: ### Input: Return system CPU count ### Response: def cpu_count(logical=True): """Return system CPU count """ if logical: from multiprocessing import cpu_count ncpu=cpu_count() else: import psutil ncpu=psutil.cpu_c...
def get_value(self, row, column): """Return the value of the DataFrame.""" # To increase the performance iat is used but that requires error # handling, so fallback uses iloc try: value = self.df.iat[row, column] except OutOfBoundsDatetime: value = ...
Return the value of the DataFrame.
Below is the the instruction that describes the task: ### Input: Return the value of the DataFrame. ### Response: def get_value(self, row, column): """Return the value of the DataFrame.""" # To increase the performance iat is used but that requires error # handling, so fallback uses iloc...
def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """ th = vtk.vtkImageThreshold() th.SetInputData(self.image) if vmin is not None and vmax is not None: th.ThresholdBetween(vmin, vmax) e...
Binary or continuous volume thresholding.
Below is the the instruction that describes the task: ### Input: Binary or continuous volume thresholding. ### Response: def threshold(self, vmin=None, vmax=None, replaceWith=None): """ Binary or continuous volume thresholding. """ th = vtk.vtkImageThreshold() th.SetInputDat...
def attrs(class_): """ Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do n...
Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __init__ for proper type-checking and do not want to repeat attribute...
Below is the the instruction that describes the task: ### Input: Like attr.s with slots=True, but with attributes extracted from __init__ method signature. slots=True ensures that signature matches what really happens (we can't define different attributes on self). It is useful if we still want __in...
def check_filepath(self, path, filename): """ Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions...
Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions.SettingsBackendError: If determined filepath ...
Below is the the instruction that describes the task: ### Input: Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exc...
def get_since_until(time_range: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None, time_shift: Optional[str] = None, relative_end: Optional[str] = None) -> Tuple[datetime, datetime]: """Return `since` and `u...
Return `since` and `until` date time tuple from string representations of time_range, since, until and time_shift. This functiom supports both reading the keys separately (from `since` and `until`), as well as the new `time_range` key. Valid formats are: - ISO 8601 - X days/years/hours/day...
Below is the the instruction that describes the task: ### Input: Return `since` and `until` date time tuple from string representations of time_range, since, until and time_shift. This functiom supports both reading the keys separately (from `since` and `until`), as well as the new `time_range` key. Va...
def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) ret...
Utility function to load an array from an iterator.
Below is the the instruction that describes the task: ### Input: Utility function to load an array from an iterator. ### Response: def _fromiter(it, dtype, count, progress, log): """Utility function to load an array from an iterator.""" if progress > 0: it = _iter_withprogress(it, progress, log) ...
def ssml_emphasis(self, words, level=None, **kwargs): """ Create a <Emphasis> element :param words: Words to emphasize :param level: Specify the degree of emphasis :param kwargs: additional attributes :returns: <Emphasis> element """ return self.nest(Ssm...
Create a <Emphasis> element :param words: Words to emphasize :param level: Specify the degree of emphasis :param kwargs: additional attributes :returns: <Emphasis> element
Below is the the instruction that describes the task: ### Input: Create a <Emphasis> element :param words: Words to emphasize :param level: Specify the degree of emphasis :param kwargs: additional attributes :returns: <Emphasis> element ### Response: def ssml_emphasis(self, words,...
def _to_bits(nqbits, ncbits=0, func=None): """Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) """ if func is None: return functools.partial(_to_bits, nqbits, ncbits) @functools.wraps(func) def wrapper(sel...
Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0])
Below is the the instruction that describes the task: ### Input: Convert gate arguments to [qu|cl]bits from integers, slices, ranges, etc. For example circuit.h(0) -> circuit.h(QuantumRegister(2)[0]) ### Response: def _to_bits(nqbits, ncbits=0, func=None): """Convert gate arguments to [qu|cl]bits from inte...
async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse HTML and get results parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.decode("latin-1"), parser) for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1): # extract...
See CoverSource.parseResults.
Below is the the instruction that describes the task: ### Input: See CoverSource.parseResults. ### Response: async def parseResults(self, api_data): """ See CoverSource.parseResults. """ results = [] # parse HTML and get results parser = lxml.etree.HTMLParser() html = lxml.etree.XML(api_data.d...
def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) """ assert self.cal1Dfn.is_file( ), 'please specify filename for each camera under [cam]/cal1Dname: in .ini file {}'.format(self.cal1Dfn) ...
NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle)
Below is the the instruction that describes the task: ### Input: NOTE: we need to retrieve values in case no modifications are done. (since we'd get a closed h5py handle) ### Response: def doorient(self): """ NOTE: we need to retrieve values in case no modifications are done. (since...
def _ParseBinaryDataAsString(self, parser_mediator, binary_data_value): """Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value ...
Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value (CSSM_DB_ATTRIBUTE_FORMAT_BLOB) Returns: str: binary data value...
Below is the the instruction that describes the task: ### Input: Parses a binary data value as string Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. binary_data_value (bytes): binary data value (CSSM...
def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("String expected.") self.db.sunionstore(key, [self.key] + [o.key for o in others]) return Set(key)
Return a new set with elements from the set and all others.
Below is the the instruction that describes the task: ### Input: Return a new set with elements from the set and all others. ### Response: def union(self, key, *others): """Return a new set with elements from the set and all others.""" if not isinstance(key, str): raise ValueError("Stri...
def _parse_nodes_section(f, current_section, nodes): """Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f Returns a dict containing the node as key """ section = {} dimensions = None if current_section == 'NODE_COORD_SECTION': dimensions = 3 # i: (i, j) elif cu...
Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f Returns a dict containing the node as key
Below is the the instruction that describes the task: ### Input: Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from file descript f Returns a dict containing the node as key ### Response: def _parse_nodes_section(f, current_section, nodes): """Parse TSPLIB NODE_COORD_SECTION or DEMAND_SECTION from fil...
def simple_merge(kls, skeletons): """ Simple concatenation of skeletons into one object without adding edges between them. """ if len(skeletons) == 0: return PrecomputedSkeleton() if type(skeletons[0]) is np.ndarray: skeletons = [ skeletons ] ct = 0 edges = [] for skel...
Simple concatenation of skeletons into one object without adding edges between them.
Below is the the instruction that describes the task: ### Input: Simple concatenation of skeletons into one object without adding edges between them. ### Response: def simple_merge(kls, skeletons): """ Simple concatenation of skeletons into one object without adding edges between them. """ ...
def _get_dataframe(self): """ Load dataframe based on specified connection :return: """ if self.source_conn is None: # Use local file return ge.read_csv(self.dataset_name, **self.dataset_params) if isinstance(self.source_conn, S3Hook): hook = Exp...
Load dataframe based on specified connection :return:
Below is the the instruction that describes the task: ### Input: Load dataframe based on specified connection :return: ### Response: def _get_dataframe(self): """ Load dataframe based on specified connection :return: """ if self.source_conn is None: # Use local file...
def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str: """Return a string defining the required types for the given combination of an exchange item group and |Node| objects. >>> from hydpy.auxs.xmltools import XSDWriter >>> print(XSDWriter.get_nodesitemtypeinsertion( ......
Return a string defining the required types for the given combination of an exchange item group and |Node| objects. >>> from hydpy.auxs.xmltools import XSDWriter >>> print(XSDWriter.get_nodesitemtypeinsertion( ... 'setitems', 1)) # doctest: +ELLIPSIS <complexType name...
Below is the the instruction that describes the task: ### Input: Return a string defining the required types for the given combination of an exchange item group and |Node| objects. >>> from hydpy.auxs.xmltools import XSDWriter >>> print(XSDWriter.get_nodesitemtypeinsertion( ... ...
def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=[]): """ Floating-point ordered comparison: name = lhs <cmpop> rhs where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' """ if cmpop in _CMP_MAP: op = 'o' + _CMP_MAP[cmpop] else: ...
Floating-point ordered comparison: name = lhs <cmpop> rhs where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
Below is the the instruction that describes the task: ### Input: Floating-point ordered comparison: name = lhs <cmpop> rhs where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno' ### Response: def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=[]): """ Floating-po...
def _reorder_lines(lines): """ Reorder lines so that the distance from the end of one to the beginning of the next is minimised. """ x = 0 y = 0 new_lines = [] # treat the list of lines as a stack, off which we keep popping the best # one to add next. while lines: # loo...
Reorder lines so that the distance from the end of one to the beginning of the next is minimised.
Below is the the instruction that describes the task: ### Input: Reorder lines so that the distance from the end of one to the beginning of the next is minimised. ### Response: def _reorder_lines(lines): """ Reorder lines so that the distance from the end of one to the beginning of the next is mini...
def _generate_data_key(self, algorithm: AlgorithmSuite, encryption_context: Dict[Text, Text]) -> DataKey: """Perform the provider-specific data key generation task. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dic...
Perform the provider-specific data key generation task. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context to use in encryption :returns: Generated data key :rtype: aw...
Below is the the instruction that describes the task: ### Input: Perform the provider-specific data key generation task. :param algorithm: Algorithm on which to base data key :type algorithm: aws_encryption_sdk.identifiers.Algorithm :param dict encryption_context: Encryption context to use ...
def assertFileEncodingNotEqual(self, filename, encoding, msg=None): '''Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str ...
Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` st...
Below is the the instruction that describes the task: ### Input: Fail if ``filename`` is encoded with the given ``encoding`` as determined by the '!=' operator. Parameters ---------- filename : str, bytes, file-like encoding : str, bytes msg : str If not ...
def amount_object_to_dict(self, amount): """Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: inst...
Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :param amount: instance of Amount object :return: dict with am...
Below is the the instruction that describes the task: ### Input: Return the dictionary representation of an Amount object. Amount object must have amount and currency properties and as_tuple method which will return (currency, amount) and as_quantized method to quantize amount property. :p...
def get_parser(parser): """ Grabs the parser. args: parser: The parser """ parser.description = textwrap.dedent(""" Segment the .po files in LOCALE(s) based on the segmenting rules in config.yaml. Note that segmenting is *not* idempotent: it modifies the input file,...
Grabs the parser. args: parser: The parser
Below is the the instruction that describes the task: ### Input: Grabs the parser. args: parser: The parser ### Response: def get_parser(parser): """ Grabs the parser. args: parser: The parser """ parser.description = textwrap.dedent(""" Segment the .po files in LO...
def process_subprotocol( headers: Headers, available_subprotocols: Optional[Sequence[Subprotocol]] ) -> Optional[Subprotocol]: """ Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotoc...
Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol.
Below is the the instruction that describes the task: ### Input: Handle the Sec-WebSocket-Protocol HTTP response header. Check that it contains exactly one supported subprotocol. Return the selected subprotocol. ### Response: def process_subprotocol( headers: Headers, available_subprotoco...
def _load_keyring_path(config): "load the keyring-path option (if present)" try: path = config.get("backend", "keyring-path").strip() sys.path.insert(0, path) except (configparser.NoOptionError, configparser.NoSectionError): pass
load the keyring-path option (if present)
Below is the the instruction that describes the task: ### Input: load the keyring-path option (if present) ### Response: def _load_keyring_path(config): "load the keyring-path option (if present)" try: path = config.get("backend", "keyring-path").strip() sys.path.insert(0, path) except ...
def get_processing_block(block_id): """Return the Processing Block Configuration for the specified ID""" identifiers = block_id.split(':') scheduling_block_id = identifiers[0] scheduling_block_config = get_scheduling_block(scheduling_block_id) for processing_block in scheduling_block_config['process...
Return the Processing Block Configuration for the specified ID
Below is the the instruction that describes the task: ### Input: Return the Processing Block Configuration for the specified ID ### Response: def get_processing_block(block_id): """Return the Processing Block Configuration for the specified ID""" identifiers = block_id.split(':') scheduling_block_id = ...
def create_temp_directory(self, **mkdtemp_kwargs) -> str: """ Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory """ kwargs = {**self.default_mkdtemp_kwargs, **mkdtemp_kwargs} ...
Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory
Below is the the instruction that describes the task: ### Input: Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory ### Response: def create_temp_directory(self, **mkdtemp_kwargs) -> str: """ ...
def disable_restricted(self, ): """Disable the restricted buttons :returns: None :rtype: None :raises: None """ todisable = [(self.reftrack.duplicate, self.duplicate_tb), (self.reftrack.delete, self.delete_tb), (self.reftrack.ref...
Disable the restricted buttons :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Disable the restricted buttons :returns: None :rtype: None :raises: None ### Response: def disable_restricted(self, ): """Disable the restricted buttons :returns: None :rtype: None :raises: No...
def _expectation(p, mean1, none1, mean2, none2, nghp=None): """ Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD """ with params_as_tensors_for(mean1): N = tf.shape(p.mu)...
Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD
Below is the the instruction that describes the task: ### Input: Compute the expectation: expectation[n] = <m1(x_n)^T m2(x_n)>_p(x_n) - m1(.) :: Linear mean function - m2(.) :: Identity mean function :return: NxQxD ### Response: def _expectation(p, mean1, none1, mean2, none2, nghp=None): ...
def checkattr(metacls, attr, value): """ Only allow class attributes that are instances of rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy """ if not isinstance(value, ( types.MethodType, types.FunctionType, classmethod, ...
Only allow class attributes that are instances of rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy
Below is the the instruction that describes the task: ### Input: Only allow class attributes that are instances of rootpy.types.Column, ROOT.TObject, or ROOT.ObjectProxy ### Response: def checkattr(metacls, attr, value): """ Only allow class attributes that are instances of rootpy.t...
def verify(self, obj): """Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reaso...
Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationError is thrown with at least the reason key set indicating ...
Below is the the instruction that describes the task: ### Input: Verify that the object conforms to this verifier's schema Args: obj (object): A python object to verify Raises: ValidationError: If there is a problem verifying the dictionary, a ValidationErro...
def _remove_previous_ned_queries( self, coordinateList): """iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **...
iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **Return:** - ``updatedCoordinateList`` -- coordinate list with previous queries r...
Below is the the instruction that describes the task: ### Input: iterate through the transient locations to see if we have recent local NED coverage of that area already **Key Arguments:** - ``coordinateList`` -- set of coordinate to check for previous queries **Return:** -...
def get_statements(self): """Process reader output to produce INDRA Statements.""" for k, v in self.reader_output.items(): for interaction in v['interactions']: self._process_interaction(k, interaction, v['text'], self.pmid, self.extr...
Process reader output to produce INDRA Statements.
Below is the the instruction that describes the task: ### Input: Process reader output to produce INDRA Statements. ### Response: def get_statements(self): """Process reader output to produce INDRA Statements.""" for k, v in self.reader_output.items(): for interaction in v['interactions...
def scatter_drag( x_points: 'Array', y_points: 'Array', *, fig=None, show_eqn=True, options={} ): """ Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: ...
Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: x_points (Array Number): x-values of points to plot y_points (Array Number): y-values of points to plot Kwargs: ...
Below is the the instruction that describes the task: ### Input: Generates an interactive scatter plot with the best fit line plotted over the points. The points can be dragged by the user and the line will automatically update. Args: x_points (Array Number): x-values of points to plot ...
def clean(self): """ Validates the topic instance. """ super().clean() if self.forum.is_category or self.forum.is_link: raise ValidationError( _('A topic can not be associated with a category or a link forum') )
Validates the topic instance.
Below is the the instruction that describes the task: ### Input: Validates the topic instance. ### Response: def clean(self): """ Validates the topic instance. """ super().clean() if self.forum.is_category or self.forum.is_link: raise ValidationError( _('A topic ...
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None): ''' Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. ''' assert len(mu) == 2 ax = ax if ax else plt.gca() # TODO use artists! t = np.hstack([np.ara...
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
Below is the the instruction that describes the task: ### Input: Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix. ### Response: def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None): ''' Plots mean and cov ellipsoid int...
def coalesce_events(self, coalesce=True): """ Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events ar...
Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled events are filtered based on their unicity, only unique events ...
Below is the the instruction that describes the task: ### Input: Coalescing events. Events are usually processed by batchs, their size depend on various factors. Thus, before processing them, events received from inotify are aggregated in a fifo queue. If this coalescing option is enabled ev...
def get_pdbs_for_gene(bigg_model, bigg_gene, cache_dir=tempfile.gettempdir(), force_rerun=False): """Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered lis...
Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered list of tuples of (pdb_id, chain_id)
Below is the the instruction that describes the task: ### Input: Attempt to get a rank-ordered list of available PDB structures for a BiGG Model and its gene. Args: bigg_model: BiGG Model ID bigg_gene: BiGG Gene ID Returns: list: rank-ordered list of tuples of (pdb_id, chain_id) ##...
def fill_hist(hist, array, weights=None, return_indices=False): """Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. T...
Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The number of columns must match the dimensionality of the histo...
Below is the the instruction that describes the task: ### Input: Fill a ROOT histogram with a NumPy array. Parameters ---------- hist : ROOT TH1, TH2, or TH3 The ROOT histogram to fill. array : numpy array of shape [n_samples, n_dimensions] The values to fill the histogram with. The...
def _get_version_properties(self): """Parses version and model information out of 'show version' output and uses the output to populate class properties. """ # Parse out version info output = self.enable('show version') self._version = str(output[0]['result']['version']) ...
Parses version and model information out of 'show version' output and uses the output to populate class properties.
Below is the the instruction that describes the task: ### Input: Parses version and model information out of 'show version' output and uses the output to populate class properties. ### Response: def _get_version_properties(self): """Parses version and model information out of 'show version' output ...
def search(self, key, default=None): """Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, return ``None``. This method never raises a ``KeyError``. """ self._find_lt(key) node = self...
Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, return ``None``. This method never raises a ``KeyError``.
Below is the the instruction that describes the task: ### Input: Find the first key-value pair with key *key* and return its value. If the key was not found, return *default*. If no default was provided, return ``None``. This method never raises a ``KeyError``. ### Response: def search(self, key, ...
def kill(self, detach=False): """This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace....
This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socketio.namespace.BaseNamespace.disconnect` methods so that you c...
Below is the the instruction that describes the task: ### Input: This function must/will be called when a socket is to be completely shut down, closed by connection timeout, connection error or explicit disconnection from the client. It will call all of the Namespace's :meth:`~socke...
def _match(names): ''' Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encounte...
Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg_delete, and a list of errors encountered.
Below is the the instruction that describes the task: ### Input: Since pkg_delete requires the full "pkgname-version" string, this function will attempt to match the package name with its version. Returns a list of partial matches and package names that match the "pkgname-version" string required by pkg...
def get_interface_detail_output_interface_configured_line_speed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_interface_detail_output_interface_configured_line_speed(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interfa...
def get_note(self, noteid): """Fetch a single note :param folderid: The UUID of the note """ if self.standard_grant_type is not "authorization_code": raise DeviantartError("Authentication through Authorization Code (Grant Type) is required in order to connect to this endpo...
Fetch a single note :param folderid: The UUID of the note
Below is the the instruction that describes the task: ### Input: Fetch a single note :param folderid: The UUID of the note ### Response: def get_note(self, noteid): """Fetch a single note :param folderid: The UUID of the note """ if self.standard_grant_type is not "autho...
def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part """ dynamic_part = self.from_python(dynamic_part) return super(DynamicRelatedFieldMixin, self).get_name_for(dynamic_part)
Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part
Below is the the instruction that describes the task: ### Input: Return the name for the current dynamic field, accepting a limpyd instance for the dynamic part ### Response: def get_name_for(self, dynamic_part): """ Return the name for the current dynamic field, accepting a limpyd ...
def encode(self, secret, algorithm='HS256'): """ Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the ...
Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with the OpenID Connect claims. secret (str): Secret used to e...
Below is the the instruction that describes the task: ### Input: Encode the set of claims to the JWT (JSON Web Token) format according to the OpenID Connect specification: http://openid.net/specs/openid-connect-basic-1_0.html#IDToken Arguments: claims (dict): A dictionary with ...
def execute_setup(self): # type: () -> Dict[str,str] """ for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return: """ ver = execute_get_text("python setup.py --version") if not ver: return None ...
for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return:
Below is the the instruction that describes the task: ### Input: for really surprising things like a dict foo in setup(**foo) consider python3 setup.py --version :return: ### Response: def execute_setup(self): # type: () -> Dict[str,str] """ for really surprising things like a dict...
def _convolve_buf(data_g, h_g, res_g=None): """ buffer variant """ assert_bufs_type(np.float32, data_g, h_g) prog = OCLProgram(abspath("kernels/convolve.cl")) if res_g is None: res_g = OCLArray.empty(data_g.shape, dtype=np.float32) Nhs = [np.int32(n) for n in h_g.shape] kerne...
buffer variant
Below is the the instruction that describes the task: ### Input: buffer variant ### Response: def _convolve_buf(data_g, h_g, res_g=None): """ buffer variant """ assert_bufs_type(np.float32, data_g, h_g) prog = OCLProgram(abspath("kernels/convolve.cl")) if res_g is None: res_g = OC...
def calculate_leapdays(init_date, final_date): """Currently unsupported, it only works for differences in years.""" leap_days = (final_date.year - 1) // 4 - (init_date.year - 1) // 4 leap_days -= (final_date.year - 1) // 100 - (init_date.year - 1) // 100 leap_days += (final_date.year - 1) // 400 - (ini...
Currently unsupported, it only works for differences in years.
Below is the the instruction that describes the task: ### Input: Currently unsupported, it only works for differences in years. ### Response: def calculate_leapdays(init_date, final_date): """Currently unsupported, it only works for differences in years.""" leap_days = (final_date.year - 1) // 4 - (init_d...
def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. """ for model in model_list: if model not in self.registry: raise NotRegistered('The model %s is not registered'...
Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered.
Below is the the instruction that describes the task: ### Input: Unregisters the given model(s). If a model isn't already registered, this will raise NotRegistered. ### Response: def unregister(self, *model_list): """ Unregisters the given model(s). If a model isn't already regist...
def refresh(self): """Reload the current page with the same request as originally done. Any change (`select_form`, or any value filled-in in the form) made to the current page before refresh is discarded. :raise ValueError: Raised if no refreshable page is loaded, e.g., when ...
Reload the current page with the same request as originally done. Any change (`select_form`, or any value filled-in in the form) made to the current page before refresh is discarded. :raise ValueError: Raised if no refreshable page is loaded, e.g., when using the shallow ``Browser``...
Below is the the instruction that describes the task: ### Input: Reload the current page with the same request as originally done. Any change (`select_form`, or any value filled-in in the form) made to the current page before refresh is discarded. :raise ValueError: Raised if no refreshable...
def slice_init(func): """ Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g., >>> X = np.ones((100, 20)) ...
Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g., >>> X = np.ones((100, 20)) >>> base = LinearBasis(onescol=...
Below is the the instruction that describes the task: ### Input: Decorator for adding partial application functionality to a basis object. This will add an "apply_ind" argument to a basis object initialiser that can be used to apply the basis function to only the dimensions specified in apply_ind. E.g....
def pd_plot_data(self): """ Plot data for phase diagram. 2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangle. Returns: (lines, stable_entries, unstable_entries): - lines is a list of list of coordinates for lines in the PD....
Plot data for phase diagram. 2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangle. Returns: (lines, stable_entries, unstable_entries): - lines is a list of list of coordinates for lines in the PD. - stable_entries is a {coordina...
Below is the the instruction that describes the task: ### Input: Plot data for phase diagram. 2-comp - Full hull with energies 3/4-comp - Projection into 2D or 3D Gibbs triangle. Returns: (lines, stable_entries, unstable_entries): - lines is a list of list of coordin...
def model_to_dict(instance, fields=None, exclude=None): """ The same implementation as django model_to_dict but editable fields are allowed """ return { field.name: field_to_dict(field, instance) for field in chain(instance._meta.concrete_fields, instance._meta.many_to_many) # pylint: ...
The same implementation as django model_to_dict but editable fields are allowed
Below is the the instruction that describes the task: ### Input: The same implementation as django model_to_dict but editable fields are allowed ### Response: def model_to_dict(instance, fields=None, exclude=None): """ The same implementation as django model_to_dict but editable fields are allowed """ ...
def parse_string(cls, content, basedir=None, resolve=True, unresolved_value=DEFAULT_SUBSTITUTION): """Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type ...
Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type resolve: boolean :param unresolved_value: assigned value value to unresolved substitution. If ...
Below is the the instruction that describes the task: ### Input: Parse URL :param content: content to parse :type content: basestring :param resolve: If true, resolve substitutions :param resolve: if true, resolve substitutions :type resolve: boolean :param unresolve...
def get_alias(self, alias): """ Given a mnemonic, get the alias name(s) it falls under. If there aren't any, you get an empty list. """ alias = alias or {} return [k for k, v in alias.items() if self.mnemonic in v]
Given a mnemonic, get the alias name(s) it falls under. If there aren't any, you get an empty list.
Below is the the instruction that describes the task: ### Input: Given a mnemonic, get the alias name(s) it falls under. If there aren't any, you get an empty list. ### Response: def get_alias(self, alias): """ Given a mnemonic, get the alias name(s) it falls under. If there aren't ...
def set_screen_config(self, size_id, rotation, config_timestamp, rate=0, timestamp=X.CurrentTime): """Sets the screen to the specified size, rate, rotation and reflection. rate can be 0 to have the server select an appropriate rate. """ return SetScreenConfig( display=self.display, opc...
Sets the screen to the specified size, rate, rotation and reflection. rate can be 0 to have the server select an appropriate rate.
Below is the the instruction that describes the task: ### Input: Sets the screen to the specified size, rate, rotation and reflection. rate can be 0 to have the server select an appropriate rate. ### Response: def set_screen_config(self, size_id, rotation, config_timestamp, rate=0, timestamp=X.CurrentTime): ...
def compress(func): """ Compress route return data with gzip compression """ @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) if ('gzip' in bottle.request.headers.get('Accept-Encoding', '') and isinstance(result, string_type) and ...
Compress route return data with gzip compression
Below is the the instruction that describes the task: ### Input: Compress route return data with gzip compression ### Response: def compress(func): """ Compress route return data with gzip compression """ @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) ...
def get_map(name, map_type, number, reverse=False): """ Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Select ...
Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Select color map type. number : int Number of defined color...
Below is the the instruction that describes the task: ### Input: Return a `BrewerMap` representation of the specified color map. Parameters ---------- name : str Name of color map. Use `print_maps` to see available color maps. map_type : {'Sequential', 'Diverging', 'Qualitative'} Se...
def destroy(force): """Destroy all indexes.""" click.secho('Destroying indexes...', fg='red', bold=True, file=sys.stderr) with click.progressbar( current_search.delete(ignore=[400, 404] if force else None), length=current_search.number_of_indexes) as bar: for name, response i...
Destroy all indexes.
Below is the the instruction that describes the task: ### Input: Destroy all indexes. ### Response: def destroy(force): """Destroy all indexes.""" click.secho('Destroying indexes...', fg='red', bold=True, file=sys.stderr) with click.progressbar( current_search.delete(ignore=[400, 404] if fo...
def deserialize(self, data=None): """ Invoke the deserializer If the payload is a collection (more than 1 records) then a list will be returned of normalized dict's. If the payload is a single item then the normalized dict will be returned (not a list) :return: list or...
Invoke the deserializer If the payload is a collection (more than 1 records) then a list will be returned of normalized dict's. If the payload is a single item then the normalized dict will be returned (not a list) :return: list or dict
Below is the the instruction that describes the task: ### Input: Invoke the deserializer If the payload is a collection (more than 1 records) then a list will be returned of normalized dict's. If the payload is a single item then the normalized dict will be returned (not a list) ...
def print_split(column_to_split, total_columns): """Print a row that splits the given column into two columns while shifting all the following columns.""" out = "" for _ in range(column_to_split): out += "| " out += "|\\" for _ in range(column_to_split + 1, total_columns): out +=...
Print a row that splits the given column into two columns while shifting all the following columns.
Below is the the instruction that describes the task: ### Input: Print a row that splits the given column into two columns while shifting all the following columns. ### Response: def print_split(column_to_split, total_columns): """Print a row that splits the given column into two columns while shifting...
def _launch_forever_coro(coro, args, kwargs, loop): ''' This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The function...
This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The function is a coroutine, which needs to be scheduled in the event ...
Below is the the instruction that describes the task: ### Input: This helper function launches an async main function that was tagged with forever=True. There are two possibilities: - The function is a normal function, which handles initializing the event loop, which is then run forever - The fun...
def inspect(self, w): """Get the latest value of the wire given, if possible.""" if isinstance(w, WireVector): w = w.name try: vals = self.tracer.trace[w] except KeyError: pass else: if not vals: raise PyrtlError('No...
Get the latest value of the wire given, if possible.
Below is the the instruction that describes the task: ### Input: Get the latest value of the wire given, if possible. ### Response: def inspect(self, w): """Get the latest value of the wire given, if possible.""" if isinstance(w, WireVector): w = w.name try: vals = s...
def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be...
Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn.
Below is the the instruction that describes the task: ### Input: Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. ### Response: def iterboxed(self, rows): """Iterator that yields each scanline in boxe...
def norm_join(prefix, suffix): """ Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string """ if (prefix is None) and (suffix is None): return "." if prefix is...
Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string
Below is the the instruction that describes the task: ### Input: Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string ### Response: def norm_join(prefix, suffix): """ Join ...
def reshape_line_plot(df, x, y): """Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers. """ idx = list(df.columns.drop(y)) if df.duplicated(idx).any(): ...
Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers.
Below is the the instruction that describes the task: ### Input: Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers. ### Response: def reshape_line_plot(df, x, y): ...
def _expand_dims(x, input_shape, output_shape): """Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor """ verify_no_new_dims([output_shape], input_sha...
Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor
Below is the the instruction that describes the task: ### Input: Expand dimensions and transpose if necessary. Args: x: a tf.Tensor input_shape: a Shape output_shape: a Shape whose dimensions are a superset of those in input_shape Returns: a tf.Tensor ### Response: def _expand_dims(x, i...
def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict """ pubmed_identifiers = list(pubmed_identifiers) url = EUTILS_URL_FMT.format(','.join( pubmed_ide...
Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict
Below is the the instruction that describes the task: ### Input: Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict ### Response: def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Uti...
def getPolicyValue(self): """Get the policy and value vectors.""" self._cur.execute("SELECT action FROM policy") r = self._cur.fetchall() policy = [x[0] for x in r] self._cur.execute("SELECT value FROM V") r = self._cur.fetchall() value = [x[0] for x in r] ...
Get the policy and value vectors.
Below is the the instruction that describes the task: ### Input: Get the policy and value vectors. ### Response: def getPolicyValue(self): """Get the policy and value vectors.""" self._cur.execute("SELECT action FROM policy") r = self._cur.fetchall() policy = [x[0] for x in r] ...
def get_menu_checked(self, request): """ 获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulistview/?app_la...
获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulistview/?app_label=easyui&model_name=UserMenu&pk=1
Below is the the instruction that describes the task: ### Input: 获取用户或者用户组checked的菜单列表 usermenu_form.html 中定义 usermenu 这两个model的定义类似,比如menus_checked和menus_show groupmenu @return eg. ['1', '8', '9', '10' ] 获取用户或者用户组的check_ids,会给出app_label, model_name, pk eg. /easyui/menulist...
def on_action_end(self, action, logs={}): """ Called at end of each action for each callback in callbackList""" for callback in self.callbacks: if callable(getattr(callback, 'on_action_end', None)): callback.on_action_end(action, logs=logs)
Called at end of each action for each callback in callbackList
Below is the the instruction that describes the task: ### Input: Called at end of each action for each callback in callbackList ### Response: def on_action_end(self, action, logs={}): """ Called at end of each action for each callback in callbackList""" for callback in self.callbacks: i...
def DownloadXilinx(self, bitfile): """We hijack this call to perform the socket connect""" self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._sock.connect((self.simulation_host, self.simulation_port)) self._iface = PickleInterface(self._sock) return True
We hijack this call to perform the socket connect
Below is the the instruction that describes the task: ### Input: We hijack this call to perform the socket connect ### Response: def DownloadXilinx(self, bitfile): """We hijack this call to perform the socket connect""" self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._so...
def policy_iteration(mdp): "Solve an MDP by policy iteration [Fig. 17.7]" U = dict([(s, 0) for s in mdp.states]) pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states]) while True: U = policy_evaluation(pi, U, mdp) unchanged = True for s in mdp.states: a =...
Solve an MDP by policy iteration [Fig. 17.7]
Below is the the instruction that describes the task: ### Input: Solve an MDP by policy iteration [Fig. 17.7] ### Response: def policy_iteration(mdp): "Solve an MDP by policy iteration [Fig. 17.7]" U = dict([(s, 0) for s in mdp.states]) pi = dict([(s, random.choice(mdp.actions(s))) for s in mdp.states]...
async def index_page(self, request): """ Return index page with initial state for admin """ context = {"initial_state": self.schema.to_json()} return render_template( self.template, request, context, app_key=TEMPLATE_APP_KEY, ...
Return index page with initial state for admin
Below is the the instruction that describes the task: ### Input: Return index page with initial state for admin ### Response: async def index_page(self, request): """ Return index page with initial state for admin """ context = {"initial_state": self.schema.to_json()} retur...
def get_records(self, hql, parameters=None): """ Get a set of records from Presto """ try: return super().get_records( self._strip_sql(hql), parameters) except DatabaseError as e: raise PrestoException(self._get_pretty_exception_message(e))
Get a set of records from Presto
Below is the the instruction that describes the task: ### Input: Get a set of records from Presto ### Response: def get_records(self, hql, parameters=None): """ Get a set of records from Presto """ try: return super().get_records( self._strip_sql(hql), pa...
def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, level=logging_level)
Setup the log object.
Below is the the instruction that describes the task: ### Input: Setup the log object. ### Response: def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, ...
def EnsureSConsVersion(self, major, minor, revision=0): """Exit abnormally if the SCons version is not late enough.""" # split string to avoid replacement during build process if SCons.__version__ == '__' + 'VERSION__': SCons.Warnings.warn(SCons.Warnings.DevelopmentVersionWarning, ...
Exit abnormally if the SCons version is not late enough.
Below is the the instruction that describes the task: ### Input: Exit abnormally if the SCons version is not late enough. ### Response: def EnsureSConsVersion(self, major, minor, revision=0): """Exit abnormally if the SCons version is not late enough.""" # split string to avoid replacement during b...
def console_load_asc(con: tcod.console.Console, filename: str) -> bool: """Update a console from a non-delimited ASCII `.asc` file.""" return bool( lib.TCOD_console_load_asc(_console(con), filename.encode("utf-8")) )
Update a console from a non-delimited ASCII `.asc` file.
Below is the the instruction that describes the task: ### Input: Update a console from a non-delimited ASCII `.asc` file. ### Response: def console_load_asc(con: tcod.console.Console, filename: str) -> bool: """Update a console from a non-delimited ASCII `.asc` file.""" return bool( lib.TCOD_consol...
def get_nodes_by_namespace(graph: BELGraph, namespaces: Strings) -> Set[BaseEntity]: """Get all nodes identified by the given namespace(s).""" return get_nodes(graph, namespace_inclusion_builder(namespaces))
Get all nodes identified by the given namespace(s).
Below is the the instruction that describes the task: ### Input: Get all nodes identified by the given namespace(s). ### Response: def get_nodes_by_namespace(graph: BELGraph, namespaces: Strings) -> Set[BaseEntity]: """Get all nodes identified by the given namespace(s).""" return get_nodes(graph, namespace...
def slice_query(self, slice_id): """ This method exposes an API endpoint to get the database query string for this slice """ viz_obj = get_viz(slice_id) security_manager.assert_datasource_permission(viz_obj.datasource) return self.get_query_string_response(viz_obj...
This method exposes an API endpoint to get the database query string for this slice
Below is the the instruction that describes the task: ### Input: This method exposes an API endpoint to get the database query string for this slice ### Response: def slice_query(self, slice_id): """ This method exposes an API endpoint to get the database query string for this slice...
def format_level_1_memory(memory): """ Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 c...
Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndarray: Measurement level 1 complex numpy array Raises: Qis...
Below is the the instruction that describes the task: ### Input: Format an experiment result memory object for measurement level 1. Args: memory (list): Memory from experiment with `meas_level==1`. `avg` or `single` will be inferred from shape of result memory. Returns: np.ndar...
def new(self, inlineparent = None): ''' Compatible to Parser.new() ''' v = list(range(0, self.size)) for i in range(0, self.size): v[i] = self.innerparser.new() return v
Compatible to Parser.new()
Below is the the instruction that describes the task: ### Input: Compatible to Parser.new() ### Response: def new(self, inlineparent = None): ''' Compatible to Parser.new() ''' v = list(range(0, self.size)) for i in range(0, self.size): v[i] = self.innerparser.ne...
def _write_header(self, image, hdu): """Write header from image object to given HDU.""" hduhdr = hdu.header # Ginga image header object for the given extension only. # Cannot use get_header() because that might also return PRI hdr. ghdr = image.metadata['header'] for ke...
Write header from image object to given HDU.
Below is the the instruction that describes the task: ### Input: Write header from image object to given HDU. ### Response: def _write_header(self, image, hdu): """Write header from image object to given HDU.""" hduhdr = hdu.header # Ginga image header object for the given extension only. ...
def get_nameserver_detail_output_show_nameserver_nameserver_redirect(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_nameserver_detail") config = get_nameserver_detail output = ET.SubElement(get_nameserver_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_nameserver_detail_output_show_nameserver_nameserver_redirect(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_nameserver_detail = ET.Element("get_n...
def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ''' if load_path is None or not isinstance(load_path, six.string_types): return None _paths = [] for _path in load_path.split(':'): if os.path...
Checks the validity of the load_path, returns a sanitized version with invalid paths removed.
Below is the the instruction that describes the task: ### Input: Checks the validity of the load_path, returns a sanitized version with invalid paths removed. ### Response: def _check_load_paths(load_path): ''' Checks the validity of the load_path, returns a sanitized version with invalid paths rem...
def stem(self, words): """ Use the porter stemmer to generate consistent forms of words, e.g.:: from walrus.search.utils import PorterStemmer stemmer = PorterStemmer() for word in ['faith', 'faiths', 'faithful']: print s.stem(word, 0, len(word...
Use the porter stemmer to generate consistent forms of words, e.g.:: from walrus.search.utils import PorterStemmer stemmer = PorterStemmer() for word in ['faith', 'faiths', 'faithful']: print s.stem(word, 0, len(word) - 1) # Prints: #...
Below is the the instruction that describes the task: ### Input: Use the porter stemmer to generate consistent forms of words, e.g.:: from walrus.search.utils import PorterStemmer stemmer = PorterStemmer() for word in ['faith', 'faiths', 'faithful']: prin...
def _stat(self, axis=None, func=None, name=None, keepdims=False): """ Compute a statistic over an axis. Can provide either a function (for use in a reduce) or a name (for use by a stat counter). Parameters ---------- axis : tuple or int, optional, default=None ...
Compute a statistic over an axis. Can provide either a function (for use in a reduce) or a name (for use by a stat counter). Parameters ---------- axis : tuple or int, optional, default=None Axis to compute statistic over, if None will compute over all a...
Below is the the instruction that describes the task: ### Input: Compute a statistic over an axis. Can provide either a function (for use in a reduce) or a name (for use by a stat counter). Parameters ---------- axis : tuple or int, optional, default=None Axis t...
def close(self, force=False): """This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the ch...
This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGINT).
Below is the the instruction that describes the task: ### Input: This closes the connection with the child application. Note that calling close() more than once is valid. This emulates standard Python behavior with files. Set force to True if you want to make sure that the child is terminate...
def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ''' ret = {} status, result = _query(action='meta', command='fields') root = ET.fromstring(result) fields = root.getchildren() for field in fields: ...
Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields
Below is the the instruction that describes the task: ### Input: Show all meta data fields for this company. CLI Example: salt myminion bamboohr.list_meta_fields ### Response: def list_meta_fields(): ''' Show all meta data fields for this company. CLI Example: salt myminion bamb...