code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def scope_deletion(sender, instance, **kwargs): """ Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ...
Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ancestors estimates and update estimate details. ...
Below is the the instruction that describes the task: ### Input: Run different actions on price estimate scope deletion. If scope is a customer - delete all customer estimates and their children. If scope is a deleted resource - redefine consumption details, recalculate ...
def tempdir(*args, **kwargs): """A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass """ d = tempfile.mkdtemp(*args, **kwargs) try: yield d finally: shuti...
A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass
Below is the the instruction that describes the task: ### Input: A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass ### Response: def tempdir(*args, **kwargs): """A contextmanager t...
def map_tree(visitor, tree): """Apply function to nodes""" newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
Apply function to nodes
Below is the the instruction that describes the task: ### Input: Apply function to nodes ### Response: def map_tree(visitor, tree): """Apply function to nodes""" newn = [map_tree(visitor, node) for node in tree.nodes] return visitor(tree, newn)
def configure_logger(simple_name, log_dest=None, detail_level=DEFAULT_LOG_DETAIL_LEVEL, log_filename=DEFAULT_LOG_FILENAME, connection=None, propagate=False): # pylint: disable=line-too-long """ Configure the pywbem loggers and optionally activat...
Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level. Parameters: simple_name (:term:`string`): Simple name (ex. `'api'`) of the single pywbem logger this method should affect, or `'all'` to affect all pywbem loggers. M...
Below is the the instruction that describes the task: ### Input: Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level. Parameters: simple_name (:term:`string`): Simple name (ex. `'api'`) of the single pywbem logger this method ...
def ReadHuntLogEntries(self, hunt_id, offset, count, with_substring=None): """Reads hunt log entries of a given hunt using given query options.""" all_entries = [] for flow_obj in self._GetHuntFlows(hunt_id): for entry in self.ReadFlowLogEntries( flow_obj.client_id, flow_obj.flow_i...
Reads hunt log entries of a given hunt using given query options.
Below is the the instruction that describes the task: ### Input: Reads hunt log entries of a given hunt using given query options. ### Response: def ReadHuntLogEntries(self, hunt_id, offset, count, with_substring=None): """Reads hunt log entries of a given hunt using given query options.""" all_entries = [...
def check(qpi_or_h5file, checks=["attributes", "background"]): """Checks various properties of a :class:`qpimage.core.QPImage` instance Parameters ---------- qpi_or_h5file: qpimage.core.QPImage or str A QPImage object or a path to an hdf5 file checks: list of str Which checks to per...
Checks various properties of a :class:`qpimage.core.QPImage` instance Parameters ---------- qpi_or_h5file: qpimage.core.QPImage or str A QPImage object or a path to an hdf5 file checks: list of str Which checks to perform ("attributes" and/or "background") Raises ------ Int...
Below is the the instruction that describes the task: ### Input: Checks various properties of a :class:`qpimage.core.QPImage` instance Parameters ---------- qpi_or_h5file: qpimage.core.QPImage or str A QPImage object or a path to an hdf5 file checks: list of str Which checks to perf...
def _create_significance_table(self,data): """ Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Re...
Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. Returns ---------- df : pandas DataFrame ...
Below is the the instruction that describes the task: ### Input: Create a table containing p-values for significance tests. Add features of the distributions and the p-values to the dataframe. Parameters ---------- data : pandas DataFrame The input dataset. ...
def visitInlineShapeDefinition(self, ctx: ShExDocParser.InlineShapeDefinitionContext): """ shapeDefinition: qualifier* '{' oneOfShape? '}' """ if ctx.qualifier(): for q in ctx.qualifier(): self.visit(q) if ctx.oneOfShape(): oneof_parser = ShexOneOfShapePar...
shapeDefinition: qualifier* '{' oneOfShape? '}'
Below is the the instruction that describes the task: ### Input: shapeDefinition: qualifier* '{' oneOfShape? '}' ### Response: def visitInlineShapeDefinition(self, ctx: ShExDocParser.InlineShapeDefinitionContext): """ shapeDefinition: qualifier* '{' oneOfShape? '}' """ if ctx.qualifier(): ...
def get_glance_url(url_base, tenant_id, user, password, region): """It get the glance url :param url_base: keystone url :param tenand_id: the id of the tenant :param user: the user :param paassword: the password """ get_url(url_base, tenant_id, user, password, 'image', region)
It get the glance url :param url_base: keystone url :param tenand_id: the id of the tenant :param user: the user :param paassword: the password
Below is the the instruction that describes the task: ### Input: It get the glance url :param url_base: keystone url :param tenand_id: the id of the tenant :param user: the user :param paassword: the password ### Response: def get_glance_url(url_base, tenant_id, user, password, region): """It g...
def store(self, filename=None, location=None, path=None, container=None, region=None, access=None, base64decode=None): """ Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ``` """ ...
Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ```
Below is the the instruction that describes the task: ### Input: Uploads and stores the current transformation as a Fileink *returns* [Filestack.Filelink] ```python filelink = transform.store() ``` ### Response: def store(self, filename=None, location=None, path=None, container=No...
def _inter_df_op_handler(self, func, other, **kwargs): """Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/scalar. other: The other Manager/scalar. Returns: New DataManager with new data and index. ...
Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/scalar. other: The other Manager/scalar. Returns: New DataManager with new data and index.
Below is the the instruction that describes the task: ### Input: Helper method for inter-manager and scalar operations. Args: func: The function to use on the Manager/scalar. other: The other Manager/scalar. Returns: New DataManager with new data and index. ### ...
def jars(self, absolute=True): ''' List of jars in the jar path ''' jars = glob(os.path.join(self._jar_path, '*.jar')) return jars if absolute else map(lambda j: os.path.abspath(j), jars)
List of jars in the jar path
Below is the the instruction that describes the task: ### Input: List of jars in the jar path ### Response: def jars(self, absolute=True): ''' List of jars in the jar path ''' jars = glob(os.path.join(self._jar_path, '*.jar')) return jars if absolute else map(lambda j: os.pa...
def simxSetIntegerParameter(clientID, paramIdentifier, paramValue, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' return c_SetIntegerParameter(clientID, paramIdentifier, paramValue, operationMode)
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxSetIntegerParameter(clientID, paramIdentifier, paramValue, operationMode): ''' Please have a look at the function description/document...
def _include_docs(self, rows): '''rows here are tuples (key, value, id), returns a list of tuples (key, value, id, doc)''' resp = list() for row in rows: if isinstance(row[1], dict) and '_id' in row[1]: d_id = row[1]['_id'] else: d_...
rows here are tuples (key, value, id), returns a list of tuples (key, value, id, doc)
Below is the the instruction that describes the task: ### Input: rows here are tuples (key, value, id), returns a list of tuples (key, value, id, doc) ### Response: def _include_docs(self, rows): '''rows here are tuples (key, value, id), returns a list of tuples (key, value, id, doc)''' ...
def register_module(self, module, idx=-1): """ Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted ...
Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is inserted at the end. :type idx: int
Below is the the instruction that describes the task: ### Input: Register a module. You could indicate position inside inner list. :param module: must be a string or a module object to register. :type module: str :param idx: position where you want to insert new module. By default it is ins...
def display_xdata(self) -> DataAndMetadata.DataAndMetadata: """Return the extended data of this data item display. Display data will always be 1d or 2d and either int, float, or RGB data type. .. versionadded:: 1.0 Scriptable: Yes """ display_data_channel = self.__disp...
Return the extended data of this data item display. Display data will always be 1d or 2d and either int, float, or RGB data type. .. versionadded:: 1.0 Scriptable: Yes
Below is the the instruction that describes the task: ### Input: Return the extended data of this data item display. Display data will always be 1d or 2d and either int, float, or RGB data type. .. versionadded:: 1.0 Scriptable: Yes ### Response: def display_xdata(self) -> DataAndMetadat...
def formatTime (self, record, datefmt=None): """Return the creation time of the specified LogRecord as formatted text.""" if datefmt is None: datefmt = '%Y-%m-%d %H:%M:%S' ct = self.converter(record.created) t = time.strftime(datefmt, ct) s = '%s.%03d' % (t...
Return the creation time of the specified LogRecord as formatted text.
Below is the the instruction that describes the task: ### Input: Return the creation time of the specified LogRecord as formatted text. ### Response: def formatTime (self, record, datefmt=None): """Return the creation time of the specified LogRecord as formatted text.""" if datefmt ...
def read_lte(self, filename): """ parse lte file first, then return dict as read_json() does """ lpins = lattice.LteParser(filename) return json.loads(lpins.file2json())
parse lte file first, then return dict as read_json() does
Below is the the instruction that describes the task: ### Input: parse lte file first, then return dict as read_json() does ### Response: def read_lte(self, filename): """ parse lte file first, then return dict as read_json() does """ lpins = lattice.LteParser(filename) return json....
def _send_http_request(self, xml_request): """ Send a request via HTTP protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. """ headers = {"Host": self._host, "Content-Type": ...
Send a request via HTTP protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string.
Below is the the instruction that describes the task: ### Input: Send a request via HTTP protocol. Args: xml_request -- A fully formed xml request string for the CPS. Returns: The raw xml response string. ### Response: def _send_http_request(self, xml_reque...
async def on_raw_kill(self, message): """ KILL command. """ by, bymeta = self._parse_user(message.source) target, targetmeta = self._parse_user(message.params[0]) reason = message.params[1] self._sync_user(target, targetmeta) if by in self.users: self._sync_u...
KILL command.
Below is the the instruction that describes the task: ### Input: KILL command. ### Response: async def on_raw_kill(self, message): """ KILL command. """ by, bymeta = self._parse_user(message.source) target, targetmeta = self._parse_user(message.params[0]) reason = message.params[1] ...
def is_valid_py_file(path): ''' Checks whether the file can be read by the coverage module. This is especially needed for .pyx files and .py files with syntax errors. ''' import os is_valid = False if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx': try: ...
Checks whether the file can be read by the coverage module. This is especially needed for .pyx files and .py files with syntax errors.
Below is the the instruction that describes the task: ### Input: Checks whether the file can be read by the coverage module. This is especially needed for .pyx files and .py files with syntax errors. ### Response: def is_valid_py_file(path): ''' Checks whether the file can be read by the coverage modul...
def p_type_def_3(t): """type_def : STRUCT ID struct_body SEMI""" id = t[2] body = t[3] lineno = t.lineno(1) if id_unique(id, 'struct', lineno): name_dict[id] = struct_info(id, body, lineno)
type_def : STRUCT ID struct_body SEMI
Below is the the instruction that describes the task: ### Input: type_def : STRUCT ID struct_body SEMI ### Response: def p_type_def_3(t): """type_def : STRUCT ID struct_body SEMI""" id = t[2] body = t[3] lineno = t.lineno(1) if id_unique(id, 'struct', lineno): name_dict[id] = struct_inf...
def file_dict(*packages, **kwargs): ''' List the files that belong to a package, sorted by group. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: ...
List the files that belong to a package, sorted by group. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/") CLI Examples: .. code-block:: bash salt '*' lowpk...
Below is the the instruction that describes the task: ### Input: List the files that belong to a package, sorted by group. Not specifying any packages will return a list of _every_ file on the system's rpm database (not generally recommended). root use root as top level directory (default: "/")...
def get_data(self, smoothed=True, masked=True, safe_copy=False): """Get the data in the image. If save_copy is True, will perform a deep copy of the data and return it. Parameters ---------- smoothed: (optional) bool If True and self._smooth_fwhm > 0 will smooth the...
Get the data in the image. If save_copy is True, will perform a deep copy of the data and return it. Parameters ---------- smoothed: (optional) bool If True and self._smooth_fwhm > 0 will smooth the data before masking. masked: (optional) bool If True a...
Below is the the instruction that describes the task: ### Input: Get the data in the image. If save_copy is True, will perform a deep copy of the data and return it. Parameters ---------- smoothed: (optional) bool If True and self._smooth_fwhm > 0 will smooth the data b...
def dictify_urn(urn, combine_interval=True): """ By default, this will put the `interval` as part of the `cell_methods` attribute (NetCDF CF style). To return `interval` as its own key, use the `combine_interval=False` parameter. """ ioos_urn = IoosUrn.from_string(urn) if ioos_u...
By default, this will put the `interval` as part of the `cell_methods` attribute (NetCDF CF style). To return `interval` as its own key, use the `combine_interval=False` parameter.
Below is the the instruction that describes the task: ### Input: By default, this will put the `interval` as part of the `cell_methods` attribute (NetCDF CF style). To return `interval` as its own key, use the `combine_interval=False` parameter. ### Response: def dictify_urn(urn, combine_interval=T...
def reserve_position(fp, fmt='I'): """ Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position """ position = fp.tell() fp.seek(struct.calcsize(str('>' + fmt)), 1) return p...
Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position
Below is the the instruction that describes the task: ### Input: Reserves the current position for write. Use with `write_position`. :param fp: file-like object :param fmt: format of the reserved position :return: the position ### Response: def reserve_position(fp, fmt='I'): """ Reserves ...
def _correct(token, term_freq): """ Correct a single token according to the term_freq """ if token.lower() in term_freq: return token e1 = [t for t in _ed1(token) if t in term_freq] if len(e1) > 0: e1.sort(key=term_freq.get) return e1[0] e2 = [t for t in _ed2(token) i...
Correct a single token according to the term_freq
Below is the the instruction that describes the task: ### Input: Correct a single token according to the term_freq ### Response: def _correct(token, term_freq): """ Correct a single token according to the term_freq """ if token.lower() in term_freq: return token e1 = [t for t in _ed1(to...
def generate_hatpi_binnedlc_pkl(binnedpklf, textlcf, timebinsec, outfile=None): ''' This reads the binned LC and writes it out to a pickle. ''' binlcdict = read_hatpi_binnedlc(binnedpklf, textlcf, timebinsec) if binlcdict: if outfile is None: ou...
This reads the binned LC and writes it out to a pickle.
Below is the the instruction that describes the task: ### Input: This reads the binned LC and writes it out to a pickle. ### Response: def generate_hatpi_binnedlc_pkl(binnedpklf, textlcf, timebinsec, outfile=None): ''' This reads the binned LC and writes it out to a pickle. ...
def GetTemplateID(alias,location,name): """Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name """ if alias is None: alias = clc.v...
Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name
Below is the the instruction that describes the task: ### Input: Given a template name return the unique OperatingSystem ID. :param alias: short code for a particular account. If none will use account's default alias :param location: datacenter where group resides :param name: template name ### Response: d...
def _find_geophysical_vars(self, ds, refresh=False): ''' Returns a list of geophysical variables. Modifies `self._geophysical_vars` :param netCDF4.Dataset ds: An open netCDF dataset :param bool refresh: if refresh is set to True, the cache is invali...
Returns a list of geophysical variables. Modifies `self._geophysical_vars` :param netCDF4.Dataset ds: An open netCDF dataset :param bool refresh: if refresh is set to True, the cache is invalidated. :rtype: list :return: A list containing strings wi...
Below is the the instruction that describes the task: ### Input: Returns a list of geophysical variables. Modifies `self._geophysical_vars` :param netCDF4.Dataset ds: An open netCDF dataset :param bool refresh: if refresh is set to True, the cache is invalidate...
def GetServices(self,filename): """Returns a list of service objects handling this file type""" objlist=[] for sobj in self.services: if sobj.KnowsFile(filename) : objlist.append(sobj) if len(objlist)==0: return None return objlist
Returns a list of service objects handling this file type
Below is the the instruction that describes the task: ### Input: Returns a list of service objects handling this file type ### Response: def GetServices(self,filename): """Returns a list of service objects handling this file type""" objlist=[] for sobj in self.services: if sobj....
def split_camel_case(text) -> list: """Splits words from CamelCase text.""" return list(reduce( lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]), text, [] ))
Splits words from CamelCase text.
Below is the the instruction that describes the task: ### Input: Splits words from CamelCase text. ### Response: def split_camel_case(text) -> list: """Splits words from CamelCase text.""" return list(reduce( lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]), text, [] ...
def _reference_rmvs(self, removes): """Prints all removed packages """ print("") self.msg.template(78) msg_pkg = "package" if len(removes) > 1: msg_pkg = "packages" print("| Total {0} {1} removed".format(len(removes), msg_pkg)) self.msg.templat...
Prints all removed packages
Below is the the instruction that describes the task: ### Input: Prints all removed packages ### Response: def _reference_rmvs(self, removes): """Prints all removed packages """ print("") self.msg.template(78) msg_pkg = "package" if len(removes) > 1: msg_...
def can_use_widgets(): """ Expanded from from http://stackoverflow.com/a/34092072/1958900 """ if 'IPython' not in sys.modules: # IPython hasn't been imported, definitely not return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance if ge...
Expanded from from http://stackoverflow.com/a/34092072/1958900
Below is the the instruction that describes the task: ### Input: Expanded from from http://stackoverflow.com/a/34092072/1958900 ### Response: def can_use_widgets(): """ Expanded from from http://stackoverflow.com/a/34092072/1958900 """ if 'IPython' not in sys.modules: # IPython hasn't been impo...
def text(self): """Get the entire text content as str""" divisions = list(self.divisions) if len(divisions) == 0: return '' elif len(divisions) == 1: return divisions[0].text.strip() else: return super().text
Get the entire text content as str
Below is the the instruction that describes the task: ### Input: Get the entire text content as str ### Response: def text(self): """Get the entire text content as str""" divisions = list(self.divisions) if len(divisions) == 0: return '' elif len(divisions) == 1: ...
def lookup(self, data): """ Returns an appropriate function to format `data` if one has been registered. """ for func in self.lazy_init: func() for type, func in self.func_registry.items(): if isinstance(data, type): return func
Returns an appropriate function to format `data` if one has been registered.
Below is the the instruction that describes the task: ### Input: Returns an appropriate function to format `data` if one has been registered. ### Response: def lookup(self, data): """ Returns an appropriate function to format `data` if one has been registered. """ fo...
def remove(self, entry): """Removes an entry""" try: list = self.cache[entry.key] list.remove(entry) except: pass
Removes an entry
Below is the the instruction that describes the task: ### Input: Removes an entry ### Response: def remove(self, entry): """Removes an entry""" try: list = self.cache[entry.key] list.remove(entry) except: pass
def metric_coherence_mimno_2011(topic_word_distrib, dtm, top_n=20, eps=1e-12, normalize=True, return_mean=False): """ Calculate coherence metric according to Mimno et al. 2011 (a.k.a. "U_Mass" coherence metric). There are two modifications to the originally suggested measure: - uses a different epsilon ...
Calculate coherence metric according to Mimno et al. 2011 (a.k.a. "U_Mass" coherence metric). There are two modifications to the originally suggested measure: - uses a different epsilon by default (set `eps=1` for original) - uses a normalizing constant by default (set `normalize=False` for original) P...
Below is the the instruction that describes the task: ### Input: Calculate coherence metric according to Mimno et al. 2011 (a.k.a. "U_Mass" coherence metric). There are two modifications to the originally suggested measure: - uses a different epsilon by default (set `eps=1` for original) - uses a normal...
def hwstatus_send(self, Vcc, I2Cerr, force_mavlink1=False): ''' Status of key hardware Vcc : board voltage (mV) (uint16_t) I2Cerr : I2C error count (uint8_t) ''' return self.send(se...
Status of key hardware Vcc : board voltage (mV) (uint16_t) I2Cerr : I2C error count (uint8_t)
Below is the the instruction that describes the task: ### Input: Status of key hardware Vcc : board voltage (mV) (uint16_t) I2Cerr : I2C error count (uint8_t) ### Response: def hwstatus_send(self, Vcc, I2Cerr, force_mavlink1=False): ...
def psnr(vref, vcmp, rng=None): """ Compute Peak Signal to Noise Ratio (PSNR) of two images. The PSNR calculation defaults to using the less common definition in terms of the actual range (i.e. max minus min) of the reference signal instead of the maximum possible range for the data type (i.e. :...
Compute Peak Signal to Noise Ratio (PSNR) of two images. The PSNR calculation defaults to using the less common definition in terms of the actual range (i.e. max minus min) of the reference signal instead of the maximum possible range for the data type (i.e. :math:`2^b-1` for a :math:`b` bit representat...
Below is the the instruction that describes the task: ### Input: Compute Peak Signal to Noise Ratio (PSNR) of two images. The PSNR calculation defaults to using the less common definition in terms of the actual range (i.e. max minus min) of the reference signal instead of the maximum possible range for ...
def set_error(self, code, msg, data=None): """ Set an error on this request, which will prevent request execution. Should only be called from "pre" hook methods. If called from a post hook, this operation will be ignored. :Parameters: code Integer error co...
Set an error on this request, which will prevent request execution. Should only be called from "pre" hook methods. If called from a post hook, this operation will be ignored. :Parameters: code Integer error code msg String description of the error ...
Below is the the instruction that describes the task: ### Input: Set an error on this request, which will prevent request execution. Should only be called from "pre" hook methods. If called from a post hook, this operation will be ignored. :Parameters: code Integer er...
def _try_backup_item(self): """Check if a backup item is available in cache and call the item handler if it is. :return: `True` if backup item was found. :returntype: `bool`""" if not self._backup_state: return False item = self.cache.get_item(self.address, s...
Check if a backup item is available in cache and call the item handler if it is. :return: `True` if backup item was found. :returntype: `bool`
Below is the the instruction that describes the task: ### Input: Check if a backup item is available in cache and call the item handler if it is. :return: `True` if backup item was found. :returntype: `bool` ### Response: def _try_backup_item(self): """Check if a backup item is ava...
def set_mkl_thread_limit(cores): """ set mkl thread limit and return old value so we can reset when finished. """ if "linux" in sys.platform: mkl_rt = ctypes.CDLL('libmkl_rt.so') else: mkl_rt = ctypes.CDLL('libmkl_rt.dylib') oldlimit = mkl_rt.mkl_get_max_threads() mkl_rt...
set mkl thread limit and return old value so we can reset when finished.
Below is the the instruction that describes the task: ### Input: set mkl thread limit and return old value so we can reset when finished. ### Response: def set_mkl_thread_limit(cores): """ set mkl thread limit and return old value so we can reset when finished. """ if "linux" in sys.platfo...
def from_api_repr(cls, resource): """Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ArrayQueryParameter` :returns: instance """ array_type = resource["...
Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ArrayQueryParameter` :returns: instance
Below is the the instruction that describes the task: ### Input: Factory: construct parameter from JSON resource. :type resource: dict :param resource: JSON mapping of parameter :rtype: :class:`~google.cloud.bigquery.query.ArrayQueryParameter` :returns: instance ### Response: def ...
def _append_domain(opts): ''' Append a domain to the existing id if it doesn't already exist ''' # Domain already exists if opts['id'].endswith(opts['append_domain']): return opts['id'] # Trailing dot should mean an FQDN that is terminated, leave it alone. if opts['id'].endswith('.')...
Append a domain to the existing id if it doesn't already exist
Below is the the instruction that describes the task: ### Input: Append a domain to the existing id if it doesn't already exist ### Response: def _append_domain(opts): ''' Append a domain to the existing id if it doesn't already exist ''' # Domain already exists if opts['id'].endswith(opts['app...
def _get_n_args(self, args, example, n): """Helper to make sure the command got the right number of arguments """ if len(args) != n: msg = ( 'Got unexpected number of arguments, expected {}. ' '(example: "{} config {}")' ).format(n, get_pro...
Helper to make sure the command got the right number of arguments
Below is the the instruction that describes the task: ### Input: Helper to make sure the command got the right number of arguments ### Response: def _get_n_args(self, args, example, n): """Helper to make sure the command got the right number of arguments """ if len(args) != n: m...
def get_subgraph_by_annotation_value(graph, annotation, values): """Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type valu...
Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values: str or iter[str] :return: A subgraph of the original BEL graph ...
Below is the the instruction that describes the task: ### Input: Induce a sub-graph over all edges whose annotations match the given key and value. :param pybel.BELGraph graph: A BEL graph :param str annotation: The annotation to group by :param values: The value(s) for the annotation :type values:...
def nodes_info(self, nodes=None): """ The cluster :ref:`nodes info <es-guide-reference-api-admin-cluster-state>` API allows to retrieve one or more (or all) of the cluster nodes information. """ parts = ["_cluster", "nodes"] if nodes: parts.append(",".join(nod...
The cluster :ref:`nodes info <es-guide-reference-api-admin-cluster-state>` API allows to retrieve one or more (or all) of the cluster nodes information.
Below is the the instruction that describes the task: ### Input: The cluster :ref:`nodes info <es-guide-reference-api-admin-cluster-state>` API allows to retrieve one or more (or all) of the cluster nodes information. ### Response: def nodes_info(self, nodes=None): """ The cluster :ref:`nod...
def _mk_connectivity_pits(self, i12, flats, elev, mag, dX, dY): """ Helper function for _mk_adjacency_matrix. This is a more general version of _mk_adjacency_flats which drains pits and flats to nearby but non-adjacent pixels. The slope magnitude (and flats mask) is updated for t...
Helper function for _mk_adjacency_matrix. This is a more general version of _mk_adjacency_flats which drains pits and flats to nearby but non-adjacent pixels. The slope magnitude (and flats mask) is updated for these pits and flats so that the TWI can be computed.
Below is the the instruction that describes the task: ### Input: Helper function for _mk_adjacency_matrix. This is a more general version of _mk_adjacency_flats which drains pits and flats to nearby but non-adjacent pixels. The slope magnitude (and flats mask) is updated for these pits and f...
def multi_click(self, locator, params=None, timeout=None): """ Presses left control or command button depending on OS, clicks and then releases control or command key. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param timeou...
Presses left control or command button depending on OS, clicks and then releases control or command key. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param timeout: (optional) time to wait for element :return: None
Below is the the instruction that describes the task: ### Input: Presses left control or command button depending on OS, clicks and then releases control or command key. :param locator: locator tuple or WebElement instance :param params: (optional) locator parameters :param timeout: (option...
def find_one_and_replace(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace """ self._arctic_lib.check_quota() return self._collection.find_one_and_replace(filter, repl...
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace
Below is the the instruction that describes the task: ### Input: See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_replace ### Response: def find_one_and_replace(self, filter, replacement, **kwargs): """ See http://api.mongodb.com/pytho...
def _set_init_vars_and_dims(self, data_vars, coords, compat): """Set the initial value of Dataset variables and dimensions """ both_data_and_coords = [k for k in data_vars if k in coords] if both_data_and_coords: raise ValueError('variables %r are found in both data_vars and ...
Set the initial value of Dataset variables and dimensions
Below is the the instruction that describes the task: ### Input: Set the initial value of Dataset variables and dimensions ### Response: def _set_init_vars_and_dims(self, data_vars, coords, compat): """Set the initial value of Dataset variables and dimensions """ both_data_and_coords = [k f...
def calculate_integral(self, T1, T2): r'''Method to compute the enthalpy integral of heat capacity from `T1` to `T2`. Analytically integrates across the piecewise spline as necessary. Parameters ---------- T1 : float Initial temperature, [K] ...
r'''Method to compute the enthalpy integral of heat capacity from `T1` to `T2`. Analytically integrates across the piecewise spline as necessary. Parameters ---------- T1 : float Initial temperature, [K] T2 : float Final temperature, ...
Below is the the instruction that describes the task: ### Input: r'''Method to compute the enthalpy integral of heat capacity from `T1` to `T2`. Analytically integrates across the piecewise spline as necessary. Parameters ---------- T1 : float Initia...
def TemporaryDirectory(suffix=None, prefix=None, dir=None, on_error='ignore'): # @ReservedAssignment ''' An extension to `tempfile.TemporaryDirectory`. Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on ``__enter__``, not a `str`. Parameters ---------- suffix : str ...
An extension to `tempfile.TemporaryDirectory`. Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on ``__enter__``, not a `str`. Parameters ---------- suffix : str See `tempfile.TemporaryDirectory`. prefix : str See `tempfile.TemporaryDirectory`. dir : ~p...
Below is the the instruction that describes the task: ### Input: An extension to `tempfile.TemporaryDirectory`. Unlike with `python:tempfile`, a :py:class:`~pathlib.Path` is yielded on ``__enter__``, not a `str`. Parameters ---------- suffix : str See `tempfile.TemporaryDirectory`. ...
def fit(self,vxvv,vxvv_err=None,pot=None,radec=False,lb=False, customsky=False,lb_to_customsky=None,pmllpmbb_to_customsky=None, tintJ=10,ntintJ=1000,integrate_method='dopr54_c', disp=False, **kwargs): """ NAME: fit PURPOSE: fi...
NAME: fit PURPOSE: fit an Orbit to data using the current orbit as the initial condition INPUT: vxvv - [:,6] array of positions and velocities along the orbit [cannot be Quantities] vxvv_err= [:,6] array of errors on positions and velocities along ...
Below is the the instruction that describes the task: ### Input: NAME: fit PURPOSE: fit an Orbit to data using the current orbit as the initial condition INPUT: vxvv - [:,6] array of positions and velocities along the orbit [cannot be Quantities] ...
def unzip(self, overwrite: bool = False): """ Flattens a MIZ file into the temp dir Args: overwrite: allow overwriting exiting files """ if self.zip_content and not overwrite: raise FileExistsError(str(self.temp_dir)) LOGGER.debug('unzipping mi...
Flattens a MIZ file into the temp dir Args: overwrite: allow overwriting exiting files
Below is the the instruction that describes the task: ### Input: Flattens a MIZ file into the temp dir Args: overwrite: allow overwriting exiting files ### Response: def unzip(self, overwrite: bool = False): """ Flattens a MIZ file into the temp dir Args: o...
def _calc_hash_da(self, rs): """Compute hash of D and A timestamps for single-step D+A case. """ self.hash_d = hash_(rs.get_state())[:6] self.hash_a = self.hash_d
Compute hash of D and A timestamps for single-step D+A case.
Below is the the instruction that describes the task: ### Input: Compute hash of D and A timestamps for single-step D+A case. ### Response: def _calc_hash_da(self, rs): """Compute hash of D and A timestamps for single-step D+A case. """ self.hash_d = hash_(rs.get_state())[:6] self.h...
def do(cmdline, runas=None, env=None): ''' Execute a ruby command with rbenv's shims from the user or the system CLI Example: .. code-block:: bash salt '*' rbenv.do 'gem list bundler' salt '*' rbenv.do 'gem list bundler' deploy ''' if not cmdline: # This is a positiona...
Execute a ruby command with rbenv's shims from the user or the system CLI Example: .. code-block:: bash salt '*' rbenv.do 'gem list bundler' salt '*' rbenv.do 'gem list bundler' deploy
Below is the the instruction that describes the task: ### Input: Execute a ruby command with rbenv's shims from the user or the system CLI Example: .. code-block:: bash salt '*' rbenv.do 'gem list bundler' salt '*' rbenv.do 'gem list bundler' deploy ### Response: def do(cmdline, runas=No...
def program_files(self, executable): """ OPTIONAL, this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool (to transport them to a cloud service, for example). Returns a list of files or directories that are necessar...
OPTIONAL, this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool (to transport them to a cloud service, for example). Returns a list of files or directories that are necessary to run the tool.
Below is the the instruction that describes the task: ### Input: OPTIONAL, this method is only necessary for situations when the benchmark environment needs to know all files belonging to a tool (to transport them to a cloud service, for example). Returns a list of files or directories that ...
def read_env(src, expr): r"""Read the environment from buffer. Advances the buffer until right after the end of the environment. Adds parsed content to the expression automatically. :param Buffer src: a buffer of tokens :param TexExpr expr: expression for the environment :rtype: TexExpr ""...
r"""Read the environment from buffer. Advances the buffer until right after the end of the environment. Adds parsed content to the expression automatically. :param Buffer src: a buffer of tokens :param TexExpr expr: expression for the environment :rtype: TexExpr
Below is the the instruction that describes the task: ### Input: r"""Read the environment from buffer. Advances the buffer until right after the end of the environment. Adds parsed content to the expression automatically. :param Buffer src: a buffer of tokens :param TexExpr expr: expression for th...
def d2ASbr_dV2(dSbr_dVa, dSbr_dVm, Sbr, Cbr, Ybr, V, lam): """ Computes 2nd derivatives of |complex power flow|**2 w.r.t. V. """ diaglam = spdiag(lam) diagSbr_conj = spdiag(conj(Sbr)) Saa, Sav, Sva, Svv = d2Sbr_dV2(Cbr, Ybr, V, diagSbr_conj * lam) Haa = 2 * ( Saa + dSbr_dVa.T * diaglam * conj(...
Computes 2nd derivatives of |complex power flow|**2 w.r.t. V.
Below is the the instruction that describes the task: ### Input: Computes 2nd derivatives of |complex power flow|**2 w.r.t. V. ### Response: def d2ASbr_dV2(dSbr_dVa, dSbr_dVm, Sbr, Cbr, Ybr, V, lam): """ Computes 2nd derivatives of |complex power flow|**2 w.r.t. V. """ diaglam = spdiag(lam) diagSbr...
def assert_rank_at_most(x, rank, data=None, summarize=None, message=None, name=None): """Assert `x` has rank equal to `rank` or smaller. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.assert_rank_at_most(x, 2)]): output = tf.reduce_sum(x)...
Assert `x` has rank equal to `rank` or smaller. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.assert_rank_at_most(x, 2)]): output = tf.reduce_sum(x) ``` Args: x: Numeric `Tensor`. rank: Scalar `Tensor`. data: The tensors to print out if the co...
Below is the the instruction that describes the task: ### Input: Assert `x` has rank equal to `rank` or smaller. Example of adding a dependency to an operation: ```python with tf.control_dependencies([tf.assert_rank_at_most(x, 2)]): output = tf.reduce_sum(x) ``` Args: x: Numeric `Tensor`. ...
def _validate_covars(covars, covariance_type, n_components): """Do basic checks on matrix covariance sizes and values.""" from scipy import linalg if covariance_type == 'spherical': if len(covars) != n_components: raise ValueError("'spherical' covars have length n_components") el...
Do basic checks on matrix covariance sizes and values.
Below is the the instruction that describes the task: ### Input: Do basic checks on matrix covariance sizes and values. ### Response: def _validate_covars(covars, covariance_type, n_components): """Do basic checks on matrix covariance sizes and values.""" from scipy import linalg if covariance_type == ...
def hager_zhang(value_and_gradients_function, initial_step_size=None, value_at_initial_step=None, value_at_zero=None, converged=None, threshold_use_approximate_wolfe_condition=1e-6, shrinkage_param=0.66, expa...
The Hager Zhang line search algorithm. Performs an inexact line search based on the algorithm of [Hager and Zhang (2006)][2]. The univariate objective function `value_and_gradients_function` is typically generated by projecting a multivariate objective function along a search direction. Suppose the multivari...
Below is the the instruction that describes the task: ### Input: The Hager Zhang line search algorithm. Performs an inexact line search based on the algorithm of [Hager and Zhang (2006)][2]. The univariate objective function `value_and_gradients_function` is typically generated by projecting a multivariate...
def get(img, light=False): """Get colorscheme.""" cols = gen_colors(img) return adjust(cols, light)
Get colorscheme.
Below is the the instruction that describes the task: ### Input: Get colorscheme. ### Response: def get(img, light=False): """Get colorscheme.""" cols = gen_colors(img) return adjust(cols, light)
def all_named_colors(): """Return an iteration over all name, color pairs in tables""" yield from _TO_COLOR_USER.items() for name, color in _TO_COLOR.items(): if name not in _TO_COLOR_USER: yield name, color
Return an iteration over all name, color pairs in tables
Below is the the instruction that describes the task: ### Input: Return an iteration over all name, color pairs in tables ### Response: def all_named_colors(): """Return an iteration over all name, color pairs in tables""" yield from _TO_COLOR_USER.items() for name, color in _TO_COLOR.items(): ...
def set_primary(self, **params): """https://developers.coinbase.com/api/v2#set-account-as-primary""" data = self.api_client.set_primary_account(self.id, **params) self.update(data) return data
https://developers.coinbase.com/api/v2#set-account-as-primary
Below is the the instruction that describes the task: ### Input: https://developers.coinbase.com/api/v2#set-account-as-primary ### Response: def set_primary(self, **params): """https://developers.coinbase.com/api/v2#set-account-as-primary""" data = self.api_client.set_primary_account(self.id, **par...
def _list_store_resources(self, request, head_id, filter_ids, resource_fetcher, block_xform): """Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block...
Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block - filtered by both id and head block - not filtered (all current resources) Note: This me...
Below is the the instruction that describes the task: ### Input: Builds a list of blocks or resources derived from blocks, handling multiple possible filter requests: - filtered by a set of ids - filtered by head block - filtered by both id and head block - no...
def _Dhcpcd(self, interfaces, logger): """Use dhcpcd to activate the interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. """ for interface in interfaces: dhcpcd = ['/sbin/dhcpcd'] try: ...
Use dhcpcd to activate the interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port.
Below is the the instruction that describes the task: ### Input: Use dhcpcd to activate the interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. ### Response: def _Dhcpcd(self, interfaces, logger): """U...
def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist""" lcat_noext = local_catalog[0:local_catalog.rfind(".lrcat")] ccat_noext = cloud_catalog...
Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist
Below is the the instruction that describes the task: ### Input: Copy Smart Previews from local to cloud or vica versa when 'local2cloud==False' NB: nothing happens if source dir doesn't exist ### Response: def copy_smart_previews(local_catalog, cloud_catalog, local2cloud=True): """Copy Smart Pre...
def migrate(config): """Perform a migration according to config. :param config: The configuration to be applied :type config: Config """ webapp = WebApp(config.web_host, config.web_port, custom_maintenance_file=config.web_custom_html) webserver = WebServer(webapp) webse...
Perform a migration according to config. :param config: The configuration to be applied :type config: Config
Below is the the instruction that describes the task: ### Input: Perform a migration according to config. :param config: The configuration to be applied :type config: Config ### Response: def migrate(config): """Perform a migration according to config. :param config: The configuration to be appli...
def stats(self, request, uuid=None): """ This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(fro...
This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number of vCPUs(from quotas) * vcpu_usage - current number of used v...
Below is the the instruction that describes the task: ### Input: This endpoint returns allocation of resources for current service setting. Answer is service-specific dictionary. Example output for OpenStack: * vcpu - maximum number of vCPUs (from hypervisors) * vcpu_quota - maximum number ...
def _validate_isvalid_t_range(self, isvalid_t_range, field, values): """Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List...
Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List of temperature values indicating low, middle, and high ranges The rule...
Below is the the instruction that describes the task: ### Input: Checks that the temperature ranges given for thermo data are valid Args: isvalid_t_range (`bool`): flag from schema indicating T range is to be checked field (`str`): T_range values (`list`): List of tempera...
def decipher_response(status_code: int, headers: Mapping[str, str], body: bytes) -> Tuple[Any, Optional[RateLimit], Optional[str]]: """Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this f...
Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this function correspond to the three main parts of an HTTP response: the status code, headers, and body. Assuming no errors which lead to an exception being r...
Below is the the instruction that describes the task: ### Input: Decipher an HTTP response for a GitHub API request. The mapping providing the headers is expected to support lowercase keys. The parameters of this function correspond to the three main parts of an HTTP response: the status code, headers...
def check_status(status): """ Check the status of a mkl functions and raise a python exeption if there is an error. """ if status: msg = lib.DftiErrorMessage(status) msg = ctypes.c_char_p(msg).value raise RuntimeError(msg)
Check the status of a mkl functions and raise a python exeption if there is an error.
Below is the the instruction that describes the task: ### Input: Check the status of a mkl functions and raise a python exeption if there is an error. ### Response: def check_status(status): """ Check the status of a mkl functions and raise a python exeption if there is an error. """ if status:...
def parse_options(self, options): """ Perform any required parsing on the option values from optparse. Attempts to call a parse_option_<name> method for each option name returned by self.get_option_names(). """ for name in self.get_option_names(): par...
Perform any required parsing on the option values from optparse. Attempts to call a parse_option_<name> method for each option name returned by self.get_option_names().
Below is the the instruction that describes the task: ### Input: Perform any required parsing on the option values from optparse. Attempts to call a parse_option_<name> method for each option name returned by self.get_option_names(). ### Response: def parse_options(self, options): """ ...
def filtered(f): ''' Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set. ''' def _filter(f, self, *args, **kwargs): frame = f(self, *args, **kwargs) ret = type(self)(frame) ret._...
Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set.
Below is the the instruction that describes the task: ### Input: Decorator function that wraps functions returning pandas dataframes, such that the dataframe is filtered according to left and right bounds set. ### Response: def filtered(f): ''' Decorator function that wraps functions returning pand...
def list_elasticache(region, filter_by_kwargs): """List all ElastiCache Clusters.""" conn = boto.elasticache.connect_to_region(region) req = conn.describe_cache_clusters() data = req["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"] if filter_by_kwargs: cluster...
List all ElastiCache Clusters.
Below is the the instruction that describes the task: ### Input: List all ElastiCache Clusters. ### Response: def list_elasticache(region, filter_by_kwargs): """List all ElastiCache Clusters.""" conn = boto.elasticache.connect_to_region(region) req = conn.describe_cache_clusters() data = req["Descr...
def harmonic(word): '''Return True if the word's vowels agree in frontness/backness.''' depth = {'ä': 0, 'ö': 0, 'y': 0, 'a': 1, 'o': 1, 'u': 1} vowels = filter(lambda ch: is_front(ch) or is_back(ch), word) depths = (depth[x.lower()] for x in vowels) return len(set(depths)) < 2
Return True if the word's vowels agree in frontness/backness.
Below is the the instruction that describes the task: ### Input: Return True if the word's vowels agree in frontness/backness. ### Response: def harmonic(word): '''Return True if the word's vowels agree in frontness/backness.''' depth = {'ä': 0, 'ö': 0, 'y': 0, 'a': 1, 'o': 1, 'u': 1} vowels = filter(l...
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(r...
Displays the login form and handles the login action.
Below is the the instruction that describes the task: ### Input: Displays the login form and handles the login action. ### Response: def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app...
def get_mac(self, use_cached=True): """Get the MAC address of this device""" device_json = self.get_device_json(use_cached) return device_json.get("devMac")
Get the MAC address of this device
Below is the the instruction that describes the task: ### Input: Get the MAC address of this device ### Response: def get_mac(self, use_cached=True): """Get the MAC address of this device""" device_json = self.get_device_json(use_cached) return device_json.get("devMac")
def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name): """Generates an ivy xml with all jars marked as intransitive using the all conflict manager.""" org = IvyUtils.INTERNAL_ORG_NAME name = resolve_hash_name extra_configurations = [conf for conf in confs if conf and conf != 'default'] ...
Generates an ivy xml with all jars marked as intransitive using the all conflict manager.
Below is the the instruction that describes the task: ### Input: Generates an ivy xml with all jars marked as intransitive using the all conflict manager. ### Response: def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name): """Generates an ivy xml with all jars marked as intransitive using the al...
def host_agent_call(self, _method, *args, **kwargs): '''Public method exposed to all the agency submodules, which need to call the method on the host agent. This works regardless if host agent already running or not. If it is still being started the method will be called when he is ready...
Public method exposed to all the agency submodules, which need to call the method on the host agent. This works regardless if host agent already running or not. If it is still being started the method will be called when he is ready.
Below is the the instruction that describes the task: ### Input: Public method exposed to all the agency submodules, which need to call the method on the host agent. This works regardless if host agent already running or not. If it is still being started the method will be called when he is ...
def _validate_max(self, max_value, field, value): """ {'nullable': False } """ try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: pass
{'nullable': False }
Below is the the instruction that describes the task: ### Input: {'nullable': False } ### Response: def _validate_max(self, max_value, field, value): """ {'nullable': False } """ try: if value > max_value: self._error(field, errors.MAX_VALUE) except TypeError: ...
def classpath(self, targets, classpath_prefix=None, classpath_product=None, exclude_scopes=None, include_scopes=None): """Builds a transitive classpath for the given targets. Optionally includes a classpath prefix or building from a non-default classpath product. :param targets: the target...
Builds a transitive classpath for the given targets. Optionally includes a classpath prefix or building from a non-default classpath product. :param targets: the targets for which to build the transitive classpath. :param classpath_prefix: optional additional entries to prepend to the classpath. :para...
Below is the the instruction that describes the task: ### Input: Builds a transitive classpath for the given targets. Optionally includes a classpath prefix or building from a non-default classpath product. :param targets: the targets for which to build the transitive classpath. :param classpath_prefi...
def write_data(data, filename): """Call right func to save data according to file extension """ name, ext = get_file_extension(filename) func = json_write_data if ext == '.json' else yaml_write_data return func(data, filename)
Call right func to save data according to file extension
Below is the the instruction that describes the task: ### Input: Call right func to save data according to file extension ### Response: def write_data(data, filename): """Call right func to save data according to file extension """ name, ext = get_file_extension(filename) func = json_write_data if ...
def populateFromRow(self, variantSetRecord): """ Populates this VariantSet from the specified DB row. """ self._created = variantSetRecord.created self._updated = variantSetRecord.updated self.setAttributesJson(variantSetRecord.attributes) self._chromFileMap = {} ...
Populates this VariantSet from the specified DB row.
Below is the the instruction that describes the task: ### Input: Populates this VariantSet from the specified DB row. ### Response: def populateFromRow(self, variantSetRecord): """ Populates this VariantSet from the specified DB row. """ self._created = variantSetRecord.created ...
def stats(self, variables=None, alpha=0.05, start=0, batches=100, chain=None, quantiles=(2.5, 25, 50, 75, 97.5)): """ Statistical output for variables. :Parameters: variables : iterable List or array of variables for which statistics are to be generated...
Statistical output for variables. :Parameters: variables : iterable List or array of variables for which statistics are to be generated. If it is not specified, all the tallied variables are summarized. alpha : float The alpha level for generating poster...
Below is the the instruction that describes the task: ### Input: Statistical output for variables. :Parameters: variables : iterable List or array of variables for which statistics are to be generated. If it is not specified, all the tallied variables are summarized. ...
def get_inbox_documents_per_page(self, per_page=1000, page=1): """ Get inbox documents per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ return self._get_resource_per_page( resourc...
Get inbox documents per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
Below is the the instruction that describes the task: ### Input: Get inbox documents per page :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list ### Response: def get_inbox_documents_per_page(self, per_page=1000, page=1): """...
def reserved_quota(self, reserved_quota): """ Sets the reserved_quota of this ServicePackageMetadata. Sum of all open reservations for this account. :param reserved_quota: The reserved_quota of this ServicePackageMetadata. :type: int """ if reserved_quota is None...
Sets the reserved_quota of this ServicePackageMetadata. Sum of all open reservations for this account. :param reserved_quota: The reserved_quota of this ServicePackageMetadata. :type: int
Below is the the instruction that describes the task: ### Input: Sets the reserved_quota of this ServicePackageMetadata. Sum of all open reservations for this account. :param reserved_quota: The reserved_quota of this ServicePackageMetadata. :type: int ### Response: def reserved_quota(self...
def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d outliers' % (0, self.oiter, len(self.outmask))) def M(x): return np.delete(x, np.concatenate( [self...
Performs iterative sigma clipping to get outliers.
Below is the the instruction that describes the task: ### Input: Performs iterative sigma clipping to get outliers. ### Response: def get_outliers(self): ''' Performs iterative sigma clipping to get outliers. ''' log.info("Clipping outliers...") log.info('Iter %d/%d: %d ou...
def from_data(data): """Create a chunk from data including header and length bytes.""" header, length = struct.unpack('4s<I', data[:8]) data = data[8:] return RiffDataChunk(header, data)
Create a chunk from data including header and length bytes.
Below is the the instruction that describes the task: ### Input: Create a chunk from data including header and length bytes. ### Response: def from_data(data): """Create a chunk from data including header and length bytes.""" header, length = struct.unpack('4s<I', data[:8]) data = data[8:] ...
def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client...
Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge
Below is the the instruction that describes the task: ### Input: Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge ### Response: def get_lmv2...
def _checksum(self, packet): '''calculate the XOR checksum of a packet in string format''' xorsum = 0 for s in packet: xorsum ^= ord(s) return xorsum
calculate the XOR checksum of a packet in string format
Below is the the instruction that describes the task: ### Input: calculate the XOR checksum of a packet in string format ### Response: def _checksum(self, packet): '''calculate the XOR checksum of a packet in string format''' xorsum = 0 for s in packet: xorsum ^= ord(s) ...
def _update_properties(self, name, value): """Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return: """ if self._auto_decode and 'properties' in self._decode_cache: self._decode_c...
Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return:
Below is the the instruction that describes the task: ### Input: Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return: ### Response: def _update_properties(self, name, value): """Update properties, and ...
def instaprint(figure='gcf', arguments='', threaded=False, file_format='pdf'): """ Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['instaprint'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a...
Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['instaprint'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a list of numbers
Below is the the instruction that describes the task: ### Input: Quick function that saves the specified figure as a postscript and then calls the command defined by spinmob.prefs['instaprint'] with this postscript file as the argument. figure='gcf' can be 'all', a number, or a list of numbers ### R...
def strip_glob(string, split_str=' '): """ Strip glob portion in `string`. >>> strip_glob('*glob*like') 'glob like' >>> strip_glob('glob?') 'glo' >>> strip_glob('glob[seq]') 'glob' >>> strip_glob('glob[!seq]') 'glob' :type string: str :rtype: str """ string = _...
Strip glob portion in `string`. >>> strip_glob('*glob*like') 'glob like' >>> strip_glob('glob?') 'glo' >>> strip_glob('glob[seq]') 'glob' >>> strip_glob('glob[!seq]') 'glob' :type string: str :rtype: str
Below is the the instruction that describes the task: ### Input: Strip glob portion in `string`. >>> strip_glob('*glob*like') 'glob like' >>> strip_glob('glob?') 'glo' >>> strip_glob('glob[seq]') 'glob' >>> strip_glob('glob[!seq]') 'glob' :type string: str :rtype: str ### R...
def create_confirm_application(message): """ Create a confirmation `Application` that returns True/False. """ registry = Registry() @registry.add_binding('y') @registry.add_binding('Y') def _(event): event.cli.buffers[DEFAULT_BUFFER].text = 'y' event.cli.set_return_value(Tru...
Create a confirmation `Application` that returns True/False.
Below is the the instruction that describes the task: ### Input: Create a confirmation `Application` that returns True/False. ### Response: def create_confirm_application(message): """ Create a confirmation `Application` that returns True/False. """ registry = Registry() @registry.add_binding(...
def overlay_mask(self, image, predictions): """ Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the mode...
Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `mask` and `label...
Below is the the instruction that describes the task: ### Input: Adds the instances contours for each predicted object. Each label has a different color. Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the...
def _print_original_webpage( self): """*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF """ self.log.debug('starting the ``_print_original_webpage`` method') if not self.title: r = requests.get(self.url)...
*print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF
Below is the the instruction that describes the task: ### Input: *print the original webpage* **Return:** - ``pdfPath`` -- the path to the generated PDF ### Response: def _print_original_webpage( self): """*print the original webpage* **Return:** - ``pd...