code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def solver_configuration(A, B=None, verb=True): """Generate a dictionary of SA parameters for an arbitray matrix A. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix (n x n) matrix to invert, CSR or BSR format preferred for efficiency B : None, array Near null-space mo...
Generate a dictionary of SA parameters for an arbitray matrix A. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix (n x n) matrix to invert, CSR or BSR format preferred for efficiency B : None, array Near null-space modes used to construct the smoothed aggregation solver ...
Below is the the instruction that describes the task: ### Input: Generate a dictionary of SA parameters for an arbitray matrix A. Parameters ---------- A : array, matrix, csr_matrix, bsr_matrix (n x n) matrix to invert, CSR or BSR format preferred for efficiency B : None, array Near...
def edge_lengths(self): """ Compute the edge-lengths of each triangle in the triangulation. """ simplex = self.simplices.T # simplex is vectors a, b, c defining the corners a = self.points[simplex[0]] b = self.points[simplex[1]] c = self.points[simplex[2]...
Compute the edge-lengths of each triangle in the triangulation.
Below is the the instruction that describes the task: ### Input: Compute the edge-lengths of each triangle in the triangulation. ### Response: def edge_lengths(self): """ Compute the edge-lengths of each triangle in the triangulation. """ simplex = self.simplices.T # simple...
def _set_ospf_level1(self, v, load=False): """ Setter method for ospf_level1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level1 (empty) If this variable is read-only (config:...
Setter method for ospf_level1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level1 (empty) If this variable is read-only (config: false) in the source YANG file, then _set_ospf_lev...
Below is the the instruction that describes the task: ### Input: Setter method for ospf_level1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/ospf/ospf_level1 (empty) If this variable is read...
def calculate_r_matrices(fine_states, reduced_matrix_elements, q=None, numeric=True, convention=1): ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, ppri...
ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, pprint >>> red = symbols("r", positive=True) >>> reduced_matrix_elements = [[0, -red], [red, 0]] >>> g = State("Rb", 87, ...
Below is the the instruction that describes the task: ### Input: ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, pprint >>> red = symbols("r", positive=True) >>> reduced...
def _validated(self, data): """Convert data or die trying.""" try: return self.convert(data) except (TypeError, ValueError) as ex: raise NotValid(*ex.args)
Convert data or die trying.
Below is the the instruction that describes the task: ### Input: Convert data or die trying. ### Response: def _validated(self, data): """Convert data or die trying.""" try: return self.convert(data) except (TypeError, ValueError) as ex: raise NotValid(*ex.args)
def getExceptionClass(errorCode): """ Converts the specified error code into the corresponding class object. Raises a KeyError if the errorCode is not found. """ classMap = {} for name, class_ in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(class_) and issubclass(class_,...
Converts the specified error code into the corresponding class object. Raises a KeyError if the errorCode is not found.
Below is the the instruction that describes the task: ### Input: Converts the specified error code into the corresponding class object. Raises a KeyError if the errorCode is not found. ### Response: def getExceptionClass(errorCode): """ Converts the specified error code into the corresponding class obj...
def store_value(self, name, value, parameters=None): """Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The value t...
Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The value to be cached :param dict parameters: The parameters on wh...
Below is the the instruction that describes the task: ### Input: Stores the value of a certain variable The value of a variable with name 'name' is stored together with the parameters that were used for the calculation. :param str name: The name of the variable :param value: The va...
def _extract_blocks(x, block_h, block_w): """Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor """ (_, height, w...
Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor
Below is the the instruction that describes the task: ### Input: Helper function for local 2d attention. Args: x: a [batch, height, width, depth] tensor block_h: An integer. block height block_w: An inteter. block width returns: a [batch, num_heads, height/block_h, width/block_w, depth] tensor...
def get_next_colour(): """ Gets the next colour in the Geckoboard colour list. """ colour = settings.GECKOBOARD_COLOURS[get_next_colour.cur_colour] get_next_colour.cur_colour += 1 if get_next_colour.cur_colour >= len(settings.GECKOBOARD_COLOURS): get_next_colour.cur_colour = 0 ret...
Gets the next colour in the Geckoboard colour list.
Below is the the instruction that describes the task: ### Input: Gets the next colour in the Geckoboard colour list. ### Response: def get_next_colour(): """ Gets the next colour in the Geckoboard colour list. """ colour = settings.GECKOBOARD_COLOURS[get_next_colour.cur_colour] get_next_colou...
def ipv6(value, allow_empty = False, **kwargs): """Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValue...
Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` i...
Below is the the instruction that describes the task: ### Input: Validate that ``value`` is a valid IP address version 6. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
def idem(cls, ops, kwargs): """Remove duplicate arguments and order them via the cls's order_key key object/function. E.g.:: >>> class Set(Operation): ... order_key = lambda val: val ... simplifications = [idem, ] >>> Set.create(1,2,3,1,3) Set(1, 2, 3) ""...
Remove duplicate arguments and order them via the cls's order_key key object/function. E.g.:: >>> class Set(Operation): ... order_key = lambda val: val ... simplifications = [idem, ] >>> Set.create(1,2,3,1,3) Set(1, 2, 3)
Below is the the instruction that describes the task: ### Input: Remove duplicate arguments and order them via the cls's order_key key object/function. E.g.:: >>> class Set(Operation): ... order_key = lambda val: val ... simplifications = [idem, ] >>> Set.create(1,2,...
def node_query(lat_min, lng_min, lat_max, lng_max, tags=None): """ Search for OSM nodes within a bounding box that match given tags. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float tags : str or list of str, optional Node tags that will be used to filter the search. ...
Search for OSM nodes within a bounding box that match given tags. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float tags : str or list of str, optional Node tags that will be used to filter the search. See http://wiki.openstreetmap.org/wiki/Overpass_API/Language_Guide ...
Below is the the instruction that describes the task: ### Input: Search for OSM nodes within a bounding box that match given tags. Parameters ---------- lat_min, lng_min, lat_max, lng_max : float tags : str or list of str, optional Node tags that will be used to filter the search. S...
def get_web_session_cookies(self): """Get web authentication cookies via WebAPI's ``AuthenticateUser`` .. note:: The cookies are valid only while :class:`.SteamClient` instance is logged on. :return: dict with authentication cookies :rtype: :class:`dict`, :class:`None` ...
Get web authentication cookies via WebAPI's ``AuthenticateUser`` .. note:: The cookies are valid only while :class:`.SteamClient` instance is logged on. :return: dict with authentication cookies :rtype: :class:`dict`, :class:`None`
Below is the the instruction that describes the task: ### Input: Get web authentication cookies via WebAPI's ``AuthenticateUser`` .. note:: The cookies are valid only while :class:`.SteamClient` instance is logged on. :return: dict with authentication cookies :rtype: :class:`di...
def find_one(self, filter=None, *args, **kwargs): """Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single :class:`~gridfs.grid_file.GridOut`, or ``None`` if no ...
Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single :class:`~gridfs.grid_file.GridOut`, or ``None`` if no matching file is found. For example:: file = fs....
Below is the the instruction that describes the task: ### Input: Get a single file from gridfs. All arguments to :meth:`find` are also valid arguments for :meth:`find_one`, although any `limit` argument will be ignored. Returns a single :class:`~gridfs.grid_file.GridOut`, or ``None`...
def tile_is_valid(self): """ Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool """ return self.tile_info is not None \ and (self.datetime == self.date or self.datetime == self.parse_datetime(self.tile...
Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool
Below is the the instruction that describes the task: ### Input: Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool ### Response: def tile_is_valid(self): """ Checks if tile has tile info and valid timestamp :return...
def bump_context(self, name): """Causes the context's tools to take priority over all others.""" data = self._context(name) data["priority"] = self._next_priority self._flush_tools()
Causes the context's tools to take priority over all others.
Below is the the instruction that describes the task: ### Input: Causes the context's tools to take priority over all others. ### Response: def bump_context(self, name): """Causes the context's tools to take priority over all others.""" data = self._context(name) data["priority"] = self._ne...
def is_none(entity, prop, name): "bool: True if the value of a property is None." return is_not_empty(entity, prop, name) and getattr(entity, name) is None
bool: True if the value of a property is None.
Below is the the instruction that describes the task: ### Input: bool: True if the value of a property is None. ### Response: def is_none(entity, prop, name): "bool: True if the value of a property is None." return is_not_empty(entity, prop, name) and getattr(entity, name) is None
def add_geo_facet(self, *args, **kwargs): """Add a geo factory facet""" self.facets.append(GeoDistanceFacet(*args, **kwargs))
Add a geo factory facet
Below is the the instruction that describes the task: ### Input: Add a geo factory facet ### Response: def add_geo_facet(self, *args, **kwargs): """Add a geo factory facet""" self.facets.append(GeoDistanceFacet(*args, **kwargs))
def abort(self, msgObj): """ Disconnect all signals and turn macro processing in the event handler back on. """ self.qteMain.qtesigKeyparsed.disconnect(self.qteKeyPress) self.qteMain.qtesigAbort.disconnect(self.abort) self.qteActive = False self.qteMain.qt...
Disconnect all signals and turn macro processing in the event handler back on.
Below is the the instruction that describes the task: ### Input: Disconnect all signals and turn macro processing in the event handler back on. ### Response: def abort(self, msgObj): """ Disconnect all signals and turn macro processing in the event handler back on. """ ...
def complete(self, filepath): ''' Marks the item as complete by moving it to the done directory and optionally gzipping it. ''' if not os.path.exists(filepath): raise FileNotFoundError("Can't Complete {}, it doesn't exist".format(filepath)) if self._devel: self.logger...
Marks the item as complete by moving it to the done directory and optionally gzipping it.
Below is the the instruction that describes the task: ### Input: Marks the item as complete by moving it to the done directory and optionally gzipping it. ### Response: def complete(self, filepath): ''' Marks the item as complete by moving it to the done directory and optionally gzipping it. ...
def _bddnode(root, lo, hi): """Return a unique BDD node.""" if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: node = _NODES[key] = BDDNode(*key) return node
Return a unique BDD node.
Below is the the instruction that describes the task: ### Input: Return a unique BDD node. ### Response: def _bddnode(root, lo, hi): """Return a unique BDD node.""" if lo is hi: node = lo else: key = (root, lo, hi) try: node = _NODES[key] except KeyError: ...
def do_reload(self, args): """Reload a module in to the framework""" if args.module is not None: if args.module not in self.frmwk.modules: self.print_error('Invalid Module Selected.') return module = self.frmwk.modules[args.module] elif self.frmwk.current_module: module = self.frmwk.current_modul...
Reload a module in to the framework
Below is the the instruction that describes the task: ### Input: Reload a module in to the framework ### Response: def do_reload(self, args): """Reload a module in to the framework""" if args.module is not None: if args.module not in self.frmwk.modules: self.print_error('Invalid Module Selected.') r...
def parallel_update_objectinfo_cplist( cplist, liststartindex=None, maxobjects=None, nworkers=NCPUS, fast_mode=False, findercmap='gray_r', finderconvolve=None, deredden_object=True, custom_bandpasses=None, gaia_submit_timeout=10.0, ...
This updates objectinfo for a list of checkplots. Useful in cases where a previous round of GAIA/finderchart/external catalog acquisition failed. This will preserve the following keys in the checkplots if they exist: comments varinfo objectinfo.objecttags Parameters ---------- cp...
Below is the the instruction that describes the task: ### Input: This updates objectinfo for a list of checkplots. Useful in cases where a previous round of GAIA/finderchart/external catalog acquisition failed. This will preserve the following keys in the checkplots if they exist: comments var...
def _build_row(cells, padding, begin, sep, end): "Return a string which represents a row of data cells." pad = " " * padding padded_cells = [pad + cell + pad for cell in cells] # SolveBio: we're only displaying Key-Value tuples (dimension of 2). # enforce that we don't wrap lines by setting a max...
Return a string which represents a row of data cells.
Below is the the instruction that describes the task: ### Input: Return a string which represents a row of data cells. ### Response: def _build_row(cells, padding, begin, sep, end): "Return a string which represents a row of data cells." pad = " " * padding padded_cells = [pad + cell + pad for cell in...
def _construct_lambda_layer(self, intrinsics_resolver): """Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list """ # Resolve intrinsics if applicable: self.LayerName = self._resolve_string_...
Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list
Below is the the instruction that describes the task: ### Input: Constructs and returns the Lambda function. :returns: a list containing the Lambda function and execution role resources :rtype: list ### Response: def _construct_lambda_layer(self, intrinsics_resolver): """Constructs and ret...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(sel...
Return a json dictionary representing this model.
Below is the the instruction that describes the task: ### Input: Return a json dictionary representing this model. ### Response: def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text...
def decide(self): """ Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters. """ next_command_name = random.choice(self.COMMAND_MAP[self.state['last_command']]) param = '' if n...
Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters.
Below is the the instruction that describes the task: ### Input: Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters. ### Response: def decide(self): """ Decides the next command to be launched based o...
def setFormat(self, start, count, format): """ Reimplemented to highlight selectively. """ start += self._current_offset super(FrontendHighlighter, self).setFormat(start, count, format)
Reimplemented to highlight selectively.
Below is the the instruction that describes the task: ### Input: Reimplemented to highlight selectively. ### Response: def setFormat(self, start, count, format): """ Reimplemented to highlight selectively. """ start += self._current_offset super(FrontendHighlighter, self).setFormat(...
def _ssh_forward_accept(ssh_session, timeout_ms): """Waiting for an incoming connection from a reverse forwarded port. Note that this results in a kernel block until a connection is received. """ ssh_channel = c_ssh_forward_accept(c_void_p(ssh_session), c_int(tim...
Waiting for an incoming connection from a reverse forwarded port. Note that this results in a kernel block until a connection is received.
Below is the the instruction that describes the task: ### Input: Waiting for an incoming connection from a reverse forwarded port. Note that this results in a kernel block until a connection is received. ### Response: def _ssh_forward_accept(ssh_session, timeout_ms): """Waiting for an incoming connection f...
def xpathNextSelf(self, ctxt): """Traversal function for the "self" direction The self axis contains just the context node itself """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o ret = libxml2mod.xmlXPathNextSelf(ctxt__o, self._o) if ret is None:raise xpathE...
Traversal function for the "self" direction The self axis contains just the context node itself
Below is the the instruction that describes the task: ### Input: Traversal function for the "self" direction The self axis contains just the context node itself ### Response: def xpathNextSelf(self, ctxt): """Traversal function for the "self" direction The self axis contains just the ...
def clean_notify(self): """ Clean the notify_on_enrollment field. """ return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
Clean the notify_on_enrollment field.
Below is the the instruction that describes the task: ### Input: Clean the notify_on_enrollment field. ### Response: def clean_notify(self): """ Clean the notify_on_enrollment field. """ return self.cleaned_data.get(self.Fields.NOTIFY, self.NotificationTypes.DEFAULT)
def process_inputs(self): """ Processes input data :return: """ ret = [] files = self.args.files if files is None: return ret for fname in files: if fname == '-': if self.args.base64stdin: for li...
Processes input data :return:
Below is the the instruction that describes the task: ### Input: Processes input data :return: ### Response: def process_inputs(self): """ Processes input data :return: """ ret = [] files = self.args.files if files is None: return ret ...
def _delete(collection_name, spec, opts, flags): """Get an OP_DELETE message.""" encoded = _dict_to_bson(spec, False, opts) # Uses extensions. return b"".join([ _ZERO_32, _make_c_string(collection_name), _pack_int(flags), encoded]), len(encoded)
Get an OP_DELETE message.
Below is the the instruction that describes the task: ### Input: Get an OP_DELETE message. ### Response: def _delete(collection_name, spec, opts, flags): """Get an OP_DELETE message.""" encoded = _dict_to_bson(spec, False, opts) # Uses extensions. return b"".join([ _ZERO_32, _make_c_st...
def dataCollections(self, countryName=None, addDerivativeVariables=None, outFields=None, suppressNullValues=False): """ The GeoEnrichment service uses the concept of a data collection to define the da...
The GeoEnrichment service uses the concept of a data collection to define the data attributes returned by the enrichment service. Each data collection has a unique name that acts as an ID that is passed in the dataCollections parameter of the GeoEnrichment service. Some data collections ...
Below is the the instruction that describes the task: ### Input: The GeoEnrichment service uses the concept of a data collection to define the data attributes returned by the enrichment service. Each data collection has a unique name that acts as an ID that is passed in the dataCollections p...
def _extract_instance_info(instances): ''' Given an instance query, return a dict of all instance data ''' ret = {} for instance in instances: # items could be type dict or list (for stopped EC2 instances) if isinstance(instance['instancesSet']['item'], list): for item in...
Given an instance query, return a dict of all instance data
Below is the the instruction that describes the task: ### Input: Given an instance query, return a dict of all instance data ### Response: def _extract_instance_info(instances): ''' Given an instance query, return a dict of all instance data ''' ret = {} for instance in instances: # ite...
def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. """ result = ContentType(json['sys']) for field in json['fields']: field_id = field['id'] del field['id'] ...
Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance.
Below is the the instruction that describes the task: ### Input: Create :class:`.resource.ContentType` from JSON. :param json: JSON dict. :return: ContentType instance. ### Response: def create_content_type(json): """Create :class:`.resource.ContentType` from JSON. :param json: JS...
def __write_aliases_file(lines): ''' Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases. ''' afn = __get_aliases_filename() adir = os.path.dirname(afn) out = tempfile.NamedTemporaryFile(dir=adir, delete=False) if not __opts__.get('integration...
Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases.
Below is the the instruction that describes the task: ### Input: Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_aliases. ### Response: def __write_aliases_file(lines): ''' Write a new copy of the aliases file. Lines is a list of lines as returned by __parse_...
def fit(self, X): """The K-Means itself """ self._X = super().cluster(X) candidates = [] for _ in range(self.n_runs): self._init_random_centroids() while True: prev_clusters = self.clusters self._assign_clusters() ...
The K-Means itself
Below is the the instruction that describes the task: ### Input: The K-Means itself ### Response: def fit(self, X): """The K-Means itself """ self._X = super().cluster(X) candidates = [] for _ in range(self.n_runs): self._init_random_centroids() whi...
def run(self, timeout = 0): """ Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. epoll timeout param is a integer number of miliseconds (seconds/1000). """ ptimeout = int(timeout.microseconds/1000+timeout....
Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. epoll timeout param is a integer number of miliseconds (seconds/1000).
Below is the the instruction that describes the task: ### Input: Run a proactor loop and return new socket events. Timeout is a timedelta object, 0 if active coros or None. epoll timeout param is a integer number of miliseconds (seconds/1000). ### Response: def run(self, timeout = 0): ...
def organization_membership_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership" api_path = "/api/v2/organization_memberships.json" return self.call(api_path, method="POST", data=data, **kwargs)
https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership
Below is the the instruction that describes the task: ### Input: https://developer.zendesk.com/rest_api/docs/core/organization_memberships#create-membership ### Response: def organization_membership_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/organization_memberships#cre...
def pandas2igraph(self, edges, directed=True): """Convert a pandas edge dataframe to an IGraph graph. Uses current bindings. Defaults to treating edges as directed. **Example** :: import graphistry g = graphistry.bind() es = pandas....
Convert a pandas edge dataframe to an IGraph graph. Uses current bindings. Defaults to treating edges as directed. **Example** :: import graphistry g = graphistry.bind() es = pandas.DataFrame({'src': [0,1,2], 'dst': [1,2,0]}) ...
Below is the the instruction that describes the task: ### Input: Convert a pandas edge dataframe to an IGraph graph. Uses current bindings. Defaults to treating edges as directed. **Example** :: import graphistry g = graphistry.bind() e...
def img2img_transformer_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_hidden_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.filter_size = 128 hparams.num_...
Tiny params.
Below is the the instruction that describes the task: ### Input: Tiny params. ### Response: def img2img_transformer_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_hidden_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attenti...
def create_environment(home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, download=False, no_setuptools=False, no_pip=False, no_wheel=False, symlink=True): """ Creates a ne...
Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared.
Below is the the instruction that describes the task: ### Input: Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared. ### Response:...
def add_or_update_record( self, final_path, ase, chunk_size, next_integrity_chunk, completed, md5): # type: (DownloadResumeManager, pathlib.Path, # blobxfer.models.azure.StorageEntity, int, int, bool, # str) -> None """Add or update a resume record ...
Add or update a resume record :param DownloadResumeManager self: this :param pathlib.Path final_path: final path :param blobxfer.models.azure.StorageEntity ase: Storage Entity :param int chunk_size: chunk size in bytes :param int next_integrity_chunk: next integrity chunk ...
Below is the the instruction that describes the task: ### Input: Add or update a resume record :param DownloadResumeManager self: this :param pathlib.Path final_path: final path :param blobxfer.models.azure.StorageEntity ase: Storage Entity :param int chunk_size: chunk size in bytes ...
def show(self, title=None, method='', indices=None, force_show=False, fig=None, **kwargs): """Display the function graphically. Parameters ---------- title : string, optional Set the title of the figure method : string, optional 1d methods: ...
Display the function graphically. Parameters ---------- title : string, optional Set the title of the figure method : string, optional 1d methods: ``'plot'`` : graph plot ``'scatter'`` : scattered 2d points (2nd axis <-> value) ...
Below is the the instruction that describes the task: ### Input: Display the function graphically. Parameters ---------- title : string, optional Set the title of the figure method : string, optional 1d methods: ``'plot'`` : graph plot ...
def save_source(driver, name): """ Save the rendered HTML of the browser. The location of the source can be configured by the environment variable `SAVED_SOURCE_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled...
Save the rendered HTML of the browser. The location of the source can be configured by the environment variable `SAVED_SOURCE_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Selenium-controlled browser. name (str): A name to use...
Below is the the instruction that describes the task: ### Input: Save the rendered HTML of the browser. The location of the source can be configured by the environment variable `SAVED_SOURCE_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver...
def operate_menu(): "Select between these operations on the database" selection = True while selection: print globals()['operate_menu'].__doc__ selection = select([ 'chill.database functions', 'execute sql file', 'render_node', 'New collectio...
Select between these operations on the database
Below is the the instruction that describes the task: ### Input: Select between these operations on the database ### Response: def operate_menu(): "Select between these operations on the database" selection = True while selection: print globals()['operate_menu'].__doc__ selection = se...
def error(self, message, print_help=False): """Provide a more helpful message if there are too few arguments.""" if 'too few arguments' in message.lower(): target = sys.argv.pop(0) sys.argv.insert( 0, os.path.basename(target) or os.path.relpath(target)) ...
Provide a more helpful message if there are too few arguments.
Below is the the instruction that describes the task: ### Input: Provide a more helpful message if there are too few arguments. ### Response: def error(self, message, print_help=False): """Provide a more helpful message if there are too few arguments.""" if 'too few arguments' in message.lower(): ...
def default_freq(**indexer): """Return the default frequency.""" freq = 'AS-JAN' if indexer: if 'DJF' in indexer.values(): freq = 'AS-DEC' if 'month' in indexer and sorted(indexer.values()) != indexer.values(): raise (NotImplementedError) return freq
Return the default frequency.
Below is the the instruction that describes the task: ### Input: Return the default frequency. ### Response: def default_freq(**indexer): """Return the default frequency.""" freq = 'AS-JAN' if indexer: if 'DJF' in indexer.values(): freq = 'AS-DEC' if 'month' in indexer and s...
def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>": isList=True else: isList=False data=[] if fname==None: fname=self.files ...
Private method for getting an attribute, called from get.
Below is the the instruction that describes the task: ### Input: Private method for getting an attribute, called from get. ### Response: def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>"...
def check_output_error_and_retcode(*popenargs, **kwargs): """ This function is used to obtain the stdout of a command. It is only used internally, recommend using the make_external_call command if you want to call external executables. """ if 'stdout' in kwargs: raise ValueError('stdout ...
This function is used to obtain the stdout of a command. It is only used internally, recommend using the make_external_call command if you want to call external executables.
Below is the the instruction that describes the task: ### Input: This function is used to obtain the stdout of a command. It is only used internally, recommend using the make_external_call command if you want to call external executables. ### Response: def check_output_error_and_retcode(*popenargs, **kwarg...
def route_acl(self, *acl, **options): """Decorator to attach an ACL to a route. E.g:: @app.route('/url/to/view') @authz.route_acl(''' ALLOW WHEEL ALL DENY ANY ALL ''') def my_admin_function(): pa...
Decorator to attach an ACL to a route. E.g:: @app.route('/url/to/view') @authz.route_acl(''' ALLOW WHEEL ALL DENY ANY ALL ''') def my_admin_function(): pass
Below is the the instruction that describes the task: ### Input: Decorator to attach an ACL to a route. E.g:: @app.route('/url/to/view') @authz.route_acl(''' ALLOW WHEEL ALL DENY ANY ALL ''') def my_admin_function()...
def check_packages(db_name): """ Check if the driver for the user defined host is available. If it is not available, download it using PIP :param db_name: :return: """ print('Checking for required Database Driver') reqs = subprocess.check_output([sys.executable, ...
Check if the driver for the user defined host is available. If it is not available, download it using PIP :param db_name: :return:
Below is the the instruction that describes the task: ### Input: Check if the driver for the user defined host is available. If it is not available, download it using PIP :param db_name: :return: ### Response: def check_packages(db_name): """ Check if the driver for the user defined...
def get_session(self, sid, namespace=None): """Return the user session for a client. :param sid: The session id of the client. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. The return value is a dictionar...
Return the user session for a client. :param sid: The session id of the client. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. The return value is a dictionary. Modifications made to this dictionary are no...
Below is the the instruction that describes the task: ### Input: Return the user session for a client. :param sid: The session id of the client. :param namespace: The Socket.IO namespace. If this argument is omitted the default namespace is used. The return value ...
def local_manager_rule(self): """Return rule for local manager. """ adm_gid = self.local_manager_gid if not adm_gid: return None config = self.root['settings']['ugm_localmanager'].attrs return config[adm_gid]
Return rule for local manager.
Below is the the instruction that describes the task: ### Input: Return rule for local manager. ### Response: def local_manager_rule(self): """Return rule for local manager. """ adm_gid = self.local_manager_gid if not adm_gid: return None config = self.root['sett...
def health(args): """ Health FireCloud Server """ r = fapi.health() fapi._check_response_code(r, 200) return r.content
Health FireCloud Server
Below is the the instruction that describes the task: ### Input: Health FireCloud Server ### Response: def health(args): """ Health FireCloud Server """ r = fapi.health() fapi._check_response_code(r, 200) return r.content
def schedule2calendar(schedule, name='课葨', using_todo=True): """ ε°†δΈŠθ―Ύζ—Άι—΄θ‘¨θ½¬ζ’δΈΊ icalendar :param schedule: δΈŠθ―Ύζ—Άι—΄θ‘¨ :param name: ζ—₯εŽ†εη§° :param using_todo: 使用 ``icalendar.Todo`` θ€ŒδΈζ˜― ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar() """ # https://zh.wikipedia.org/wiki/ICalendar # http://i...
ε°†δΈŠθ―Ύζ—Άι—΄θ‘¨θ½¬ζ’δΈΊ icalendar :param schedule: δΈŠθ―Ύζ—Άι—΄θ‘¨ :param name: ζ—₯εŽ†εη§° :param using_todo: 使用 ``icalendar.Todo`` θ€ŒδΈζ˜― ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar()
Below is the the instruction that describes the task: ### Input: ε°†δΈŠθ―Ύζ—Άι—΄θ‘¨θ½¬ζ’δΈΊ icalendar :param schedule: δΈŠθ―Ύζ—Άι—΄θ‘¨ :param name: ζ—₯εŽ†εη§° :param using_todo: 使用 ``icalendar.Todo`` θ€ŒδΈζ˜― ``icalendar.Event`` 作为活动类 :return: icalendar.Calendar() ### Response: def schedule2calendar(schedule, name='课葨', using_todo=Tru...
def clear_caches(): # suppress(unused-function) """Clear all caches.""" for _, reader in _spellchecker_cache.values(): reader.close() _spellchecker_cache.clear() _valid_words_cache.clear() _user_dictionary_cache.clear()
Clear all caches.
Below is the the instruction that describes the task: ### Input: Clear all caches. ### Response: def clear_caches(): # suppress(unused-function) """Clear all caches.""" for _, reader in _spellchecker_cache.values(): reader.close() _spellchecker_cache.clear() _valid_words_cache.clear() ...
def text(draw, xy, txt, fill=None, font=None): """ Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the prescribed fill and font. :param draw: A valid canvas to draw the text onto. :type draw: PIL.ImageDraw :param txt: The text string to display (must be ASCII only). :type tx...
Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the prescribed fill and font. :param draw: A valid canvas to draw the text onto. :type draw: PIL.ImageDraw :param txt: The text string to display (must be ASCII only). :type txt: str :param xy: An ``(x, y)`` tuple denoting the top-...
Below is the the instruction that describes the task: ### Input: Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the prescribed fill and font. :param draw: A valid canvas to draw the text onto. :type draw: PIL.ImageDraw :param txt: The text string to display (must be ASCII only). ...
def as_yml(self): """ Return yml compatible version of self """ return YmlFileEvent(name=str(self.name), subfolder=str(self.subfolder))
Return yml compatible version of self
Below is the the instruction that describes the task: ### Input: Return yml compatible version of self ### Response: def as_yml(self): """ Return yml compatible version of self """ return YmlFileEvent(name=str(self.name), subfolder=str(self.subfolder))
def add_child(self, child=None, name=None, dist=None, support=None): """ Adds a new child to this node. If child node is not suplied as an argument, a new node instance will be created. Parameters ---------- child: the node instance to be added as a...
Adds a new child to this node. If child node is not suplied as an argument, a new node instance will be created. Parameters ---------- child: the node instance to be added as a child. name: the name that will be given to the child. dist...
Below is the the instruction that describes the task: ### Input: Adds a new child to this node. If child node is not suplied as an argument, a new node instance will be created. Parameters ---------- child: the node instance to be added as a child. name...
def version(*args, **attrs): """Show the version and exit.""" if hasattr(sys, "_getframe"): package = attrs.pop("package", sys._getframe(1).f_globals.get("__package__")) if package: attrs.setdefault("version", get_version(package)) return click.version_option(*args, **attrs)
Show the version and exit.
Below is the the instruction that describes the task: ### Input: Show the version and exit. ### Response: def version(*args, **attrs): """Show the version and exit.""" if hasattr(sys, "_getframe"): package = attrs.pop("package", sys._getframe(1).f_globals.get("__package__")) if package: ...
def prior_rvs(self, size=1, prior=None): """Returns random variates drawn from the prior. If the ``sampling_params`` are different from the ``variable_params``, the variates are transformed to the `sampling_params` parameter space before being returned. Parameters -----...
Returns random variates drawn from the prior. If the ``sampling_params`` are different from the ``variable_params``, the variates are transformed to the `sampling_params` parameter space before being returned. Parameters ---------- size : int, optional Numbe...
Below is the the instruction that describes the task: ### Input: Returns random variates drawn from the prior. If the ``sampling_params`` are different from the ``variable_params``, the variates are transformed to the `sampling_params` parameter space before being returned. Paramet...
def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ''' if not model: raise ValueError('Unsupported model specifications') if isinstance(model, basest...
Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists
Below is the the instruction that describes the task: ### Input: Resolve a model given a name or dict with `class` entry. :raises ValueError: model specification is wrong or does not exists ### Response: def resolve_model(self, model): ''' Resolve a model given a name or dict with `class` ...
def reorder(self, single_column=False): """Force a reorder of the displayed items""" if single_column: columns = self.sortOrder[:1] else: columns = self.sortOrder for ascending,column in columns[::-1]: # Python 2.2+ guarantees stable sort, so sort by e...
Force a reorder of the displayed items
Below is the the instruction that describes the task: ### Input: Force a reorder of the displayed items ### Response: def reorder(self, single_column=False): """Force a reorder of the displayed items""" if single_column: columns = self.sortOrder[:1] else: columns = s...
def bna_config_cmd_output_status_string(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") bna_config_cmd = ET.Element("bna_config_cmd") config = bna_config_cmd output = ET.SubElement(bna_config_cmd, "output") status_string = ET.SubElement(o...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def bna_config_cmd_output_status_string(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") bna_config_cmd = ET.Element("bna_config_cmd") config = bna_con...
def accuracy_curve(self, delta_tau=0.01): """ Computes the relationship between probability threshold and classification accuracy. """ # compute thresholds based on the sorted probabilities orig_thresh = self.threshold sorted_labels, sorted_probs = self.sorted_values sco...
Computes the relationship between probability threshold and classification accuracy.
Below is the the instruction that describes the task: ### Input: Computes the relationship between probability threshold and classification accuracy. ### Response: def accuracy_curve(self, delta_tau=0.01): """ Computes the relationship between probability threshold and classification accura...
def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, mac) except AddrFormatError: return ('', '', []) all_interfaces = _get_mine('net.interfaces') all_ipaddrs = _get_mine('net.i...
Helper to search the interfaces IPs using the MAC address.
Below is the the instruction that describes the task: ### Input: Helper to search the interfaces IPs using the MAC address. ### Response: def _find_interfaces_ip(mac): ''' Helper to search the interfaces IPs using the MAC address. ''' try: mac = napalm_helpers.convert(napalm_helpers.mac, ma...
def user_absent(name): ''' Ensure a user is not present name username to remove if it exists Examples: .. code-block:: yaml delete: onyx.user_absent: - name: daniel ''' ret = {'name': name, 'result': False, 'changes': {}, ...
Ensure a user is not present name username to remove if it exists Examples: .. code-block:: yaml delete: onyx.user_absent: - name: daniel
Below is the the instruction that describes the task: ### Input: Ensure a user is not present name username to remove if it exists Examples: .. code-block:: yaml delete: onyx.user_absent: - name: daniel ### Response: def user_absent(name): ''' Ensure a ...
def package_info(self): """ :return: list of package info on installed packages """ import subprocess # create a commandline like pip show Pillow show package_names = self.installed_packages() if not package_names: # No installed packages yet, so noth...
:return: list of package info on installed packages
Below is the the instruction that describes the task: ### Input: :return: list of package info on installed packages ### Response: def package_info(self): """ :return: list of package info on installed packages """ import subprocess # create a commandline like pip show Pill...
def setup_toolbar(self): """Setup toolbar""" load_button = create_toolbutton(self, text=_('Import data'), icon=ima.icon('fileimport'), triggered=lambda: self.import_data()) self.save_button = create_toolbutton(s...
Setup toolbar
Below is the the instruction that describes the task: ### Input: Setup toolbar ### Response: def setup_toolbar(self): """Setup toolbar""" load_button = create_toolbutton(self, text=_('Import data'), icon=ima.icon('fileimport'), ...
def qteStartRecordingHook(self, msgObj): """ Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately. """...
Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately.
Below is the the instruction that describes the task: ### Input: Commence macro recording. Macros are recorded by connecting to the 'keypressed' signal it emits. If the recording has already commenced, or if this method was called during a macro replay, then return immediately. ###...
def _walk(self, root_path='', root_id=''): ''' a generator method which walks the file structure of the dropbox collection ''' title = '%s._walk' % self.__class__.__name__ if root_id: pass elif root_path: root_id, root_parent = self._get...
a generator method which walks the file structure of the dropbox collection
Below is the the instruction that describes the task: ### Input: a generator method which walks the file structure of the dropbox collection ### Response: def _walk(self, root_path='', root_id=''): ''' a generator method which walks the file structure of the dropbox collection ''' ...
def _parse_thead_tbody_tfoot(self, table_html): """ Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ...
Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ----- Header and body are lists-of-lists. Top level list i...
Below is the the instruction that describes the task: ### Input: Given a table, return parsed header, body, and foot. Parameters ---------- table_html : node-like Returns ------- tuple of (header, body, footer), each a list of list-of-text rows. Notes ...
def create_action_from_dict(name, spec, base_class=ActionsAction, metaclass=type, pop_keys=False): """Creates an action class based on a dict loaded using load_grouped_actions() """ actions = load_grouped_actions(spec, pop_keys=pop_keys) attrs = {"actions": actions, "name": name} if "as" in spec: ...
Creates an action class based on a dict loaded using load_grouped_actions()
Below is the the instruction that describes the task: ### Input: Creates an action class based on a dict loaded using load_grouped_actions() ### Response: def create_action_from_dict(name, spec, base_class=ActionsAction, metaclass=type, pop_keys=False): """Creates an action class based on a dict loaded using l...
def _action_set_subsumption(self, action_set): """Perform action set subsumption.""" # Select a condition with maximum bit count among those having # sufficient experience and sufficiently low error. selected_rule = None selected_bit_count = None for rule in action_set: ...
Perform action set subsumption.
Below is the the instruction that describes the task: ### Input: Perform action set subsumption. ### Response: def _action_set_subsumption(self, action_set): """Perform action set subsumption.""" # Select a condition with maximum bit count among those having # sufficient experience and suff...
def _version_less_than_or_equal_to(self, v1, v2): """ Returns true if v1 <= v2. """ # pylint: disable=no-name-in-module, import-error from distutils.version import LooseVersion return LooseVersion(v1) <= LooseVersion(v2)
Returns true if v1 <= v2.
Below is the the instruction that describes the task: ### Input: Returns true if v1 <= v2. ### Response: def _version_less_than_or_equal_to(self, v1, v2): """ Returns true if v1 <= v2. """ # pylint: disable=no-name-in-module, import-error from distutils.version import LooseVersion r...
def is_str(arg): ''' is_str(x) yields True if x is a string object or a 0-dim numpy array of a string and yields False otherwise. ''' return (isinstance(arg, six.string_types) or is_npscalar(arg, 'string') or is_npvalue(arg, 'string'))
is_str(x) yields True if x is a string object or a 0-dim numpy array of a string and yields False otherwise.
Below is the the instruction that describes the task: ### Input: is_str(x) yields True if x is a string object or a 0-dim numpy array of a string and yields False otherwise. ### Response: def is_str(arg): ''' is_str(x) yields True if x is a string object or a 0-dim numpy array of a string and yields ...
def resolve_symbols(self, database, link_resolver, page=None): """Will call resolve_symbols on all the stale subpages of the tree. Args: page: hotdoc.core.tree.Page, the page to resolve symbols in, will recurse on potential subpages. """ page = page or self.root ...
Will call resolve_symbols on all the stale subpages of the tree. Args: page: hotdoc.core.tree.Page, the page to resolve symbols in, will recurse on potential subpages.
Below is the the instruction that describes the task: ### Input: Will call resolve_symbols on all the stale subpages of the tree. Args: page: hotdoc.core.tree.Page, the page to resolve symbols in, will recurse on potential subpages. ### Response: def resolve_symbols(self, database, link...
def get_state_repr(self, path): """ Returns the current state, or sub-state, depending on the path. """ if path == "ips": return { "failed_ips" : self.failed_ips, "questionable_ips" : self.questionable_ips, "working_set" ...
Returns the current state, or sub-state, depending on the path.
Below is the the instruction that describes the task: ### Input: Returns the current state, or sub-state, depending on the path. ### Response: def get_state_repr(self, path): """ Returns the current state, or sub-state, depending on the path. """ if path == "ips": retur...
def merge_into_nodeset(target, source): """Place all the nodes from the source node-set into the target node-set, preserving document order. Both node-sets must be in document order to begin with. """ if len(target) == 0: target.extend(source) return source = [n for n in sourc...
Place all the nodes from the source node-set into the target node-set, preserving document order. Both node-sets must be in document order to begin with.
Below is the the instruction that describes the task: ### Input: Place all the nodes from the source node-set into the target node-set, preserving document order. Both node-sets must be in document order to begin with. ### Response: def merge_into_nodeset(target, source): """Place all the nodes from t...
def create(dataset, features=None, distance=None, radius=1., min_core_neighbors=10, verbose=True): """ Create a DBSCAN clustering model. The DBSCAN method partitions the input dataset into three types of points, based on the estimated probability density at each point. - **Core** points ...
Create a DBSCAN clustering model. The DBSCAN method partitions the input dataset into three types of points, based on the estimated probability density at each point. - **Core** points have a large number of points within a given neighborhood. Specifically, `min_core_neighbors` must be within distanc...
Below is the the instruction that describes the task: ### Input: Create a DBSCAN clustering model. The DBSCAN method partitions the input dataset into three types of points, based on the estimated probability density at each point. - **Core** points have a large number of points within a given neighbor...
def flip(self, reactions): """Flip the specified reactions.""" for reaction in reactions: if reaction in self._flipped: self._flipped.remove(reaction) else: self._flipped.add(reaction)
Flip the specified reactions.
Below is the the instruction that describes the task: ### Input: Flip the specified reactions. ### Response: def flip(self, reactions): """Flip the specified reactions.""" for reaction in reactions: if reaction in self._flipped: self._flipped.remove(reaction) ...
def available(name): ''' Return True if the named service is available. CLI Example: .. code-block:: bash salt '*' service.available sshd ''' cmd = '{0} get {1}'.format(_cmd(), name) if __salt__['cmd.retcode'](cmd) == 2: return False return True
Return True if the named service is available. CLI Example: .. code-block:: bash salt '*' service.available sshd
Below is the the instruction that describes the task: ### Input: Return True if the named service is available. CLI Example: .. code-block:: bash salt '*' service.available sshd ### Response: def available(name): ''' Return True if the named service is available. CLI Example: ....
def set_raw_datadir(self, directory=None): """Set the directory containing .res-files. Used for setting directory for looking for res-files.@ A valid directory name is required. Args: directory (str): path to res-directory Example: >>> d = CellpyData() ...
Set the directory containing .res-files. Used for setting directory for looking for res-files.@ A valid directory name is required. Args: directory (str): path to res-directory Example: >>> d = CellpyData() >>> directory = "MyData/Arbindata" ...
Below is the the instruction that describes the task: ### Input: Set the directory containing .res-files. Used for setting directory for looking for res-files.@ A valid directory name is required. Args: directory (str): path to res-directory Example: >>> d ...
def dav_index(context, data): """List files in a WebDAV directory.""" # This is made to work with ownCloud/nextCloud, but some rumor has # it they are "standards compliant" and it should thus work for # other DAV servers. url = data.get('url') result = context.http.request('PROPFIND', url) f...
List files in a WebDAV directory.
Below is the the instruction that describes the task: ### Input: List files in a WebDAV directory. ### Response: def dav_index(context, data): """List files in a WebDAV directory.""" # This is made to work with ownCloud/nextCloud, but some rumor has # it they are "standards compliant" and it should thu...
def IntervalReader( f ): """ Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored. """ current_chrom = None current_pos = None current_step = None # always for wiggle data strand = '+' mode = "bed" ...
Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored.
Below is the the instruction that describes the task: ### Input: Iterator yielding chrom, start, end, strand, value. Values are zero-based, half-open. Regions which lack a score are ignored. ### Response: def IntervalReader( f ): """ Iterator yielding chrom, start, end, strand, value. Values ar...
def add_delta_step(self, delta: float): """ Inform Metrics class about time to step in environment. """ if self.delta_last_experience_collection: self.delta_last_experience_collection += delta else: self.delta_last_experience_collection = delta
Inform Metrics class about time to step in environment.
Below is the the instruction that describes the task: ### Input: Inform Metrics class about time to step in environment. ### Response: def add_delta_step(self, delta: float): """ Inform Metrics class about time to step in environment. """ if self.delta_last_experience_collection: ...
def get_abstract_locations(self, addr, size): """ Get a list of abstract locations that is within the range of [addr, addr + size] This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now. :param addr:...
Get a list of abstract locations that is within the range of [addr, addr + size] This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now. :param addr: Starting address of the memory region. :param size: ...
Below is the the instruction that describes the task: ### Input: Get a list of abstract locations that is within the range of [addr, addr + size] This implementation is pretty slow. But since this method won't be called frequently, we can live with the bad implementation for now. :param ad...
def destroy(self): '''Unsubscribes callback from observable''' self._observable.release(self._key, self._callback) self._observable = None self._key = None self._callback = None
Unsubscribes callback from observable
Below is the the instruction that describes the task: ### Input: Unsubscribes callback from observable ### Response: def destroy(self): '''Unsubscribes callback from observable''' self._observable.release(self._key, self._callback) self._observable = None self._key = None se...
def write(self, version): # type: (str) -> None """ Write the project version to .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and substitute the version string for the new version. """ with open(self.version_file) as fp: ...
Write the project version to .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and substitute the version string for the new version.
Below is the the instruction that describes the task: ### Input: Write the project version to .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and substitute the version string for the new version. ### Response: def write(self, version): # type: (...
def draw(self): """Draw the figures and those that are shared and have been changed""" for fig in self.figs2draw: fig.canvas.draw() self._figs2draw.clear()
Draw the figures and those that are shared and have been changed
Below is the the instruction that describes the task: ### Input: Draw the figures and those that are shared and have been changed ### Response: def draw(self): """Draw the figures and those that are shared and have been changed""" for fig in self.figs2draw: fig.canvas.draw() sel...
def get_status_code_and_schema_rst(self, responses): ''' Function for prepare information about responses with example, prepare only responses with status code from `101` to `299` :param responses: -- dictionary that contains responses, with status code as key :type responses: di...
Function for prepare information about responses with example, prepare only responses with status code from `101` to `299` :param responses: -- dictionary that contains responses, with status code as key :type responses: dict :return:
Below is the the instruction that describes the task: ### Input: Function for prepare information about responses with example, prepare only responses with status code from `101` to `299` :param responses: -- dictionary that contains responses, with status code as key :type responses: dict ...
def optionsFromEnvironment(defaults=None): """Fetch root URL and credentials from the standard TASKCLUSTER_… environment variables and return them in a format suitable for passing to a client constructor.""" options = defaults or {} credentials = options.get('credentials', {}) rootUrl = os.envi...
Fetch root URL and credentials from the standard TASKCLUSTER_… environment variables and return them in a format suitable for passing to a client constructor.
Below is the the instruction that describes the task: ### Input: Fetch root URL and credentials from the standard TASKCLUSTER_… environment variables and return them in a format suitable for passing to a client constructor. ### Response: def optionsFromEnvironment(defaults=None): """Fetch root URL and ...
def connect_partial_nodirect(self, config): """ Create a partially-connected genome, with (unless no hidden nodes) no direct input-output connections.""" assert 0 <= config.connection_fraction <= 1 all_connections = self.compute_full_connections(config, False) shuffle(all...
Create a partially-connected genome, with (unless no hidden nodes) no direct input-output connections.
Below is the the instruction that describes the task: ### Input: Create a partially-connected genome, with (unless no hidden nodes) no direct input-output connections. ### Response: def connect_partial_nodirect(self, config): """ Create a partially-connected genome, with (unless no ...
def iter_initial_relations(self, subject_graph): """Iterate over all valid initial relations for a match""" vertex0 = 0 for vertex1 in range(subject_graph.num_vertices): yield vertex0, vertex1
Iterate over all valid initial relations for a match
Below is the the instruction that describes the task: ### Input: Iterate over all valid initial relations for a match ### Response: def iter_initial_relations(self, subject_graph): """Iterate over all valid initial relations for a match""" vertex0 = 0 for vertex1 in range(subject_graph.num_...
def get_scalar(mesh, name, preference='cell', info=False, err=False): """ Searches both point and cell data for an array Parameters ---------- name : str The name of the array to get the range. preference : str, optional When scalars is specified, this is the perfered scalar type t...
Searches both point and cell data for an array Parameters ---------- name : str The name of the array to get the range. preference : str, optional When scalars is specified, this is the perfered scalar type to search for in the dataset. Must be either ``'point'`` or ``'cell'``...
Below is the the instruction that describes the task: ### Input: Searches both point and cell data for an array Parameters ---------- name : str The name of the array to get the range. preference : str, optional When scalars is specified, this is the perfered scalar type to ...
def eligible_cost(self, column=None, value=None, **kwargs): """ The assistance dollar amounts by eligible cost category. >>> GICS().eligible_cost('amount', 100000) """ return self._resolve_call('GIC_ELIGIBLE_COST', column, value, **kwargs)
The assistance dollar amounts by eligible cost category. >>> GICS().eligible_cost('amount', 100000)
Below is the the instruction that describes the task: ### Input: The assistance dollar amounts by eligible cost category. >>> GICS().eligible_cost('amount', 100000) ### Response: def eligible_cost(self, column=None, value=None, **kwargs): """ The assistance dollar amounts by eligible cost ...
def bez2poly(bez, numpy_ordering=True, return_poly1d=False): """Converts a Bezier object or tuple of Bezier control points to a tuple of coefficients of the expanded polynomial. return_poly1d : returns a numpy.poly1d object. This makes computations of derivatives/anti-derivatives and many other operati...
Converts a Bezier object or tuple of Bezier control points to a tuple of coefficients of the expanded polynomial. return_poly1d : returns a numpy.poly1d object. This makes computations of derivatives/anti-derivatives and many other operations quite quick. numpy_ordering : By default (to accommodate num...
Below is the the instruction that describes the task: ### Input: Converts a Bezier object or tuple of Bezier control points to a tuple of coefficients of the expanded polynomial. return_poly1d : returns a numpy.poly1d object. This makes computations of derivatives/anti-derivatives and many other operat...
def get_recipe(cls, name, ctx): '''Returns the Recipe with the given name, if it exists.''' name = name.lower() if not hasattr(cls, "recipes"): cls.recipes = {} if name in cls.recipes: return cls.recipes[name] recipe_file = None for recipes_dir in...
Returns the Recipe with the given name, if it exists.
Below is the the instruction that describes the task: ### Input: Returns the Recipe with the given name, if it exists. ### Response: def get_recipe(cls, name, ctx): '''Returns the Recipe with the given name, if it exists.''' name = name.lower() if not hasattr(cls, "recipes"): cl...