code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def create_network(batch_size, update_freq): """Create a linear regression network for performing SVRG optimization. Parameters ---------- batch_size: int Size of data split update_freq: int Update Frequency for calculating full gradients Returns ---------- di: mx.io.NDA...
Create a linear regression network for performing SVRG optimization. Parameters ---------- batch_size: int Size of data split update_freq: int Update Frequency for calculating full gradients Returns ---------- di: mx.io.NDArrayIter Data iterator update_freq: SVRG...
Below is the the instruction that describes the task: ### Input: Create a linear regression network for performing SVRG optimization. Parameters ---------- batch_size: int Size of data split update_freq: int Update Frequency for calculating full gradients Returns ---------- ...
def _rotated_files(path): """Generator. Yields the next rotated file as a tuple: (path, rotation_id) """ for globbed_path in iglob(path + FILE_NAME_GLOB): match = re.search(FILE_NAME_REGEX, globbed_path) if match: yield globbed_path, int(match.group('rotation_id'))
Generator. Yields the next rotated file as a tuple: (path, rotation_id)
Below is the the instruction that describes the task: ### Input: Generator. Yields the next rotated file as a tuple: (path, rotation_id) ### Response: def _rotated_files(path): """Generator. Yields the next rotated file as a tuple: (path, rotation_id) """ for globbed_path in iglob(path + FILE_N...
def md( self, url, width="original"): """*generate a multimarkdown image link viewable anywhere (no sign-in needed for private photos)* **Key Arguments:** - ``url`` -- the share URL for the flickr image (or just the unique photoid) - ``width`...
*generate a multimarkdown image link viewable anywhere (no sign-in needed for private photos)* **Key Arguments:** - ``url`` -- the share URL for the flickr image (or just the unique photoid) - ``width`` -- the pixel width of the fully resolved image. Default *original*. [75, 100, 150, ...
Below is the the instruction that describes the task: ### Input: *generate a multimarkdown image link viewable anywhere (no sign-in needed for private photos)* **Key Arguments:** - ``url`` -- the share URL for the flickr image (or just the unique photoid) - ``width`` -- the pixel w...
def get_reversed_statuses(context): """Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings. """ _rev = {v: k for k, v in STATUSES.items()} _rev.updat...
Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings.
Below is the the instruction that describes the task: ### Input: Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings. ### Response: def get_reversed_statuses(con...
def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True): """Predict the location of a robot given wirelss signal strength readings.""" try:import pods except ImportError: print('pods unavailable, see https://github.com/sods/ods for example datasets') return data = pods.d...
Predict the location of a robot given wirelss signal strength readings.
Below is the the instruction that describes the task: ### Input: Predict the location of a robot given wirelss signal strength readings. ### Response: def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True): """Predict the location of a robot given wirelss signal strength readings.""" try:...
def fix_simple_errors(self): ''' This attempts to fix the easy errors raised by ValidationError. This includes removing items from the cart that are no longer available, recalculating all of the discounts, and removing voucher codes that are no longer available. ''' # Fix vouche...
This attempts to fix the easy errors raised by ValidationError. This includes removing items from the cart that are no longer available, recalculating all of the discounts, and removing voucher codes that are no longer available.
Below is the the instruction that describes the task: ### Input: This attempts to fix the easy errors raised by ValidationError. This includes removing items from the cart that are no longer available, recalculating all of the discounts, and removing voucher codes that are no longer availabl...
def audioread(filename): """Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal """ try: if '.wav' in filename.lower(): ...
Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal
Below is the the instruction that describes the task: ### Input: Reads an audio signal from file. Supported formats : wav :param filename: filename of the audiofile to load :type filename: str :returns: int, numpy.ndarray -- samplerate, array containing the audio signal ### Response: def audiorea...
def sortByNamespacePrefix(urisList, nsList): """ Given an ordered list of namespaces prefixes, order a list of uris based on that. Eg In [7]: ll Out[7]: [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef(u'printGenericTreeorg...
Given an ordered list of namespaces prefixes, order a list of uris based on that. Eg In [7]: ll Out[7]: [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef(u'printGenericTreeorg/2000/01/rdf-schema#comment'), rdflib.term.URIRef(u'...
Below is the the instruction that describes the task: ### Input: Given an ordered list of namespaces prefixes, order a list of uris based on that. Eg In [7]: ll Out[7]: [rdflib.term.URIRef(u'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.term.URIRef(u'printGeneri...
def adjust_contrast_gamma(arr, gamma): """ Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. dtype support:: * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: yes; tested (2) (3) * ``uint64``: yes; tested ...
Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. dtype support:: * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: yes; tested (2) (3) * ``uint64``: yes; tested (2) (3) (4) * ``int8``: limited; tested (2)...
Below is the the instruction that describes the task: ### Input: Adjust contrast by scaling each pixel value to ``255 * ((I_ij/255)**gamma)``. dtype support:: * ``uint8``: yes; fully tested (1) (2) (3) * ``uint16``: yes; tested (2) (3) * ``uint32``: yes; tested (2) (3) * ``uint...
def no_exception(on_exception, logger=None): """ 处理函数抛出异常的装饰器, ATT: on_exception必填 :param on_exception: 遇到异常时函数返回什么内容 """ def decorator(function): def wrapper(*args, **kwargs): try: result = function(*args, **kwargs) except Exception, e: ...
处理函数抛出异常的装饰器, ATT: on_exception必填 :param on_exception: 遇到异常时函数返回什么内容
Below is the the instruction that describes the task: ### Input: 处理函数抛出异常的装饰器, ATT: on_exception必填 :param on_exception: 遇到异常时函数返回什么内容 ### Response: def no_exception(on_exception, logger=None): """ 处理函数抛出异常的装饰器, ATT: on_exception必填 :param on_exception: 遇到异常时函数返回什么内容 """ def decorator(functi...
def signature(self, block_size=None): "Calculates signature for local file." kwargs = {} if block_size: kwargs['block_size'] = block_size return librsync.signature(open(self.path, 'rb'), **kwargs)
Calculates signature for local file.
Below is the the instruction that describes the task: ### Input: Calculates signature for local file. ### Response: def signature(self, block_size=None): "Calculates signature for local file." kwargs = {} if block_size: kwargs['block_size'] = block_size return librsync.s...
def from_string(locale, strict=True): """ Return an instance ``Locale`` corresponding to the string representation of a locale. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash char...
Return an instance ``Locale`` corresponding to the string representation of a locale. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash character ``-`` and a ISO 3166-1 alpha-2 code. @param...
Below is the the instruction that describes the task: ### Input: Return an instance ``Locale`` corresponding to the string representation of a locale. @param locale: a string representation of a locale, i.e., a ISO 639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash ...
def write(self, row, col, data, style=None): """ Write data to row, col of worksheet (ws) using the style information. Again, I'm wrapping this because you'll have to do it if you create large amounts of formatted entries in your spreadsheet (else Excel, but probably not...
Write data to row, col of worksheet (ws) using the style information. Again, I'm wrapping this because you'll have to do it if you create large amounts of formatted entries in your spreadsheet (else Excel, but probably not OOo will crash).
Below is the the instruction that describes the task: ### Input: Write data to row, col of worksheet (ws) using the style information. Again, I'm wrapping this because you'll have to do it if you create large amounts of formatted entries in your spreadsheet (else Excel, but probably...
def add_term(self, t): """Add a term to this section and set it's ownership. Should only be used on root level terms""" if t not in self.terms: if t.parent_term_lc == 'root': self.terms.append(t) self.doc.add_term(t, add_section=False) t.set_...
Add a term to this section and set it's ownership. Should only be used on root level terms
Below is the the instruction that describes the task: ### Input: Add a term to this section and set it's ownership. Should only be used on root level terms ### Response: def add_term(self, t): """Add a term to this section and set it's ownership. Should only be used on root level terms""" if t not ...
def lock_input_target_config_target_running_running(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") lock = ET.Element("lock") config = lock input = ET.SubElement(lock, "input") target = ET.SubElement(input, "target") config_target...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def lock_input_target_config_target_running_running(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") lock = ET.Element("lock") config = lock in...
def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs """ name = self._get_softmax_name() return self.get_layer(x, name)
:param x: A symbolic representation of the network input. :return: A symbolic representation of the probs
Below is the the instruction that describes the task: ### Input: :param x: A symbolic representation of the network input. :return: A symbolic representation of the probs ### Response: def get_probs(self, x): """ :param x: A symbolic representation of the network input. :return: A symbolic represen...
def parse_property(self, tup_tree): """ Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType; ...
Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType; #REQUIRED %ClassOrigin; ...
Below is the the instruction that describes the task: ### Input: Parse PROPERTY into a CIMProperty object. VAL is just the pcdata of the enclosed VALUE node. :: <!ELEMENT PROPERTY (QUALIFIER*, VALUE?)> <!ATTLIST PROPERTY %CIMName; %CIMType...
def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None): """ List users in group category. Returns a list of users in the group category. """ path = {} data = {} params = {} # REQUIRED - PATH - group_categor...
List users in group category. Returns a list of users in the group category.
Below is the the instruction that describes the task: ### Input: List users in group category. Returns a list of users in the group category. ### Response: def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None): """ List users in group category. ...
def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
bottom of the stator
Below is the the instruction that describes the task: ### Input: bottom of the stator ### Response: def mate_bottom(self): " bottom of the stator" return Mate(self, CoordSystem( origin=(0, 0, -self.length/2), xDir=(1, 0, 0), normal=(0, 0, -1) ))
def _two_point_interp(times, altitudes, horizon=0*u.deg): """ Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between ...
Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between altitudes : array of `~astropy.units.Quantity` Two altitu...
Below is the the instruction that describes the task: ### Input: Do linear interpolation between two ``altitudes`` at two ``times`` to determine the time where the altitude goes through zero. Parameters ---------- times : `~astropy.time.Time` Two times for linear interpolation between ...
def get_gfe(self, annotation, locus): """ creates GFE from a sequence annotation :param locus: The gene locus :type locus: ``str`` :param annotation: An sequence annotation object :type annotation: ``List`` :rtype: ``List`` Returns: The GFE ...
creates GFE from a sequence annotation :param locus: The gene locus :type locus: ``str`` :param annotation: An sequence annotation object :type annotation: ``List`` :rtype: ``List`` Returns: The GFE notation and the associated features in an array
Below is the the instruction that describes the task: ### Input: creates GFE from a sequence annotation :param locus: The gene locus :type locus: ``str`` :param annotation: An sequence annotation object :type annotation: ``List`` :rtype: ``List`` Returns: ...
def indexes_some(ol,value,*seqs): ''' from elist.elist import * ol = [1,'a',3,'a',4,'a',5] indexes_some(ol,'a',0,2) indexes_some(ol,'a',0,1) indexes_some(ol,'a',1,2) indexes_some(ol,'a',3,4) ''' seqs = list(seqs) length = ol.__len__() indexes =[] s...
from elist.elist import * ol = [1,'a',3,'a',4,'a',5] indexes_some(ol,'a',0,2) indexes_some(ol,'a',0,1) indexes_some(ol,'a',1,2) indexes_some(ol,'a',3,4)
Below is the the instruction that describes the task: ### Input: from elist.elist import * ol = [1,'a',3,'a',4,'a',5] indexes_some(ol,'a',0,2) indexes_some(ol,'a',0,1) indexes_some(ol,'a',1,2) indexes_some(ol,'a',3,4) ### Response: def indexes_some(ol,value,*seqs): ''' ...
def pending(self): ''' Returns an array of updates that are currently in the buffer for an individual social media profile. ''' pending_updates = [] url = PATHS['GET_PENDING'] % self.profile_id response = self.api.get(url=url) for update in response['updates']: pending_update...
Returns an array of updates that are currently in the buffer for an individual social media profile.
Below is the the instruction that describes the task: ### Input: Returns an array of updates that are currently in the buffer for an individual social media profile. ### Response: def pending(self): ''' Returns an array of updates that are currently in the buffer for an individual social medi...
def make_rpc_call(func_name, args=None, remote=None): """Performs an RPC function call (local or remote) with the given arguments. :param str|unicode func_name: RPC function name to call. :param Iterable args: Function arguments. :param str|unicode remote: :rtype: bytes|str :raises ValueErr...
Performs an RPC function call (local or remote) with the given arguments. :param str|unicode func_name: RPC function name to call. :param Iterable args: Function arguments. :param str|unicode remote: :rtype: bytes|str :raises ValueError: If unable to call RPC function.
Below is the the instruction that describes the task: ### Input: Performs an RPC function call (local or remote) with the given arguments. :param str|unicode func_name: RPC function name to call. :param Iterable args: Function arguments. :param str|unicode remote: :rtype: bytes|str :raises ...
def symm_block_tridiag_matmul(H_diag, H_upper_diag, v): """ Compute matrix-vector product with a symmetric block tridiagonal matrix H and vector v. :param H_diag: block diagonal terms of H :param H_upper_diag: upper block diagonal terms of H :param v: vector to multipl...
Compute matrix-vector product with a symmetric block tridiagonal matrix H and vector v. :param H_diag: block diagonal terms of H :param H_upper_diag: upper block diagonal terms of H :param v: vector to multiple :return: H * v
Below is the the instruction that describes the task: ### Input: Compute matrix-vector product with a symmetric block tridiagonal matrix H and vector v. :param H_diag: block diagonal terms of H :param H_upper_diag: upper block diagonal terms of H :param v: vector to multip...
def create_label(label_tuple, extra_label=None): """Return a label based on my_tuple (a,b) and extra label. a and b are string. The output will be something like: [a - b] extra_label """ if extra_label is not None: return '[' + ' - '.join(label_tuple) + '] ' + str(extra_lab...
Return a label based on my_tuple (a,b) and extra label. a and b are string. The output will be something like: [a - b] extra_label
Below is the the instruction that describes the task: ### Input: Return a label based on my_tuple (a,b) and extra label. a and b are string. The output will be something like: [a - b] extra_label ### Response: def create_label(label_tuple, extra_label=None): """Return a label based on...
def _call(self, path, method, body=None, headers=None): """ Wrapper around http.do_call that transforms some HTTPError into our own exceptions """ try: resp = self.http.do_call(path, method, body, headers) except http.HTTPError as err: if err.statu...
Wrapper around http.do_call that transforms some HTTPError into our own exceptions
Below is the the instruction that describes the task: ### Input: Wrapper around http.do_call that transforms some HTTPError into our own exceptions ### Response: def _call(self, path, method, body=None, headers=None): """ Wrapper around http.do_call that transforms some HTTPError into ...
def add_vcenter(self, **kwargs): """ Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function):...
Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter callback (function): A function executed upon completion of the ...
Below is the the instruction that describes the task: ### Input: Add vCenter on the switch Args: id(str) : Name of an established vCenter url (bool) : vCenter URL username (str): Username of the vCenter password (str): Password of the vCenter call...
def _convert_service_properties_to_xml(logging, hour_metrics, minute_metrics, cors, target_version=None, delete_retention_policy=None, static_website=None): ''' <?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>ver...
<?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> <RetentionPolicy> <Enabled>true|false</Enabl...
Below is the the instruction that describes the task: ### Input: <?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> ...
def query(method='servers', server_id=None, command=None, args=None, http_method='GET', root='api_root'): ''' Make a call to the Scaleway API. ''' if root == 'api_root': default_url = 'https://cp-par1.scaleway.com' else: default_url = 'https://api-marketplace.scaleway.com' ...
Make a call to the Scaleway API.
Below is the the instruction that describes the task: ### Input: Make a call to the Scaleway API. ### Response: def query(method='servers', server_id=None, command=None, args=None, http_method='GET', root='api_root'): ''' Make a call to the Scaleway API. ''' if root == 'api_root': de...
def _t_update_b(self): r""" A method to update 'b' array at each time step according to 't_scheme' and the source term value """ network = self.project.network phase = self.project.phases()[self.settings['phase']] Vi = network['pore.volume'] dt = self.sett...
r""" A method to update 'b' array at each time step according to 't_scheme' and the source term value
Below is the the instruction that describes the task: ### Input: r""" A method to update 'b' array at each time step according to 't_scheme' and the source term value ### Response: def _t_update_b(self): r""" A method to update 'b' array at each time step according to 't_sch...
def installFuncVersionedLib(target, source, env): """Install a versioned library into a target using the function specified as the INSTALLVERSIONEDLIB construction variable.""" try: install = env['INSTALLVERSIONEDLIB'] except KeyError: raise SCons.Errors.UserError('Missing INSTALLVERSION...
Install a versioned library into a target using the function specified as the INSTALLVERSIONEDLIB construction variable.
Below is the the instruction that describes the task: ### Input: Install a versioned library into a target using the function specified as the INSTALLVERSIONEDLIB construction variable. ### Response: def installFuncVersionedLib(target, source, env): """Install a versioned library into a target using the fu...
def _get_related_indicators_page_generator(self, indicators=None, enclave_ids=None, start_page=0, page_size=None): """ Creates a generator from the |get_related_indicators_page| method that returns each successive page. :param indicators: list of indicator values to search for :...
Creates a generator from the |get_related_indicators_page| method that returns each successive page. :param indicators: list of indicator values to search for :param enclave_ids: list of IDs of enclaves to search in :param start_page: The page to start on. :param page_size: The ...
Below is the the instruction that describes the task: ### Input: Creates a generator from the |get_related_indicators_page| method that returns each successive page. :param indicators: list of indicator values to search for :param enclave_ids: list of IDs of enclaves to search in :p...
def process_formdata(self, valuelist): """Join time string.""" if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format) self.data = datetime.time(*timetuple[3:6]) except ValueError: ...
Join time string.
Below is the the instruction that describes the task: ### Input: Join time string. ### Response: def process_formdata(self, valuelist): """Join time string.""" if valuelist: time_str = u' '.join(valuelist) try: timetuple = time.strptime(time_str, self.format)...
def write(self, oprot): ''' Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration ''' oprot.write_struc...
Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration
Below is the the instruction that describes the task: ### Input: Write this object to the given output protocol and return self. :type oprot: thryft.protocol._output_protocol._OutputProtocol :rtype: pastpy.gen.database.impl.dummy.dummy_database_configuration.DummyDatabaseConfiguration ### Response:...
def enroll(self, uuid, organization, from_date=MIN_PERIOD_DATE, to_date=MAX_PERIOD_DATE, merge=False): """Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exi...
Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before creating the new enrollment. The period of the enrollment can be given with the parame...
Below is the the instruction that describes the task: ### Input: Enroll a unique identity in an organization. This method adds a new relationship between the unique identity, identified by <uuid>, and <organization>. Both entities must exist on the registry before creating the new enrollmen...
def array2ntpl(arr): """ Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by :func:`ntpl2array` Returns ...
Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by :func:`ntpl2array` Returns ------- ntpl : collections.n...
Below is the the instruction that describes the task: ### Input: Convert a :class:`numpy.ndarray` object constructed by :func:`ntpl2array` back to the original :func:`collections.namedtuple` representation. Parameters ---------- arr : ndarray Array representation of named tuple constructed by...
def serialize(self): ''' Return a JSON string of the serialized topology ''' return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
Return a JSON string of the serialized topology
Below is the the instruction that describes the task: ### Input: Return a JSON string of the serialized topology ### Response: def serialize(self): ''' Return a JSON string of the serialized topology ''' return json.dumps(json_graph.node_link_data(self.__nxgraph), cls=Encoder)
def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs): """Produce a list of upgrade statements.""" if metadata is None: # Note, all SQLAlchemy models must have been loaded to produce # accurate results. metadata = db....
Produce a list of upgrade statements.
Below is the the instruction that describes the task: ### Input: Produce a list of upgrade statements. ### Response: def produce_upgrade_operations( ctx=None, metadata=None, include_symbol=None, include_object=None, **kwargs): """Produce a list of upgrade statements.""" if metadata is None:...
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): """start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner """ print '%s call joinCommissioned' % self.port se...
start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner
Below is the the instruction that describes the task: ### Input: start joiner Args: strPSKd: Joiner's PSKd Returns: True: successful to start joiner False: fail to start joiner ### Response: def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20): ...
def _load(self, exit_on_failure): """One you have added all your configuration data (Section, Element, ...) you need to load data from the config file.""" # pylint: disable-msg=W0621 log = logging.getLogger('argtoolbox') discoveredFileList = [] if self.config_file: ...
One you have added all your configuration data (Section, Element, ...) you need to load data from the config file.
Below is the the instruction that describes the task: ### Input: One you have added all your configuration data (Section, Element, ...) you need to load data from the config file. ### Response: def _load(self, exit_on_failure): """One you have added all your configuration data (Section, Element, ...
def shadow_reference(self, dispatcher, node): """ Only simply make a reference to the value in the current scope, specifically for the FuncBase type. """ # as opposed to the previous one, only add the value of the # identifier itself to the scope so that it becomes reser...
Only simply make a reference to the value in the current scope, specifically for the FuncBase type.
Below is the the instruction that describes the task: ### Input: Only simply make a reference to the value in the current scope, specifically for the FuncBase type. ### Response: def shadow_reference(self, dispatcher, node): """ Only simply make a reference to the value in the current scope...
def cpp_app_builder(build_context, target): """Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed. """ yprint(build_context.conf, 'Build CppApp...
Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed.
Below is the the instruction that describes the task: ### Input: Pack a C++ binary as a Docker image with its runtime dependencies. TODO(itamar): Dynamically analyze the binary and copy shared objects from its buildenv image to the runtime image, unless they're installed. ### Response: def cpp_app_builder...
def _element_get_id(self, element): """Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute depending on the level. """ if self._reader._level > 1: entry_id = element.get('id') else: ...
Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute depending on the level.
Below is the the instruction that describes the task: ### Input: Get id of reaction or species element. In old levels the name is used as the id. This method returns the correct attribute depending on the level. ### Response: def _element_get_id(self, element): """Get id of reaction or spe...
def _hash_url(self, url): """ Hash the URL to an md5sum. """ if isinstance(url, six.text_type): url = url.encode('utf-8') return hashlib.md5(url).hexdigest()
Hash the URL to an md5sum.
Below is the the instruction that describes the task: ### Input: Hash the URL to an md5sum. ### Response: def _hash_url(self, url): """ Hash the URL to an md5sum. """ if isinstance(url, six.text_type): url = url.encode('utf-8') return hashlib.md5(url).hexdigest...
def getinputfile(self, outputfile, loadmetadata=True, client=None,requiremetadata=False): """Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()""" if isinstance(ou...
Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles()
Below is the the instruction that describes the task: ### Input: Grabs one input file for the specified output filename (raises a KeyError exception if there is no such output, StopIteration if there are no input files for it). Shortcut for getinputfiles() ### Response: def getinputfile(self, outputfile, loadmetad...
def get_query(self, q, request): """ return a query set searching for the query string q either implement this method yourself or set the search_field in the LookupChannel class definition """ return Group.objects.filter( Q(name__icontains=q) | Q(d...
return a query set searching for the query string q either implement this method yourself or set the search_field in the LookupChannel class definition
Below is the the instruction that describes the task: ### Input: return a query set searching for the query string q either implement this method yourself or set the search_field in the LookupChannel class definition ### Response: def get_query(self, q, request): """ return a query ...
def check_archs(copied_libs, require_archs=(), stop_fast=False): """ Check compatibility of archs in `copied_libs` dict Parameters ---------- copied_libs : dict dict containing the (key, value) pairs of (``copied_lib_path``, ``dependings_dict``), where ``copied_lib_path`` is a library r...
Check compatibility of archs in `copied_libs` dict Parameters ---------- copied_libs : dict dict containing the (key, value) pairs of (``copied_lib_path``, ``dependings_dict``), where ``copied_lib_path`` is a library real path that has been copied during delocation, and ``dependings...
Below is the the instruction that describes the task: ### Input: Check compatibility of archs in `copied_libs` dict Parameters ---------- copied_libs : dict dict containing the (key, value) pairs of (``copied_lib_path``, ``dependings_dict``), where ``copied_lib_path`` is a library real ...
def concrete_descendents(parentclass): """ Return a dictionary containing all subclasses of the specified parentclass, including the parentclass. Only classes that are defined in scripts that have been run or modules that have been imported are included, so the caller will usually first do ``from ...
Return a dictionary containing all subclasses of the specified parentclass, including the parentclass. Only classes that are defined in scripts that have been run or modules that have been imported are included, so the caller will usually first do ``from package import *``. Only non-abstract class...
Below is the the instruction that describes the task: ### Input: Return a dictionary containing all subclasses of the specified parentclass, including the parentclass. Only classes that are defined in scripts that have been run or modules that have been imported are included, so the caller will usually...
def tags(self): """Returns a dictionary that lists all available tags that can be used for further filtering """ ret = {} for typ in _meta_fields_twig: if typ in ['uniqueid', 'plugin', 'feedback', 'fitting', 'history', 'twig', 'uniquetwig']: continue ...
Returns a dictionary that lists all available tags that can be used for further filtering
Below is the the instruction that describes the task: ### Input: Returns a dictionary that lists all available tags that can be used for further filtering ### Response: def tags(self): """Returns a dictionary that lists all available tags that can be used for further filtering """ ...
def set_connection_ip_list(addresses=None, grant_by_default=False, server=_DEFAULT_SERVER): ''' Set the IPGrant list for the SMTP virtual server. :param str addresses: A dictionary of IP + subnet pairs. :param bool grant_by_default: Whether the addresses should be a blacklist or whitelist. :param s...
Set the IPGrant list for the SMTP virtual server. :param str addresses: A dictionary of IP + subnet pairs. :param bool grant_by_default: Whether the addresses should be a blacklist or whitelist. :param str server: The SMTP server name. :return: A boolean representing whether the change succeeded. ...
Below is the the instruction that describes the task: ### Input: Set the IPGrant list for the SMTP virtual server. :param str addresses: A dictionary of IP + subnet pairs. :param bool grant_by_default: Whether the addresses should be a blacklist or whitelist. :param str server: The SMTP server name. ...
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instan...
Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance
Below is the the instruction that describes the task: ### Input: Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance ### Response: def manipulate(self, stored_instance, component_instance): """ ...
def decodeString(encoded): ''' Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed ''' length = encoded[0]*256 + encoded[1] return (encoded[2:2+length].decode('utf-8'), encoded[2+length:])
Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed
Below is the the instruction that describes the task: ### Input: Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the decoded string and renaining bytearray to be parsed ### Response: def decodeString(encoded): ''' Decodes an UTF-8 string from an encoded MQTT bytearray. Returns the d...
def write(self, text, color): """ Write the given text to the stream in the given color. """ color = self._colors[color] self.stream.write('\x1b[{}m{}\x1b[0m'.format(color, text))
Write the given text to the stream in the given color.
Below is the the instruction that describes the task: ### Input: Write the given text to the stream in the given color. ### Response: def write(self, text, color): """ Write the given text to the stream in the given color. """ color = self._colors[color] self.stream.write('\...
def operations_map(self): # type: () -> Dict[Union[str, None], str] """ returns a Mapping of operation names and it's associated types. E.g. {'myQuery': 'query', 'myMutation': 'mutation'} """ document_ast = self.document_ast operations = {} # type: Dict[Union[str...
returns a Mapping of operation names and it's associated types. E.g. {'myQuery': 'query', 'myMutation': 'mutation'}
Below is the the instruction that describes the task: ### Input: returns a Mapping of operation names and it's associated types. E.g. {'myQuery': 'query', 'myMutation': 'mutation'} ### Response: def operations_map(self): # type: () -> Dict[Union[str, None], str] """ returns a Mappin...
def authorize(self, ctx, identity, ops): '''Implements Authorizer.authorize by calling f with the given identity for each operation. ''' allowed = [] caveats = [] for op in ops: ok, fcaveats = self._f(ctx, identity, op) allowed.append(ok) ...
Implements Authorizer.authorize by calling f with the given identity for each operation.
Below is the the instruction that describes the task: ### Input: Implements Authorizer.authorize by calling f with the given identity for each operation. ### Response: def authorize(self, ctx, identity, ops): '''Implements Authorizer.authorize by calling f with the given identity for each o...
def scientificformat(value, fmt='%13.9E', sep=' ', sep2=':'): """ :param value: the value to convert into a string :param fmt: the formatting string to use for float values :param sep: separator to use for vector-like values :param sep2: second separator to use for matrix-like values Convert a ...
:param value: the value to convert into a string :param fmt: the formatting string to use for float values :param sep: separator to use for vector-like values :param sep2: second separator to use for matrix-like values Convert a float or an array into a string by using the scientific notation and a...
Below is the the instruction that describes the task: ### Input: :param value: the value to convert into a string :param fmt: the formatting string to use for float values :param sep: separator to use for vector-like values :param sep2: second separator to use for matrix-like values Convert a float...
def SwitchToAlert(): ''' <input value="Test" type="button" onClick="alert('OK')" > ''' try: alert = WebDriverWait(Web.driver, 10).until(lambda driver: driver.switch_to_alert()) return alert except: print("Waring: Time...
<input value="Test" type="button" onClick="alert('OK')" >
Below is the the instruction that describes the task: ### Input: <input value="Test" type="button" onClick="alert('OK')" > ### Response: def SwitchToAlert(): ''' <input value="Test" type="button" onClick="alert('OK')" > ''' try: alert = WebDriverWait(Web.driver, 10).unti...
def get_fields_in_model(instance): """ Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The...
Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: Model :return: The list of fields for the given model (instance) ...
Below is the the instruction that describes the task: ### Input: Returns the list of fields in the given model instance. Checks whether to use the official _meta API or use the raw data. This method excludes many to many fields. :param instance: The model instance to get the fields for :type instance: ...
def delete_value(self, label=None): """Delete the labelled value (or all values) on this Point Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#I...
Delete the labelled value (or all values) on this Point Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException) ...
Below is the the instruction that describes the task: ### Input: Delete the labelled value (or all values) on this Point Raises [IOTException](./Exceptions.m.html#IoticAgent.IOT.Exceptions.IOTException) containing the error if the infrastructure detects a problem Raises [LinkException](../...
def add_product_error(self, product, error): ''' Adds an error to the given product's field ''' ''' if product in field_names: field = field_names[product] elif isinstance(product, inventory.Product): return else: field = None ''' self.add_er...
Adds an error to the given product's field
Below is the the instruction that describes the task: ### Input: Adds an error to the given product's field ### Response: def add_product_error(self, product, error): ''' Adds an error to the given product's field ''' ''' if product in field_names: field = field_names[product] ...
def loadBWT(bwtDir, logger=None): ''' Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neith...
Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated
Below is the the instruction that describes the task: ### Input: Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression and assign the appropriate class preferring the decompressed version if both exist. @return - a MultiStringBWT, Compress...
def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, n_cations, balance_error, method): '''Helper method for balance_ions for the proportional family of methods. See balance_ions for a description of the methods; parameters are fairly obvious. ''' ...
Helper method for balance_ions for the proportional family of methods. See balance_ions for a description of the methods; parameters are fairly obvious.
Below is the the instruction that describes the task: ### Input: Helper method for balance_ions for the proportional family of methods. See balance_ions for a description of the methods; parameters are fairly obvious. ### Response: def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, ...
def serialize(self, obj, level=0, objname=None, topLevelKeysToIgnore=None, toBytes=True): """ Create a string representation of the given object. Examples: :: >>> serialize("str") 'str' >>> serialize([1,2,3,4,5]) '1,2,3,4,5' >>> ...
Create a string representation of the given object. Examples: :: >>> serialize("str") 'str' >>> serialize([1,2,3,4,5]) '1,2,3,4,5' >>> signing.serlize({1:'a', 2:'b'}) '1:a|2:b' >>> signing.serlize({1:'a', 2:'b', 3:[1,{2:'k'}]}) '1:a|2:b|3:...
Below is the the instruction that describes the task: ### Input: Create a string representation of the given object. Examples: :: >>> serialize("str") 'str' >>> serialize([1,2,3,4,5]) '1,2,3,4,5' >>> signing.serlize({1:'a', 2:'b'}) '1:a|2:b' >...
def new_mapper(agent): """Creates a mapper object on witch add_mapping() and remove_mapping() can be called. It uses fire-and-forget notifications so it has a very low overhead and latency but a little less guarantees.""" recp = recipient.Broadcast(MappingUpdatesPoster.protocol_id, 'lobby') return a...
Creates a mapper object on witch add_mapping() and remove_mapping() can be called. It uses fire-and-forget notifications so it has a very low overhead and latency but a little less guarantees.
Below is the the instruction that describes the task: ### Input: Creates a mapper object on witch add_mapping() and remove_mapping() can be called. It uses fire-and-forget notifications so it has a very low overhead and latency but a little less guarantees. ### Response: def new_mapper(agent): """Creat...
def parse(self, parser): """Main method to render data into the template.""" lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): parser.stream.skip(1) short = parser.parse_expression() else: short = nodes.Const(False) ...
Main method to render data into the template.
Below is the the instruction that describes the task: ### Input: Main method to render data into the template. ### Response: def parse(self, parser): """Main method to render data into the template.""" lineno = next(parser.stream).lineno if parser.stream.skip_if('name:short'): ...
def _to_dict(self): ''' Returns a dictionary representation of this object ''' return dict(area= self.area._to_dict(), earthquakes = [q._to_dict() for q in self.earthquakes], title = self.title)
Returns a dictionary representation of this object
Below is the the instruction that describes the task: ### Input: Returns a dictionary representation of this object ### Response: def _to_dict(self): ''' Returns a dictionary representation of this object ''' return dict(area= self.area._to_dict(), earthquakes = [q._to_dict() fo...
def install_dap_from_path(path, update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Installs a dap from a given path''' will_uninstall = False dap_obj = dapi.Dap(path) name = dap_obj.meta['package_name'] if name in ge...
Installs a dap from a given path
Below is the the instruction that describes the task: ### Input: Installs a dap from a given path ### Response: def install_dap_from_path(path, update=False, update_allpaths=False, first=True, force=False, nodeps=False, reinstall=False, __ui__=''): '''Installs a dap from a given path'...
def convert(pinyin, style, strict, default=None, **kwargs): """根据拼音风格把原始拼音转换为不同的格式 :param pinyin: 原始有声调的单个拼音 :type pinyin: unicode :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict` :type strict: bool :param default: 拼音风格对应的实现不存在时返回的默认值 :return: 按照拼音风格进行处理过后的拼音字符串...
根据拼音风格把原始拼音转换为不同的格式 :param pinyin: 原始有声调的单个拼音 :type pinyin: unicode :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict` :type strict: bool :param default: 拼音风格对应的实现不存在时返回的默认值 :return: 按照拼音风格进行处理过后的拼音字符串 :rtype: unicode
Below is the the instruction that describes the task: ### Input: 根据拼音风格把原始拼音转换为不同的格式 :param pinyin: 原始有声调的单个拼音 :type pinyin: unicode :param style: 拼音风格 :param strict: 是否严格遵照《汉语拼音方案》来处理声母和韵母,详见 :ref:`strict` :type strict: bool :param default: 拼音风格对应的实现不存在时返回的默认值 :return: 按照拼音风格进行处理过后的拼音字...
def btc_tx_serialize(_txobj): """ Given a transaction dict returned by btc_tx_deserialize, convert it back into a hex-encoded byte string. Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools) """ # output buffer o = [] txobj = ...
Given a transaction dict returned by btc_tx_deserialize, convert it back into a hex-encoded byte string. Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools)
Below is the the instruction that describes the task: ### Input: Given a transaction dict returned by btc_tx_deserialize, convert it back into a hex-encoded byte string. Derived from code written by Vitalik Buterin in pybitcointools (https://github.com/vbuterin/pybitcointools) ### Response: def btc_tx_ser...
def _connect(self): """Connect to Squid Proxy Manager interface.""" if sys.version_info[:2] < (2,6): self._conn = httplib.HTTPConnection(self._host, self._port) else: self._conn = httplib.HTTPConnection(self._host, self._port, ...
Connect to Squid Proxy Manager interface.
Below is the the instruction that describes the task: ### Input: Connect to Squid Proxy Manager interface. ### Response: def _connect(self): """Connect to Squid Proxy Manager interface.""" if sys.version_info[:2] < (2,6): self._conn = httplib.HTTPConnection(self._host, self._port) ...
def find_invalid_chars(self, text, context_size=20): """Find invalid characters in text and store information about the findings. Parameters ---------- context_size: int How many characters to return as the context. """ result = defaultdict(list) ...
Find invalid characters in text and store information about the findings. Parameters ---------- context_size: int How many characters to return as the context.
Below is the the instruction that describes the task: ### Input: Find invalid characters in text and store information about the findings. Parameters ---------- context_size: int How many characters to return as the context. ### Response: def find_invalid_chars(self, te...
def function(self, x, y, amp, R_sersic, Re, n_sersic, gamma, e1, e2, center_x=0, center_y=0, alpha=3.): """ returns Core-Sersic function """ phi_G, q = param_util.ellipticity2phi_q(e1, e2) Rb = R_sersic x_shift = x - center_x y_shift = y - center_y cos_ph...
returns Core-Sersic function
Below is the the instruction that describes the task: ### Input: returns Core-Sersic function ### Response: def function(self, x, y, amp, R_sersic, Re, n_sersic, gamma, e1, e2, center_x=0, center_y=0, alpha=3.): """ returns Core-Sersic function """ phi_G, q = param_util.ellipticity2...
def _wait_for_file(cls, filename, timeout=FAIL_WAIT_SEC, want_content=True): """Wait up to timeout seconds for filename to appear with a non-zero size or raise Timeout().""" def file_waiter(): return os.path.exists(filename) and (not want_content or os.path.getsize(filename)) action_msg = 'file {} to...
Wait up to timeout seconds for filename to appear with a non-zero size or raise Timeout().
Below is the the instruction that describes the task: ### Input: Wait up to timeout seconds for filename to appear with a non-zero size or raise Timeout(). ### Response: def _wait_for_file(cls, filename, timeout=FAIL_WAIT_SEC, want_content=True): """Wait up to timeout seconds for filename to appear with a non-...
def resetn(self): """ reset a core. After a call to this function, the core is running """ #Regular reset will kick NRF out of DBG mode logging.debug("target_nrf51.reset: enable reset pin") self.write_memory(RESET, RESET_ENABLE) #reset logging.debu...
reset a core. After a call to this function, the core is running
Below is the the instruction that describes the task: ### Input: reset a core. After a call to this function, the core is running ### Response: def resetn(self): """ reset a core. After a call to this function, the core is running """ #Regular reset will kick NRF out...
def det4D(m): ''' det4D(array) yields the determinate of the given matrix array, which may have more than 2 dimensions, in which case the later dimensions are multiplied and added point-wise. ''' # I just solved this in Mathematica, copy-pasted, and replaced the string '] m' with ']*m': # Math...
det4D(array) yields the determinate of the given matrix array, which may have more than 2 dimensions, in which case the later dimensions are multiplied and added point-wise.
Below is the the instruction that describes the task: ### Input: det4D(array) yields the determinate of the given matrix array, which may have more than 2 dimensions, in which case the later dimensions are multiplied and added point-wise. ### Response: def det4D(m): ''' det4D(array) yields the determ...
def start_service(self, stack, service): """启动服务 启动指定名称服务的所有容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} -...
启动服务 启动指定名称服务的所有容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
Below is the the instruction that describes the task: ### Input: 启动服务 启动指定名称服务的所有容器。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回空dict{},失败返回{"error": "<errMsg string...
def _rgb_triangle(ax, r_label, g_label, b_label, loc): """ Draw an RGB triangle legend on the desired axis """ if not loc in range(1, 11): loc = 2 from mpl_toolkits.axes_grid1.inset_locator import inset_axes inset_ax = inset_axes(ax, width=1, height=1, loc=lo...
Draw an RGB triangle legend on the desired axis
Below is the the instruction that describes the task: ### Input: Draw an RGB triangle legend on the desired axis ### Response: def _rgb_triangle(ax, r_label, g_label, b_label, loc): """ Draw an RGB triangle legend on the desired axis """ if not loc in range(1, 11): loc =...
def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match """ # andreikop: This check is not described in kate docs, and I haven't found it in the code if not textToMatchObject.isWordStart: ...
Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match
Below is the the instruction that describes the task: ### Input: Try to find themselves in the text. Returns (count, matchedRule) or (None, None) if doesn't match ### Response: def _tryMatch(self, textToMatchObject): """Try to find themselves in the text. Returns (count, matchedRule) or (No...
def enter_command_mode(self): """ Go into command mode. """ self.application.layout.focus(self.command_buffer) self.application.vi_state.input_mode = InputMode.INSERT self.previewer.save()
Go into command mode.
Below is the the instruction that describes the task: ### Input: Go into command mode. ### Response: def enter_command_mode(self): """ Go into command mode. """ self.application.layout.focus(self.command_buffer) self.application.vi_state.input_mode = InputMode.INSERT ...
def new(cls, ns_path, script, campaign_dir, runner_type='Auto', overwrite=False, optimized=True, check_repo=True): """ Create a new campaign from an ns-3 installation and a campaign directory. This method will create a DatabaseManager, which will install a database i...
Create a new campaign from an ns-3 installation and a campaign directory. This method will create a DatabaseManager, which will install a database in the specified campaign_dir. If a database is already available at the ns_path described in the specified campaign_dir and its con...
Below is the the instruction that describes the task: ### Input: Create a new campaign from an ns-3 installation and a campaign directory. This method will create a DatabaseManager, which will install a database in the specified campaign_dir. If a database is already available at th...
def teardown_app_request(self, func: Callable) -> Callable: """Add a teardown request function to the app. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_request`. It applies to all requests to the app this blueprint is registered ...
Add a teardown request function to the app. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_request`. It applies to all requests to the app this blueprint is registered on. An example usage, .. code-block:: python ...
Below is the the instruction that describes the task: ### Input: Add a teardown request function to the app. This is designed to be used as a decorator, and has the same arguments as :meth:`~quart.Quart.teardown_request`. It applies to all requests to the app this blueprint is registered on...
def to_dict(x, depth, exclude_keys=set(), depth_threshold=8): """Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int...
Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int, bool, None values. This is a recursive function so by defa...
Below is the the instruction that describes the task: ### Input: Transform a nested object/dict/list into a regular dict json.dump(s) and pickle don't like to un/serialize regular Python objects so this function should handle arbitrarily nested objects to be serialized to regular string, float, int...
def _float_or_str(value): """Internal method to attempt `float(value)` handling a `ValueError` """ # remove any surrounding quotes value = QUOTE_REGEX.sub('', value) try: # attempt `float()` conversion return float(value) except ValueError: # just return the input return value
Internal method to attempt `float(value)` handling a `ValueError`
Below is the the instruction that describes the task: ### Input: Internal method to attempt `float(value)` handling a `ValueError` ### Response: def _float_or_str(value): """Internal method to attempt `float(value)` handling a `ValueError` """ # remove any surrounding quotes value = QUOTE_REGEX.sub...
def unquote(value): """Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped """ if len(value) > 1 and valu...
Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unescaped
Below is the the instruction that describes the task: ### Input: Remove wrapping quotes from a string. :param value: A string that might be wrapped in double quotes, such as a HTTP cookie value. :returns: Beginning and ending quotes removed and escaped quotes (``\"``) unesca...
def parse_list_objects(data, bucket_name): """ Parser for list objects response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Replies back three distinctive components. - List of :class:`Object <Object>` - True if list is truncated...
Parser for list objects response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Replies back three distinctive components. - List of :class:`Object <Object>` - True if list is truncated, False otherwise. - Object name marker for the ...
Below is the the instruction that describes the task: ### Input: Parser for list objects response. :param data: Response data for list objects. :param bucket_name: Response for the bucket. :return: Replies back three distinctive components. - List of :class:`Object <Object>` - True if lis...
def change_password(self, body, username=None, params=None): """ `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :ar...
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :arg refresh: If `true` (the default) then refresh the affected shards t...
Below is the the instruction that describes the task: ### Input: `<https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-change-password.html>`_ :arg body: the new password for the user :arg username: The username of the user to change the password for :arg refresh: I...
def sext(self, num): """Sign-extend this farray by *num* bits. Returns a new farray. """ sign = self._items[-1] return self.__class__(self._items + [sign] * num, ftype=self.ftype)
Sign-extend this farray by *num* bits. Returns a new farray.
Below is the the instruction that describes the task: ### Input: Sign-extend this farray by *num* bits. Returns a new farray. ### Response: def sext(self, num): """Sign-extend this farray by *num* bits. Returns a new farray. """ sign = self._items[-1] return self._...
def copy_data(self): """ Copy the data from the it's point of origin, serializing it, storing it serialized as well as in it's raw form and calculate a running hash of the serialized representation """ HASH_FUNCTION = hashlib.sha256() try: raw_iterato...
Copy the data from the it's point of origin, serializing it, storing it serialized as well as in it's raw form and calculate a running hash of the serialized representation
Below is the the instruction that describes the task: ### Input: Copy the data from the it's point of origin, serializing it, storing it serialized as well as in it's raw form and calculate a running hash of the serialized representation ### Response: def copy_data(self): """ Copy t...
def get_server_certificate(server_certificate, flags=FLAGS.BASE, **conn): """ Orchestrates all the calls required to fully build out an IAM User in the following format: { "Arn": ..., "ServerCertificateName": ..., "Path": ..., "ServerCertificateId": ..., "UploadDate"...
Orchestrates all the calls required to fully build out an IAM User in the following format: { "Arn": ..., "ServerCertificateName": ..., "Path": ..., "ServerCertificateId": ..., "UploadDate": ..., # str "Expiration": ..., # str "CertificateBody": ..., ...
Below is the the instruction that describes the task: ### Input: Orchestrates all the calls required to fully build out an IAM User in the following format: { "Arn": ..., "ServerCertificateName": ..., "Path": ..., "ServerCertificateId": ..., "UploadDate": ..., # str ...
def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve1(annot) if annot.get('Rect') is not None: annot['bbox'] = annot.pop('Rect') # Rena...
Adds annotations to the layout object
Below is the the instruction that describes the task: ### Input: Adds annotations to the layout object ### Response: def _add_annots(self, layout, annots): """Adds annotations to the layout object """ if annots: for annot in resolve1(annots): annot = resolve...
def build_component(res, parent=None): "Create a gui2py control based on the python resource" # control specs (parameters) kwargs = dict(res.items()) comtype = kwargs.pop('type') if 'components' in res: components = kwargs.pop('components') elif comtype == 'Menu' and 'items' in res: ...
Create a gui2py control based on the python resource
Below is the the instruction that describes the task: ### Input: Create a gui2py control based on the python resource ### Response: def build_component(res, parent=None): "Create a gui2py control based on the python resource" # control specs (parameters) kwargs = dict(res.items()) comtype = kwargs....
def page_length(self, length): '''Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than ...
Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError: Length must be less than 12000.
Below is the the instruction that describes the task: ### Input: Specifies page length. This command is only valid with continuous length labels. Args: length: The length of the page, in dots. Can't exceed 12000. Returns: None Raises: RuntimeError...
def get_dot(stop=True): """Returns a string containing a DOT file. Setting stop to True will cause the trace to stop. """ defaults = [] nodes = [] edges = [] # define default attributes for comp, comp_attr in graph_attributes.items(): attr = ', '.join( '%s = "%s"' % (attr...
Returns a string containing a DOT file. Setting stop to True will cause the trace to stop.
Below is the the instruction that describes the task: ### Input: Returns a string containing a DOT file. Setting stop to True will cause the trace to stop. ### Response: def get_dot(stop=True): """Returns a string containing a DOT file. Setting stop to True will cause the trace to stop. """ def...
def _cache(self): """ Populates the list with a number of gradient colors. The list has Gradient.steps colors that interpolate between the fixed base Gradient.colors. The spread parameter controls the midpoint of the gradient, you can shift it right and left. A separate...
Populates the list with a number of gradient colors. The list has Gradient.steps colors that interpolate between the fixed base Gradient.colors. The spread parameter controls the midpoint of the gradient, you can shift it right and left. A separate gradient is calculated for ea...
Below is the the instruction that describes the task: ### Input: Populates the list with a number of gradient colors. The list has Gradient.steps colors that interpolate between the fixed base Gradient.colors. The spread parameter controls the midpoint of the gradient, you can shif...
def locate_fixed_differences(ac1, ac2): """Locate variants with no shared alleles between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the first population. ac2 : array_like, int, shape (n_variants, n_alleles) A...
Locate variants with no shared alleles between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the first population. ac2 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the second population. ...
Below is the the instruction that describes the task: ### Input: Locate variants with no shared alleles between two populations. Parameters ---------- ac1 : array_like, int, shape (n_variants, n_alleles) Allele counts array from the first population. ac2 : array_like, int, shape (n_variants...
def status_message(self): """Detailed message about whether the dependency is installed. :rtype: str """ if self.is_available: return "INSTALLED {0!s}" elif self.why and self.package: return "MISSING {0!s:<20}needed for {0.why}, part of the {0.package} ...
Detailed message about whether the dependency is installed. :rtype: str
Below is the the instruction that describes the task: ### Input: Detailed message about whether the dependency is installed. :rtype: str ### Response: def status_message(self): """Detailed message about whether the dependency is installed. :rtype: str """ if self.is_availa...
def set_dims(self, dims, shape=None): """Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dims : str or sequence ...
Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dims : str or sequence of str or dict Dimensions to include ...
Below is the the instruction that describes the task: ### Input: Return a new variable with given set of dimensions. This method might be used to attach new dimension(s) to variable. When possible, this operation does not copy this variable's data. Parameters ---------- dim...
def _update_conda_devel(): """Update to the latest development conda package. """ conda_bin = _get_conda_bin() channels = _get_conda_channels(conda_bin) assert conda_bin, "Could not find anaconda distribution for upgrading bcbio" subprocess.check_call([conda_bin, "install", "--quiet", "--yes"] +...
Update to the latest development conda package.
Below is the the instruction that describes the task: ### Input: Update to the latest development conda package. ### Response: def _update_conda_devel(): """Update to the latest development conda package. """ conda_bin = _get_conda_bin() channels = _get_conda_channels(conda_bin) assert conda_bi...
def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDate'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] instructor = fo...
Create slots and return success message.
Below is the the instruction that describes the task: ### Input: Create slots and return success message. ### Response: def form_valid(self, form): ''' Create slots and return success message. ''' startDate = form.cleaned_data['startDate'] endDate = form.cleaned_data['endDat...