code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._open_channels.append(destination_id) self.send_message( destination_id, NS_CONNECTION, {...
Ensure we opened a channel to destination_id.
Below is the the instruction that describes the task: ### Input: Ensure we opened a channel to destination_id. ### Response: def _ensure_channel_connected(self, destination_id): """ Ensure we opened a channel to destination_id. """ if destination_id not in self._open_channels: self._ope...
def _normalize_correlation_data(self, corr_data, norm_unit): """Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data ...
Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data in shape [num_samples, num_processed_voxels, num_voxels] norm_...
Below is the the instruction that describes the task: ### Input: Normalize the correlation data if necessary. Fisher-transform and then z-score the data for every norm_unit samples if norm_unit > 1. Parameters ---------- corr_data: the correlation data i...
def youtube_id(self): """Extract and return Youtube video id""" m = re.search(r'/embed/([A-Za-z0-9\-=_]*)', self.embed) if m: return m.group(1) return ''
Extract and return Youtube video id
Below is the the instruction that describes the task: ### Input: Extract and return Youtube video id ### Response: def youtube_id(self): """Extract and return Youtube video id""" m = re.search(r'/embed/([A-Za-z0-9\-=_]*)', self.embed) if m: return m.group(1) return ''
def obj2str(obj, pk_protocol=pk_protocol): """Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1L...
Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQFLAVgBAAAAYnECSwJ1Lg==' **中文文档** 将可Pickle化的Python对象转化为utf-8...
Below is the the instruction that describes the task: ### Input: Convert arbitrary object to utf-8 string, using base64encode algorithm. Usage:: >>> from weatherlab.lib.dataIO.pk import obj2str >>> data = {"a": 1, "b": 2} >>> obj2str(data, pk_protocol=2) 'gAJ9cQAoWAEAAABhcQ...
def _parse_next_token(self): """Will parse patterns until it gets to the next token or EOF.""" while self._position < self.limit: token = self._next_pattern() if token: return token return None
Will parse patterns until it gets to the next token or EOF.
Below is the the instruction that describes the task: ### Input: Will parse patterns until it gets to the next token or EOF. ### Response: def _parse_next_token(self): """Will parse patterns until it gets to the next token or EOF.""" while self._position < self.limit: token = self._next...
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: QueueContext for this QueueInstance :rtype: twilio.rest.api.v2010.account.queue.QueueContext ...
Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: QueueContext for this QueueInstance :rtype: twilio.rest.api.v2010.account.queue.QueueContext
Below is the the instruction that describes the task: ### Input: Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: QueueContext for this QueueInstance :rtype: twilio.rest.api.v2010....
def newidfobject(self, key, aname='', defaultvalues=True, **kwargs): """ Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", ...
Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interior Ceiling_class', Outside_Layer='LW Concrete', ...
Below is the the instruction that describes the task: ### Input: Add a new idfobject to the model. If you don't specify a value for a field, the default value will be set. For example :: newidfobject("CONSTRUCTION") newidfobject("CONSTRUCTION", Name='Interio...
def get_field_values_as_list(self,field): ''' :param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as...
:param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as_list('product_name_exact') ['Mauris risus risus l...
Below is the the instruction that describes the task: ### Input: :param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_va...
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
Remove a module from the context
Below is the the instruction that describes the task: ### Input: Remove a module from the context ### Response: def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
def verify_firebase_token(id_token, request, audience=None): """Verifies an ID Token issued by Firebase Authentication. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The ...
Verifies an ID Token issued by Firebase Authentication. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The audience that this token is intended for. This is typica...
Below is the the instruction that describes the task: ### Input: Verifies an ID Token issued by Firebase Authentication. Args: id_token (Union[str, bytes]): The encoded token. request (google.auth.transport.Request): The object used to make HTTP requests. audience (str): The...
def get_lb_pkgs(self): """Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages """ _filter = {'items': {'description': utils.query_filter('*Load Balancer*')}} packages = self.prod_pkg.getItems(id=...
Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages
Below is the the instruction that describes the task: ### Input: Retrieves the local load balancer packages. :returns: A dictionary containing the load balancer packages ### Response: def get_lb_pkgs(self): """Retrieves the local load balancer packages. :returns: A dictionary containing t...
def cancel(self): """ Cancel a pending publish task """ target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_url) logger.info("cancel(): %s", r.status_code)
Cancel a pending publish task
Below is the the instruction that describes the task: ### Input: Cancel a pending publish task ### Response: def cancel(self): """ Cancel a pending publish task """ target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_ur...
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_...
The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_array`
Below is the the instruction that describes the task: ### Input: The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler sys...
def mock_server_receive(sock, length): """Receive `length` bytes from a socket object.""" msg = b'' while length: chunk = sock.recv(length) if chunk == b'': raise socket.error(errno.ECONNRESET, 'closed') length -= len(chunk) msg += chunk return msg
Receive `length` bytes from a socket object.
Below is the the instruction that describes the task: ### Input: Receive `length` bytes from a socket object. ### Response: def mock_server_receive(sock, length): """Receive `length` bytes from a socket object.""" msg = b'' while length: chunk = sock.recv(length) if chunk == b'': ...
def connect(self): """ Starts the mongodb connection. Must be called before anything else will work. """ self.client = MongoClient(self.mongo_uri) self.db = self.client[self.db_name]
Starts the mongodb connection. Must be called before anything else will work.
Below is the the instruction that describes the task: ### Input: Starts the mongodb connection. Must be called before anything else will work. ### Response: def connect(self): """ Starts the mongodb connection. Must be called before anything else will work. """ self....
def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict """ array = super(PassportFile, self).to_array() array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str a...
Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict
Below is the the instruction that describes the task: ### Input: Serializes this PassportFile to a dictionary. :return: dictionary representation of this object. :rtype: dict ### Response: def to_array(self): """ Serializes this PassportFile to a dictionary. :return: dicti...
def _get_next_or_previous_by_order(self, is_next, **kwargs): """ Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. """ ...
Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method.
Below is the the instruction that describes the task: ### Input: Retrieves next or previous object by order. We implement our own version instead of Django's so we can hook into the published manager, concrete subclasses and our custom ``with_respect_to`` method. ### Response: def _get_next...
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613 ''' List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades ''' if salt.utils.data.is_true(refresh): refresh_db() upgrades = {} lines = __sal...
List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades
Below is the the instruction that describes the task: ### Input: List all available package upgrades on this system CLI Example: .. code-block:: bash salt '*' pkgutil.list_upgrades ### Response: def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613 ''' List all available pa...
def ndimage_to_list(image): """ Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages Arguments --------- image : ANTsImage n-dimensional image to split Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ...
Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages Arguments --------- image : ANTsImage n-dimensional image to split Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16'...
Below is the the instruction that describes the task: ### Input: Split a n dimensional ANTsImage into a list of n-1 dimensional ANTsImages Arguments --------- image : ANTsImage n-dimensional image to split Returns ------- list of ANTsImage types Example ------- >>>...
def iiOfAny(instance, classes): """ Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are comparing class seriali...
Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are comparing class serialized in one module and deserialized in anothe...
Below is the the instruction that describes the task: ### Input: Returns true, if `instance` is instance of any (iiOfAny) of the `classes`. This function doesn't use :py:func:`isinstance` check, it just compares the `class` names. This can be generaly dangerous, but it is really useful when you are ...
def init_environment(): """Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None """ os.environ['DJANGO_SETTINGS_MODULE'] = 'jukeboxcore.djsettings' pluginpath = os.pathsep.join((os.environ.get('JUKEBOX_PLUGIN_PATH', ''), constants.BUILTIN_...
Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Set environment variables that are important for the pipeline. :returns: None :rtype: None :raises: None ### Response: def init_environment(): """Set environment variables that are important for the pipeline. :returns: None ...
def create_session(self, user_agent, remote_address, client_version): """ Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id ...
Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id :rtype: int
Below is the the instruction that describes the task: ### Input: Create a new session. :param str user_agent: Client user agent :param str remote_addr: Remote address of client :param str client_version: Remote client version :return: The new session id :rtype: int ### Respo...
def checksum(self, path, hashtype='sha1'): """Returns the checksum of the given path.""" return self._handler.checksum(hashtype, posix_path(path))
Returns the checksum of the given path.
Below is the the instruction that describes the task: ### Input: Returns the checksum of the given path. ### Response: def checksum(self, path, hashtype='sha1'): """Returns the checksum of the given path.""" return self._handler.checksum(hashtype, posix_path(path))
def make_tensor_proto(values, dtype=None, shape=None, verify_shape=False): """Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: B...
Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: Boolean that enables verification of a shape of values. Returns: A `TensorPr...
Below is the the instruction that describes the task: ### Input: Create a TensorProto. Args: values: Values to put in the TensorProto. dtype: Optional tensor_pb2 DataType value. shape: List of integers representing the dimensions of tensor. verify_shape: Boolean that e...
def execute(self, image = None, command = None, app = None, writable = False, contain = False, bind = None, stream = False, nv = False, return_result=False): ''' execute: send a command to a container ...
execute: send a command to a container Parameters ========== image: full path to singularity image command: command to send to container app: if not None, execute a command in context of an app writable: This option makes the file system accessible as read/write ...
Below is the the instruction that describes the task: ### Input: execute: send a command to a container Parameters ========== image: full path to singularity image command: command to send to container app: if not None, execute a command in context of an app wri...
def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command n...
Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command needs it. To get the current value you can do: >>> from peltak.comm...
Below is the the instruction that describes the task: ### Input: Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command needs i...
def check_version(version, range_=None): """Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object. """ if range_ and version not in range_: raise RezBind...
Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object.
Below is the the instruction that describes the task: ### Input: Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object. ### Response: def check_version(version, range_=...
def put(self, key, value, lease=None): """Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean ...
Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean
Below is the the instruction that describes the task: ### Input: Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :retu...
def filter(self, *filt, **kwargs): """Filter this `TimeSeries` with an IIR or FIR filter Parameters ---------- *filt : filter arguments 1, 2, 3, or 4 arguments defining the filter to be applied, - an ``Nx1`` `~numpy.ndarray` of FIR coefficients ...
Filter this `TimeSeries` with an IIR or FIR filter Parameters ---------- *filt : filter arguments 1, 2, 3, or 4 arguments defining the filter to be applied, - an ``Nx1`` `~numpy.ndarray` of FIR coefficients - an ``Nx6`` `~numpy.ndarray` of SOS coeffi...
Below is the the instruction that describes the task: ### Input: Filter this `TimeSeries` with an IIR or FIR filter Parameters ---------- *filt : filter arguments 1, 2, 3, or 4 arguments defining the filter to be applied, - an ``Nx1`` `~numpy.ndarray` of FIR coe...
def find_node(self, name, create=False): """Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyEr...
Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool @raises KeyError: the name is not known and create was not specif...
Below is the the instruction that describes the task: ### Input: Find a node in the zone, possibly creating it. @param name: the name of the node to find @type name: dns.name.Name object or string @param create: should the node be created if it doesn't exist? @type create: bool ...
def apply(expr, func, axis=0, names=None, types=None, reduce=False, resources=None, keep_nulls=False, args=(), **kwargs): """ Apply a function to a row when axis=1 or column when axis=0. :param expr: :param func: function to apply :param axis: row when axis=1 else column :param names:...
Apply a function to a row when axis=1 or column when axis=0. :param expr: :param func: function to apply :param axis: row when axis=1 else column :param names: output names :param types: output types :param reduce: if True will return a sequence else return a collection :param resources: re...
Below is the the instruction that describes the task: ### Input: Apply a function to a row when axis=1 or column when axis=0. :param expr: :param func: function to apply :param axis: row when axis=1 else column :param names: output names :param types: output types :param reduce: if True wil...
def isdir(path): """ Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists. """ system = get_instance(path) # User may use directory path without trailing '/' ...
Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists.
Below is the the instruction that describes the task: ### Input: Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists. ### Response: def isdir(path): """ Return True if...
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
Read config values from `kwargs`.
Below is the the instruction that describes the task: ### Input: Read config values from `kwargs`. ### Response: def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(...
def get_session(user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, **kwargs): # type: (Optional[str], Optional[str], Optional[str], Any) -> requests.Session """Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user ag...
Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user agent parameter(s) to be completed. Args: user_agent (Optional[str]): User agent string. HDXPythonUtilities/X.X.X- is prefixed. user_agent_config_yaml (Optional[str]): ...
Below is the the instruction that describes the task: ### Input: Set up and return Session object that is set up with retrying. Requires either global user agent to be set or appropriate user agent parameter(s) to be completed. Args: user_agent (Optional[str]): User agent string. HDXPythonUtilities...
def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchbase.exceptions.NotFoundError: cb_.add(six.text_type(jid), {}, ttl=_get_ttl()) jid_doc = cb_.get(six.tex...
Save the load to the specified jid
Below is the the instruction that describes the task: ### Input: Save the load to the specified jid ### Response: def save_load(jid, clear_load, minion=None): ''' Save the load to the specified jid ''' cb_ = _get_connection() try: jid_doc = cb_.get(six.text_type(jid)) except couchb...
def _get_cross_pt_dual_simp(self, dual_simp): """ |normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices from...
|normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices from the dual convex hull i, j, k: plane index(same or...
Below is the the instruction that describes the task: ### Input: |normal| = 1, e_surf is plane's distance to (0, 0, 0), plane function: normal[0]x + normal[1]y + normal[2]z = e_surf from self: normal_e_m to get the plane functions dual_simp: (i, j, k) simplices f...
def do_videoplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return VideoPlaceholderNode(name, **params)
Method that parse the imageplaceholder template tag.
Below is the the instruction that describes the task: ### Input: Method that parse the imageplaceholder template tag. ### Response: def do_videoplaceholder(parser, token): """ Method that parse the imageplaceholder template tag. """ name, params = parse_placeholder(parser, token) return VideoPl...
def check(frame) -> None: """ Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values. """ # The first parameter is called `frame` rather than `self`, # but it's the ins...
Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values.
Below is the the instruction that describes the task: ### Input: Check that this frame contains acceptable values. Raise :exc:`~websockets.exceptions.WebSocketProtocolError` if this frame contains incorrect values. ### Response: def check(frame) -> None: """ Check that this frame c...
def result(self): """Return the context result object pulled from the persistence_engine if it has been set. """ if not self._result: if not self._persistence_engine: return None self._result = self._persistence_engine.get_context_result(self) ...
Return the context result object pulled from the persistence_engine if it has been set.
Below is the the instruction that describes the task: ### Input: Return the context result object pulled from the persistence_engine if it has been set. ### Response: def result(self): """Return the context result object pulled from the persistence_engine if it has been set. """ ...
def download_historical(tickers_list, output_folder): """Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :p...
Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv. :param tickers_list: List of tickers that will be returned. ...
Below is the the instruction that describes the task: ### Input: Download historical data from Yahoo Finance. Downloads full historical data from Yahoo Finance as CSV. The following fields are available: Adj Close, Close, High, Low, Open and Volume. Files will be saved to output_folder as <ticker>.csv....
def attach_template(self, _template, _key, **unbound_var_values): """Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_va...
Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer...
Below is the the instruction that describes the task: ### Input: Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_va...
def onecmd(self, statement: Union[Statement, str]) -> bool: """ This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative...
This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative acceptance of a str is present only for backw...
Below is the the instruction that describes the task: ### Input: This executes the actual do_* method for a command. If the command provided doesn't exist, then it executes default() instead. :param statement: intended to be a Statement instance parsed command from the input stream, alternative ...
def major_tick_mark(self): """ Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis. """ majorTickMark = self._element.majorTickMark if majorTickMark is None: return XL_TICK_MARK.CROSS return majorTickMark.v...
Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis.
Below is the the instruction that describes the task: ### Input: Read/write :ref:`XlTickMark` value specifying the type of major tick mark to display on this axis. ### Response: def major_tick_mark(self): """ Read/write :ref:`XlTickMark` value specifying the type of major tick mark ...
def make_application(): """ Create a application configured to send metrics. Metrics will be sent to localhost:8125 namespaced with ``webapps``. Run netcat or a similar listener then run this example. HTTP GETs will result in a metric like:: webapps.SimpleHandler.GET.204:255.24497032165527...
Create a application configured to send metrics. Metrics will be sent to localhost:8125 namespaced with ``webapps``. Run netcat or a similar listener then run this example. HTTP GETs will result in a metric like:: webapps.SimpleHandler.GET.204:255.24497032165527|ms
Below is the the instruction that describes the task: ### Input: Create a application configured to send metrics. Metrics will be sent to localhost:8125 namespaced with ``webapps``. Run netcat or a similar listener then run this example. HTTP GETs will result in a metric like:: webapps.SimpleH...
def _parse_binding_config(self, binding_config): """Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ]) """ parsed_...
Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ])
Below is the the instruction that describes the task: ### Input: Parse configured interface -> ACL bindings Bindings are returned as a set of (intf, name, direction) tuples: set([(intf1, acl_name, direction), (intf2, acl_name, direction), ..., ]) ### Response: def...
def WriteAllCrashDetails(client_id, crash_details, flow_session_id=None, hunt_session_id=None, token=None): """Updates the last crash attribute of the client.""" # AFF4. if data_store.AFF4Enabled(): with aff4.F...
Updates the last crash attribute of the client.
Below is the the instruction that describes the task: ### Input: Updates the last crash attribute of the client. ### Response: def WriteAllCrashDetails(client_id, crash_details, flow_session_id=None, hunt_session_id=None, ...
def search_shows_by_keyword(self, keyword, unite=0, source_site=None, category=None, release_year=None, area=None, orderby='view-count', paid=None, hasvideotype=None, page=1, count=20): ...
doc: http://open.youku.com/docs/doc?id=82
Below is the the instruction that describes the task: ### Input: doc: http://open.youku.com/docs/doc?id=82 ### Response: def search_shows_by_keyword(self, keyword, unite=0, source_site=None, category=None, release_year=None, area=None, orderby='view-c...
def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ total, correct = 0.0, 0.0 for true_response, guess_dict in conf_matrix.items(): for guess, count in guess_dict.items(): if t...
Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml
Below is the the instruction that describes the task: ### Input: Given a confusion matrix, returns the accuracy. Accuracy Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml ### Response: def accuracy(conf_matrix): """ Given a confusion matrix, returns the accuracy. Accuracy D...
def find_device(self, service_uuids=[], name=None, timeout_sec=TIMEOUT_SEC): """Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all a...
Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all and immediately return a result. When no device is found a value of None is ...
Below is the the instruction that describes the task: ### Input: Return the first device that advertises the specified service UUIDs or has the specified name. Will wait up to timeout_sec seconds for the device to be found, and if the timeout is zero then it will not wait at all and immediat...
def _reset(self, constraints=None): """Auxiliary method to reset the smtlib external solver to initial defaults""" if self._proc is None: self._start_proc() else: if self.support_reset: self._send("(reset)") for cfg in self._init: ...
Auxiliary method to reset the smtlib external solver to initial defaults
Below is the the instruction that describes the task: ### Input: Auxiliary method to reset the smtlib external solver to initial defaults ### Response: def _reset(self, constraints=None): """Auxiliary method to reset the smtlib external solver to initial defaults""" if self._proc is None: ...
def update_one(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one """ self._arctic_lib.check_quota() return self._collection.update_one(filter, update, **kwargs)
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one
Below is the the instruction that describes the task: ### Input: See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one ### Response: def update_one(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/col...
def load(self): """Load data from Graphite.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much time', target='waiting', ntype='common') else: self.waiting = True try: ...
Load data from Graphite.
Below is the the instruction that describes the task: ### Input: Load data from Graphite. ### Response: def load(self): """Load data from Graphite.""" LOGGER.debug('%s: start checking: %s', self.name, self.query) if self.waiting: self.notify('warning', 'Process takes too much ti...
def write_matrix(outputfile, matrix): """ Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write. """ try: stream = open(outputfile, 'w') for row...
Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write.
Below is the the instruction that describes the task: ### Input: Write down the provided matrix in the specified outputfile. :arg outputfile, name of the outputfile in which the QTLs found are written. :arg matrix, the list of lists of data to write. ### Response: def write_matrix(outputfile, matri...
def host_type(host): """ Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal or octal notation when begining...
Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal or octal notation when begining respectively with '0x'/'0X' and ...
Below is the the instruction that describes the task: ### Input: Correctly classify correct RFC 3986 compliant hostnames, but do not try hard to validate compliance anyway... NOTE: indeed we allow a small deviation from the RFC 3986: IPv4 addresses are allowed to contain bytes represented in hexadecimal...
def try_next(self): """Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change...
Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while stream.alive: change = stream.try_next() ...
Below is the the instruction that describes the task: ### Input: Advance the cursor without blocking indefinitely. This method returns the next change document without waiting indefinitely for the next change. For example:: with db.collection.watch() as stream: while st...
def get(self, key, default=None): """Return the value at key ``key``, or default value ``default`` which is None by default. >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.get('l0') ['1', '2', '3', '4'] >>> dc['l0'] ['1', '2', '3', '4'] >>...
Return the value at key ``key``, or default value ``default`` which is None by default. >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.get('l0') ['1', '2', '3', '4'] >>> dc['l0'] ['1', '2', '3', '4'] >>> dc.clear() :param key: key of valu...
Below is the the instruction that describes the task: ### Input: Return the value at key ``key``, or default value ``default`` which is None by default. >>> dc = Dictator() >>> dc['l0'] = [1, 2, 3, 4] >>> dc.get('l0') ['1', '2', '3', '4'] >>> dc['l0'] ['1', '...
def to_color(self, value, maxvalue, scale, minvalue=0.0): """ convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the i...
convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the input values in linear scale (default is 0) :return: the color correspo...
Below is the the instruction that describes the task: ### Input: convert continuous values into colors using matplotlib colorscales :param value: value to be converted :param maxvalue: max value in the colorscale :param scale: lin, log, sqrt :param minvalue: minimum of the input valu...
def author_structure(user): """ An author structure. """ return {'user_id': user.pk, 'user_login': user.get_username(), 'display_name': user.__str__(), 'user_email': user.email}
An author structure.
Below is the the instruction that describes the task: ### Input: An author structure. ### Response: def author_structure(user): """ An author structure. """ return {'user_id': user.pk, 'user_login': user.get_username(), 'display_name': user.__str__(), 'user_email...
def check_command(self, command): """ Check if command can be called. """ # Use `command` to see if command is callable, store exit code code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command)) # If exit code is not 0, report which command fai...
Check if command can be called.
Below is the the instruction that describes the task: ### Input: Check if command can be called. ### Response: def check_command(self, command): """ Check if command can be called. """ # Use `command` to see if command is callable, store exit code code = os.system("command ...
def print_summary(self) -> None: """ Prints the tasks' timing summary. """ print("Tasks execution time summary:") for mon_task in self._monitor_tasks: print("%s:\t%.4f (sec)" % (mon_task.task_name, mon_task.total_time))
Prints the tasks' timing summary.
Below is the the instruction that describes the task: ### Input: Prints the tasks' timing summary. ### Response: def print_summary(self) -> None: """ Prints the tasks' timing summary. """ print("Tasks execution time summary:") for mon_task in self._monitor_tasks: ...
def compile_protos(): """Builds necessary assets from sources.""" # If there's no makefile, we're likely installing from an sdist, # so there's no need to compile the protos (they should be already # compiled). if not os.path.exists(os.path.join(THIS_DIRECTORY, "makefile.py")): return # Only compile pr...
Builds necessary assets from sources.
Below is the the instruction that describes the task: ### Input: Builds necessary assets from sources. ### Response: def compile_protos(): """Builds necessary assets from sources.""" # If there's no makefile, we're likely installing from an sdist, # so there's no need to compile the protos (they should be al...
def delete_token(self, token_name, project_name, dataset_name): """ Delete a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on ...
Delete a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on token_name (str): Token name channel_name (str): Channel name project is based on Returns: bool: True if ...
Below is the the instruction that describes the task: ### Input: Delete a token with the given parameters. Arguments: project_name (str): Project name dataset_name (str): Dataset name project is based on token_name (str): Token name channel_name (str): Channel...
def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None): """ Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The...
Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The namespace to query :param name: The name of the resource instance to query :param label_selector: The label selector with which to filte...
Below is the the instruction that describes the task: ### Input: Stream events for a resource from the Kubernetes API :param resource: The API resource object that will be used to query the API :param namespace: The namespace to query :param name: The name of the resource instance to query ...
async def _connect_and_read(self): """Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' is specified we ...
Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' is specified we retrieve a new url and reconnect any time the...
Below is the the instruction that describes the task: ### Input: Retreives and connects to Slack's RTM API. Makes an authenticated call to Slack's RTM API to retrieve a websocket URL. Then connects to the message server and reads event messages as they come in. If 'auto_reconnect' ...
def adjoint(self): """Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This is currently not supported. Re...
Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This is currently not supported. Returns ------- ...
Below is the the instruction that describes the task: ### Input: Adjoint of this operator. The adjoint is given by taking the transpose of the matrix and the adjoint of each component operator. In weighted product spaces, the adjoint needs to take the weightings into account. This ...
def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0): """ 1. determine bin coverage 2. determine rRNA gene coverage 3. compare """ cov = {} # cov[scaffold] = [bases, length] s2bins, bins2s = parse_s2bins(s2bins) rna_cov = parse_rna(rna, s2bins, min_rna) s2bins, bins2s = fi...
1. determine bin coverage 2. determine rRNA gene coverage 3. compare
Below is the the instruction that describes the task: ### Input: 1. determine bin coverage 2. determine rRNA gene coverage 3. compare ### Response: def copies(mapping, s2bins, rna, min_rna = 800, mismatches = 0): """ 1. determine bin coverage 2. determine rRNA gene coverage 3. compare "...
def index_with_dupes(values_list, unique_together=2, model_number_i=0, serial_number_i=1, verbosity=1): '''Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == (...
Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5, 6): (5, 6, 7)}, {(5, 6): [(5, 6, 7), (5, 6, 8)]}) True
Below is the the instruction that describes the task: ### Input: Create dict from values_list with first N values as a compound key. Default N (number of columns assumbed to be "unique_together") is 2. >>> index_with_dupes([(1,2,3), (5,6,7), (5,6,8), (2,1,3)]) == ({(1, 2): (1, 2, 3), (2, 1): (2, 1, 3), (5,...
def experiment(parser, token): """ Split Testing experiment tag has the following syntax : {% experiment <experiment_name> <alternative> %} experiment content goes here {% endexperiment %} If the alternative name is neither 'test' nor 'control' an exception is raised during render...
Split Testing experiment tag has the following syntax : {% experiment <experiment_name> <alternative> %} experiment content goes here {% endexperiment %} If the alternative name is neither 'test' nor 'control' an exception is raised during rendering.
Below is the the instruction that describes the task: ### Input: Split Testing experiment tag has the following syntax : {% experiment <experiment_name> <alternative> %} experiment content goes here {% endexperiment %} If the alternative name is neither 'test' nor 'control' an exception i...
def set_mode(self, mode): """Set Abode alarm mode.""" if not mode: raise AbodeException(ERROR.MISSING_ALARM_MODE) elif mode.lower() not in CONST.ALL_MODES: raise AbodeException(ERROR.INVALID_ALARM_MODE, CONST.ALL_MODES) mode = mode.lower() response = sel...
Set Abode alarm mode.
Below is the the instruction that describes the task: ### Input: Set Abode alarm mode. ### Response: def set_mode(self, mode): """Set Abode alarm mode.""" if not mode: raise AbodeException(ERROR.MISSING_ALARM_MODE) elif mode.lower() not in CONST.ALL_MODES: raise Abod...
def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name) certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name) certificate_request_path = '{}/...
Sign certificate with acme_tiny for let's encrypt
Below is the the instruction that describes the task: ### Input: Sign certificate with acme_tiny for let's encrypt ### Response: def acme_sign_certificate(common_name, size=DEFAULT_KEY_SIZE): ''' Sign certificate with acme_tiny for let's encrypt ''' private_key_path = '{}/{}.key'.format(CERTIFI...
def move_active_window(x, y): """ Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized """ window_id = get_window_id() ...
Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized
Below is the the instruction that describes the task: ### Input: Moves the active window to a given position given the window_id and absolute co ordinates, --sync option auto passed in, will wait until actually moved before giving control back to us will do nothing if the window is maximized ### Response:...
def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.children) == (other.type, other.children)
Compare two nodes for equality.
Below is the the instruction that describes the task: ### Input: Compare two nodes for equality. ### Response: def _eq(self, other): """Compare two nodes for equality.""" return (self.type, self.children) == (other.type, other.children)
def _to_chi(rep, data, input_dim, output_dim): """Transform a QuantumChannel to the Chi representation.""" if rep == 'Chi': return data # Check valid n-qubit input _check_nqubit_dim(input_dim, output_dim) if rep == 'Operator': return _from_operator('Chi', data, input_dim, output_dim)...
Transform a QuantumChannel to the Chi representation.
Below is the the instruction that describes the task: ### Input: Transform a QuantumChannel to the Chi representation. ### Response: def _to_chi(rep, data, input_dim, output_dim): """Transform a QuantumChannel to the Chi representation.""" if rep == 'Chi': return data # Check valid n-qubit inpu...
def save_session(zap_helper, file_path): """Save the session.""" console.debug('Saving the session to "{0}"'.format(file_path)) zap_helper.zap.core.save_session(file_path, overwrite='true')
Save the session.
Below is the the instruction that describes the task: ### Input: Save the session. ### Response: def save_session(zap_helper, file_path): """Save the session.""" console.debug('Saving the session to "{0}"'.format(file_path)) zap_helper.zap.core.save_session(file_path, overwrite='true')
def sanitize_url(url: str) -> str: """ Sanitize the given url so that it can be used as a valid filename. :param url: url to create filename from :raise ValueError: when the given url can not be sanitized :return: created filename """ for part in reversed(url.split('/')): filename ...
Sanitize the given url so that it can be used as a valid filename. :param url: url to create filename from :raise ValueError: when the given url can not be sanitized :return: created filename
Below is the the instruction that describes the task: ### Input: Sanitize the given url so that it can be used as a valid filename. :param url: url to create filename from :raise ValueError: when the given url can not be sanitized :return: created filename ### Response: def sanitize_url(url: str) -> s...
def start(configfile=None, daemonize=False, environment=None, fastcgi=False, scgi=False, pidfile=None, cgi=False, debug=False): """Subscribe all engine plugins and start the engine.""" sys.path = [''] + sys.path # monkey patching cherrypy to disable config interpolation def new_as_d...
Subscribe all engine plugins and start the engine.
Below is the the instruction that describes the task: ### Input: Subscribe all engine plugins and start the engine. ### Response: def start(configfile=None, daemonize=False, environment=None, fastcgi=False, scgi=False, pidfile=None, cgi=False, debug=False): """Subscribe all engine plugins a...
def combine_lists_reducer( key: str, merged_list: list, component: COMPONENT ) -> list: """ Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: ...
Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: The accumulated list of values populated by previous calls to this reducer function :param component: T...
Below is the the instruction that describes the task: ### Input: Reducer function to combine the lists for the specified key into a single, flat list :param key: The key on the COMPONENT instances to operate upon :param merged_list: The accumulated list of values populated by previous c...
def chrome_tracing_object_transfer_dump(self, filename=None): """Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing ...
Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in the Chrome web browser and load the dumped file. Make sure to ...
Below is the the instruction that describes the task: ### Input: Return a list of transfer events that can viewed as a timeline. To view this information as a timeline, simply dump it as a json file by passing in "filename" or using using json.dump, and then load go to chrome://tracing in t...
def get(cls, id, api=None): """ Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object. """ id = Transform.to_resource(id) api = api if api else cls._API if 'get' in cls....
Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object.
Below is the the instruction that describes the task: ### Input: Fetches the resource from the server. :param id: Resource identifier :param api: sevenbridges Api instance. :return: Resource object. ### Response: def get(cls, id, api=None): """ Fetches the resource from the ...
def make_encoder(self,formula_dict,inter_list,param_dict): """ make the encoder function """ X_dict = {} Xcol_dict = {} encoder_dict = {} # first, replace param_dict[key] = values, with param_dict[key] = dmatrix for key in formula_dict: encodin...
make the encoder function
Below is the the instruction that describes the task: ### Input: make the encoder function ### Response: def make_encoder(self,formula_dict,inter_list,param_dict): """ make the encoder function """ X_dict = {} Xcol_dict = {} encoder_dict = {} # first, replace...
def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., lin_ftrs:Collection[int]=None, ps:Collection[float]=None, pad_idx:int=1) -> nn.Module: "Create a text classifier from `arch` and it...
Create a text classifier from `arch` and its `config`, maybe `pretrained`.
Below is the the instruction that describes the task: ### Input: Create a text classifier from `arch` and its `config`, maybe `pretrained`. ### Response: def get_text_classifier(arch:Callable, vocab_sz:int, n_class:int, bptt:int=70, max_len:int=20*70, config:dict=None, drop_mult:float=1., ...
def sign(self, method, params): """Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate """ query_str = utils.percent_encode(params.items(), True) ...
Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate
Below is the the instruction that describes the task: ### Input: Calculate signature with the SIG_METHOD(HMAC-SHA1) Returns a base64 encoeded string of the hex signature :param method: the http verb :param params: the params needs calculate ### Response: def sign(self, method, params): ...
def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0): """ Get the list of bids """ get_bids_data = {} if bid_ids: get_bids_data['bids[]'] = bid_ids if project_ids: get_bids_data['projects[]'] = project_ids get_bids_data['limit'] = limit get_bids_data['off...
Get the list of bids
Below is the the instruction that describes the task: ### Input: Get the list of bids ### Response: def get_bids(session, project_ids=[], bid_ids=[], limit=10, offset=0): """ Get the list of bids """ get_bids_data = {} if bid_ids: get_bids_data['bids[]'] = bid_ids if project_ids: ...
def acquire_lock(cls, mode, user=None): """Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty. """ if not user: return with...
Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty.
Below is the the instruction that describes the task: ### Input: Set a context manager to lock the whole storage. ``mode`` must either be "r" for shared access or "w" for exclusive access. ``user`` is the name of the logged in user or empty. ### Response: def acquire_lock(cls, mode, user=...
def get_next_invalid_time_from_t(self, timestamp): # pylint: disable=too-many-branches """ Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float ...
Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float
Below is the the instruction that describes the task: ### Input: Get the next invalid time :param timestamp: timestamp in seconds (of course) :type timestamp: int or float :return: timestamp of next invalid time :rtype: int or float ### Response: def get_next_invalid_time_from_t(se...
def _subset(self, subset): """Return a new pipeline with a subset of the sections""" pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(self): if group_name not in subset: continue pl[group_name] = pl_segment return pl
Return a new pipeline with a subset of the sections
Below is the the instruction that describes the task: ### Input: Return a new pipeline with a subset of the sections ### Response: def _subset(self, subset): """Return a new pipeline with a subset of the sections""" pl = Pipeline(bundle=self.bundle) for group_name, pl_segment in iteritems(s...
def hide(self, selections): '''Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection represent...
Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import Selection representation.hide({'atoms': Selection([0], sys...
Below is the the instruction that describes the task: ### Input: Hide objects in this representation. BallAndStickRepresentation support selections of atoms and bonds. To hide the first atom and the first bond you can use the following code:: from chemlab.mviewer.state import S...
def variableMissingValue(ncVar): """ Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. """ attributes = ncVarAttributes(ncVar) if not attribute...
Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found.
Below is the the instruction that describes the task: ### Input: Returns the missingData given a NetCDF variable Looks for one of the following attributes: _FillValue, missing_value, MissingValue, missingValue. Returns None if these attributes are not found. ### Response: def variableMissingValue(...
def process_cancel(self): """ Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing. """ ...
Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does nothing.
Below is the the instruction that describes the task: ### Input: Process the incoming token stream until it finds an end token DONE with the cancel flag set. At that point the connection should be ready to handle a new query. In case when no cancel request is pending this function does noth...
def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them """ if isinstance(field, forms.DateTimeField): value = parse_datetime(value) elif isinstance(field, forms.DateField): value ...
Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them
Below is the the instruction that describes the task: ### Input: Some types get serialized to JSON, as strings. If we know what they are supposed to be, we can deserialize them ### Response: def deserialize_by_field(value, field): """ Some types get serialized to JSON, as strings. If we know what t...
def write_data(hyper_params, mode, sequence, num_threads): """ Write a tf record containing a feature dict and a label dict. :param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}} :param mode: The mode sp...
Write a tf record containing a feature dict and a label dict. :param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}} :param mode: The mode specifies the purpose of the data. Typically it is either "train" or "validation". :param sequence: A tf.keras.uti...
Below is the the instruction that describes the task: ### Input: Write a tf record containing a feature dict and a label dict. :param hyper_params: The hyper parameters required for writing {"problem": {"augmentation": {"steps": Int}}} :param mode: The mode specifies the purpose of the data. Typically it i...
def _api_put(self, url, **kwargs): """ A convenience wrapper for _put. Adds headers, auth and base url by default """ kwargs['url'] = self.url + url kwargs['auth'] = self.auth headers = deepcopy(self.headers) headers.update(kwargs.get('headers', {})) ...
A convenience wrapper for _put. Adds headers, auth and base url by default
Below is the the instruction that describes the task: ### Input: A convenience wrapper for _put. Adds headers, auth and base url by default ### Response: def _api_put(self, url, **kwargs): """ A convenience wrapper for _put. Adds headers, auth and base url by default """ ...
def send_audio_packet(self, data, *, encode=True): """Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool ...
Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool Indicates if ``data`` should be encoded into Opus. ...
Below is the the instruction that describes the task: ### Input: Sends an audio packet composed of the data. You must be connected to play audio. Parameters ---------- data: bytes The :term:`py:bytes-like object` denoting PCM or Opus voice data. encode: bool ...
def get_objects(self): """ Returns dictionary with the instance objects for each form. Keys should match the corresponding form. """ objects = {} for key in six.iterkeys(self.form_classes): objects[key] = None return objects
Returns dictionary with the instance objects for each form. Keys should match the corresponding form.
Below is the the instruction that describes the task: ### Input: Returns dictionary with the instance objects for each form. Keys should match the corresponding form. ### Response: def get_objects(self): """ Returns dictionary with the instance objects for each form. Keys should match the ...
def process(self, frames, eod): """Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than the buffer size. "...
Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than the buffer size.
Below is the the instruction that describes the task: ### Input: Returns an iterator over tuples of the form (buffer, eod) where buffer is a fixed-sized block of data, and eod indicates whether this is the last block. In case padding is deactivated the last block may be smaller than ...
def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)
Given a dictionary of parameters, will extract the ranged task parameter value
Below is the the instruction that describes the task: ### Input: Given a dictionary of parameters, will extract the ranged task parameter value ### Response: def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ d...
def mget(self, *keys): """ -> #list of values at the specified @keys """ keys = list(map(self.get_key, keys)) return list(map(self._loads, self._client.mget(*keys)))
-> #list of values at the specified @keys
Below is the the instruction that describes the task: ### Input: -> #list of values at the specified @keys ### Response: def mget(self, *keys): """ -> #list of values at the specified @keys """ keys = list(map(self.get_key, keys)) return list(map(self._loads, self._client.mget(*keys)))
def deleteMetadata(self, remote, address, key): """Delete metadata of device""" try: return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key) except Exception as err: LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err))
Delete metadata of device
Below is the the instruction that describes the task: ### Input: Delete metadata of device ### Response: def deleteMetadata(self, remote, address, key): """Delete metadata of device""" try: return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key) ...
def parse_refresh(text): '''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) if match: url = match.group(1) if url.startswith('"'): url = url.strip('"') elif url.startswith("'"): ...
Parses text for HTTP Refresh URL. Returns: str, None
Below is the the instruction that describes the task: ### Input: Parses text for HTTP Refresh URL. Returns: str, None ### Response: def parse_refresh(text): '''Parses text for HTTP Refresh URL. Returns: str, None ''' match = re.search(r'url\s*=(.+)', text, re.IGNORECASE) ...
def from_dict(self, description): """Configures the task store to be the task_store described in description""" assert(self.ident == description['ident']) self.partitions = description['partitions'] self.indices = description['indices']
Configures the task store to be the task_store described in description
Below is the the instruction that describes the task: ### Input: Configures the task store to be the task_store described in description ### Response: def from_dict(self, description): """Configures the task store to be the task_store described in description""" assert(sel...