code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def apply_obb(self): """ Apply the oriented bounding box transform to the current mesh. This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB. Returns ---------- matrix : (4, 4) float Transformation matrix th...
Apply the oriented bounding box transform to the current mesh. This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB. Returns ---------- matrix : (4, 4) float Transformation matrix that was applied to mesh to move ...
Below is the the instruction that describes the task: ### Input: Apply the oriented bounding box transform to the current mesh. This will result in a mesh with an AABB centered at the origin and the same dimensions as the OBB. Returns ---------- matrix : (4, 4) float ...
def getUser(self): """Returns the linked Plone User or None """ username = self.getUsername() if not username: return None user = api.user.get(userid=username) return user
Returns the linked Plone User or None
Below is the the instruction that describes the task: ### Input: Returns the linked Plone User or None ### Response: def getUser(self): """Returns the linked Plone User or None """ username = self.getUsername() if not username: return None user = api.user.get(use...
def pythons(): '''Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions. ''' if not _pyenv_exists(): print('\npyenv is not installed. You can install it with fabsetup ' '(https://gi...
Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions.
Below is the the instruction that describes the task: ### Input: Install latest pythons with pyenv. The python version will be activated in the projects base dir. Will skip already installed latest python versions. ### Response: def pythons(): '''Install latest pythons with pyenv. The python ver...
def load_secret(self, secret): """ Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the generated secret ...
Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the generated secret (in encrypted form). @param secret: YubiKe...
Below is the the instruction that describes the task: ### Input: Ask YubiHSM to load a pre-existing YubiKey secret. The data is stored internally in the YubiHSM in temporary memory - this operation would typically be followed by one or more L{generate_aead} commands to actually retreive the...
def updateColumnValues(self, networkId, tableType, columnName, default, body, verbose=None): """ Sets the values for cells in the table specified by the `tableType` and `networkId` parameters. If the 'default` parameter is not specified, the message body should consist of key-value pair...
Sets the values for cells in the table specified by the `tableType` and `networkId` parameters. If the 'default` parameter is not specified, the message body should consist of key-value pairs with which to set values. If the `default` parameter is specified, its value will be used for ...
Below is the the instruction that describes the task: ### Input: Sets the values for cells in the table specified by the `tableType` and `networkId` parameters. If the 'default` parameter is not specified, the message body should consist of key-value pairs with which to set values. ...
def colorline(ax, x, y, z, **kwargs): """ http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the array z Option...
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the array z Optionally specify a colormap, a norm function and a lin...
Below is the the instruction that describes the task: ### Input: http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb http://matplotlib.org/examples/pylab_examples/multicolored_line.html Plot a colored line with coordinates x and y Optionally specify colors in the...
def dispose(self): """ Disposes every performed registration; the container can then be used again """ for registration in self._registrations.values(): registration.dispose() self._registrations = {}
Disposes every performed registration; the container can then be used again
Below is the the instruction that describes the task: ### Input: Disposes every performed registration; the container can then be used again ### Response: def dispose(self): """ Disposes every performed registration; the container can then be used again """ for registration in self....
def get_store_profile_by_id(cls, store_profile_id, **kwargs): """Find StoreProfile Return single instance of StoreProfile by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_p...
Find StoreProfile Return single instance of StoreProfile by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_profile_by_id(store_profile_id, async=True) >>> result = thread.ge...
Below is the the instruction that describes the task: ### Input: Find StoreProfile Return single instance of StoreProfile by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_profi...
def reverse( self, query, exactly_one=True, timeout=DEFAULT_SENTINEL, ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query:...
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :pa...
Below is the the instruction that describes the task: ### Input: Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longi...
def setup_option_actions(self, exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported): """Setup the actions to show in the cog menu.""" self.setup_in_progress = True self.exclude_private_action = create_action(self, _("Ex...
Setup the actions to show in the cog menu.
Below is the the instruction that describes the task: ### Input: Setup the actions to show in the cog menu. ### Response: def setup_option_actions(self, exclude_private, exclude_uppercase, exclude_capitalized, exclude_unsupported): """Setup the actions to show in the cog menu...
def timeout(self): """ Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value of :attr:`couchbase.bucket.Bu...
Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value of :attr:`couchbase.bucket.Bucket.n1ql_timeout` property...
Below is the the instruction that describes the task: ### Input: Optional per-query timeout. If set, this will limit the amount of time in which the query can be executed and waited for. .. note:: The effective timeout for the query will be either this property or the value...
def expand_window(center, window_size, array_size): """Generate a bounded windows. maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is ``array_size - 1``. Example:: >>> expand_window(center=50, window_size=3, max=100) [47, 48, 49, 50, 51, 52, 53] >>> expand...
Generate a bounded windows. maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is ``array_size - 1``. Example:: >>> expand_window(center=50, window_size=3, max=100) [47, 48, 49, 50, 51, 52, 53] >>> expand_window(center=2, window_size=3, max=100) [0, 1, 2,...
Below is the the instruction that describes the task: ### Input: Generate a bounded windows. maxlength = 2 * window_size + 1, lower bound is 0 and upper bound is ``array_size - 1``. Example:: >>> expand_window(center=50, window_size=3, max=100) [47, 48, 49, 50, 51, 52, 53] ...
def b32decode(s, casefold=False, map01=None): """Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0...
Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mapping of the digit 0 (zero) to the letter O (oh), and for optional ma...
Below is the the instruction that describes the task: ### Input: Decode a Base32 encoded string. s is the string to decode. Optional casefold is a flag specifying whether a lowercase alphabet is acceptable as input. For security purposes, the default is False. RFC 3548 allows for optional mappin...
def get_identities(self, item): """ Return the identities from an item """ identities = [] if 'data' not in item: return identities if 'revisions' not in item['data']: return identities revisions = item['data']['revisions'] for revision in revis...
Return the identities from an item
Below is the the instruction that describes the task: ### Input: Return the identities from an item ### Response: def get_identities(self, item): """ Return the identities from an item """ identities = [] if 'data' not in item: return identities if 'revisions' not in it...
def _register_config_file(self, key, val): """ Persist a newly added config file, or update (overwrite) the value of a previously persisted config. """ state = self.__load_state() if 'config_files' not in state: state['config_files'] = {} state['config_files']...
Persist a newly added config file, or update (overwrite) the value of a previously persisted config.
Below is the the instruction that describes the task: ### Input: Persist a newly added config file, or update (overwrite) the value of a previously persisted config. ### Response: def _register_config_file(self, key, val): """ Persist a newly added config file, or update (overwrite) the value ...
def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang = dictionary_options.get('lang', 'en_US') wordlists = dictionary_options.get('wordlists', []) ...
Setup dictionary.
Below is the the instruction that describes the task: ### Input: Setup dictionary. ### Response: def setup_dictionary(self, task): """Setup dictionary.""" dictionary_options = task.get('dictionary', {}) output = os.path.abspath(dictionary_options.get('output', self.dict_bin)) lang ...
def get_date_range(year=None, month=None, day=None): """ Return a start..end range to query for a specific month, day or year. """ if year is None: return None if month is None: # year only start = datetime(year, 1, 1, 0, 0, 0, tzinfo=utc) end = datetime(year, 12, 31...
Return a start..end range to query for a specific month, day or year.
Below is the the instruction that describes the task: ### Input: Return a start..end range to query for a specific month, day or year. ### Response: def get_date_range(year=None, month=None, day=None): """ Return a start..end range to query for a specific month, day or year. """ if year is None: ...
def get(self): """Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure. """ logger.info( 'Loading refresh_token from %s', repr(self._filename) ) try: with open(self._filename) as f: return f.r...
Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure.
Below is the the instruction that describes the task: ### Input: Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure. ### Response: def get(self): """Get cached refresh token. Returns: Cached refresh token, or ``None`` on failure. ...
def setNetworkName(self, networkName='GRL'): """set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname """ print '%s call s...
set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname
Below is the the instruction that describes the task: ### Input: set Thread Network name Args: networkName: the networkname string to be set Returns: True: successful to set the Thread Networkname False: fail to set the Thread Networkname ### Response: def setN...
def delete_translations_for_item_and_its_children(self, item, languages=None): """ deletes the translations task of an item and its children used when a model is not enabled anymore :param item: :param languages: :return: """ self.log('--- Deleting transl...
deletes the translations task of an item and its children used when a model is not enabled anymore :param item: :param languages: :return:
Below is the the instruction that describes the task: ### Input: deletes the translations task of an item and its children used when a model is not enabled anymore :param item: :param languages: :return: ### Response: def delete_translations_for_item_and_its_children(self, item, lan...
def list_availability_zones(call=None): ''' List all availability zones in the current region ''' ret = {} params = {'Action': 'DescribeZones', 'RegionId': get_location()} items = query(params) for zone in items['Zones']['Zone']: ret[zone['ZoneId']] = {} for i...
List all availability zones in the current region
Below is the the instruction that describes the task: ### Input: List all availability zones in the current region ### Response: def list_availability_zones(call=None): ''' List all availability zones in the current region ''' ret = {} params = {'Action': 'DescribeZones', 'Region...
def call_orig(self, *args, **kwargs): ''' Calls the original function. Simulates __new__ and __init__ together. ''' rval = super(StubNew, self).call_orig(self._type) rval.__init__(*args, **kwargs) return rval
Calls the original function. Simulates __new__ and __init__ together.
Below is the the instruction that describes the task: ### Input: Calls the original function. Simulates __new__ and __init__ together. ### Response: def call_orig(self, *args, **kwargs): ''' Calls the original function. Simulates __new__ and __init__ together. ''' rval = super(StubN...
def parse_nds2_enums(func): """Decorate a function to translate a type string into an integer """ @wraps(func) def wrapped_func(*args, **kwargs): # pylint: disable=missing-docstring for kwd, enum_ in (('type', Nds2ChannelType), ('dtype', Nds2DataType)): if...
Decorate a function to translate a type string into an integer
Below is the the instruction that describes the task: ### Input: Decorate a function to translate a type string into an integer ### Response: def parse_nds2_enums(func): """Decorate a function to translate a type string into an integer """ @wraps(func) def wrapped_func(*args, **kwargs): # pylint: ...
def address_reencode(address, blockchain='bitcoin', **blockchain_opts): """ Reencode an address """ if blockchain == 'bitcoin': return btc_address_reencode(address, **blockchain_opts) else: raise ValueError("Unknown blockchain '{}'".format(blockchain))
Reencode an address
Below is the the instruction that describes the task: ### Input: Reencode an address ### Response: def address_reencode(address, blockchain='bitcoin', **blockchain_opts): """ Reencode an address """ if blockchain == 'bitcoin': return btc_address_reencode(address, **blockchain_opts) else...
def speak(self, textstr, lang='en-US', gender='female', format='riff-16khz-16bit-mono-pcm'): """ Run will call Microsoft Translate API and and produce audio """ # print("speak(textstr=%s, lang=%s, gender=%s, format=%s)" % (textstr, lang, gender, format)) concatkey = '%s-%s-%s-%s'...
Run will call Microsoft Translate API and and produce audio
Below is the the instruction that describes the task: ### Input: Run will call Microsoft Translate API and and produce audio ### Response: def speak(self, textstr, lang='en-US', gender='female', format='riff-16khz-16bit-mono-pcm'): """ Run will call Microsoft Translate API and and produce audio ...
def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(obj())
Initialization queries
Below is the the instruction that describes the task: ### Input: Initialization queries ### Response: def _run_init_queries(self): ''' Initialization queries ''' for obj in (Package, PackageCfgFile, PayloadFile, IgnoredDir, AllowedDir): self._db.create_table_from_object(...
def get_app_metadata(template_dict): """ Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundErr...
Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises ApplicationMetadataNotFoundError
Below is the the instruction that describes the task: ### Input: Get the application metadata from a SAM template. :param template_dict: SAM template as a dictionary :type template_dict: dict :return: Application metadata as defined in the template :rtype: ApplicationMetadata :raises Applicatio...
def compute_performance(SC, verbose=True, output='dict'): """ Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- ...
Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- performance: dict or pandas.Serie depending output param
Below is the the instruction that describes the task: ### Input: Return some performance value for comparison. Parameters ------- SC: SortingComparison instance The SortingComparison verbose: bool Display on console or not output: dict or pandas Returns ---------- ...
def fcoe_get_login_output_fcoe_login_list_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login output = ET.SubElement(fcoe_get_login, "output") fcoe_login_lis...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def fcoe_get_login_output_fcoe_login_list_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") ...
def _set_master_state(self, state): """Set the state of the SDPMaster.""" if state == 'init': self._service_state.update_current_state('init', force=True) self.set_state(DevState.INIT) elif state == 'on': self.set_state(DevState.ON) self._service_...
Set the state of the SDPMaster.
Below is the the instruction that describes the task: ### Input: Set the state of the SDPMaster. ### Response: def _set_master_state(self, state): """Set the state of the SDPMaster.""" if state == 'init': self._service_state.update_current_state('init', force=True) self.set_...
def was_applied(self): """ For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. ...
For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch succeeds or fails. Only valid when one of the of the in...
Below is the the instruction that describes the task: ### Input: For LWT results, returns whether the transaction was applied. Result is indeterminate if called on a result that was not an LWT request or on a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch ...
def izip_exact(*iterables): """ A lazy izip() that ensures that all iterables have the same length. A LengthMismatch exception is raised if the iterables' lengths differ. Examples -------- >>> list(zip_exc([])) [] >>> list(zip_exc((), (), ())) [] >>> list(zi...
A lazy izip() that ensures that all iterables have the same length. A LengthMismatch exception is raised if the iterables' lengths differ. Examples -------- >>> list(zip_exc([])) [] >>> list(zip_exc((), (), ())) [] >>> list(zip_exc("abc", range(3))) [('a', 0...
Below is the the instruction that describes the task: ### Input: A lazy izip() that ensures that all iterables have the same length. A LengthMismatch exception is raised if the iterables' lengths differ. Examples -------- >>> list(zip_exc([])) [] >>> list(zip_exc((), (), ())) ...
def getPerfInfo(rh, useridlist): """ Get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure ...
Get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, non-zero: failure rc - RC returned from SMCLI if over...
Below is the the instruction that describes the task: ### Input: Get the performance information for a userid Input: Request Handle Userid to query <- may change this to a list later. Output: Dictionary containing the following: overallRC - overall return code, 0: success, n...
def parse_create(prs, conn): """Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information """ prs_create = prs.add_parser( 'create', help='create record of specific zone') set_option(prs_create, 'domain') conn_options(prs_creat...
Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information
Below is the the instruction that describes the task: ### Input: Create record. Arguments: prs: parser object of argparse conn: dictionary of connection information ### Response: def parse_create(prs, conn): """Create record. Arguments: prs: parser object of argparse ...
def list_namespaced_job(self, namespace, **kwargs): # noqa: E501 """list_namespaced_job # noqa: E501 list or watch objects of kind Job # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> th...
list_namespaced_job # noqa: E501 list or watch objects of kind Job # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_job(namespace, async_req=True) >>> result ...
Below is the the instruction that describes the task: ### Input: list_namespaced_job # noqa: E501 list or watch objects of kind Job # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = a...
def get_bilinear_residuals_stepp(input_params, xvals, yvals, slope1_fit): ''' Returns the residual sum-of-squares value of a bilinear fit to a data set - with a segment - 1 gradient fixed by an input value (slope_1_fit) :param list input_params: Input parameters for the bilinear model [slope2, ...
Returns the residual sum-of-squares value of a bilinear fit to a data set - with a segment - 1 gradient fixed by an input value (slope_1_fit) :param list input_params: Input parameters for the bilinear model [slope2, crossover_point, intercept] :para...
Below is the the instruction that describes the task: ### Input: Returns the residual sum-of-squares value of a bilinear fit to a data set - with a segment - 1 gradient fixed by an input value (slope_1_fit) :param list input_params: Input parameters for the bilinear model [slope2, crossover_point, ...
def _fetchDevAll(self, namestr, devlist, statsfunc): """Initialize I/O stats for devices. @param namestr: Field name component indicating device type. @param devlist: List of devices. @param statsfunc: Function for retrieving stats for device. """ fo...
Initialize I/O stats for devices. @param namestr: Field name component indicating device type. @param devlist: List of devices. @param statsfunc: Function for retrieving stats for device.
Below is the the instruction that describes the task: ### Input: Initialize I/O stats for devices. @param namestr: Field name component indicating device type. @param devlist: List of devices. @param statsfunc: Function for retrieving stats for device. ### Response: def _fetchD...
def call_workflow_event(instance, event, after=True): """Calls the instance's workflow event """ if not event.transition: return False portal_type = instance.portal_type wf_module = _load_wf_module('{}.events'.format(portal_type.lower())) if not wf_module: return False # In...
Calls the instance's workflow event
Below is the the instruction that describes the task: ### Input: Calls the instance's workflow event ### Response: def call_workflow_event(instance, event, after=True): """Calls the instance's workflow event """ if not event.transition: return False portal_type = instance.portal_type w...
def _retrieve_userinfo(self, access_token=None): """ Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict """ if 'userinfo_uri' not in self.client_secrets: l...
Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict
Below is the the instruction that describes the task: ### Input: Requests extra user information from the Provider's UserInfo and returns the result. :returns: The contents of the UserInfo endpoint. :rtype: dict ### Response: def _retrieve_userinfo(self, access_token=None): """ ...
def open(filename, mode='r', content_type=None, options=None, read_buffer_size=storage_api.ReadBuffer.DEFAULT_BUFFER_SIZE, retry_params=None, _account_id=None, offset=0): """Opens a Google Cloud Storage file and returns it as a File-like object. Args: ...
Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist. In writing mode, a file will be created or be overrode. c...
Below is the the instruction that describes the task: ### Input: Opens a Google Cloud Storage file and returns it as a File-like object. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. mode: 'r' for reading mode. 'w' for writing mode. In reading mode, the file must exist...
def nodes_by_category(self, category): """ Returns nodes with the given category attribute. """ return [n for n in self.nodes if n.category == category]
Returns nodes with the given category attribute.
Below is the the instruction that describes the task: ### Input: Returns nodes with the given category attribute. ### Response: def nodes_by_category(self, category): """ Returns nodes with the given category attribute. """ return [n for n in self.nodes if n.category == category]
def get_key(self): """ Return the call key, even if it has to be parsed from the source. """ if not isinstance(self.key, Unparseable): return self.key line = self.source[self.col_offset:] regex = re.compile('''pyconfig\.[eginst]+\(([^,]+).*?\)''') ma...
Return the call key, even if it has to be parsed from the source.
Below is the the instruction that describes the task: ### Input: Return the call key, even if it has to be parsed from the source. ### Response: def get_key(self): """ Return the call key, even if it has to be parsed from the source. """ if not isinstance(self.key, Unparseable): ...
def randomSize(cls, widthLimits, heightLimits, origin=None): ''' :param: widthLimits - iterable of integers with length >= 2 :param: heightLimits - iterable of integers with length >= 2 :param: origin - optional Point subclass :return: Rectangle ''' r = cl...
:param: widthLimits - iterable of integers with length >= 2 :param: heightLimits - iterable of integers with length >= 2 :param: origin - optional Point subclass :return: Rectangle
Below is the the instruction that describes the task: ### Input: :param: widthLimits - iterable of integers with length >= 2 :param: heightLimits - iterable of integers with length >= 2 :param: origin - optional Point subclass :return: Rectangle ### Response: def randomSize(cls, widt...
def _do_poll_problems(self): """Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread. """ try: # grouped futures (all scheduled within _POLL_GROUP_TIMEFRAME) frame_futures = {} def...
Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread.
Below is the the instruction that describes the task: ### Input: Poll the server for the status of a set of problems. Note: This method is always run inside of a daemon thread. ### Response: def _do_poll_problems(self): """Poll the server for the status of a set of problems. N...
def resnet_v2(inputs, block_fn, layer_blocks, filters, data_format="channels_first", is_training=False, is_cifar=False, use_td=False, targeting_rate=None, keep_prob=None): """Resnet model. ...
Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include in each of the 3 or 4 block groups. Each group consists of blo...
Below is the the instruction that describes the task: ### Input: Resnet model. Args: inputs: `Tensor` images. block_fn: `function` for the block to use within the model. Either `residual_block` or `bottleneck_block`. layer_blocks: list of 3 or 4 `int`s denoting the number of blocks to include...
def get_user_details(self, response): """ Return user details from Dataporten Set username to eduPersonPrincipalName """ user = super(DataportenFeideOAuth2, self).get_user_details(response) sec_userids = user['userid_sec'] for userid in sec_userids: u...
Return user details from Dataporten Set username to eduPersonPrincipalName
Below is the the instruction that describes the task: ### Input: Return user details from Dataporten Set username to eduPersonPrincipalName ### Response: def get_user_details(self, response): """ Return user details from Dataporten Set username to eduPersonPrincipalName ""...
def main(): """ iodp_samples_magic.py OPTIONS: -f FILE, input csv file -Fsa FILE, output samples file for updating, default is to overwrite existing samples file """ if "-h" in sys.argv: print(main.__doc__) sys.exit() dataframe = extractor.command_line_dataframe(...
iodp_samples_magic.py OPTIONS: -f FILE, input csv file -Fsa FILE, output samples file for updating, default is to overwrite existing samples file
Below is the the instruction that describes the task: ### Input: iodp_samples_magic.py OPTIONS: -f FILE, input csv file -Fsa FILE, output samples file for updating, default is to overwrite existing samples file ### Response: def main(): """ iodp_samples_magic.py OPTIONS: -f ...
def _autocorr_func2(mags, lag, maglen, magmed, magstd): ''' This is an alternative function to calculate the autocorrelation. This version is from (first definition): https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations Parameters ---------- mags : np.array Th...
This is an alternative function to calculate the autocorrelation. This version is from (first definition): https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations Parameters ---------- mags : np.array This is the magnitudes array. MUST NOT have any nans. lag : float...
Below is the the instruction that describes the task: ### Input: This is an alternative function to calculate the autocorrelation. This version is from (first definition): https://en.wikipedia.org/wiki/Correlogram#Estimation_of_autocorrelations Parameters ---------- mags : np.array T...
def palette(fg, bg=-1): """ Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function """ if not hasattr(palette, "counter"): palette.counter = 1 if not hasattr(palette, "selections"): palette.s...
Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function
Below is the the instruction that describes the task: ### Input: Since curses only supports a finite amount of initialised colour pairs we memoise any selections you've made as an attribute on this function ### Response: def palette(fg, bg=-1): """ Since curses only supports a finite amount of initiali...
def get_label_items(self, label_id, top=None, skip=None): """GetLabelItems. Get items under a label. :param str label_id: Unique identifier of label :param int top: Max number of items to return :param int skip: Number of items to skip :rtype: [TfvcItem] """ ...
GetLabelItems. Get items under a label. :param str label_id: Unique identifier of label :param int top: Max number of items to return :param int skip: Number of items to skip :rtype: [TfvcItem]
Below is the the instruction that describes the task: ### Input: GetLabelItems. Get items under a label. :param str label_id: Unique identifier of label :param int top: Max number of items to return :param int skip: Number of items to skip :rtype: [TfvcItem] ### Response: de...
def abbreviate(s, maxlength=25): """Color-aware abbreviator""" assert maxlength >= 4 skip = False abbrv = None i = 0 for j, c in enumerate(s): if c == '\033': skip = True elif skip: if c == 'm': skip = False else: i += 1...
Color-aware abbreviator
Below is the the instruction that describes the task: ### Input: Color-aware abbreviator ### Response: def abbreviate(s, maxlength=25): """Color-aware abbreviator""" assert maxlength >= 4 skip = False abbrv = None i = 0 for j, c in enumerate(s): if c == '\033': skip = Tr...
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app...
Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' ...
Below is the the instruction that describes the task: ### Input: Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' ...
def add_lv_grid_district(self, lv_grid_district): # TODO: check docstring """Adds a LV grid district to _lv_grid_districts if not already existing Args ---- lv_grid_district: :shapely:`Shapely Polygon object<polygons>` Descr """ if lv_grid_di...
Adds a LV grid district to _lv_grid_districts if not already existing Args ---- lv_grid_district: :shapely:`Shapely Polygon object<polygons>` Descr
Below is the the instruction that describes the task: ### Input: Adds a LV grid district to _lv_grid_districts if not already existing Args ---- lv_grid_district: :shapely:`Shapely Polygon object<polygons>` Descr ### Response: def add_lv_grid_district(self, lv_grid_dist...
def glob(self, pattern): """ Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directories. """ cls = sel...
Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directories.
Below is the the instruction that describes the task: ### Input: Return a list of path objects that match the pattern. pattern - a path relative to this directory, with wildcards. For example, path('/users').glob('*/bin/*') returns a list of all the files users have in their bin directorie...
def AdaptiveFilter(model="lms", **kwargs): """ Function that filter data with selected adaptive filter. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Kwargs:** * Any ...
Function that filter data with selected adaptive filter. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Kwargs:** * Any key argument that can be accepted with selected filter ...
Below is the the instruction that describes the task: ### Input: Function that filter data with selected adaptive filter. **Args:** * `d` : desired value (1 dimensional array) * `x` : input matrix (2-dimensional array). Rows are samples, columns are input arrays. **Kwargs:** ...
def ParseOptions(cls, options, configuration_object): """Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is o...
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type.
Below is the the instruction that describes the task: ### Input: Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration obj...
def filter_variant_sequences( variant_sequences, preferred_sequence_length, min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,): """ Drop variant sequences which are shorter than request or don't have enough supporting reads. """ variant_sequences = trim_variant_seq...
Drop variant sequences which are shorter than request or don't have enough supporting reads.
Below is the the instruction that describes the task: ### Input: Drop variant sequences which are shorter than request or don't have enough supporting reads. ### Response: def filter_variant_sequences( variant_sequences, preferred_sequence_length, min_variant_sequence_coverage=MIN_VARIA...
def epoch(self): """GPS epoch associated with these data :type: `~astropy.time.Time` """ try: if self._epoch is None: return None return Time(*modf(self._epoch)[::-1], format='gps', scale='utc') except AttributeError: self._epo...
GPS epoch associated with these data :type: `~astropy.time.Time`
Below is the the instruction that describes the task: ### Input: GPS epoch associated with these data :type: `~astropy.time.Time` ### Response: def epoch(self): """GPS epoch associated with these data :type: `~astropy.time.Time` """ try: if self._epoch is None:...
def ds_IsEmpty(ds): """Check to see if dataset is empty after warp """ out = False b = ds.GetRasterBand(1) #Looks like this throws: #ERROR 1: Failed to compute min/max, no valid pixels found in sampling. #Should just catch this rater than bothering with logic below try: mm = b.C...
Check to see if dataset is empty after warp
Below is the the instruction that describes the task: ### Input: Check to see if dataset is empty after warp ### Response: def ds_IsEmpty(ds): """Check to see if dataset is empty after warp """ out = False b = ds.GetRasterBand(1) #Looks like this throws: #ERROR 1: Failed to compute min/max,...
def finish(self): """Wait for GL commands to to finish This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this function will return before GL has finished processing the commands. """ if ...
Wait for GL commands to to finish This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this function will return before GL has finished processing the commands.
Below is the the instruction that describes the task: ### Input: Wait for GL commands to to finish This creates a GLIR command for glFinish and then processes the GLIR commands. If the GLIR interpreter is remote (e.g. WebGL), this function will return before GL has finished processi...
async def handle_callback(self, aws_callback: typing.Coroutine, response): """Process coroutine callback function""" callback_result = None try: callback_result = await aws_callback except NothingMatchedError as e: self.logger.error(f'<Item: {str(e).lower()}>') ...
Process coroutine callback function
Below is the the instruction that describes the task: ### Input: Process coroutine callback function ### Response: async def handle_callback(self, aws_callback: typing.Coroutine, response): """Process coroutine callback function""" callback_result = None try: callback_result = ...
def scheduler(self, sleep_time=0.2): """Starts the scheduler to check for scheduled calls and execute them at the correct time. Args: sleep_time (float): The amount of time to wait in seconds between each loop iteration. This prevents the scheduler from consuming ...
Starts the scheduler to check for scheduled calls and execute them at the correct time. Args: sleep_time (float): The amount of time to wait in seconds between each loop iteration. This prevents the scheduler from consuming 100% of the host's CPU. Defaults to 0.2 secon...
Below is the the instruction that describes the task: ### Input: Starts the scheduler to check for scheduled calls and execute them at the correct time. Args: sleep_time (float): The amount of time to wait in seconds between each loop iteration. This prevents the scheduler fro...
def set_current_language(self, language_code, initialize=False): """ Switch the currently activate language of the object. """ self._current_language = normalize_language_code(language_code or get_language()) # Ensure the translation is present for __get__ queries. if in...
Switch the currently activate language of the object.
Below is the the instruction that describes the task: ### Input: Switch the currently activate language of the object. ### Response: def set_current_language(self, language_code, initialize=False): """ Switch the currently activate language of the object. """ self._current_language ...
def set(self, key, value, key_length=0): """Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value """ if key_length < 1: key_length = len(key) if self.k: self._...
Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value
Below is the the instruction that describes the task: ### Input: Set value to key-value Params: <str> key <int> value <int> key_length Return: <int> key_value ### Response: def set(self, key, value, key_length=0): """Set value to key-value ...
def get_full_page_box_list_assigning_media_and_crop(input_doc, quiet=False): """Get a list of all the full-page box values for each page. The argument input_doc should be a PdfFileReader object. The boxes on the list are in the simple 4-float list format used by this program, not RectangleObject format.""...
Get a list of all the full-page box values for each page. The argument input_doc should be a PdfFileReader object. The boxes on the list are in the simple 4-float list format used by this program, not RectangleObject format.
Below is the the instruction that describes the task: ### Input: Get a list of all the full-page box values for each page. The argument input_doc should be a PdfFileReader object. The boxes on the list are in the simple 4-float list format used by this program, not RectangleObject format. ### Response: d...
def saturated_vapor_pressure(t_kelvin): """Saturated Vapor Pressure (Pa) at t_kelvin (K). This function accounts for the different behaviour above vs. below the freezing point of water. Note: [1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic Properties of Ordi...
Saturated Vapor Pressure (Pa) at t_kelvin (K). This function accounts for the different behaviour above vs. below the freezing point of water. Note: [1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic Properties of Ordinary Water Substance for General and Scientific...
Below is the the instruction that describes the task: ### Input: Saturated Vapor Pressure (Pa) at t_kelvin (K). This function accounts for the different behaviour above vs. below the freezing point of water. Note: [1] W. Wagner and A. Pru:" The IAPWS Formulation 1995 for the Thermodynamic ...
def pull_env_credential(env, param, value): """ Dissects a keyring credential lookup string from the supernova config file and returns the username/password combo """ rex = "USE_KEYRING\[([\x27\x22])(.*)\\1\]" # This is the old-style, per-environment keyring credential if value == "USE_KEYR...
Dissects a keyring credential lookup string from the supernova config file and returns the username/password combo
Below is the the instruction that describes the task: ### Input: Dissects a keyring credential lookup string from the supernova config file and returns the username/password combo ### Response: def pull_env_credential(env, param, value): """ Dissects a keyring credential lookup string from the supernov...
def _link_barcodes(self): """ Private function. Links Sample barcodes in a dictionary as [Assembly].barcodes, with barcodes parsed from the 'barcodes_path' parameter. This function is called during set_params() when setting the barcodes_path. """ ## parse barcode...
Private function. Links Sample barcodes in a dictionary as [Assembly].barcodes, with barcodes parsed from the 'barcodes_path' parameter. This function is called during set_params() when setting the barcodes_path.
Below is the the instruction that describes the task: ### Input: Private function. Links Sample barcodes in a dictionary as [Assembly].barcodes, with barcodes parsed from the 'barcodes_path' parameter. This function is called during set_params() when setting the barcodes_path. ### Response: ...
def set_level(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position) except Exception as err: LOG.debug("HelperLevel.set_level: Exception %s" % (err,)) return False self.writ...
Seek a specific value by specifying a float() from 0.0 to 1.0.
Below is the the instruction that describes the task: ### Input: Seek a specific value by specifying a float() from 0.0 to 1.0. ### Response: def set_level(self, position, channel=None): """Seek a specific value by specifying a float() from 0.0 to 1.0.""" try: position = float(position)...
def humanize_filesize(filesize: int) -> Tuple[str, str]: """Return human readable pair of size and unit from the given filesize in bytes.""" for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']: if filesize < 1024.0: return '{:3.1f}'.format(filesize), unit+'B' filesize /= 1024.0
Return human readable pair of size and unit from the given filesize in bytes.
Below is the the instruction that describes the task: ### Input: Return human readable pair of size and unit from the given filesize in bytes. ### Response: def humanize_filesize(filesize: int) -> Tuple[str, str]: """Return human readable pair of size and unit from the given filesize in bytes.""" for unit ...
def _get_object_menu_models(): """ we need to create basic permissions for only CRUD enabled models """ from pyoko.conf import settings enabled_models = [] for entry in settings.OBJECT_MENU.values(): for mdl in entry: if 'wf' not in mdl: enabled_models.app...
we need to create basic permissions for only CRUD enabled models
Below is the the instruction that describes the task: ### Input: we need to create basic permissions for only CRUD enabled models ### Response: def _get_object_menu_models(): """ we need to create basic permissions for only CRUD enabled models """ from pyoko.conf import settings enabled...
def install_default_handler(self, http_error_code): """Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404. """ logger.debug( "Set Default HTTP error handler for status code %...
Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404.
Below is the the instruction that describes the task: ### Input: Install a default error handler for `http_error_code`. The default error handler renders a template named error404.html for http_error_code 404. ### Response: def install_default_handler(self, http_error_code): """Install a d...
def from_dict(cls, raw_data, **kwargs): """ This factory for :class:`Model` creates a Model from a dict object. """ instance = cls() instance.populate(raw_data, **kwargs) instance.validate(**kwargs) return instance
This factory for :class:`Model` creates a Model from a dict object.
Below is the the instruction that describes the task: ### Input: This factory for :class:`Model` creates a Model from a dict object. ### Response: def from_dict(cls, raw_data, **kwargs): """ This factory for :class:`Model` creates a Model from a dict object. """ instance = cls() ...
def appendQKeyEvent(self, keyEvent: QtGui.QKeyEvent): """ Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one ...
Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argument has an invalid type.
Below is the the instruction that describes the task: ### Input: Append another key to the key sequence represented by this object. |Args| * ``keyEvent`` (**QKeyEvent**): the key to add. |Returns| **None** |Raises| * **QtmacsArgumentError** if at least one argum...
def _wrap_event(event_): """Wrap hangouts_pb2.Event in ConversationEvent subclass.""" cls = conversation_event.ConversationEvent if event_.HasField('chat_message'): cls = conversation_event.ChatMessageEvent elif event_.HasField('otr_modification'): cls = conversat...
Wrap hangouts_pb2.Event in ConversationEvent subclass.
Below is the the instruction that describes the task: ### Input: Wrap hangouts_pb2.Event in ConversationEvent subclass. ### Response: def _wrap_event(event_): """Wrap hangouts_pb2.Event in ConversationEvent subclass.""" cls = conversation_event.ConversationEvent if event_.HasField('chat_mes...
def filter_variants(variant_collection, patient, filter_fn, **kwargs): """Filter variants from the Variant Collection Parameters ---------- variant_collection : varcode.VariantCollection patient : cohorts.Patient filter_fn: function Takes a FilterableVariant and returns a boolean. Only ...
Filter variants from the Variant Collection Parameters ---------- variant_collection : varcode.VariantCollection patient : cohorts.Patient filter_fn: function Takes a FilterableVariant and returns a boolean. Only variants returning True are preserved. Returns ------- varcode.Va...
Below is the the instruction that describes the task: ### Input: Filter variants from the Variant Collection Parameters ---------- variant_collection : varcode.VariantCollection patient : cohorts.Patient filter_fn: function Takes a FilterableVariant and returns a boolean. Only variants ...
def _secondary_min(self): """Getter for the minimum series value""" return ( self.secondary_range[0] if (self.secondary_range and self.secondary_range[0] is not None) else (min(self._secondary_values) if self._secondary_values else None) )
Getter for the minimum series value
Below is the the instruction that describes the task: ### Input: Getter for the minimum series value ### Response: def _secondary_min(self): """Getter for the minimum series value""" return ( self.secondary_range[0] if (self.secondary_range and self.secondary...
def magic_timeit(setup, stmt, ncalls=None, repeat=3, force_ms=False): """Time execution of a Python statement or expression Usage:\\ %timeit [-n<N> -r<R> [-t|-c]] statement Time execution of a Python statement or expression using the timeit module. Options: -n<N>: execute the given stateme...
Time execution of a Python statement or expression Usage:\\ %timeit [-n<N> -r<R> [-t|-c]] statement Time execution of a Python statement or expression using the timeit module. Options: -n<N>: execute the given statement <N> times in a loop. If this value is not given, a fitting value is ch...
Below is the the instruction that describes the task: ### Input: Time execution of a Python statement or expression Usage:\\ %timeit [-n<N> -r<R> [-t|-c]] statement Time execution of a Python statement or expression using the timeit module. Options: -n<N>: execute the given statement <N> t...
def _csv(self, cursor, fieldnames, output_fh): """Writes the rows of `cursor` in CSV format to `output_fh` and returns it. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnames: `list` ...
Writes the rows of `cursor` in CSV format to `output_fh` and returns it. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnames: `list` :param output_fh: file to write data to :t...
Below is the the instruction that describes the task: ### Input: Writes the rows of `cursor` in CSV format to `output_fh` and returns it. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnam...
def draw(self, **kwargs): """Draw the polygon Optional Inputs: ------------ All optional inputs are passed to ``matplotlib.patches.Polygon`` Notes: --------- Does not accept maptype as an argument. """ ax = mp.gca() shape = matplotlib.pa...
Draw the polygon Optional Inputs: ------------ All optional inputs are passed to ``matplotlib.patches.Polygon`` Notes: --------- Does not accept maptype as an argument.
Below is the the instruction that describes the task: ### Input: Draw the polygon Optional Inputs: ------------ All optional inputs are passed to ``matplotlib.patches.Polygon`` Notes: --------- Does not accept maptype as an argument. ### Response: def draw(self, **...
def cross_v2(vec1, vec2): """Return the crossproduct of the two vectors as a Vec2. Cross product doesn't really make sense in 2D, but return the Z component of the 3d result. """ return vec1.y * vec2.x - vec1.x * vec2.y
Return the crossproduct of the two vectors as a Vec2. Cross product doesn't really make sense in 2D, but return the Z component of the 3d result.
Below is the the instruction that describes the task: ### Input: Return the crossproduct of the two vectors as a Vec2. Cross product doesn't really make sense in 2D, but return the Z component of the 3d result. ### Response: def cross_v2(vec1, vec2): """Return the crossproduct of the two vectors as a V...
def convert_activation(net, node, module, builder): """Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder ...
Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuilder A neural network builder object.
Below is the the instruction that describes the task: ### Input: Convert an activation layer from mxnet to coreml. Parameters ---------- network: net A mxnet network object. layer: node Node to convert. module: module An module for MXNet builder: NeuralNetworkBuil...
def _GetDirectory(self): """Retrieves a directory. Returns: CPIODirectory: a directory or None if not available. """ if self.entry_type != definitions.FILE_ENTRY_TYPE_DIRECTORY: return None return CPIODirectory(self._file_system, self.path_spec)
Retrieves a directory. Returns: CPIODirectory: a directory or None if not available.
Below is the the instruction that describes the task: ### Input: Retrieves a directory. Returns: CPIODirectory: a directory or None if not available. ### Response: def _GetDirectory(self): """Retrieves a directory. Returns: CPIODirectory: a directory or None if not available. """ ...
def p_pragma_assign(self, p): 'pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN' p[0] = Pragma(PragmaEntry(p[3], p[5], lineno=p.lineno(1)), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN
Below is the the instruction that describes the task: ### Input: pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN ### Response: def p_pragma_assign(self, p): 'pragma : LPAREN TIMES ID EQUALS expression TIMES RPAREN' p[0] = Pragma(PragmaEntry(p[3], p[5], lineno=p.lineno(1)), ...
def _make_text_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME text explainer. """ def _predict_fn(perturbed_text): predict_input = [] for x in perturbed_text: instance_copy = dict(instance) i...
Create a predict_fn that can be used by LIME text explainer.
Below is the the instruction that describes the task: ### Input: Create a predict_fn that can be used by LIME text explainer. ### Response: def _make_text_predict_fn(self, labels, instance, column_to_explain): """Create a predict_fn that can be used by LIME text explainer. """ def _predict_fn(pert...
def write_collection(self, filename, collection): """ Writes a collection of stop words into a file. """ collection = sorted(list(collection)) with open(filename, 'wb+') as fd: fd.truncate() fd.write('\n'.join(collection).encode('utf-8'))
Writes a collection of stop words into a file.
Below is the the instruction that describes the task: ### Input: Writes a collection of stop words into a file. ### Response: def write_collection(self, filename, collection): """ Writes a collection of stop words into a file. """ collection = sorted(list(collection)) with o...
def canonical_request(self): """ The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: request_method + '\n' + ...
The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: request_method + '\n' + canonical_uri_path + '\n' + ...
Below is the the instruction that describes the task: ### Input: The AWS SigV4 canonical request given parameters from an HTTP request. This process is outlined here: http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html The canonical request is: reque...
def pageview(self, cur_p=''): ''' View the list of the Log. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(ML...
View the list of the Log.
Below is the the instruction that describes the task: ### Input: View the list of the Log. ### Response: def pageview(self, cur_p=''): ''' View the list of the Log. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) ...
def maybe_download(url, filename): """Download the data from Yann's website, unless it's already here.""" if not os.path.exists(WORK_DIRECTORY): os.mkdir(WORK_DIRECTORY) filepath = os.path.join(WORK_DIRECTORY, filename) if not os.path.exists(filepath): filepath, _ = request.urlretrieve(url + filename, f...
Download the data from Yann's website, unless it's already here.
Below is the the instruction that describes the task: ### Input: Download the data from Yann's website, unless it's already here. ### Response: def maybe_download(url, filename): """Download the data from Yann's website, unless it's already here.""" if not os.path.exists(WORK_DIRECTORY): os.mkdir(WORK_DIRE...
def pixelToMap(pX, pY, geoTransform): """Convert pixel coordinates to map coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) """ pX = np.asarray(pX, dtype=float) pY = np.asarray(pY, d...
Convert pixel coordinates to map coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform)
Below is the the instruction that describes the task: ### Input: Convert pixel coordinates to map coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) ### Response: def pixelToMap(pX, pY, geoTrans...
def _set_catalog_view(self, session): """Sets the underlying catalog view to match current view""" if self._catalog_view == COMPARATIVE: try: session.use_comparative_catalog_view() except AttributeError: pass else: try: ...
Sets the underlying catalog view to match current view
Below is the the instruction that describes the task: ### Input: Sets the underlying catalog view to match current view ### Response: def _set_catalog_view(self, session): """Sets the underlying catalog view to match current view""" if self._catalog_view == COMPARATIVE: try: ...
def _clean_up_columns( self): """clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text ...
clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstring text - check sublime snippet exists - clip...
Below is the the instruction that describes the task: ### Input: clean up columns of the NED table .. todo :: - update key arguments values and definitions with defaults - update return values and definitions - update usage examples and text - update docstri...
def timestamp_feature(catalog, soup): """The datetime the xml file was last modified. """ catalog.timestamp = int(soup.coursedb['timestamp']) catalog.datetime = datetime.datetime.fromtimestamp(catalog.timestamp) logger.info('Catalog last updated on %s' % catalog.datetime)
The datetime the xml file was last modified.
Below is the the instruction that describes the task: ### Input: The datetime the xml file was last modified. ### Response: def timestamp_feature(catalog, soup): """The datetime the xml file was last modified. """ catalog.timestamp = int(soup.coursedb['timestamp']) catalog.datetime = datetime.datet...
def list(self, activity_name=values.unset, activity_sid=values.unset, available=values.unset, friendly_name=values.unset, target_workers_expression=values.unset, task_queue_name=values.unset, task_queue_sid=values.unset, limit=None, page_size=None): """ Lists Worke...
Lists WorkerInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode activity_name: Filter by workers that are in a particular Activity by Friendly Name :param unicode activity_sid: Filte...
Below is the the instruction that describes the task: ### Input: Lists WorkerInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode activity_name: Filter by workers that are in a particular...
def IsDir(v): """Verify the directory exists. >>> IsDir()('/') '/' >>> with raises(DirInvalid, 'Not a directory'): ... IsDir()(None) """ try: if v: v = str(v) return os.path.isdir(v) else: raise DirInvalid("Not a directory") except T...
Verify the directory exists. >>> IsDir()('/') '/' >>> with raises(DirInvalid, 'Not a directory'): ... IsDir()(None)
Below is the the instruction that describes the task: ### Input: Verify the directory exists. >>> IsDir()('/') '/' >>> with raises(DirInvalid, 'Not a directory'): ... IsDir()(None) ### Response: def IsDir(v): """Verify the directory exists. >>> IsDir()('/') '/' >>> with raises(D...
def get_items_by_search(self, item_query, item_search): """Pass through to provider ItemSearchSession.get_items_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can('search'): raise Permi...
Pass through to provider ItemSearchSession.get_items_by_search
Below is the the instruction that describes the task: ### Input: Pass through to provider ItemSearchSession.get_items_by_search ### Response: def get_items_by_search(self, item_query, item_search): """Pass through to provider ItemSearchSession.get_items_by_search""" # Implemented from azosid templa...
def _getRightsAssignments(user_right): ''' helper function to return all the user rights assignments/users ''' sids = [] polHandle = win32security.LsaOpenPolicy(None, win32security.POLICY_ALL_ACCESS) sids = win32security.LsaEnumerateAccountsWithUserRight(polHandle, user_right) return sids
helper function to return all the user rights assignments/users
Below is the the instruction that describes the task: ### Input: helper function to return all the user rights assignments/users ### Response: def _getRightsAssignments(user_right): ''' helper function to return all the user rights assignments/users ''' sids = [] polHandle = win32security.LsaOp...
def _most_recent_assembly(assembly_names): """ Given list of (in this case, matched) assemblies, identify the most recent ("recency" here is determined by sorting based on the numeric element of the assembly name) """ match_recency = [ int(re.search('\d+', assembly_name).group()) ...
Given list of (in this case, matched) assemblies, identify the most recent ("recency" here is determined by sorting based on the numeric element of the assembly name)
Below is the the instruction that describes the task: ### Input: Given list of (in this case, matched) assemblies, identify the most recent ("recency" here is determined by sorting based on the numeric element of the assembly name) ### Response: def _most_recent_assembly(assembly_names): """ Given l...
def delete_certificate(ctx, slot, management_key, pin): """ Delete a certificate. Delete a certificate from a slot on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.delete_certificate(slot)
Delete a certificate. Delete a certificate from a slot on the YubiKey.
Below is the the instruction that describes the task: ### Input: Delete a certificate. Delete a certificate from a slot on the YubiKey. ### Response: def delete_certificate(ctx, slot, management_key, pin): """ Delete a certificate. Delete a certificate from a slot on the YubiKey. """ cont...
def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()
Iterate through lines of file.
Below is the the instruction that describes the task: ### Input: Iterate through lines of file. ### Response: def txt_line_iterator(path): """Iterate through lines of file.""" with tf.gfile.Open(path) as f: for line in f: yield line.strip()