code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def atlasdb_cache_zonefile_info( con=None, path=None ): """ Load up and cache our zonefile inventory from the database """ global ZONEFILE_INV, NUM_ZONEFILES, ZONEFILE_INV_LOCK inv = None with ZONEFILE_INV_LOCK: inv_len = atlasdb_zonefile_inv_length( con=con, path=path ) inv...
Load up and cache our zonefile inventory from the database
Below is the the instruction that describes the task: ### Input: Load up and cache our zonefile inventory from the database ### Response: def atlasdb_cache_zonefile_info( con=None, path=None ): """ Load up and cache our zonefile inventory from the database """ global ZONEFILE_INV, NUM_ZONEFILES, ZO...
def _OpenFileObject(self, path_spec): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. Returns: pyqcow.file: a file-like object. Raises: PathSpecError: if the path specification is incorrect. """ if not path_spec.Ha...
Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. Returns: pyqcow.file: a file-like object. Raises: PathSpecError: if the path specification is incorrect.
Below is the the instruction that describes the task: ### Input: Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. Returns: pyqcow.file: a file-like object. Raises: PathSpecError: if the path specification is incorrect. ### Res...
def create_device(self, layout): """Creates a uinput device using the specified layout.""" events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [], ecodes.EV_REL: []} # Joystick device if layout.axes or layout.buttons or layout.hats: self.joystick_dev = next_joystic...
Creates a uinput device using the specified layout.
Below is the the instruction that describes the task: ### Input: Creates a uinput device using the specified layout. ### Response: def create_device(self, layout): """Creates a uinput device using the specified layout.""" events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [], ecodes.EV_R...
def get_series(self, *args, **kwargs): """Fetches lists of events. get /v1/public/events :returns: SeriesDataWrapper >>> #Find all the series that involved Wolverine >>> #wolverine's id: 1009718 >>> m = Marvel(public_key, private_key) >>> respo...
Fetches lists of events. get /v1/public/events :returns: SeriesDataWrapper >>> #Find all the series that involved Wolverine >>> #wolverine's id: 1009718 >>> m = Marvel(public_key, private_key) >>> response = m.get_series(characters="1009718") >...
Below is the the instruction that describes the task: ### Input: Fetches lists of events. get /v1/public/events :returns: SeriesDataWrapper >>> #Find all the series that involved Wolverine >>> #wolverine's id: 1009718 >>> m = Marvel(public_key, private_key...
def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. """ if self.meta_curriculum is not None: return env.reset(train_mode=self.fast_simulatio...
Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment.
Below is the the instruction that describes the task: ### Input: Resets the environment. Returns: A Data structure corresponding to the initial reset state of the environment. ### Response: def _reset_env(self, env: BaseUnityEnvironment): """Resets the environment. ...
def cancel_download_task(self, task_id, expires=None, **kwargs): """取消离线下载任务. :param task_id: 要取消的任务ID号。 :type task_id: str :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象 """ data = { 'expires': expires, ...
取消离线下载任务. :param task_id: 要取消的任务ID号。 :type task_id: str :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象
Below is the the instruction that describes the task: ### Input: 取消离线下载任务. :param task_id: 要取消的任务ID号。 :type task_id: str :param expires: 请求失效时间,如果有,则会校验。 :type expires: int :return: Response 对象 ### Response: def cancel_download_task(self, task_id, expires=None, **kwargs): ...
def ungrant_role(self, principal, role, object=None): """Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`).""" assert principal principal = unwrap(principal) session = object_session(object) if object is not None else db.session ...
Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`).
Below is the the instruction that describes the task: ### Input: Ungrant `role` to `user` (either globally, if `object` is None, or on the specific `object`). ### Response: def ungrant_role(self, principal, role, object=None): """Ungrant `role` to `user` (either globally, if `object` is None, or ...
def filename_from_url(url): """:return: detected filename or None""" fname = os.path.basename(urlparse.urlparse(url).path) if len(fname.strip(" \n\t.")) == 0: return None return fname
:return: detected filename or None
Below is the the instruction that describes the task: ### Input: :return: detected filename or None ### Response: def filename_from_url(url): """:return: detected filename or None""" fname = os.path.basename(urlparse.urlparse(url).path) if len(fname.strip(" \n\t.")) == 0: return None return...
def _new_packet_cb(self, packet): """Callback for newly arrived packets with TOC information""" chan = packet.channel cmd = packet.data[0] payload = packet.data[1:] if (chan == CHAN_SETTINGS): id = payload[0] error_status = payload[1] block = ...
Callback for newly arrived packets with TOC information
Below is the the instruction that describes the task: ### Input: Callback for newly arrived packets with TOC information ### Response: def _new_packet_cb(self, packet): """Callback for newly arrived packets with TOC information""" chan = packet.channel cmd = packet.data[0] payload =...
def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ' 'This will be required starting in {version}.' ) opts = {} global...
Generate a jid
Below is the the instruction that describes the task: ### Input: Generate a jid ### Response: def gen_jid(opts=None): ''' Generate a jid ''' if opts is None: salt.utils.versions.warn_until( 'Sodium', 'The `opts` argument was not passed into salt.utils.jid.gen_jid(). ...
def inject(self, other): """Add two compatible `Series` along their shared x-axis values. Parameters ---------- other : `Series` a `Series` whose xindex intersects with `self.xindex` Returns ------- out : `Series` the sum of `self` and `o...
Add two compatible `Series` along their shared x-axis values. Parameters ---------- other : `Series` a `Series` whose xindex intersects with `self.xindex` Returns ------- out : `Series` the sum of `self` and `other` along their shared x-axis valu...
Below is the the instruction that describes the task: ### Input: Add two compatible `Series` along their shared x-axis values. Parameters ---------- other : `Series` a `Series` whose xindex intersects with `self.xindex` Returns ------- out : `Series` ...
def _read_from_paths(): """ Try to read data from configuration paths ($HOME/_SETTINGS_PATH, /etc/_SETTINGS_PATH). """ home = os.environ.get("HOME", "/") home_path = os.path.join(home, _SETTINGS_PATH) etc_path = os.path.join("/etc", _SETTINGS_PATH) read_path = None if home and os.pa...
Try to read data from configuration paths ($HOME/_SETTINGS_PATH, /etc/_SETTINGS_PATH).
Below is the the instruction that describes the task: ### Input: Try to read data from configuration paths ($HOME/_SETTINGS_PATH, /etc/_SETTINGS_PATH). ### Response: def _read_from_paths(): """ Try to read data from configuration paths ($HOME/_SETTINGS_PATH, /etc/_SETTINGS_PATH). """ home =...
def format_time_small(seconds): """ Same as format_time() but always uses SI-prefix and 3 significant figures. """ if not isinstance(seconds, (int, float)): return str(seconds) if math.isnan(seconds): return "-" if abs(seconds)<1: milliseconds = 1000*seconds if...
Same as format_time() but always uses SI-prefix and 3 significant figures.
Below is the the instruction that describes the task: ### Input: Same as format_time() but always uses SI-prefix and 3 significant figures. ### Response: def format_time_small(seconds): """ Same as format_time() but always uses SI-prefix and 3 significant figures. """ if not isinstance(seconds, (i...
def symbol(self): """Gets the symbol under the current cursor.""" if self._symbol is None: self._symbol = self._symbol_extract(cache.RE_CURSOR) return self._symbol
Gets the symbol under the current cursor.
Below is the the instruction that describes the task: ### Input: Gets the symbol under the current cursor. ### Response: def symbol(self): """Gets the symbol under the current cursor.""" if self._symbol is None: self._symbol = self._symbol_extract(cache.RE_CURSOR) r...
def from_xml(cls, child, result=None): """ Create new way element from XML data :param child: XML node to be parsed :type child: xml.etree.ElementTree.Element :param result: The result this node belongs to :type result: overpy.Result :return: New Way oject ...
Create new way element from XML data :param child: XML node to be parsed :type child: xml.etree.ElementTree.Element :param result: The result this node belongs to :type result: overpy.Result :return: New Way oject :rtype: overpy.Way :raises overpy.exception.Eleme...
Below is the the instruction that describes the task: ### Input: Create new way element from XML data :param child: XML node to be parsed :type child: xml.etree.ElementTree.Element :param result: The result this node belongs to :type result: overpy.Result :return: New Way oj...
async def grant_model(self, username, model_uuid, acl='read'): """Grant a user access to a model. Note that if the user already has higher permissions than the provided ACL, this will do nothing (see revoke_model for a way to remove permissions). :param str username: Username ...
Grant a user access to a model. Note that if the user already has higher permissions than the provided ACL, this will do nothing (see revoke_model for a way to remove permissions). :param str username: Username :param str model_uuid: The UUID of the model to change. :par...
Below is the the instruction that describes the task: ### Input: Grant a user access to a model. Note that if the user already has higher permissions than the provided ACL, this will do nothing (see revoke_model for a way to remove permissions). :param str username: Username ...
def extract_table_identifiers(token_stream): """yields tuples of (schema_name, table_name, table_alias)""" for item in token_stream: if isinstance(item, IdentifierList): for identifier in item.get_identifiers(): # Sometimes Keywords (such as FROM ) are classified as ...
yields tuples of (schema_name, table_name, table_alias)
Below is the the instruction that describes the task: ### Input: yields tuples of (schema_name, table_name, table_alias) ### Response: def extract_table_identifiers(token_stream): """yields tuples of (schema_name, table_name, table_alias)""" for item in token_stream: if isinstance(item, Identifier...
def scale_out(self, blocks=1): """Scales out the number of active workers by 1. This method is notImplemented for threads and will raise the error if called. Parameters: blocks : int Number of blocks to be provisioned. """ r = [] for i in rang...
Scales out the number of active workers by 1. This method is notImplemented for threads and will raise the error if called. Parameters: blocks : int Number of blocks to be provisioned.
Below is the the instruction that describes the task: ### Input: Scales out the number of active workers by 1. This method is notImplemented for threads and will raise the error if called. Parameters: blocks : int Number of blocks to be provisioned. ### Response: def sc...
def merge_lines(top, bot, icod="top"): """ Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Default: "top"...
Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Default: "top". Returns: str: The merge of both lines...
Below is the the instruction that describes the task: ### Input: Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Defa...
def _combine_w0614(self, messages): """ For the "unused import from wildcard import" messages, we want to combine all warnings about the same line into a single message. """ by_loc = defaultdict(list) out = [] for message in messages: if messa...
For the "unused import from wildcard import" messages, we want to combine all warnings about the same line into a single message.
Below is the the instruction that describes the task: ### Input: For the "unused import from wildcard import" messages, we want to combine all warnings about the same line into a single message. ### Response: def _combine_w0614(self, messages): """ For the "unused import from wildca...
def remove_repositories(repositories, default_repositories): """ Remove no default repositories """ repos = [] for repo in repositories: if repo in default_repositories: repos.append(repo) return repos
Remove no default repositories
Below is the the instruction that describes the task: ### Input: Remove no default repositories ### Response: def remove_repositories(repositories, default_repositories): """ Remove no default repositories """ repos = [] for repo in repositories: if repo in default_repositories: ...
def matrix_multiplication_blockwise(self, matrix, blocksize): """ http://en.wikipedia.org/wiki/Block_matrix#Block_matrix_multiplication """ #Create the blockwise version of self and matrix selfBlockwise = self.matrix_to_blockmatrix(blocksize) matrixBlockwise = matrix.matr...
http://en.wikipedia.org/wiki/Block_matrix#Block_matrix_multiplication
Below is the the instruction that describes the task: ### Input: http://en.wikipedia.org/wiki/Block_matrix#Block_matrix_multiplication ### Response: def matrix_multiplication_blockwise(self, matrix, blocksize): """ http://en.wikipedia.org/wiki/Block_matrix#Block_matrix_multiplication """ ...
def analyze(self): """Run complete anaylysis and return results.""" self.calculate_cache_access() self.calculate_cycles() self.results['flops per iteration'] = sum(self.kernel._flops.values()) return self.results
Run complete anaylysis and return results.
Below is the the instruction that describes the task: ### Input: Run complete anaylysis and return results. ### Response: def analyze(self): """Run complete anaylysis and return results.""" self.calculate_cache_access() self.calculate_cycles() self.results['flops per iteration'] = s...
def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype """ if ary is not None: shape, dtype = ary.shape, ary.dtype elif shape is None or dtype is None: raise ValueErr...
Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype
Below is the the instruction that describes the task: ### Input: Returns a random array of the same shape and type as the supplied array argument, or the supplied shape and dtype ### Response: def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as th...
def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs): """ test func for kwargs parseing """ foo = kwargs.get('foo', None) bar = kwargs.pop('bar', 4) foo2 = kwargs['foo2'] foobar = str(foo) + str(bar) + str(foo2) return foobar
test func for kwargs parseing
Below is the the instruction that describes the task: ### Input: test func for kwargs parseing ### Response: def dummy_func(arg1, arg2, arg3=None, arg4=[1, 2, 3], arg5={}, **kwargs): """ test func for kwargs parseing """ foo = kwargs.get('foo', None) bar = kwargs.pop('bar', 4) foo2 = kwargs...
def match_function_id(self, function_id, match): """Matches the function identified by the given ``Id``. arg: function_id (osid.id.Id): the Id of the ``Function`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgumen...
Matches the function identified by the given ``Id``. arg: function_id (osid.id.Id): the Id of the ``Function`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: NullArgument - ``function_id`` is ``null`` *compliance: mandato...
Below is the the instruction that describes the task: ### Input: Matches the function identified by the given ``Id``. arg: function_id (osid.id.Id): the Id of the ``Function`` arg: match (boolean): ``true`` if a positive match, ``false`` for a negative match raise: Nu...
def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: """Build an edge predicate that passes for edges whose data dictionaries match the given dictionary. If the given dictionary is empty, will always evaluate to true. :param annotations: The annotation query dic...
Build an edge predicate that passes for edges whose data dictionaries match the given dictionary. If the given dictionary is empty, will always evaluate to true. :param annotations: The annotation query dict to match
Below is the the instruction that describes the task: ### Input: Build an edge predicate that passes for edges whose data dictionaries match the given dictionary. If the given dictionary is empty, will always evaluate to true. :param annotations: The annotation query dict to match ### Response: def build...
def unlink_parameter(self, param): """ :param param: param object to remove from being a parameter of this parameterized object. """ if not param in self.parameters: try: raise HierarchyError("{} does not belong to this object {}, remove parameters directly fr...
:param param: param object to remove from being a parameter of this parameterized object.
Below is the the instruction that describes the task: ### Input: :param param: param object to remove from being a parameter of this parameterized object. ### Response: def unlink_parameter(self, param): """ :param param: param object to remove from being a parameter of this parameterized object. ...
def alpha_gen(x): """ Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/cplfit, though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. Docstring for the generated alpha function:: ...
Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/cplfit, though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. Docstring for the generated alpha function:: Given a sorted da...
Below is the the instruction that describes the task: ### Input: Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/cplfit, though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. Do...
def marginal_counts(counts, meas_qubits): """ Compute the marginal counts for a subset of measured qubits. Args: counts (dict): the counts returned from a backend ({str: int}). meas_qubits (list[int]): the qubits to return the marginal counts distribution fo...
Compute the marginal counts for a subset of measured qubits. Args: counts (dict): the counts returned from a backend ({str: int}). meas_qubits (list[int]): the qubits to return the marginal counts distribution for. Returns: dict: A counts dict for the m...
Below is the the instruction that describes the task: ### Input: Compute the marginal counts for a subset of measured qubits. Args: counts (dict): the counts returned from a backend ({str: int}). meas_qubits (list[int]): the qubits to return the marginal counts ...
def options(self, session=None): """Get the options set on this collection. Returns a dictionary of options and their values - see :meth:`~pymongo.database.Database.create_collection` for more information on the possible options. Returns an empty dictionary if the collection has...
Get the options set on this collection. Returns a dictionary of options and their values - see :meth:`~pymongo.database.Database.create_collection` for more information on the possible options. Returns an empty dictionary if the collection has not been created yet. :Parameters:...
Below is the the instruction that describes the task: ### Input: Get the options set on this collection. Returns a dictionary of options and their values - see :meth:`~pymongo.database.Database.create_collection` for more information on the possible options. Returns an empty diction...
def match(self): """ Used to get exploitable result of re.search :return: The data of the match status. :rtype: mixed """ # We initate this variable which gonna contain the returned data result = [] # We compile the regex string to_match = comp(...
Used to get exploitable result of re.search :return: The data of the match status. :rtype: mixed
Below is the the instruction that describes the task: ### Input: Used to get exploitable result of re.search :return: The data of the match status. :rtype: mixed ### Response: def match(self): """ Used to get exploitable result of re.search :return: The data of the match s...
def editMeta(self, title=None, description=None): """Set metadata for photo. (flickr.photos.setMeta)""" method = 'flickr.photosets.editMeta' if title is None: title = self.title if description is None: description = self.description _dopost(m...
Set metadata for photo. (flickr.photos.setMeta)
Below is the the instruction that describes the task: ### Input: Set metadata for photo. (flickr.photos.setMeta) ### Response: def editMeta(self, title=None, description=None): """Set metadata for photo. (flickr.photos.setMeta)""" method = 'flickr.photosets.editMeta' if title is None: ...
def get(self, block=True, timeout=None): """get.""" try: item = super().get(block, timeout) self._getsocket.recv(1) return item except queue.Empty: raise queue.Empty
get.
Below is the the instruction that describes the task: ### Input: get. ### Response: def get(self, block=True, timeout=None): """get.""" try: item = super().get(block, timeout) self._getsocket.recv(1) return item except queue.Empty: raise queue...
def get_long_task_info(self, long_task_id, expand=None, callback=None): """ Returns information about a long-running task. :param long_task_id (string): The key of the task to be returned. :param expand (string): A comma separated list of properties to expand on the task. Default: Empty ...
Returns information about a long-running task. :param long_task_id (string): The key of the task to be returned. :param expand (string): A comma separated list of properties to expand on the task. Default: Empty :param callback: OPTIONAL: The callback to execute on the resulting data, before the...
Below is the the instruction that describes the task: ### Input: Returns information about a long-running task. :param long_task_id (string): The key of the task to be returned. :param expand (string): A comma separated list of properties to expand on the task. Default: Empty :param callback...
def env_string(name, required=False, default=empty): """Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: ...
Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :type name: str :param required: Whether the environment variable i...
Below is the the instruction that describes the task: ### Input: Pulls an environment variable out of the environment returning it as a string. If not present in the environment and no default is specified, an empty string is returned. :param name: The name of the environment variable be pulled :ty...
def method(self, method): """Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str """ if method is None: raise ValueError("Invalid value...
Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str
Below is the the instruction that describes the task: ### Input: Sets the method of this Notificant. The notification method used for notification target. # noqa: E501 :param method: The method of this Notificant. # noqa: E501 :type: str ### Response: def method(self, method): "...
def warn(self, cmd, desc=''): ''' Style for warning message. ''' return self._label_desc(cmd, desc, self.warn_color)
Style for warning message.
Below is the the instruction that describes the task: ### Input: Style for warning message. ### Response: def warn(self, cmd, desc=''): ''' Style for warning message. ''' return self._label_desc(cmd, desc, self.warn_color)
def _execute_trade_cmd( self, trade_cmd, users, expire_seconds, entrust_prop, send_interval ): """分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: """ for use...
分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return:
Below is the the instruction that describes the task: ### Input: 分发交易指令到对应的 user 并执行 :param trade_cmd: :param users: :param expire_seconds: :param entrust_prop: :param send_interval: :return: ### Response: def _execute_trade_cmd( self, trade_cmd, users, expir...
def as_frame(self): """ :return: Multi-Index DataFrame """ sids, frames = self.response_map.keys(), self.response_map.values() frame = pd.concat(frames, keys=sids, axis=1) return frame
:return: Multi-Index DataFrame
Below is the the instruction that describes the task: ### Input: :return: Multi-Index DataFrame ### Response: def as_frame(self): """ :return: Multi-Index DataFrame """ sids, frames = self.response_map.keys(), self.response_map.values() frame = pd.concat(frames, keys=sids, axis=1) r...
def end_of(self, event_id, import_options=True): """ Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE ...
Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE
Below is the the instruction that describes the task: ### Input: Set Date-Picker as the end-date of a date-range. Args: - event_id (string): User-defined unique id for linking two fields - import_options (bool): inherit options from start-date input, default: TRUE ### ...
def load_examples(tmp_dir, prop_train=0.09, prop_val=0.01): """Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits. "...
Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits.
Below is the the instruction that describes the task: ### Input: Loads exampls from the tsv file. Args: tmp_dir: temp directory. prop_train: proportion of the train data prop_val: proportion of the validation data Returns: All examples in the dataset pluse train, test, and development splits. ...
def QA_fetch_stock_min(code, start, end, format='numpy', frequence='1min', collections=DATABASE.stock_min): '获取股票分钟线' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: frequence = '5min' elif frequence in ['15min', '15m']: frequence = '15min' ...
获取股票分钟线
Below is the the instruction that describes the task: ### Input: 获取股票分钟线 ### Response: def QA_fetch_stock_min(code, start, end, format='numpy', frequence='1min', collections=DATABASE.stock_min): '获取股票分钟线' if frequence in ['1min', '1m']: frequence = '1min' elif frequence in ['5min', '5m']: ...
def encoding_and_executable(notebook, metadata, ext): """Return encoding and executable lines for a notebook, if applicable""" lines = [] comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment') jupytext_metadata = metadata.get('jupytext', {}) if ext not in ['.Rmd', '.md'] and 'executable' in jupyt...
Return encoding and executable lines for a notebook, if applicable
Below is the the instruction that describes the task: ### Input: Return encoding and executable lines for a notebook, if applicable ### Response: def encoding_and_executable(notebook, metadata, ext): """Return encoding and executable lines for a notebook, if applicable""" lines = [] comment = _SCRIPT_E...
def utf8(s): """ Coerce an object to bytes if it is Unicode. """ if isinstance(s, mitogen.core.UnicodeType): s = s.encode('utf-8') return s
Coerce an object to bytes if it is Unicode.
Below is the the instruction that describes the task: ### Input: Coerce an object to bytes if it is Unicode. ### Response: def utf8(s): """ Coerce an object to bytes if it is Unicode. """ if isinstance(s, mitogen.core.UnicodeType): s = s.encode('utf-8') return s
def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__dict__) d.pop('_weights', None) d.pop('_A', None) d.pop('_B', None) d.pop('_f', None) d.pop('_mK', None) ...
Saves all of the de-trending information to disk in an `npz` file
Below is the the instruction that describes the task: ### Input: Saves all of the de-trending information to disk in an `npz` file ### Response: def _save_npz(self): ''' Saves all of the de-trending information to disk in an `npz` file ''' # Save the data d = dict(self.__d...
def download_pip_based_installations(env, pip_invocation, requirements, download_cache_folder): """Download requirements for pip based installation.""" if config.installation_cache_folder() is None: raise EnvironmentSetupError("Local installation cache folder not " "defined but ...
Download requirements for pip based installation.
Below is the the instruction that describes the task: ### Input: Download requirements for pip based installation. ### Response: def download_pip_based_installations(env, pip_invocation, requirements, download_cache_folder): """Download requirements for pip based installation.""" if config.insta...
def now (time_t = None, slug = False): '''Gives current time as tuple (t, t_str) where t is integer portion from time.time() t_str string of t using DEFAULT_TIMEFORMAT ''' if not time_t: time_t = time () time_s = strftime ( DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT, gmtime (time_t...
Gives current time as tuple (t, t_str) where t is integer portion from time.time() t_str string of t using DEFAULT_TIMEFORMAT
Below is the the instruction that describes the task: ### Input: Gives current time as tuple (t, t_str) where t is integer portion from time.time() t_str string of t using DEFAULT_TIMEFORMAT ### Response: def now (time_t = None, slug = False): '''Gives current time as tuple (t, t_str) where t is i...
def make_published(self, request, queryset): """ Marks selected news items as published """ rows_updated = queryset.update(is_published=True) self.message_user(request, ungettext('%(count)d newsitem was published', ...
Marks selected news items as published
Below is the the instruction that describes the task: ### Input: Marks selected news items as published ### Response: def make_published(self, request, queryset): """ Marks selected news items as published """ rows_updated = queryset.update(is_published=True) self.messag...
def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: - url (str): xbahn connection url """ return connection(url, prefix=get_prefix(prefix), **kwargs)
connect and return a connection instance from url arguments: - url (str): xbahn connection url
Below is the the instruction that describes the task: ### Input: connect and return a connection instance from url arguments: - url (str): xbahn connection url ### Response: def connect(url, prefix=None, **kwargs): """ connect and return a connection instance from url arguments: -...
def get_port_profile_for_vlan(self, vlan_id, device_id): """Returns Vlan id associated with the port profile.""" entry = self.session.query(ucsm_model.PortProfile).filter_by( vlan_id=vlan_id, device_id=device_id).first() return entry.profile_id if entry else None
Returns Vlan id associated with the port profile.
Below is the the instruction that describes the task: ### Input: Returns Vlan id associated with the port profile. ### Response: def get_port_profile_for_vlan(self, vlan_id, device_id): """Returns Vlan id associated with the port profile.""" entry = self.session.query(ucsm_model.PortProfile).filter...
def get_metric_index(self, data_source): """ This function will return the elasticsearch index for a corresponding data source. It chooses in between the default and the user inputed es indices and returns the user inputed one if it is available. :param data_source: the data sou...
This function will return the elasticsearch index for a corresponding data source. It chooses in between the default and the user inputed es indices and returns the user inputed one if it is available. :param data_source: the data source for which the index has to be returned :returns: ...
Below is the the instruction that describes the task: ### Input: This function will return the elasticsearch index for a corresponding data source. It chooses in between the default and the user inputed es indices and returns the user inputed one if it is available. :param data_source: the ...
def queue_file_io_task(self, fileobj, data, offset): """Queue IO write for submission to the IO executor. This method accepts an IO executor and information about the downloaded data, and handles submitting this to the IO executor. This method may defer submission to the IO executor if...
Queue IO write for submission to the IO executor. This method accepts an IO executor and information about the downloaded data, and handles submitting this to the IO executor. This method may defer submission to the IO executor if necessary.
Below is the the instruction that describes the task: ### Input: Queue IO write for submission to the IO executor. This method accepts an IO executor and information about the downloaded data, and handles submitting this to the IO executor. This method may defer submission to the IO execut...
def get_bright(mask, image, ret_data="avg,sd"): """Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool ...
Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtype bool The mask values, True where the event is located in `i...
Below is the the instruction that describes the task: ### Input: Compute avg and/or std of the event brightness The event brightness is defined by the gray-scale values of the image data within the event mask area. Parameters ---------- mask: ndarray or list of ndarrays of shape (M,N) and dtyp...
def get_chunk_coords(self): """ Return the x,z coordinates and length of the chunks that are defined in te regionfile. This includes chunks which may not be readable for whatever reason. This method is deprecated. Use :meth:`get_metadata` instead. """ chunks = []...
Return the x,z coordinates and length of the chunks that are defined in te regionfile. This includes chunks which may not be readable for whatever reason. This method is deprecated. Use :meth:`get_metadata` instead.
Below is the the instruction that describes the task: ### Input: Return the x,z coordinates and length of the chunks that are defined in te regionfile. This includes chunks which may not be readable for whatever reason. This method is deprecated. Use :meth:`get_metadata` instead. ### Respon...
def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: return block, column block = block.previous() raise UserWarning()
Find end of the last expression
Below is the the instruction that describes the task: ### Input: Find end of the last expression ### Response: def _findExpressionEnd(self, block): """Find end of the last expression """ while block.isValid(): column = self._lastColumn(block) if column > 0: ...
def get_meta(self, name, meta_key=None): '''Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. If a differen...
Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. If a different meta key needs to be matched, it can be specified ...
Below is the the instruction that describes the task: ### Input: Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. ...
def verify_image_checksum(image_location, expected_checksum): """Verifies checksum (md5) of image file against the expected one. This method generates the checksum of the image file on the fly and verifies it against the expected checksum provided as argument. :param image_location: location of image ...
Verifies checksum (md5) of image file against the expected one. This method generates the checksum of the image file on the fly and verifies it against the expected checksum provided as argument. :param image_location: location of image file whose checksum is verified. :param expected_checksum: checks...
Below is the the instruction that describes the task: ### Input: Verifies checksum (md5) of image file against the expected one. This method generates the checksum of the image file on the fly and verifies it against the expected checksum provided as argument. :param image_location: location of image ...
def description(self, request, id, description): """Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description """ request.d...
Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description
Below is the the instruction that describes the task: ### Input: Updates the description of a gist Arguments: request: an initial request object id: the id of the gist we want to edit the description for description: the new description ### Response: def de...
def macro(name): """Replaces :func:`~flask_admin.model.template.macro`, adding support for using macros imported from another file. For example: .. code:: html+jinja {# templates/admin/column_formatters.html #} {% macro email(model, column) %} {% set address = model[column] %} ...
Replaces :func:`~flask_admin.model.template.macro`, adding support for using macros imported from another file. For example: .. code:: html+jinja {# templates/admin/column_formatters.html #} {% macro email(model, column) %} {% set address = model[column] %} <a href="mailto...
Below is the the instruction that describes the task: ### Input: Replaces :func:`~flask_admin.model.template.macro`, adding support for using macros imported from another file. For example: .. code:: html+jinja {# templates/admin/column_formatters.html #} {% macro email(model, column) %} ...
def alias(*aliases): """ Decorating a class with @alias('FOO', 'BAR', ..) allows the class to be referenced by each of the names provided as arguments. """ def decorator(cls): # alias must be set in globals from caller's frame caller = sys._getframe(1) globals_dict = caller.f...
Decorating a class with @alias('FOO', 'BAR', ..) allows the class to be referenced by each of the names provided as arguments.
Below is the the instruction that describes the task: ### Input: Decorating a class with @alias('FOO', 'BAR', ..) allows the class to be referenced by each of the names provided as arguments. ### Response: def alias(*aliases): """ Decorating a class with @alias('FOO', 'BAR', ..) allows the class to ...
def prep_itasser_modeling(self, itasser_installation, itlib_folder, runtype, create_in_dir=None, execute_from_dir=None, all_genes=False, print_exec=False, **kwargs): """Prepare to run I-TASSER homology modeling for genes without structures, or all genes. Args: it...
Prepare to run I-TASSER homology modeling for genes without structures, or all genes. Args: itasser_installation (str): Path to I-TASSER folder, i.e. ``~/software/I-TASSER4.4`` itlib_folder (str): Path to ITLIB folder, i.e. ``~/software/ITLIB`` runtype: How you will be runni...
Below is the the instruction that describes the task: ### Input: Prepare to run I-TASSER homology modeling for genes without structures, or all genes. Args: itasser_installation (str): Path to I-TASSER folder, i.e. ``~/software/I-TASSER4.4`` itlib_folder (str): Path to ITLIB folder,...
def delete_gene(self, *gene_ids): """Delete one or more gene ids form the list.""" self.gene_ids = [gene_id for gene_id in self.gene_ids if gene_id not in gene_ids]
Delete one or more gene ids form the list.
Below is the the instruction that describes the task: ### Input: Delete one or more gene ids form the list. ### Response: def delete_gene(self, *gene_ids): """Delete one or more gene ids form the list.""" self.gene_ids = [gene_id for gene_id in self.gene_ids if gene_id not ...
def C_ISA_1932_nozzle(D, Do, rho, mu, m): r'''Calculates the coefficient of discharge of an ISA 1932 style nozzle used for measuring flow rate of fluid, based on the geometry of the nozzle, mass flow rate through the nozzle, and the density and viscosity of the fluid. .. math:: C = 0....
r'''Calculates the coefficient of discharge of an ISA 1932 style nozzle used for measuring flow rate of fluid, based on the geometry of the nozzle, mass flow rate through the nozzle, and the density and viscosity of the fluid. .. math:: C = 0.9900 - 0.2262\beta^{4.1} - (0.00175\beta^2 - 0...
Below is the the instruction that describes the task: ### Input: r'''Calculates the coefficient of discharge of an ISA 1932 style nozzle used for measuring flow rate of fluid, based on the geometry of the nozzle, mass flow rate through the nozzle, and the density and viscosity of the fluid. ....
def fcoe_fcoe_fabric_map_fcoe_fcf_map_fcf_map_fcf_rbid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade.com:mgmt:brocade-fcoe") fcoe_fabric_map = ET.SubElement(fcoe, "fcoe-fabric-map") fcoe_f...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def fcoe_fcoe_fabric_map_fcoe_fcf_map_fcf_map_fcf_rbid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe = ET.SubElement(config, "fcoe", xmlns="urn:brocade...
def _get_recursive_state(widget, store=None, drop_defaults=False): """Gets the embed state of a widget, and all other widgets it refers to as well""" if store is None: store = dict() state = widget._get_embed_state(drop_defaults=drop_defaults) store[widget.model_id] = state # Loop over all ...
Gets the embed state of a widget, and all other widgets it refers to as well
Below is the the instruction that describes the task: ### Input: Gets the embed state of a widget, and all other widgets it refers to as well ### Response: def _get_recursive_state(widget, store=None, drop_defaults=False): """Gets the embed state of a widget, and all other widgets it refers to as well""" i...
def fill_blind_pores(im): r""" Fills all pores that are not connected to the edges of the image. Parameters ---------- im : ND-array The image of the porous material Returns ------- image : ND-array A version of ``im`` but with all the disconnected pores removed. S...
r""" Fills all pores that are not connected to the edges of the image. Parameters ---------- im : ND-array The image of the porous material Returns ------- image : ND-array A version of ``im`` but with all the disconnected pores removed. See Also -------- find_...
Below is the the instruction that describes the task: ### Input: r""" Fills all pores that are not connected to the edges of the image. Parameters ---------- im : ND-array The image of the porous material Returns ------- image : ND-array A version of ``im`` but with all...
def _generate(num_particles, D, box, rs): """Generate a list of `Particle` objects.""" X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1 Y0 = rs.rand(num_particles) * (box.y2 - box.y1) + box.y1 Z0 = rs.rand(num_particles) * (box.z2 - box.z1) + box.z1 return [Particle(D=D, ...
Generate a list of `Particle` objects.
Below is the the instruction that describes the task: ### Input: Generate a list of `Particle` objects. ### Response: def _generate(num_particles, D, box, rs): """Generate a list of `Particle` objects.""" X0 = rs.rand(num_particles) * (box.x2 - box.x1) + box.x1 Y0 = rs.rand(num_particles) *...
def get_data(name): """ This function extracts the data from the Tplot Variables stored in memory. Parameters: name : str Name of the tplot variable Returns: time_val : pandas dataframe index data_val : list Examples: >>> # R...
This function extracts the data from the Tplot Variables stored in memory. Parameters: name : str Name of the tplot variable Returns: time_val : pandas dataframe index data_val : list Examples: >>> # Retrieve the data from Variable 1...
Below is the the instruction that describes the task: ### Input: This function extracts the data from the Tplot Variables stored in memory. Parameters: name : str Name of the tplot variable Returns: time_val : pandas dataframe index data_val : list ...
def write_items(self, calendar): """ Write all events to the calendar """ for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_FIELD_MAP: val = item.get(ifield) if val is not None: event.add(e...
Write all events to the calendar
Below is the the instruction that describes the task: ### Input: Write all events to the calendar ### Response: def write_items(self, calendar): """ Write all events to the calendar """ for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_...
def default_subreddits(self, *args, **kwargs): """Return a get_content generator for the default subreddits. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. """ url = self.config['default_subreddits'] ...
Return a get_content generator for the default subreddits. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered.
Below is the the instruction that describes the task: ### Input: Return a get_content generator for the default subreddits. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` parameter cannot be altered. ### Response: def default_subreddits(self, *args, **kwar...
def load(name, **kwargs): ''' Loads the configuration provided onto the junos device. .. code-block:: yaml Install the mentioned config: junos: - load - path: salt//configs/interface.set .. code-block:: yaml Install the mentioned ...
Loads the configuration provided onto the junos device. .. code-block:: yaml Install the mentioned config: junos: - load - path: salt//configs/interface.set .. code-block:: yaml Install the mentioned config: junos: ...
Below is the the instruction that describes the task: ### Input: Loads the configuration provided onto the junos device. .. code-block:: yaml Install the mentioned config: junos: - load - path: salt//configs/interface.set .. code-block:: yaml ...
def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs): "Agrego un PrecioClase a la liq." precioclase = dict(claseTabaco=clase_tabaco, precio=precio, totalKilos=total_kilos, totalFardos=total_fardos) self.solicitud['precioClas...
Agrego un PrecioClase a la liq.
Below is the the instruction that describes the task: ### Input: Agrego un PrecioClase a la liq. ### Response: def AgregarPrecioClase(self, clase_tabaco, precio, total_kilos=None, total_fardos=None, **kwargs): "Agrego un PrecioClase a la liq." precioclase = dict(claseTabaco=clase_tabaco, precio=pre...
def commissionerUnregister(self): """stop commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner """ print '%s call commissionerUnregister' % self.port cmd = 'commissioner stop' print cmd return self._...
stop commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner
Below is the the instruction that describes the task: ### Input: stop commissioner Returns: True: successful to stop commissioner False: fail to stop commissioner ### Response: def commissionerUnregister(self): """stop commissioner Returns: True: succes...
def getLogger(cls, name=None): """ Retrieves the Python native logger :param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root. :return: The instacne of the Python logger object. """ return logging.getLo...
Retrieves the Python native logger :param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root. :return: The instacne of the Python logger object.
Below is the the instruction that describes the task: ### Input: Retrieves the Python native logger :param name: The name of the logger instance in the VSG namespace (VSG.<name>); a None value will use the VSG root. :return: The instacne of the Python logger object. ### Response: def get...
def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, name=self.name, id=self.id))
Creates the node.
Below is the the instruction that describes the task: ### Input: Creates the node. ### Response: def create(self): """ Creates the node. """ log.info("{module}: {name} [{id}] created".format(module=self.manager.module_name, ...
def create_endpoints_csv_file(self, timeout=-1): """ Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its compl...
Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: dict: Endpoint CSV File Response...
Below is the the instruction that describes the task: ### Input: Creates an endpoints CSV file for a SAN. Args: timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its compl...
def sample_double_norm(mean, std_upper, std_lower, size): """Note that this function requires Scipy.""" from scipy.special import erfinv # There's probably a better way to do this. We first draw percentiles # uniformly between 0 and 1. We want the peak of the distribution to occur # at `mean`. Howe...
Note that this function requires Scipy.
Below is the the instruction that describes the task: ### Input: Note that this function requires Scipy. ### Response: def sample_double_norm(mean, std_upper, std_lower, size): """Note that this function requires Scipy.""" from scipy.special import erfinv # There's probably a better way to do this. We...
def ungrab_server(self, onerror = None): """Release the server if it was previously grabbed by this client.""" request.UngrabServer(display = self.display, onerror = onerror)
Release the server if it was previously grabbed by this client.
Below is the the instruction that describes the task: ### Input: Release the server if it was previously grabbed by this client. ### Response: def ungrab_server(self, onerror = None): """Release the server if it was previously grabbed by this client.""" request.UngrabServer(display = self.display, ...
def filter_curve(self): """filter the poor performing curve Returns ------- None """ avg = np.sum(self.trial_history) / self.point_num standard = avg * avg * self.point_num predict_data = [] tmp_model = [] for i in range(NUM_OF_FUN...
filter the poor performing curve Returns ------- None
Below is the the instruction that describes the task: ### Input: filter the poor performing curve Returns ------- None ### Response: def filter_curve(self): """filter the poor performing curve Returns ------- None """ avg = n...
def add_item(self, text, font=("default", 12, "bold"), backgroundcolor="yellow", textcolor="black", highlightcolor="blue"): """ Add a new item on the Canvas. :param text: text to display :type text: str :param font: font of the text :type font: t...
Add a new item on the Canvas. :param text: text to display :type text: str :param font: font of the text :type font: tuple or :class:`~tkinter.font.Font` :param backgroundcolor: background color :type backgroundcolor: str :param textcolor: text color ...
Below is the the instruction that describes the task: ### Input: Add a new item on the Canvas. :param text: text to display :type text: str :param font: font of the text :type font: tuple or :class:`~tkinter.font.Font` :param backgroundcolor: background color ...
def code2color(color_string): """Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0]""" color_tuple = ast.literal_eval(color_string) color_tuple_int = map(lambda x: int(x * 255.0), color_tuple) return wx.Colour(*color_tuple_int)
Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0]
Below is the the instruction that describes the task: ### Input: Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0] ### Response: def code2color(color_string): """Returns wx.Colour from a string of a 3-tuple of floats in [0.0, 1.0]""" color_tuple = ast.literal_eval(color_string) colo...
def get_local(self, name, recurse=True): """Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field """ self._dlog("getting local '{}'".format(name)) return self._search("vars", name, recurse)
Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field
Below is the the instruction that describes the task: ### Input: Get the local field (search for it) from the scope stack. An alias for ``get_var`` :name: The name of the local field ### Response: def get_local(self, name, recurse=True): """Get the local field (search for it) from the scop...
def _set_def_prompt(self): """Sets the default prompt to match the currently active unit test.""" if len(self.active) > 15: ids = self.active.split(".") if len(ids) > 2: module, executable, compiler = ids else: module, executable = ids ...
Sets the default prompt to match the currently active unit test.
Below is the the instruction that describes the task: ### Input: Sets the default prompt to match the currently active unit test. ### Response: def _set_def_prompt(self): """Sets the default prompt to match the currently active unit test.""" if len(self.active) > 15: ids = self.active.s...
def timestamp_from_datetime(date_time): """Returns POSIX timestamp as float""" if date_time.tzinfo is None: return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hour, date_time.minute, date_time.second, -1, -1, -1)) + date_time.m...
Returns POSIX timestamp as float
Below is the the instruction that describes the task: ### Input: Returns POSIX timestamp as float ### Response: def timestamp_from_datetime(date_time): """Returns POSIX timestamp as float""" if date_time.tzinfo is None: return time.mktime((date_time.year, date_time.month, date_time.day, date_time.hou...
def write_base (self, url_data): """Write url_data.base_ref.""" self.write(self.part("base") + self.spaces("base")) self.writeln(url_data.base_ref, color=self.colorbase)
Write url_data.base_ref.
Below is the the instruction that describes the task: ### Input: Write url_data.base_ref. ### Response: def write_base (self, url_data): """Write url_data.base_ref.""" self.write(self.part("base") + self.spaces("base")) self.writeln(url_data.base_ref, color=self.colorbase)
def error_handler(f): """Handle uncaught OAuth errors.""" @wraps(f) def decorated(*args, **kwargs): try: return f(*args, **kwargs) except OAuth2Error as e: # Only FatalClientError are handled by Flask-OAuthlib (as these # errors should not be redirect back...
Handle uncaught OAuth errors.
Below is the the instruction that describes the task: ### Input: Handle uncaught OAuth errors. ### Response: def error_handler(f): """Handle uncaught OAuth errors.""" @wraps(f) def decorated(*args, **kwargs): try: return f(*args, **kwargs) except OAuth2Error as e: ...
def send_text(self, chat_id, content, safe=0): """ 发送文本消息 详情请参考:https://work.weixin.qq.com/api/doc#90000/90135/90248/文本消息/ :param chat_id: 群聊id :param content: 消息内容 :param safe: 表示是否是保密消息,0表示否,1表示是,默认0 :return: """ return self.send(chat_id, 'text...
发送文本消息 详情请参考:https://work.weixin.qq.com/api/doc#90000/90135/90248/文本消息/ :param chat_id: 群聊id :param content: 消息内容 :param safe: 表示是否是保密消息,0表示否,1表示是,默认0 :return:
Below is the the instruction that describes the task: ### Input: 发送文本消息 详情请参考:https://work.weixin.qq.com/api/doc#90000/90135/90248/文本消息/ :param chat_id: 群聊id :param content: 消息内容 :param safe: 表示是否是保密消息,0表示否,1表示是,默认0 :return: ### Response: def send_text(self, chat_id, conte...
def request_announcement_view(request): """The request announcement page.""" if request.method == "POST": form = AnnouncementRequestForm(request.POST) logger.debug(form) logger.debug(form.data) if form.is_valid(): teacher_objs = form.cleaned_data["teachers_requested"...
The request announcement page.
Below is the the instruction that describes the task: ### Input: The request announcement page. ### Response: def request_announcement_view(request): """The request announcement page.""" if request.method == "POST": form = AnnouncementRequestForm(request.POST) logger.debug(form) log...
def update(ctx, migrate=False): '''Perform a development update''' msg = 'Update all dependencies' if migrate: msg += ' and migrate data' header(msg) info('Updating Python dependencies') lrun('pip install -r requirements/develop.pip') lrun('pip install -e .') info('Updating JavaS...
Perform a development update
Below is the the instruction that describes the task: ### Input: Perform a development update ### Response: def update(ctx, migrate=False): '''Perform a development update''' msg = 'Update all dependencies' if migrate: msg += ' and migrate data' header(msg) info('Updating Python depende...
def _init_module_cache(): """ Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. """ # While there are not loaded modules, load these ones if len(FieldTranslation._modules) < len...
Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done.
Below is the the instruction that describes the task: ### Input: Module caching, it helps with not having to import again and again same modules. @return: boolean, True if module caching has been done, False if module caching was already done. ### Response: def _init_module_cache(): """ Module caching, it h...
def menu(self, choices, prompt='Please choose from the provided options:', error='Invalid choice', intro=None, strict=True, default=None, numerator=lambda x: [i + 1 for i in range(x)], formatter=lambda x, y: '{0:>3}) {1}'.format(x, y), clean=utils.safeint): ""...
Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. For example:: 1) foo 2) bar Formattin...
Below is the the instruction that describes the task: ### Input: Print a menu The choices must be an iterable of two-tuples where the first value is the value of the menu item, and the second is the label for that matches the value. The menu will be printed with numeric choices. Fo...
def override_environment(settings, **kwargs): # type: (Settings, **str) -> Generator """ Override env vars and reload the Settings object NOTE: Obviously this context has to be in place before you import any module which reads env values at import time. NOTE: The values in `kwargs` mus...
Override env vars and reload the Settings object NOTE: Obviously this context has to be in place before you import any module which reads env values at import time. NOTE: The values in `kwargs` must be strings else you will get a cryptic: TypeError: execve() arg 3 contains a non-string va...
Below is the the instruction that describes the task: ### Input: Override env vars and reload the Settings object NOTE: Obviously this context has to be in place before you import any module which reads env values at import time. NOTE: The values in `kwargs` must be strings else you will get a...
def do_unfullscreen(self, widget): """ Widget Action to set Windowed Mode. """ self.unfullscreen() self.is_fullscreen = False self.bot._screen_ratio = None
Widget Action to set Windowed Mode.
Below is the the instruction that describes the task: ### Input: Widget Action to set Windowed Mode. ### Response: def do_unfullscreen(self, widget): """ Widget Action to set Windowed Mode. """ self.unfullscreen() self.is_fullscreen = False self.bot._screen_ratio = N...
def get_contact_list(self, list_filter, skip=None, count=None, scope='graph/read'): """ Retrieve the Mxit user's full contact list User authentication required with the following scope: 'graph/read' """ params = { 'filter': list_filter } if skip: ...
Retrieve the Mxit user's full contact list User authentication required with the following scope: 'graph/read'
Below is the the instruction that describes the task: ### Input: Retrieve the Mxit user's full contact list User authentication required with the following scope: 'graph/read' ### Response: def get_contact_list(self, list_filter, skip=None, count=None, scope='graph/read'): """ Retrieve the ...
def from_dict(self, d): """ Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set """ self.sitting = d['sitting'] self.id = d.get('id', None) ...
Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set
Below is the the instruction that describes the task: ### Input: Set this person from dict :param d: Dictionary representing a person ('sitting'[, 'id']) :type d: dict :rtype: Person :raises KeyError: 'sitting' not set ### Response: def from_dict(self, d): """ Set t...
def remove(self, key, where=None, start=None, stop=None): """ Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional ...
Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start : integer (defaults to None), row number to start selection st...
Below is the the instruction that describes the task: ### Input: Remove pandas object partially by specifying the where condition Parameters ---------- key : string Node to remove or delete rows from where : list of Term (or convertible) objects, optional start :...
def AddList(self, listName, description, templateID): """Create a new List Provide: List Name, List Description, and List Template Templates Include: Announcements Contacts Custom List Custom List in Datasheet View ...
Create a new List Provide: List Name, List Description, and List Template Templates Include: Announcements Contacts Custom List Custom List in Datasheet View DataSources Discussion Board Docume...
Below is the the instruction that describes the task: ### Input: Create a new List Provide: List Name, List Description, and List Template Templates Include: Announcements Contacts Custom List Custom List in Datasheet View ...
def senaite_url_fetcher(url): """Uses plone.subrequest to fetch an internal image resource. If the URL points to an external resource, the URL is handed to weasyprint.default_url_fetcher. Please see these links for details: - https://github.com/plone/plone.subrequest - https://pypi.py...
Uses plone.subrequest to fetch an internal image resource. If the URL points to an external resource, the URL is handed to weasyprint.default_url_fetcher. Please see these links for details: - https://github.com/plone/plone.subrequest - https://pypi.python.org/pypi/plone.subrequest ...
Below is the the instruction that describes the task: ### Input: Uses plone.subrequest to fetch an internal image resource. If the URL points to an external resource, the URL is handed to weasyprint.default_url_fetcher. Please see these links for details: - https://github.com/plone/plone.subr...
def logChange(self, nowTime, sig, nextVal): """ This method is called for every value change of any signal. """ try: self.vcdWriter.logChange(nowTime, sig, nextVal) except KeyError: # not every signal has to be registered pass
This method is called for every value change of any signal.
Below is the the instruction that describes the task: ### Input: This method is called for every value change of any signal. ### Response: def logChange(self, nowTime, sig, nextVal): """ This method is called for every value change of any signal. """ try: self.vcdWriter....