code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def WriteClientSnapshot(self, snapshot): """Writes new client snapshot.""" client_id = snapshot.client_id if client_id not in self.metadatas: raise db.UnknownClientError(client_id) startup_info = snapshot.startup_info snapshot.startup_info = None ts = rdfvalue.RDFDatetime.Now() hist...
Writes new client snapshot.
Below is the the instruction that describes the task: ### Input: Writes new client snapshot. ### Response: def WriteClientSnapshot(self, snapshot): """Writes new client snapshot.""" client_id = snapshot.client_id if client_id not in self.metadatas: raise db.UnknownClientError(client_id) sta...
def alter_retention_policy(self, name, database=None, duration=None, replication=None, default=None, shard_duration=None): """Modify an existing retention policy for a database. :param name: the name of the retention policy to modify ...
Modify an existing retention policy for a database. :param name: the name of the retention policy to modify :type name: str :param database: the database for which the retention policy is modified. Defaults to current client's database :type database: str :param dura...
Below is the the instruction that describes the task: ### Input: Modify an existing retention policy for a database. :param name: the name of the retention policy to modify :type name: str :param database: the database for which the retention policy is modified. Defaults to curr...
def _M2_dense(X, Y, weights=None, diag_only=False): """ 2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms """ if weights is not None: if diag_only: return np.sum(weights[:, None] * X * Y...
2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms
Below is the the instruction that describes the task: ### Input: 2nd moment matrix using dense matrix computations. This function is encapsulated such that we can make easy modifications of the basic algorithms ### Response: def _M2_dense(X, Y, weights=None, diag_only=False): """ 2nd moment matrix using d...
def _build_new_virtualenv(self): '''Build a new virtualenvironment if self._virtualenv is set to None''' if self._virtualenv is None: # virtualenv was "None" which means "do default" self._pkg_venv = os.path.join(self._temp_workspace, 'venv') self._venv_pip = 'bin/pip...
Build a new virtualenvironment if self._virtualenv is set to None
Below is the the instruction that describes the task: ### Input: Build a new virtualenvironment if self._virtualenv is set to None ### Response: def _build_new_virtualenv(self): '''Build a new virtualenvironment if self._virtualenv is set to None''' if self._virtualenv is None: # virtua...
def simulate_custom_policy(PolicyInputList=None, ActionNames=None, ResourceArns=None, ResourcePolicy=None, ResourceOwner=None, CallerArn=None, ContextEntries=None, ResourceHandlingOption=None, MaxItems=None, Marker=None): """ Simulate how a set of IAM policies and optionally a resource-based policy works with a...
Simulate how a set of IAM policies and optionally a resource-based policy works with a list of API actions and AWS resources to determine the policies' effective permissions. The policies are provided as strings. The simulation does not perform the API actions; it only checks the authorization to determine if the s...
Below is the the instruction that describes the task: ### Input: Simulate how a set of IAM policies and optionally a resource-based policy works with a list of API actions and AWS resources to determine the policies' effective permissions. The policies are provided as strings. The simulation does not perform th...
def canny(img, threshold1=255/3, threshold2=255, **kwargs): """ canny edge """ import cv2 # edges=None, apertureSize=None, L2gradient=None if img.ndim <= 3: edge = cv2.Canny(img, threshold1, threshold2, **kwargs) if edge.ndim == 2: edge = np.expand_dims(edge, 2) elif img....
canny edge
Below is the the instruction that describes the task: ### Input: canny edge ### Response: def canny(img, threshold1=255/3, threshold2=255, **kwargs): """ canny edge """ import cv2 # edges=None, apertureSize=None, L2gradient=None if img.ndim <= 3: edge = cv2.Canny(img, threshold1, threshold2...
def remove_permission(self, file_id, permission_id): """Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str """ url = '{0}/{1}/permissions/{2...
Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str
Below is the the instruction that describes the task: ### Input: Deletes a permission from a file. :param file_id: a spreadsheet ID (aka file ID.) :type file_id: str :param permission_id: an ID for the permission. :type permission_id: str ### Response: def remove_permission(self, f...
def main(port, export, css, files): """ \b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e - | less # export ST...
\b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e - | less # export STDIN to STDOUT
Below is the the instruction that describes the task: ### Input: \b Examples: $ moo README.md # live preview README.md $ moo -e *.md # export all markdown files $ moo --no-css -e README.md # export README.md without CSS $ cat README.md | moo -e -...
def update_letter(self, letter_id, letter_dict): """ Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict """ return self._create_put_request( resource=LETTERS, billomat_id=letter_id, send_dat...
Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict
Below is the the instruction that describes the task: ### Input: Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict ### Response: def update_letter(self, letter_id, letter_dict): """ Updates a letter :param letter_id: the letter...
def Compile(self, filter_implemention): """Returns the data_store filter implementation from the attribute.""" return self.operator_method(self.attribute_obj, filter_implemention, *self.args)
Returns the data_store filter implementation from the attribute.
Below is the the instruction that describes the task: ### Input: Returns the data_store filter implementation from the attribute. ### Response: def Compile(self, filter_implemention): """Returns the data_store filter implementation from the attribute.""" return self.operator_method(self.attribute_obj, filt...
def _generate_next_task(self): """ submit consumer framework defined task :return: """ if self.consumer_status == ConsumerStatus.INITIALIZING: self.current_task_exist = True self.task_future = self.executor.submit(consumer_initialize_task, self.processor, ...
submit consumer framework defined task :return:
Below is the the instruction that describes the task: ### Input: submit consumer framework defined task :return: ### Response: def _generate_next_task(self): """ submit consumer framework defined task :return: """ if self.consumer_status == ConsumerStatus.INITIALIZIN...
def send_packet(self, packet): """Send a UDP packet along the wire.""" data = json.dumps(packet) byte = data.encode('utf-8') self.udp_socket.sendto(byte, (self._host, self._udp_port))
Send a UDP packet along the wire.
Below is the the instruction that describes the task: ### Input: Send a UDP packet along the wire. ### Response: def send_packet(self, packet): """Send a UDP packet along the wire.""" data = json.dumps(packet) byte = data.encode('utf-8') self.udp_socket.sendto(byte, (self._host, sel...
def load_font(self, prefix, ttf_filename, charmap_filename, directory=None): """Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when acce...
Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font set ttf_filename: str Ttf font filename c...
Below is the the instruction that describes the task: ### Input: Loads a font file and the associated charmap. If ``directory`` is None, the files will be looked for in ``./fonts/``. Parameters ---------- prefix: str Prefix string to be used when accessing a given font ...
def print_cli(msg, retries=10, step=0.01): ''' Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely). ''' while retries: try: try: print(msg) except UnicodeEncodeError...
Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely).
Below is the the instruction that describes the task: ### Input: Wrapper around print() that suppresses tracebacks on broken pipes (i.e. when salt output is piped to less and less is stopped prematurely). ### Response: def print_cli(msg, retries=10, step=0.01): ''' Wrapper around print() that suppresse...
def ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip", xmlns="urn:brocade.com:mgmt:brocade-common-def") hide_ext_community_list_holder = ET.SubElement...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def ip_hide_ext_community_list_holder_extcommunity_list_extcommunity_list_num(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ip = ET.SubElement(config, "ip",...
def raise_(type_, value=None, traceback=None): # pylint: disable=W0613 """ Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is...
Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty carefull with tracebacks. If it is possible, use sys.exc_info...
Below is the the instruction that describes the task: ### Input: Does the same as ordinary ``raise`` with arguments do in Python 2. But works in Python 3 (>= 3.3) also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be...
def get_cell(self, row, column): """ Gets the range object containing the single cell based on row and column numbers. """ url = self.build_url(self._endpoints.get('get_cell').format(row=row, column=column)) response = self.session.get(url) if not response: return None ...
Gets the range object containing the single cell based on row and column numbers.
Below is the the instruction that describes the task: ### Input: Gets the range object containing the single cell based on row and column numbers. ### Response: def get_cell(self, row, column): """ Gets the range object containing the single cell based on row and column numbers. """ url = self.buil...
def get_role(self, item, state_root, from_state=False): """ Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value shoul...
Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value should be read directly from state, instead of using the cached v...
Below is the the instruction that describes the task: ### Input: Used to retrieve an identity role. Args: item (string): the name of the role to be fetched state_root(string): The state root of the previous block. from_state (bool): Whether the identity value should be re...
def get_filename_ds(ds, dump=True, paths=None, **kwargs): """ Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path infor...
Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path information for dump: bool If True and the dataset has not been...
Below is the the instruction that describes the task: ### Input: Return the filename of the corresponding to a dataset This method returns the path to the `ds` or saves the dataset if there exists no filename Parameters ---------- ds: xarray.Dataset The dataset you want the path inform...
def role_and_interface_to_relations(role, interface_name): """ Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A list of relation names. """ ...
Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A list of relation names.
Below is the the instruction that describes the task: ### Input: Given a role and interface name, return a list of relation names for the current charm that use that interface under that role (where role is one of ``provides``, ``requires``, or ``peers``). :returns: A list of relation names. ### Respon...
def lis_to_bio_map(folder): """ Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has. """ logger.info("Opening legislator csv for lis_dct creation") lis_dic = {} leg_path = "{0}/legislators.csv".format(fol...
Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has.
Below is the the instruction that describes the task: ### Input: Senators have a lis_id that is used in some places. That's dumb. Build a dict from lis_id to bioguide_id which every member of congress has. ### Response: def lis_to_bio_map(folder): """ Senators have a lis_id that is used in some places....
def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # Do not display spin text for ok state self._text = None _text = to_text(text) if text else u"OK" err = err or not self.write_to_stdout self._freeze(_text, err=err)
Set Ok (success) finalizer to a spinner.
Below is the the instruction that describes the task: ### Input: Set Ok (success) finalizer to a spinner. ### Response: def ok(self, text=u"OK", err=False): """Set Ok (success) finalizer to a spinner.""" # Do not display spin text for ok state self._text = None _text = to_text(text...
def getsize(o_file): """ get the size, either by seeeking to the end. """ startpos = o_file.tell() o_file.seek(0) o_file.seek(0, SEEK_END) size = o_file.tell() o_file.seek(startpos) return size
get the size, either by seeeking to the end.
Below is the the instruction that describes the task: ### Input: get the size, either by seeeking to the end. ### Response: def getsize(o_file): """ get the size, either by seeeking to the end. """ startpos = o_file.tell() o_file.seek(0) o_file.seek(0, SEEK_END) size = o_file.tell() ...
def wc_wrap(text, length): """ Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation. """ line_words = [] line_len = 0 words = re....
Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation.
Below is the the instruction that describes the task: ### Input: Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation. ### Response: def wc_wrap(text...
def dispatch_missing(op, left, right, result): """ Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) ...
Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reversed ops) result : ndarray Returns ------- result : ...
Below is the the instruction that describes the task: ### Input: Fill nulls caused by division by zero, casting to a diffferent dtype if necessary. Parameters ---------- op : function (operator.add, operator.div, ...) left : object (Index for non-reversed ops) right : object (Index fof reve...
def parse(self, stride=None): """Read and cache the file as a numpy array. Store every *stride* line of data; if ``None`` then the class default is used. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1...
Read and cache the file as a numpy array. Store every *stride* line of data; if ``None`` then the class default is used. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = Y1, ... .
Below is the the instruction that describes the task: ### Input: Read and cache the file as a numpy array. Store every *stride* line of data; if ``None`` then the class default is used. The array is returned with column-first indexing, i.e. for a data file with columns X Y1 Y2 Y3 ... the a...
def require(method): """ Decorator for managing chained dependencies of different class properties. The @require decorator allows developers to specify that a function call must be operated on before another property or function call is accessed, so that data and processing for an entire class c...
Decorator for managing chained dependencies of different class properties. The @require decorator allows developers to specify that a function call must be operated on before another property or function call is accessed, so that data and processing for an entire class can be evaluated in a lazy way (i....
Below is the the instruction that describes the task: ### Input: Decorator for managing chained dependencies of different class properties. The @require decorator allows developers to specify that a function call must be operated on before another property or function call is accessed, so that data and ...
def saveNetwork(self, filename, makeWrapper = 1, mode = "pickle", counter = None): """ Saves network to file using pickle. """ self.saveNetworkToFile(filename, makeWrapper, mode, counter)
Saves network to file using pickle.
Below is the the instruction that describes the task: ### Input: Saves network to file using pickle. ### Response: def saveNetwork(self, filename, makeWrapper = 1, mode = "pickle", counter = None): """ Saves network to file using pickle. """ self.saveNetworkToFile(filename, makeWrap...
def build(port=8000, fixtures=None): """ Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file """ extractor = Extractor() parser = Par...
Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file
Below is the the instruction that describes the task: ### Input: Builds a server file. 1. Extract mock response details from all valid docstrings in existing views 2. Parse and generate mock values 3. Create a store of all endpoints and data 4. Construct server file ### Response: def build(port=80...
def dbcon(func): """Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.""" @wraps(func) def wrapper(*args, **kwargs): self = args[0] if self.dbcon is None: # set up connection self.dbco...
Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created.
Below is the the instruction that describes the task: ### Input: Set up connection before executing function, commit and close connection afterwards. Unless a connection already has been created. ### Response: def dbcon(func): """Set up connection before executing function, commit and close connection ...
def setup_statemachine(self): """Setup and start state machine""" machine = QtCore.QStateMachine() # _______________ # | | # | | # | | # |_______________| # group = util.QState("group", QtCore.QState.Par...
Setup and start state machine
Below is the the instruction that describes the task: ### Input: Setup and start state machine ### Response: def setup_statemachine(self): """Setup and start state machine""" machine = QtCore.QStateMachine() # _______________ # | | # | | ...
def delete_table_column_statistics(self, db_name, tbl_name, col_name): """ Parameters: - db_name - tbl_name - col_name """ self.send_delete_table_column_statistics(db_name, tbl_name, col_name) return self.recv_delete_table_column_statistics()
Parameters: - db_name - tbl_name - col_name
Below is the the instruction that describes the task: ### Input: Parameters: - db_name - tbl_name - col_name ### Response: def delete_table_column_statistics(self, db_name, tbl_name, col_name): """ Parameters: - db_name - tbl_name - col_name """ self.send_delete_table_...
def up_capture(self, benchmark, threshold=0.0, compare_op="ge"): """Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's ...
Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's monthly return during the periods of positive benchmark performa...
Below is the the instruction that describes the task: ### Input: Upside capture ratio. Measures the performance of `self` relative to benchmark conditioned on periods where `benchmark` is gt or ge to `threshold`. Upside capture ratios are calculated by taking the fund's mon...
def get_annotated_fields(cls, instance, select=lambda *p: True): """Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict """ result = {} for _, member in getmembers(instance): ...
Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict
Below is the the instruction that describes the task: ### Input: Get dict of {annotated fields: annotations} by cls of input instance. :return: a set of (annotated fields, annotations). :rtype: dict ### Response: def get_annotated_fields(cls, instance, select=lambda *p: True): """G...
def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds """ if super_entity_kinds: if len(super_entity_kinds) == 1: # Optimize for the case of just one ...
Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds
Below is the the instruction that describes the task: ### Input: Each returned entity will have superentites whos combined entity_kinds included *super_entity_kinds ### Response: def is_sub_to_all_kinds(self, *super_entity_kinds): """ Each returned entity will have superentites whos combined entity...
def connect(uri, factory=pymongo.MongoClient): """ Use the factory to establish a connection to uri. """ warnings.warn( "do not use. Just call MongoClient directly.", DeprecationWarning) return factory(uri)
Use the factory to establish a connection to uri.
Below is the the instruction that describes the task: ### Input: Use the factory to establish a connection to uri. ### Response: def connect(uri, factory=pymongo.MongoClient): """ Use the factory to establish a connection to uri. """ warnings.warn( "do not use. Just call MongoClient directl...
def delete_module(modname, paranoid=None): """ Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return: """ from sys import modules try: thismod = modules[modname] except KeyError: raise ValueError(modname) these_symbols = dir(thism...
Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return:
Below is the the instruction that describes the task: ### Input: Delete a module.http://stackoverflow.com/a/1668289 :param modname: :param paranoid: :return: ### Response: def delete_module(modname, paranoid=None): """ Delete a module.http://stackoverflow.com/a/1668289 :param modname: :para...
def _make_png(data, level=6): """Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 control...
Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 controlling the level of compression: ...
Below is the the instruction that describes the task: ### Input: Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress ...
def serialize(self): """Convert Entity to python dictionary.""" # Serialize fields to a dict data = {} for field_name in self: value = self._values.get(field_name) field = self.fields.get(field_name) if value is not None: if field.all: ...
Convert Entity to python dictionary.
Below is the the instruction that describes the task: ### Input: Convert Entity to python dictionary. ### Response: def serialize(self): """Convert Entity to python dictionary.""" # Serialize fields to a dict data = {} for field_name in self: value = self._values.get(fie...
def get_code_num(s: str) -> Optional[int]: """ Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found. """ if ';' in s: # Extended fore/back codes. numberstr = s.rpartition(';')[-1][:-1] else: # Fore, back, style, codes. number...
Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found.
Below is the the instruction that describes the task: ### Input: Get code number from an escape code. Raises InvalidEscapeCode if an invalid number is found. ### Response: def get_code_num(s: str) -> Optional[int]: """ Get code number from an escape code. Raises InvalidEscapeCode if an invalid ...
def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.strip()) #dump(x, 0, i, '', object) i += 1
shows structured information of a object, list, tuple etc
Below is the the instruction that describes the task: ### Input: shows structured information of a object, list, tuple etc ### Response: def var_dump(*obs): """ shows structured information of a object, list, tuple etc """ i = 0 for x in obs: str = var_dump_output(x, 0, ' ', '\n', True) print (str.s...
def maybe_from_tuple(tup_or_range): """Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range...
Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters ---------- tup_or_range : tuple or range A tuple to pass t...
Below is the the instruction that describes the task: ### Input: Convert a tuple into a range but pass ranges through silently. This is useful to ensure that input is a range so that attributes may be accessed with `.start`, `.stop` or so that containment checks are constant time. Parameters -...
def appendSpacePadding(str, blocksize=AES_blocksize): 'Pad with spaces' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
Pad with spaces
Below is the the instruction that describes the task: ### Input: Pad with spaces ### Response: def appendSpacePadding(str, blocksize=AES_blocksize): 'Pad with spaces' pad_len = paddingLength(len(str), blocksize) padding = '\0'*pad_len return str + padding
def from_config(cls, cfg, **kwargs): """return an instance configured with the ``cfg`` dict""" cfg = dict(cfg, **kwargs) pythonpath = cfg.get('pythonpath', []) if 'here' in cfg: pythonpath.append(cfg['here']) for path in pythonpath: sys.path.append(os.path...
return an instance configured with the ``cfg`` dict
Below is the the instruction that describes the task: ### Input: return an instance configured with the ``cfg`` dict ### Response: def from_config(cls, cfg, **kwargs): """return an instance configured with the ``cfg`` dict""" cfg = dict(cfg, **kwargs) pythonpath = cfg.get('pythonpath', []) ...
def validate_depth(self, depth: DepthDefinitionType) -> Optional[int]: """ Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid """ if depth is not None: try: depth = int(depth) ...
Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid
Below is the the instruction that describes the task: ### Input: Converts the depth to int and validates that the value can be used. :raise ValueError: If the provided depth is not valid ### Response: def validate_depth(self, depth: DepthDefinitionType) -> Optional[int]: """ Converts the depth to ...
def read(self): """Return a single byte from the output buffer """ if self._output_buffer: b, self._output_buffer = (self._output_buffer[0:1], self._output_buffer[1:]) return b return b''
Return a single byte from the output buffer
Below is the the instruction that describes the task: ### Input: Return a single byte from the output buffer ### Response: def read(self): """Return a single byte from the output buffer """ if self._output_buffer: b, self._output_buffer = (self._output_buffer[0:1], ...
def beta_to_uni(text, strict=False): """ Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text. """ # Check if the requ...
Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text.
Below is the the instruction that describes the task: ### Input: Converts the given text from betacode to unicode. Args: text: The beta code text to convert. All of this text must be betacode. strict: Flag to allow for flexible diacritic order on input. Returns: The converted text. ### Respons...
def activate(self, key): """ Activates a new registree on the LEX with given activation key :rtype: None """ url = self._base + 'user/activate' r = requests.get(url, params={ 'activation_key': key }) r.raise_for_status()
Activates a new registree on the LEX with given activation key :rtype: None
Below is the the instruction that describes the task: ### Input: Activates a new registree on the LEX with given activation key :rtype: None ### Response: def activate(self, key): """ Activates a new registree on the LEX with given activation key :rtype: None """ url...
def _maybe_parse_basic_type(self): """Try to parse a basic type (str, bool, number).""" token_value = '' # Allow a leading dash to handle negative numbers. if self._current_token.value == '-': token_value += self._current_token.value self._advance() basic_type_tokens = [tokenize.NAME, t...
Try to parse a basic type (str, bool, number).
Below is the the instruction that describes the task: ### Input: Try to parse a basic type (str, bool, number). ### Response: def _maybe_parse_basic_type(self): """Try to parse a basic type (str, bool, number).""" token_value = '' # Allow a leading dash to handle negative numbers. if self._current_...
def resolve_calls(func): """Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the func...
Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarly, functions defined inside of the function that we are trying to r...
Below is the the instruction that describes the task: ### Input: Parse a function into an AST with function calls resolved. Since the calls are resolved using the global and local namespace of the function it means that procedural parameters (i.e. functions passed as arguments) won't be resolved. Similarl...
def update_momentum_by_name(self, name, **kwargs): """Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value ...
Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new value for `until`. :returns: a momentum updated. :...
Below is the the instruction that describes the task: ### Input: Updates a momentum by the given name. :param name: the momentum name. :param velocity: (keyword-only) a new value for `velocity`. :param since: (keyword-only) a new value for `since`. :param until: (keyword-only) a new...
def associate_vpc_with_hosted_zone(HostedZoneId=None, Name=None, VPCId=None, VPCName=None, VPCRegion=None, Comment=None, region=None, key=None, keyid=None, profile=None): ''' Associates an Amazon VPC with a private hosted zone. To perfor...
Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from one AWS account with a zone from a another, the AWS account owning...
Below is the the instruction that describes the task: ### Input: Associates an Amazon VPC with a private hosted zone. To perform the association, the VPC and the private hosted zone must already exist. You can't convert a public hosted zone into a private hosted zone. If you want to associate a VPC from ...
def get_usb_controller_count_by_type(self, type_p): """Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int """ if not isinstance(type_p, USBControllerType): raise Ty...
Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int
Below is the the instruction that describes the task: ### Input: Returns the number of USB controllers of the given type attached to the VM. in type_p of type :class:`USBControllerType` return controllers of type int ### Response: def get_usb_controller_count_by_type(self, type_p): """Ret...
def handle_cd(self, cmd): """changes dir """ if len(cmd) != 2: print("Invalid syntax: cd path", file=self.output) return path = os.path.expandvars(os.path.expanduser(cmd[1])) try: os.chdir(path) except OSError as ex: print("cd: %s\n...
changes dir
Below is the the instruction that describes the task: ### Input: changes dir ### Response: def handle_cd(self, cmd): """changes dir """ if len(cmd) != 2: print("Invalid syntax: cd path", file=self.output) return path = os.path.expandvars(os.path.expanduser(cmd[1])) ...
def downstream_index_dinf(dinfdir_value, i, j): """find downslope coordinate for Dinf of TauDEM Args: dinfdir_value: dinf direction value i: current row j: current col Returns: downstream (row, col)s """ down_dirs = DinfUtil.dinf_d...
find downslope coordinate for Dinf of TauDEM Args: dinfdir_value: dinf direction value i: current row j: current col Returns: downstream (row, col)s
Below is the the instruction that describes the task: ### Input: find downslope coordinate for Dinf of TauDEM Args: dinfdir_value: dinf direction value i: current row j: current col Returns: downstream (row, col)s ### Response: def downstream_index_d...
def of(jvalue, bigdl_type="float"): """ Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer """ def get_py_name(jclass_name): if jclass_name == "StaticGraph" or jclass_name == ...
Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer
Below is the the instruction that describes the task: ### Input: Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer ### Response: def of(jvalue, bigdl_type="float"): """ Create a Python Layer base o...
def visit_create_library_command(element, compiler, **kw): """ Returns the actual sql query for the CreateLibraryCommand class. """ query = """ CREATE {or_replace} LIBRARY {name} LANGUAGE pythonplu FROM :location WITH CREDENTIALS AS :credentials {region} """ ...
Returns the actual sql query for the CreateLibraryCommand class.
Below is the the instruction that describes the task: ### Input: Returns the actual sql query for the CreateLibraryCommand class. ### Response: def visit_create_library_command(element, compiler, **kw): """ Returns the actual sql query for the CreateLibraryCommand class. """ query = """ CRE...
def git_check(): """ Check that all changes , besides versioning files, are committed :return: """ # check that changes staged for commit are pushed to origin output = local('git diff --name-only | egrep -v "^(pynb/version.py)|(version.py)$" | tr "\\n" " "', capture=True).str...
Check that all changes , besides versioning files, are committed :return:
Below is the the instruction that describes the task: ### Input: Check that all changes , besides versioning files, are committed :return: ### Response: def git_check(): """ Check that all changes , besides versioning files, are committed :return: """ # check that changes staged for commit...
def _init(self, server, nick, user, real_name, password, port=None, tls=True, tls_verify=True, proxy=False, proxy_type='SOCKS5', proxy_server=None, proxy_port=None, proxy_username=None, proxy_password=None): """ Connect and register with the IRC server and - ...
Connect and register with the IRC server and - set server-related information variables. Required arguments: * server - Server to connect to. * nick - Nick to use. If a tuple/list is specified it will try to use the first, and if the first is already used - ...
Below is the the instruction that describes the task: ### Input: Connect and register with the IRC server and - set server-related information variables. Required arguments: * server - Server to connect to. * nick - Nick to use. If a tuple/list is specified it will tr...
def ToArray(value): """ Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes """ ms = StreamManager.GetStream() writer =...
Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes
Below is the the instruction that describes the task: ### Input: Serialize the given `value` to a an array of bytes. Args: value (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin. Returns: bytes: hex formatted bytes ### Response: def ToArray(value): ...
def _crop_img_to(image, slices, copy=True): """Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data(...
Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Ima...
Below is the the instruction that describes the task: ### Input: Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any obj...
def make_request(self, request, captcha_response=None): """Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response """ logger.debug...
Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response
Below is the the instruction that describes the task: ### Input: Make api request helper function :param request: vk_requests.api.Request instance :param captcha_response: None or dict, e.g {'sid': <sid>, 'key': <key>} :return: dict: json decoded http response ### Response: def make_reques...
def _get_bandgap_from_bands(energies, nelec): """Compute difference in conduction band min and valence band max""" nelec = int(nelec) valence = [x[nelec-1] for x in energies] conduction = [x[nelec] for x in energies] return max(min(conduction) - max(valence), 0.0)
Compute difference in conduction band min and valence band max
Below is the the instruction that describes the task: ### Input: Compute difference in conduction band min and valence band max ### Response: def _get_bandgap_from_bands(energies, nelec): """Compute difference in conduction band min and valence band max""" nelec = int(nelec) valence = [x[ne...
def normalize_by_center_of_mass(coords, radii): ''' Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0]]), np.a...
Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0]]), np.array([1.0, 1.0, 1.0])) array([[-1., -1.], [ 1...
Below is the the instruction that describes the task: ### Input: Given coordinates of circle centers and radii, as two arrays, returns new coordinates array, computed such that the center of mass of the three circles is (0, 0). >>> normalize_by_center_of_mass(np.array([[0.0, 0.0], [2.0, 0.0], [1.0, 3.0...
def get_netconf_client_capabilities_input_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf_client_capabilities") config = get_netconf_client_capabilities input = ET.SubElement(ge...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_netconf_client_capabilities_input_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_netconf_client_capabilities = ET.Element("get_netconf...
def extract_subjects(cert_pem): """Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: 2-tuple: - The primary subject string, extracted from the certificate DN. - A se...
Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: 2-tuple: - The primary subject string, extracted from the certificate DN. - A set of equivalent identities, group membe...
Below is the the instruction that describes the task: ### Input: Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate. Args: cert_pem: str or bytes PEM (Base64) encoded X.509 v3 certificate Returns: 2-tuple: - The primary subject string, extracted from the ...
def convert_rom(ADDR_WIDTH=8, DATA_WIDTH=8, CONTENT=(4,5,6,7)): ''' Convert ROM''' addr = Signal(intbv(0)[ADDR_WIDTH:]) dout = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(rom, addr, dout, CONTENT)
Convert ROM
Below is the the instruction that describes the task: ### Input: Convert ROM ### Response: def convert_rom(ADDR_WIDTH=8, DATA_WIDTH=8, CONTENT=(4,5,6,7)): ''' Convert ROM''' addr = Signal(intbv(0)[ADDR_WIDTH:]) dout = Signal(intbv(0)[DATA_WIDTH:]) toVerilog(rom, addr, dout, CONTENT)
def select_write(self, timeout=None): """ Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boole...
Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: A boolean - if the socket is ready for writing. Will only be Fals...
Below is the the instruction that describes the task: ### Input: Blocks until the socket is ready to be written to, or the timeout is hit :param timeout: A float - the period of time to wait for the socket to be ready to written to. None for no time limit. :return: ...
def issue_section(issue): """Returns the section heading for the issue, or None if this issue should be ignored.""" labels = issue.get('labels', []) for label in labels: if not label['name'].startswith('type: '): continue if label['name'] in LOG_SECTION: return LOG_S...
Returns the section heading for the issue, or None if this issue should be ignored.
Below is the the instruction that describes the task: ### Input: Returns the section heading for the issue, or None if this issue should be ignored. ### Response: def issue_section(issue): """Returns the section heading for the issue, or None if this issue should be ignored.""" labels = issue.get('labels',...
def _make_authorization_grant_assertion(self): """Create the OAuth 2.0 assertion. This assertion is used during the OAuth 2.0 grant to acquire an access token. Returns: bytes: The authorization grant assertion. """ now = _helpers.utcnow() lifetime = ...
Create the OAuth 2.0 assertion. This assertion is used during the OAuth 2.0 grant to acquire an access token. Returns: bytes: The authorization grant assertion.
Below is the the instruction that describes the task: ### Input: Create the OAuth 2.0 assertion. This assertion is used during the OAuth 2.0 grant to acquire an access token. Returns: bytes: The authorization grant assertion. ### Response: def _make_authorization_grant_asserti...
def complexity_fd_higushi(signal, k_max): """ Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int The maximal val...
Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int The maximal value of k. The point at which the FD plateaus is conside...
Below is the the instruction that describes the task: ### Input: Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int ...
def _parse_cookies(cookie_str, dictionary): """Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictiona...
Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictionary['my'] == 'value' :param cookie_str: A strin...
Below is the the instruction that describes the task: ### Input: Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is Tru...
def parse_version_string(name: str) -> Tuple[str, str]: """Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will therefore mat...
Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will therefore match in spirit, but not necessarily in string form.
Below is the the instruction that describes the task: ### Input: Parse a version string (name ID 5) and return (major, minor) strings. Example of the expected format: 'Version 01.003; Comments'. Version strings like "Version 1.3" will be post-processed into ("1", "300"). The parsed version numbers will there...
def start_poll(args): """Starts a poll.""" if args.type == 'privmsg': return "We don't have secret ballots in this benevolent dictatorship!" if not args.msg: return "Polls need a question." ctrlchan = args.config['core']['ctrlchan'] poll = Polls(question=args.msg, submitter=args.nick...
Starts a poll.
Below is the the instruction that describes the task: ### Input: Starts a poll. ### Response: def start_poll(args): """Starts a poll.""" if args.type == 'privmsg': return "We don't have secret ballots in this benevolent dictatorship!" if not args.msg: return "Polls need a question." ...
def build_recursive_localize_command(destination, inputs, file_provider): """Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider str...
Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider string used to filter the output params; the returned command wil...
Below is the the instruction that describes the task: ### Input: Return a multi-line string with a shell script to copy recursively. Arguments: destination: Folder where to put the data. For example /mnt/data inputs: a list of InputFileParam file_provider: file provider string used t...
def token_handler_str_default( token, dispatcher, node, subnode, sourcepath_stack=(None,)): """ Standard token handler that will return the value, ignoring any tokens or strings that have been remapped. """ if isinstance(token.pos, int): _, lineno, colno = node.getpos(subnode, token...
Standard token handler that will return the value, ignoring any tokens or strings that have been remapped.
Below is the the instruction that describes the task: ### Input: Standard token handler that will return the value, ignoring any tokens or strings that have been remapped. ### Response: def token_handler_str_default( token, dispatcher, node, subnode, sourcepath_stack=(None,)): """ Standard toke...
def intersect_range(self, start=None, stop=None): """Intersect with range defined by `start` and `stop` values **inclusive**. Parameters ---------- start : int, optional Start value. stop : int, optional Stop value. Returns ------...
Intersect with range defined by `start` and `stop` values **inclusive**. Parameters ---------- start : int, optional Start value. stop : int, optional Stop value. Returns ------- idx : SortedIndex Examples -------...
Below is the the instruction that describes the task: ### Input: Intersect with range defined by `start` and `stop` values **inclusive**. Parameters ---------- start : int, optional Start value. stop : int, optional Stop value. Returns ...
def linear(target, m, b, prop): r""" Calculates a property as a linear function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides acce...
r""" Calculates a property as a linear function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid pr...
Below is the the instruction that describes the task: ### Input: r""" Calculates a property as a linear function of a given property Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated arra...
def parser(): """Return a parser for setting one or more configuration paths""" parser = argparse.ArgumentParser() parser.add_argument('-c', '--config_paths', default=[], action='append', help='path to a configuration directory') return parser
Return a parser for setting one or more configuration paths
Below is the the instruction that describes the task: ### Input: Return a parser for setting one or more configuration paths ### Response: def parser(): """Return a parser for setting one or more configuration paths""" parser = argparse.ArgumentParser() parser.add_argument('-c', '--config_paths', def...
def attributes_layout(self, EdgeAttribute=None, maxwidth=None, minrad=None, \ network=None, NodeAttribute=None,nodeList=None, radmult=None, \ spacingx=None, spacingy=None, verbose=False): """ Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column ...
Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column containing numeric values that will be used as weights in the layout algorithm. Only columns containing numeric values are shown :param maxwidth (string, optional): Maximum width of a row, i...
Below is the the instruction that describes the task: ### Input: Execute the Group Attributes Layout on a network :param EdgeAttribute (string, optional): The name of the edge column containing numeric values that will be used as weights in the layout algorithm. Only columns containing numeric values are ...
def _usage_endpoint(self, endpoint, year=None, month=None): """ Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. D...
Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. Defaults to None. If used, it must be accompanied by ``month``. :param i...
Below is the the instruction that describes the task: ### Input: Common helper for getting usage and billing reports with optional year and month URL elements. :param str endpoint: Cloudant usage endpoint. :param int year: Year to query against. Optional parameter. Defaults to ...
def _snort_cmd(self, pcap): """ Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file """ cmdline = "'{0}' -A console -N -y -c '{1}' {2} -r '{3}'" \ .format(self.c...
Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file
Below is the the instruction that describes the task: ### Input: Given a pcap filename, get the commandline to run. :param pcap: Pcap filename to scan :returns: list of snort command args to scan supplied pcap file ### Response: def _snort_cmd(self, pcap): """ Given a pcap filename...
def extract_number_oscillations(osc_dyn, index = 0, amplitude_threshold = 1.0): """! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (...
! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example, ...
Below is the the instruction that describes the task: ### Input: ! @brief Extracts number of oscillations of specified oscillator. @param[in] osc_dyn (list): Dynamic of oscillators. @param[in] index (uint): Index of oscillator in dynamic. @param[in] amplitude_threshold (double): Amplitude ...
def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_lat="pm_b", pm_long_out="pm_ra", pm_lat_out="pm_dec", name_prefix="__proper_motion_gal2eq", right_ascension_galactic_pole=192.85, ...
Transform/rotate proper motions from galactic to equatorial coordinates. Inverse of :py:`add_virtual_columns_proper_motion_eq2gal`
Below is the the instruction that describes the task: ### Input: Transform/rotate proper motions from galactic to equatorial coordinates. Inverse of :py:`add_virtual_columns_proper_motion_eq2gal` ### Response: def add_virtual_columns_proper_motion_gal2eq(self, long_in="ra", lat_in="dec", pm_long="pm_l", pm_la...
def assemble(cls): """Assemble a single document using the blueprint""" document = {} for field_name, maker in cls._instructions.items(): with maker.target(document): document[field_name] = maker() return document
Assemble a single document using the blueprint
Below is the the instruction that describes the task: ### Input: Assemble a single document using the blueprint ### Response: def assemble(cls): """Assemble a single document using the blueprint""" document = {} for field_name, maker in cls._instructions.items(): with maker.targ...
def run(): ''' This client calls a bunch of help commands from workbench ''' # Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # C...
This client calls a bunch of help commands from workbench
Below is the the instruction that describes the task: ### Input: This client calls a bunch of help commands from workbench ### Response: def run(): ''' This client calls a bunch of help commands from workbench ''' # Grab server args args = client_helper.grab_server_args() # Start up workbench...
def make(env_name, *args, **kwargs): """Try to get the equivalent functionality of gym.make in a sloppy way.""" if env_name not in REGISTERED_ENVS: raise Exception( "Environment {} not found. Make sure it is a registered environment among: {}".format( env_name, ", ".join(REGI...
Try to get the equivalent functionality of gym.make in a sloppy way.
Below is the the instruction that describes the task: ### Input: Try to get the equivalent functionality of gym.make in a sloppy way. ### Response: def make(env_name, *args, **kwargs): """Try to get the equivalent functionality of gym.make in a sloppy way.""" if env_name not in REGISTERED_ENVS: rai...
def spiral(Di, rmax, rmin, pitch, fd): r'''Returns loss coefficient for any size constant-pitch spiral as shown in [1]_. Has applications in immersed coils in tanks. .. math:: K = \frac{r_{max} - r_{min}}{p} \left[ f\pi\left(\frac{r_{max} +r_{min}}{d}\right) + 0.20 + 4.8f\right] + \...
r'''Returns loss coefficient for any size constant-pitch spiral as shown in [1]_. Has applications in immersed coils in tanks. .. math:: K = \frac{r_{max} - r_{min}}{p} \left[ f\pi\left(\frac{r_{max} +r_{min}}{d}\right) + 0.20 + 4.8f\right] + \frac{13.2f}{(r_{min}/d)^2} Parameters ...
Below is the the instruction that describes the task: ### Input: r'''Returns loss coefficient for any size constant-pitch spiral as shown in [1]_. Has applications in immersed coils in tanks. .. math:: K = \frac{r_{max} - r_{min}}{p} \left[ f\pi\left(\frac{r_{max} +r_{min}}{d}\right) + 0.20...
def create_comment(self, body, commit_id, path, position): """ :calls: `POST /repos/:owner/:repo/pulls/:number/comments <http://developer.github.com/v3/pulls/comments>`_ :param body: string :param commit_id: :class:`github.Commit.Commit` :param path: string :param positio...
:calls: `POST /repos/:owner/:repo/pulls/:number/comments <http://developer.github.com/v3/pulls/comments>`_ :param body: string :param commit_id: :class:`github.Commit.Commit` :param path: string :param position: integer :rtype: :class:`github.PullRequestComment.PullRequestComment...
Below is the the instruction that describes the task: ### Input: :calls: `POST /repos/:owner/:repo/pulls/:number/comments <http://developer.github.com/v3/pulls/comments>`_ :param body: string :param commit_id: :class:`github.Commit.Commit` :param path: string :param position: integer...
def get_requires(self, build_requires=False, private_build_requires=False): """Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. ...
Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. Returns: List of `Requirement` objects.
Below is the the instruction that describes the task: ### Input: Get the requirements of the variant. Args: build_requires (bool): If True, include build requirements. private_build_requires (bool): If True, include private build requirements. Returns: ...
def connect(remote_host): """ Connect to remote host and show our status """ if remote_host in ('master', 'server'): remote_host = nago.settings.get_option('server') node = nago.core.get_node(remote_host) if not node: try: address = socket.gethostbyname(remote_host) ...
Connect to remote host and show our status
Below is the the instruction that describes the task: ### Input: Connect to remote host and show our status ### Response: def connect(remote_host): """ Connect to remote host and show our status """ if remote_host in ('master', 'server'): remote_host = nago.settings.get_option('server') node = ...
def is_container_system_config_file(file): """Determine whether a given file is one of the files created by setup_container_system_config(). @param file: Absolute file path as string. """ if not file.startswith("/etc/"): return False return file in [os.path.join("/etc", f.decode()) for f in ...
Determine whether a given file is one of the files created by setup_container_system_config(). @param file: Absolute file path as string.
Below is the the instruction that describes the task: ### Input: Determine whether a given file is one of the files created by setup_container_system_config(). @param file: Absolute file path as string. ### Response: def is_container_system_config_file(file): """Determine whether a given file is one of the...
def buttonbox(msg="",title=" " ,choices=("Button1", "Button2", "Button3") , image=None , root=None ): """ Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg...
Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list or tuple of the choices to be displayed
Below is the the instruction that describes the task: ### Input: Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @arg c...
def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets): """Build complete consumer offsets from parsed current consumer-offsets and lowmarks and highmarks from current-offsets for. """ new_offsets = defaultdict(dict) try: for topic, ...
Build complete consumer offsets from parsed current consumer-offsets and lowmarks and highmarks from current-offsets for.
Below is the the instruction that describes the task: ### Input: Build complete consumer offsets from parsed current consumer-offsets and lowmarks and highmarks from current-offsets for. ### Response: def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets): """Buil...
def compressedpubkey(self): """ Derive uncompressed public key """ secret = unhexlify(repr(self._wif)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).curve.generator.order() p = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1).ver...
Derive uncompressed public key
Below is the the instruction that describes the task: ### Input: Derive uncompressed public key ### Response: def compressedpubkey(self): """ Derive uncompressed public key """ secret = unhexlify(repr(self._wif)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k...
def split_unbalanced(chunks): """Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags that are closed but were not opene...
Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags that are closed but were not opened. Extracting these might mean s...
Below is the the instruction that describes the task: ### Input: Return (unbalanced_start, balanced, unbalanced_end), where each is a list of text and tag chunks. unbalanced_start is a list of all the tags that are opened, but not closed in this span. Similarly, unbalanced_end is a list of tags th...
def _split_path(self, path): """ Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the ...
Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle is always one of the following integer constants: - L{win...
Below is the the instruction that describes the task: ### Input: Splits a Registry path and returns the hive and key. @type path: str @param path: Registry path. @rtype: tuple( int, str ) @return: Tuple containing the hive handle and the subkey path. The hive handle i...
def calc_freefree_eta(ne, t, hz): """Dulk (1985) equations 7 and 20, assuming pure hydrogen.""" kappa = calc_freefree_kappa(ne, t, hz) return kappa * cgs.k * t * hz**2 / cgs.c**2
Dulk (1985) equations 7 and 20, assuming pure hydrogen.
Below is the the instruction that describes the task: ### Input: Dulk (1985) equations 7 and 20, assuming pure hydrogen. ### Response: def calc_freefree_eta(ne, t, hz): """Dulk (1985) equations 7 and 20, assuming pure hydrogen.""" kappa = calc_freefree_kappa(ne, t, hz) return kappa * cgs.k * t * hz**2 ...
def _averageFromHeader(self, header, keyword): """ Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list. """ _list = '' for _kw in keyword.split(','): if _kw in header: _list = _list + '...
Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list.
Below is the the instruction that describes the task: ### Input: Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list. ### Response: def _averageFromHeader(self, header, keyword): """ Averages out values taken from header. The keywor...
def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ alternation([ self.alpha_character, "_" ]), zero_or_more( alternation([ self.alpha_character, "...
identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;
Below is the the instruction that describes the task: ### Input: identifier = alpha_character | "_" . {alpha_character | "_" | digit} ; ### Response: def identifier(self, text): """identifier = alpha_character | "_" . {alpha_character | "_" | digit} ;""" self._attempting(text) return concatenation([ ...