code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def _gotitem(self, key: Union[str, List[str]], ndim: int, subset: Optional[Union[Series, ABCDataFrame]] = None, ) -> Union[Series, ABCDataFrame]: """ Sub-classes to define. Return a sliced object. Parameters ---------- ...
Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on
Below is the the instruction that describes the task: ### Input: Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on ...
def _model_unpickle(cls, data): """Unpickle a model by retrieving it from the database.""" auto_field_value = data['pk'] try: obj = cls.objects.get(pk=auto_field_value) except Exception as e: if isinstance(e, OperationalError): # Attempt reconnect, we've probably hit; ...
Unpickle a model by retrieving it from the database.
Below is the the instruction that describes the task: ### Input: Unpickle a model by retrieving it from the database. ### Response: def _model_unpickle(cls, data): """Unpickle a model by retrieving it from the database.""" auto_field_value = data['pk'] try: obj = cls.objects.get(pk=auto_field_v...
def all(cls, domain=None): """ Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site """ Site = cls site = Session.query(Site) if domain: site.filter(Site.domain == domain) return s...
Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site
Below is the the instruction that describes the task: ### Input: Return all sites @param domain: The domain to filter by @type domain: Domain @rtype: list of Site ### Response: def all(cls, domain=None): """ Return all sites @param domain: The domain to filter by...
def list(self): '''Returns the `list` representation of this Key. Note that this method assumes the key is immutable. ''' if not self._list: self._list = map(Namespace, self._string.split('/')) return self._list
Returns the `list` representation of this Key. Note that this method assumes the key is immutable.
Below is the the instruction that describes the task: ### Input: Returns the `list` representation of this Key. Note that this method assumes the key is immutable. ### Response: def list(self): '''Returns the `list` representation of this Key. Note that this method assumes the key is immutable. '...
def get(self, endpoint): '''Return the result of a GET request to `endpoint` on boatd''' json_body = urlopen(self.url(endpoint)).read().decode('utf-8') return json.loads(json_body)
Return the result of a GET request to `endpoint` on boatd
Below is the the instruction that describes the task: ### Input: Return the result of a GET request to `endpoint` on boatd ### Response: def get(self, endpoint): '''Return the result of a GET request to `endpoint` on boatd''' json_body = urlopen(self.url(endpoint)).read().decode('utf-8') re...
def conversions(self): """ Returns a string showing the available conversions. Useful tool in interactive mode. """ return "\n".join(str(self.to(unit)) for unit in self.supported_units)
Returns a string showing the available conversions. Useful tool in interactive mode.
Below is the the instruction that describes the task: ### Input: Returns a string showing the available conversions. Useful tool in interactive mode. ### Response: def conversions(self): """ Returns a string showing the available conversions. Useful tool in interactive mode. ...
def _bbox(nodes): """Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple[float, float, float, float]: The left, righ...
Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple[float, float, float, float]: The left, right, bottom and top...
Below is the the instruction that describes the task: ### Input: Get the bounding box for set of points. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes (numpy.ndarray): A set of points. Returns: Tuple...
def on_to_state_edited(self, renderer, path, new_state_identifier): """Connects the outcome with a transition to the newly set state :param Gtk.CellRendererText renderer: The cell renderer that was edited :param str path: The path string of the renderer :param str new_state_identifier: ...
Connects the outcome with a transition to the newly set state :param Gtk.CellRendererText renderer: The cell renderer that was edited :param str path: The path string of the renderer :param str new_state_identifier: An identifier for the new state that was selected
Below is the the instruction that describes the task: ### Input: Connects the outcome with a transition to the newly set state :param Gtk.CellRendererText renderer: The cell renderer that was edited :param str path: The path string of the renderer :param str new_state_identifier: An identif...
def run(self, subcmd_name, arg): """Run subcmd_name with args using obj for the environent""" entry=self.lookup(subcmd_name) if entry: entry['callback'](arg) else: self.cmdproc.undefined_cmd(entry.__class__.name, subcmd_name) pass return
Run subcmd_name with args using obj for the environent
Below is the the instruction that describes the task: ### Input: Run subcmd_name with args using obj for the environent ### Response: def run(self, subcmd_name, arg): """Run subcmd_name with args using obj for the environent""" entry=self.lookup(subcmd_name) if entry: entry['cal...
def get_page_number_from_request( request, querystring_key=PAGE_LABEL, default=1): """Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned. """ try: return int(request.GET[querystri...
Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned.
Below is the the instruction that describes the task: ### Input: Retrieve the current page number from *GET* or *POST* data. If the page does not exists in *request*, or is not a number, then *default* number is returned. ### Response: def get_page_number_from_request( request, querystring_key=PAGE...
def _mirror_idx_cov(self, f_values, idx1): # will most likely be removed """obsolete and subject to removal (TODO), return indices for negative ("active") update of the covariance matrix assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are the corresponding mirrored values ...
obsolete and subject to removal (TODO), return indices for negative ("active") update of the covariance matrix assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are the corresponding mirrored values computes the index of the worse solution sorted by the f-value of the b...
Below is the the instruction that describes the task: ### Input: obsolete and subject to removal (TODO), return indices for negative ("active") update of the covariance matrix assuming that ``f_values[idx1[i]]`` and ``f_values[-1-i]`` are the corresponding mirrored values computes t...
async def release_cursor(self, cursor, in_transaction=False): """Release cursor coroutine. Unless in transaction, the connection is also released back to the pool. """ conn = cursor.connection await cursor.close() if not in_transaction: self.release(conn)
Release cursor coroutine. Unless in transaction, the connection is also released back to the pool.
Below is the the instruction that describes the task: ### Input: Release cursor coroutine. Unless in transaction, the connection is also released back to the pool. ### Response: async def release_cursor(self, cursor, in_transaction=False): """Release cursor coroutine. Unless in transaction, ...
def union(df, other, index=False, keep='first'): """ Returns rows that appear in either DataFrame. Args: df (pandas.DataFrame): data passed in through the pipe. other (pandas.DataFrame): other DataFrame to use for set operation with the first. Kwargs: index (bool): ...
Returns rows that appear in either DataFrame. Args: df (pandas.DataFrame): data passed in through the pipe. other (pandas.DataFrame): other DataFrame to use for set operation with the first. Kwargs: index (bool): Boolean indicating whether to consider the pandas index ...
Below is the the instruction that describes the task: ### Input: Returns rows that appear in either DataFrame. Args: df (pandas.DataFrame): data passed in through the pipe. other (pandas.DataFrame): other DataFrame to use for set operation with the first. Kwargs: index ...
def spawn_process(self, port): """Create an Application and HTTPServer for the given port. :param int port: The port to listen on :rtype: multiprocessing.Process """ return process.Process(name="ServerProcess.%i" % port, kwargs={'namespace': self....
Create an Application and HTTPServer for the given port. :param int port: The port to listen on :rtype: multiprocessing.Process
Below is the the instruction that describes the task: ### Input: Create an Application and HTTPServer for the given port. :param int port: The port to listen on :rtype: multiprocessing.Process ### Response: def spawn_process(self, port): """Create an Application and HTTPServer for the give...
def buildingname(ddtt): """return building name""" idf = ddtt.theidf building = idf.idfobjects['building'.upper()][0] return building.Name
return building name
Below is the the instruction that describes the task: ### Input: return building name ### Response: def buildingname(ddtt): """return building name""" idf = ddtt.theidf building = idf.idfobjects['building'.upper()][0] return building.Name
def probability_of_n_purchases_up_to_time(self, t, n): r""" Compute the probability of n purchases. .. math:: P( N(t) = n | \text{model} ) where N(t) is the number of repeat purchases a customer makes in t units of time. Parameters ---------- t: float...
r""" Compute the probability of n purchases. .. math:: P( N(t) = n | \text{model} ) where N(t) is the number of repeat purchases a customer makes in t units of time. Parameters ---------- t: float number units of time n: int nu...
Below is the the instruction that describes the task: ### Input: r""" Compute the probability of n purchases. .. math:: P( N(t) = n | \text{model} ) where N(t) is the number of repeat purchases a customer makes in t units of time. Parameters ---------- t:...
def unmount(self, cid): """ Unmounts and cleans-up after a previous mount(). """ driver = self.client.info()['Driver'] driver_unmount_fn = getattr(self, "_unmount_" + driver, self._unsupported_backend) driver_unmount_fn(cid)
Unmounts and cleans-up after a previous mount().
Below is the the instruction that describes the task: ### Input: Unmounts and cleans-up after a previous mount(). ### Response: def unmount(self, cid): """ Unmounts and cleans-up after a previous mount(). """ driver = self.client.info()['Driver'] driver_unmount_fn = getattr(...
def user_method(user_event): """Decorator of the Pdb user_* methods that controls the RemoteSocket.""" def wrapper(self, *args): stdin = self.stdin is_sock = isinstance(stdin, RemoteSocket) try: try: if is_sock and not stdin.connect(): retu...
Decorator of the Pdb user_* methods that controls the RemoteSocket.
Below is the the instruction that describes the task: ### Input: Decorator of the Pdb user_* methods that controls the RemoteSocket. ### Response: def user_method(user_event): """Decorator of the Pdb user_* methods that controls the RemoteSocket.""" def wrapper(self, *args): stdin = self.stdin ...
def _get_contig_id(contig_str): """Tries to retrieve contig id. Returns the original string if it is unable to retrieve the id. Parameters ---------- contig_str : str Full contig string (fasta header) Returns ------- str Contig id...
Tries to retrieve contig id. Returns the original string if it is unable to retrieve the id. Parameters ---------- contig_str : str Full contig string (fasta header) Returns ------- str Contig id
Below is the the instruction that describes the task: ### Input: Tries to retrieve contig id. Returns the original string if it is unable to retrieve the id. Parameters ---------- contig_str : str Full contig string (fasta header) Returns ------- ...
def upgrade(self, only): """Remove all package lists with changelog and checksums files and create lists again""" repositories = self.meta.repositories if only: repositories = only for repo in repositories: changelogs = "{0}{1}{2}".format(self.log_path, re...
Remove all package lists with changelog and checksums files and create lists again
Below is the the instruction that describes the task: ### Input: Remove all package lists with changelog and checksums files and create lists again ### Response: def upgrade(self, only): """Remove all package lists with changelog and checksums files and create lists again""" reposit...
def delete(self, request, bot_id, id, format=None): """ Delete existing Messenger Bot --- responseMessages: - code: 401 message: Not authenticated """ return super(MessengerBotDetail, self).delete(request, bot_id, id, format)
Delete existing Messenger Bot --- responseMessages: - code: 401 message: Not authenticated
Below is the the instruction that describes the task: ### Input: Delete existing Messenger Bot --- responseMessages: - code: 401 message: Not authenticated ### Response: def delete(self, request, bot_id, id, format=None): """ Delete existing Messenger Bot ...
def RdatabasesBM(host=rbiomart_host): """ Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing """ biomaRt = importr("biomaRt") print(biomaRt.listMarts(host=host))
Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing
Below is the the instruction that describes the task: ### Input: Lists BioMart databases through a RPY2 connection. :param host: address of the host server, default='www.ensembl.org' :returns: nothing ### Response: def RdatabasesBM(host=rbiomart_host): """ Lists BioMart databases through a RPY2 c...
def locate(connection, agent_id): ''' Return the hostname of the agency where given agent runs or None. ''' connection = IDatabaseClient(connection) log.log('locate', 'Locate called for agent_id: %r', agent_id) try: desc = yield connection.get_document(agent_id) log.log('locate',...
Return the hostname of the agency where given agent runs or None.
Below is the the instruction that describes the task: ### Input: Return the hostname of the agency where given agent runs or None. ### Response: def locate(connection, agent_id): ''' Return the hostname of the agency where given agent runs or None. ''' connection = IDatabaseClient(connection) l...
def config(key, default=None): """ Shortcut to access the application's config in your class :param key: The key to access :param default: The default value when None :returns mixed: """ return Mocha._app.config.get(key, default) if Mocha._app else default
Shortcut to access the application's config in your class :param key: The key to access :param default: The default value when None :returns mixed:
Below is the the instruction that describes the task: ### Input: Shortcut to access the application's config in your class :param key: The key to access :param default: The default value when None :returns mixed: ### Response: def config(key, default=None): """ Shortcut to access the applicatio...
def firmware_download_input_protocol_type_ftp_protocol_ftp_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_download") config = firmware_download input = ET.SubElement(firmware_download, "input") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def firmware_download_input_protocol_type_ftp_protocol_ftp_password(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") firmware_download = ET.Element("firmware_d...
def get_resource_method(name, template): """ Creates a function that is suitable as a method for ResourceCollection. """ def rsr_meth(self, **kwargs): http_method = template['http_method'] extra_path = template.get('extra_path') if extra_path: fills = {'res_id': kwarg...
Creates a function that is suitable as a method for ResourceCollection.
Below is the the instruction that describes the task: ### Input: Creates a function that is suitable as a method for ResourceCollection. ### Response: def get_resource_method(name, template): """ Creates a function that is suitable as a method for ResourceCollection. """ def rsr_meth(self, **kwargs...
def _doAction(self, action): """This function will perform a FileMaker action.""" if self._db == '': raise FMError, 'No database was selected' result = '' try: request = [ uu({'-db': self._db }) ] if self._layout != '': request.append(uu({'-lay': self._layout })) if action == '-find'...
This function will perform a FileMaker action.
Below is the the instruction that describes the task: ### Input: This function will perform a FileMaker action. ### Response: def _doAction(self, action): """This function will perform a FileMaker action.""" if self._db == '': raise FMError, 'No database was selected' result = '' try: request = [ ...
def __load(self): """ Loads dynamically the class that acts like a namespace for constants. """ parts = self.__class_name.split('.') module_name = ".".join(parts[:-1]) module = __import__(module_name) modules = [] for comp in parts[1:]: module ...
Loads dynamically the class that acts like a namespace for constants.
Below is the the instruction that describes the task: ### Input: Loads dynamically the class that acts like a namespace for constants. ### Response: def __load(self): """ Loads dynamically the class that acts like a namespace for constants. """ parts = self.__class_name.split('.') ...
def _get_calibration_for_mchits(hits, lookup): """Append the position, direction and t0 columns and add t0 to time""" n_hits = len(hits) cal = np.empty((n_hits, 9)) for i in range(n_hits): cal[i] = lookup[hits['pmt_id'][i]] dir_x = cal[:, 3] dir_y = cal[:, 4] dir_z = cal[:, 5] du...
Append the position, direction and t0 columns and add t0 to time
Below is the the instruction that describes the task: ### Input: Append the position, direction and t0 columns and add t0 to time ### Response: def _get_calibration_for_mchits(hits, lookup): """Append the position, direction and t0 columns and add t0 to time""" n_hits = len(hits) cal = np.empty((n_hits...
def _set_lsp_frr(self, v, load=False): """ Setter method for lsp_frr, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr is considered as a private method. Backends looki...
Setter method for lsp_frr, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr is considered as a private method. Backends looking to populate this variable should do so via c...
Below is the the instruction that describes the task: ### Input: Setter method for lsp_frr, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/lsp_frr (container) If this variable is read-only (config: false) in the source YANG file, then _set_lsp_frr is considered as a private meth...
def send(self, relative_path, http_method, **requests_args): """ Makes an API-key-authorized request :param relative_path: URL path relative to self.base_url :param http_method: HTTP method :param requests_args: kwargs to be sent to requests :type relative_path: str ...
Makes an API-key-authorized request :param relative_path: URL path relative to self.base_url :param http_method: HTTP method :param requests_args: kwargs to be sent to requests :type relative_path: str :type http_method: str :type requests_args: kwargs :return: ...
Below is the the instruction that describes the task: ### Input: Makes an API-key-authorized request :param relative_path: URL path relative to self.base_url :param http_method: HTTP method :param requests_args: kwargs to be sent to requests :type relative_path: str :type ht...
def open(self, tile, process, **kwargs): """ Open process output as input for other process. Parameters ---------- tile : ``Tile`` process : ``MapcheteProcess`` kwargs : keyword arguments """ return InputTile(tile, process, kwargs.get("resampling"...
Open process output as input for other process. Parameters ---------- tile : ``Tile`` process : ``MapcheteProcess`` kwargs : keyword arguments
Below is the the instruction that describes the task: ### Input: Open process output as input for other process. Parameters ---------- tile : ``Tile`` process : ``MapcheteProcess`` kwargs : keyword arguments ### Response: def open(self, tile, process, **kwargs): """...
def firstUrn(resource): """ Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str """ resource = xmlparser(resource) urn = resource.xpath("//ti:repl...
Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str
Below is the the instruction that describes the task: ### Input: Parse a resource to get the first URN :param resource: XML Resource :type resource: etree._Element :return: Tuple representing previous and next urn :rtype: str ### Response: def firstUrn(resource): """ Parse ...
def _delete_extraneous_files(self): # type: (SyncCopy) -> None """Delete extraneous files on the remote :param SyncCopy self: this """ if not self._spec.options.delete_extraneous_destination: return # list blobs for all destinations checked = set() ...
Delete extraneous files on the remote :param SyncCopy self: this
Below is the the instruction that describes the task: ### Input: Delete extraneous files on the remote :param SyncCopy self: this ### Response: def _delete_extraneous_files(self): # type: (SyncCopy) -> None """Delete extraneous files on the remote :param SyncCopy self: this ...
def process_event(self, event): """ Process a new input event. This method will pass the event on to any Effects in reverse Z order so that the top-most Effect has priority. :param event: The Event that has been triggered. :returns: None if the Scene processed the event...
Process a new input event. This method will pass the event on to any Effects in reverse Z order so that the top-most Effect has priority. :param event: The Event that has been triggered. :returns: None if the Scene processed the event, else the original event.
Below is the the instruction that describes the task: ### Input: Process a new input event. This method will pass the event on to any Effects in reverse Z order so that the top-most Effect has priority. :param event: The Event that has been triggered. :returns: None if the Scene pr...
def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False): """Opens a new gcs file for writing.""" if use_tmp_bucket: bucket = cls._get_tmp_gcs_bucket(writer_spec) account_id = cls._get_tmp_account_id(writer_spec) else: bucket = cls._get_gcs_bucket(writer_spec) account_...
Opens a new gcs file for writing.
Below is the the instruction that describes the task: ### Input: Opens a new gcs file for writing. ### Response: def _open_file(cls, writer_spec, filename_suffix, use_tmp_bucket=False): """Opens a new gcs file for writing.""" if use_tmp_bucket: bucket = cls._get_tmp_gcs_bucket(writer_spec) acco...
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): """Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination direct...
Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors informati...
Below is the the instruction that describes the task: ### Input: Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: To...
def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ if not hasattr(actor, name): object = cls(actor) setattr(actor, name, object) else: object = getattr(actor...
Command for executing remote calls on a remote object
Below is the the instruction that describes the task: ### Input: Command for executing remote calls on a remote object ### Response: def remote_call(request, cls, method, args, kw): '''Command for executing remote calls on a remote object ''' actor = request.actor name = 'remote_%s' % cls.__name__ ...
def domain_list(gandi): """List domains manageable by REST API.""" domains = gandi.dns.list() for domain in domains: gandi.echo(domain['fqdn']) return domains
List domains manageable by REST API.
Below is the the instruction that describes the task: ### Input: List domains manageable by REST API. ### Response: def domain_list(gandi): """List domains manageable by REST API.""" domains = gandi.dns.list() for domain in domains: gandi.echo(domain['fqdn']) return domains
def parse(cls, args): """ Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create method Raises: ...
Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create method Raises: ParseError: when the arguments are no...
Below is the the instruction that describes the task: ### Input: Parse command line arguments to construct a dictionary of command parameters that can be used to create a command Args: `args`: sequence of arguments Returns: Dictionary that can be used in create meth...
def foreignkey(element, exceptions): ''' function to determine if each select field needs a create button or not ''' label = element.field.__dict__['label'] try: label = unicode(label) except NameError: pass if (not label) or (label in exceptions): return False el...
function to determine if each select field needs a create button or not
Below is the the instruction that describes the task: ### Input: function to determine if each select field needs a create button or not ### Response: def foreignkey(element, exceptions): ''' function to determine if each select field needs a create button or not ''' label = element.field.__dict__[...
def next(self, fetch: bool = False, next_symbol: _NextSymbol = DEFAULT_NEXT_SYMBOL) -> _Next: """Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL. ...
Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL.
Below is the the instruction that describes the task: ### Input: Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL. ### Response: def next(self, fetch: bool = ...
def install_defaults(self): """Installs the default skills, updates all others""" def install_or_update_skill(skill): if skill.is_local: self.update(skill) else: self.install(skill, origin='default') return self.apply(install_or_update_sk...
Installs the default skills, updates all others
Below is the the instruction that describes the task: ### Input: Installs the default skills, updates all others ### Response: def install_defaults(self): """Installs the default skills, updates all others""" def install_or_update_skill(skill): if skill.is_local: self.u...
def chdir(new_dir): """ stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/ """ cur_dir = os.getcwd() _mkdir(new_dir) os.chdir(new_dir) try: yield finally: os....
stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/
Below is the the instruction that describes the task: ### Input: stolen from bcbio. Context manager to temporarily change to a new directory. http://lucentbeing.com/blog/context-managers-and-the-with-statement-in-python/ ### Response: def chdir(new_dir): """ stolen from bcbio. Context manager ...
def clear_zone_conditions(self): """stub""" if (self.get_zone_conditions_metadata().is_read_only() or self.get_zone_conditions_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['zoneConditions'] = \ self._zone_conditions_metadata...
stub
Below is the the instruction that describes the task: ### Input: stub ### Response: def clear_zone_conditions(self): """stub""" if (self.get_zone_conditions_metadata().is_read_only() or self.get_zone_conditions_metadata().is_required()): raise NoAccess() self.my_...
def md5(self): """ MD5 of scene which will change when meshes or transforms are changed Returns -------- hashed: str, MD5 hash of scene """ # start with transforms hash hashes = [self.graph.md5()] for g in self.geometry.values(): ...
MD5 of scene which will change when meshes or transforms are changed Returns -------- hashed: str, MD5 hash of scene
Below is the the instruction that describes the task: ### Input: MD5 of scene which will change when meshes or transforms are changed Returns -------- hashed: str, MD5 hash of scene ### Response: def md5(self): """ MD5 of scene which will change when meshes or ...
def drop_edges(self) -> None: """Drop all edges in the database.""" t = time.time() self.session.query(Edge).delete() self.session.commit() log.info('dropped all edges in %.2f seconds', time.time() - t)
Drop all edges in the database.
Below is the the instruction that describes the task: ### Input: Drop all edges in the database. ### Response: def drop_edges(self) -> None: """Drop all edges in the database.""" t = time.time() self.session.query(Edge).delete() self.session.commit() log.info('dropped all ...
def call_moses_detokenizer(workspace_dir: str, input_fname: str, output_fname: str, lang_code: Optional[str] = None): """ Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized i...
Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized input file, plain text or gzipped. :param output_fname: Path of tokenized output file, plain text. :param lang_code: Langua...
Below is the the instruction that describes the task: ### Input: Call Moses detokenizer. :param workspace_dir: Workspace third-party directory where Moses tokenizer is checked out. :param input_fname: Path of tokenized input file, plain text or gzipped. :param output_fname: Pa...
def Open(self): """Opens the process for reading.""" self.h_process = kernel32.OpenProcess( PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, self.pid) if not self.h_process: raise process_error.ProcessError( "Failed to open process (pid %d)." % self.pid) if self.Is64bit(): ...
Opens the process for reading.
Below is the the instruction that describes the task: ### Input: Opens the process for reading. ### Response: def Open(self): """Opens the process for reading.""" self.h_process = kernel32.OpenProcess( PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, 0, self.pid) if not self.h_process: raise...
def _env_filenames(filenames, env): """ Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list """ env_filenames ...
Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list
Below is the the instruction that describes the task: ### Input: Extend filenames with ennv indication of environments. :param list filenames: list of strings indicating filenames :param str env: environment indicator :returns: list of filenames extended with environment version :rtype: list ### R...
def get_table_metadata(engine, table): """ Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Dictionary of infos """ metadata = MetaData() metadata.reflect(bind=engine, only=[table]) table_metadata = ...
Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Dictionary of infos
Below is the the instruction that describes the task: ### Input: Extract all useful infos from the given table Args: engine: SQLAlchemy connection engine table: table name Returns: Dictionary of infos ### Response: def get_table_metadata(engine, table): """ Extract all useful ...
def create(self, parties): """Create the barrier for the given number of parties. Parameters: parties(int): The number of parties to wait for. Returns: bool: Whether or not the new barrier was successfully created. """ assert parties > 0, "parties must be a ...
Create the barrier for the given number of parties. Parameters: parties(int): The number of parties to wait for. Returns: bool: Whether or not the new barrier was successfully created.
Below is the the instruction that describes the task: ### Input: Create the barrier for the given number of parties. Parameters: parties(int): The number of parties to wait for. Returns: bool: Whether or not the new barrier was successfully created. ### Response: def create(se...
def monkeycache(apis): """ Feed this a dictionary of api bananas, it spits out processed cache """ if isinstance(type(apis), type(None)) or apis is None: return {} verbs = set() cache = {} cache['count'] = apis['count'] cache['asyncapis'] = [] apilist = apis['api'] if a...
Feed this a dictionary of api bananas, it spits out processed cache
Below is the the instruction that describes the task: ### Input: Feed this a dictionary of api bananas, it spits out processed cache ### Response: def monkeycache(apis): """ Feed this a dictionary of api bananas, it spits out processed cache """ if isinstance(type(apis), type(None)) or apis is None...
def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item() elif event == QKeySequence.Copy: self.copy() elif event == QKeySequence.P...
Reimplement Qt methods
Below is the the instruction that describes the task: ### Input: Reimplement Qt methods ### Response: def keyPressEvent(self, event): """Reimplement Qt methods""" if event.key() == Qt.Key_Delete: self.remove_item() elif event.key() == Qt.Key_F2: self.rename_item...
def channel_view(x:Tensor)->Tensor: "Make channel the first axis of `x` and flatten remaining axes" return x.transpose(0,1).contiguous().view(x.shape[1],-1)
Make channel the first axis of `x` and flatten remaining axes
Below is the the instruction that describes the task: ### Input: Make channel the first axis of `x` and flatten remaining axes ### Response: def channel_view(x:Tensor)->Tensor: "Make channel the first axis of `x` and flatten remaining axes" return x.transpose(0,1).contiguous().view(x.shape[1],-1)
def get_formatted_content(self, pyobj): '''typecode data --> text ''' u = urlencode(pyobj, self.reserved) return String.get_formatted_content(self, u)
typecode data --> text
Below is the the instruction that describes the task: ### Input: typecode data --> text ### Response: def get_formatted_content(self, pyobj): '''typecode data --> text ''' u = urlencode(pyobj, self.reserved) return String.get_formatted_content(self, u)
def draw(self, dx=0, dy=0, weighted=False, directed=False, highlight=[], traffic=None): """ Layout the graph incrementally. The graph is drawn at the center of the canvas. The weighted and directed parameters visualize edge weight and direction. The highlight specifies ...
Layout the graph incrementally. The graph is drawn at the center of the canvas. The weighted and directed parameters visualize edge weight and direction. The highlight specifies list of connected nodes. The path will be colored according to the "highlight" style. Clicki...
Below is the the instruction that describes the task: ### Input: Layout the graph incrementally. The graph is drawn at the center of the canvas. The weighted and directed parameters visualize edge weight and direction. The highlight specifies list of connected nodes. The pa...
def _read_bands(self): """ Reads a band with rasterio """ bands = [] try: for i, band in enumerate(self.bands): bands.append(rasterio.open(self.bands_path[i]).read_band(1)) except IOError as e: exit(e.message, 1) return bands
Reads a band with rasterio
Below is the the instruction that describes the task: ### Input: Reads a band with rasterio ### Response: def _read_bands(self): """ Reads a band with rasterio """ bands = [] try: for i, band in enumerate(self.bands): bands.append(rasterio.open(self.bands_path[i...
def add_all_from_dict(self, dictionary, **kwargs): """ Batch-add function implementations to the library. :param dictionary: A mapping from name to procedure class, i.e. the first two arguments to add() :param kwargs: Any additional kwargs will be passed to the constructors of _ea...
Batch-add function implementations to the library. :param dictionary: A mapping from name to procedure class, i.e. the first two arguments to add() :param kwargs: Any additional kwargs will be passed to the constructors of _each_ procedure class
Below is the the instruction that describes the task: ### Input: Batch-add function implementations to the library. :param dictionary: A mapping from name to procedure class, i.e. the first two arguments to add() :param kwargs: Any additional kwargs will be passed to the constructors of _each...
def leaveEvent(self, event): """ Mark the hovered state as being false. :param event | <QtCore.QLeaveEvent> """ super(XViewPanelItem, self).leaveEvent(event) # store the hover state and mark for a repaint self._hovered = False self.update()
Mark the hovered state as being false. :param event | <QtCore.QLeaveEvent>
Below is the the instruction that describes the task: ### Input: Mark the hovered state as being false. :param event | <QtCore.QLeaveEvent> ### Response: def leaveEvent(self, event): """ Mark the hovered state as being false. :param event | <QtCore.QLeaveEvent> "...
def parse(cls, fptr, offset, length): """Parse data entry URL box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns -----...
Parse data entry URL box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- DataEntryURLbox Instance o...
Below is the the instruction that describes the task: ### Input: Parse data entry URL box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. R...
def incoming_references(self, client=None, query={}): """Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optiona...
Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (optional) Dict with API options. :return: List of :class:`Entry ...
Below is the the instruction that describes the task: ### Input: Fetches all entries referencing the entry API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/links-to-asset :param client Client instance :param query: (opt...
def query(name, use_kerberos=None, debug=False): """Query the Channel Information System for details on the given channel name Parameters ---------- name : `~gwpy.detector.Channel`, or `str` Name of the channel of interest Returns ------- channel : `~gwpy.detector.Channel` ...
Query the Channel Information System for details on the given channel name Parameters ---------- name : `~gwpy.detector.Channel`, or `str` Name of the channel of interest Returns ------- channel : `~gwpy.detector.Channel` Channel with all details as acquired from the CIS
Below is the the instruction that describes the task: ### Input: Query the Channel Information System for details on the given channel name Parameters ---------- name : `~gwpy.detector.Channel`, or `str` Name of the channel of interest Returns ------- channel : `~gwpy.detector....
def _get_files(file_patterns, top=HERE): """Expand file patterns to a list of paths. Parameters ----------- file_patterns: list or str A list of glob patterns for the data file locations. The globs can be recursive if they include a `**`. They should be relative paths from the t...
Expand file patterns to a list of paths. Parameters ----------- file_patterns: list or str A list of glob patterns for the data file locations. The globs can be recursive if they include a `**`. They should be relative paths from the top directory or absolute paths. top:...
Below is the the instruction that describes the task: ### Input: Expand file patterns to a list of paths. Parameters ----------- file_patterns: list or str A list of glob patterns for the data file locations. The globs can be recursive if they include a `**`. They should be rela...
def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
Recursively iterate through values in nested lists.
Below is the the instruction that describes the task: ### Input: Recursively iterate through values in nested lists. ### Response: def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): ...
def postprocess_input_todo(self, p_todo): """ Post-processes a parsed todo when adding it to the list. * It converts relative dates to absolute ones. * Automatically inserts a creation date if not present. * Handles more user-friendly dependencies with before:, partof: and ...
Post-processes a parsed todo when adding it to the list. * It converts relative dates to absolute ones. * Automatically inserts a creation date if not present. * Handles more user-friendly dependencies with before:, partof: and after: tags
Below is the the instruction that describes the task: ### Input: Post-processes a parsed todo when adding it to the list. * It converts relative dates to absolute ones. * Automatically inserts a creation date if not present. * Handles more user-friendly dependencies with before:, partof: an...
def text(self, tag, textdata, step=None): """Saves a text summary. Args: tag: str: label for this data textdata: string, or 1D/2D list/numpy array of strings step: int: training step Note: markdown formatting is rendered by tensorboard. """ if step is None: step = self._step...
Saves a text summary. Args: tag: str: label for this data textdata: string, or 1D/2D list/numpy array of strings step: int: training step Note: markdown formatting is rendered by tensorboard.
Below is the the instruction that describes the task: ### Input: Saves a text summary. Args: tag: str: label for this data textdata: string, or 1D/2D list/numpy array of strings step: int: training step Note: markdown formatting is rendered by tensorboard. ### Response: def text(self, ta...
def get(self, *keys, fallback=None): """Retrieve a value in the config, if the value is not available give the fallback value specified. """ section, *keys = keys out = super().get(section, fallback) while isinstance(out, dict): key = keys.pop(0) ...
Retrieve a value in the config, if the value is not available give the fallback value specified.
Below is the the instruction that describes the task: ### Input: Retrieve a value in the config, if the value is not available give the fallback value specified. ### Response: def get(self, *keys, fallback=None): """Retrieve a value in the config, if the value is not available give the fall...
def waypoint_count_send(self, seq): '''wrapper for waypoint_count_send''' if self.mavlink10(): self.mav.mission_count_send(self.target_system, self.target_component, seq) else: self.mav.waypoint_count_send(self.target_system, self.target_component, seq)
wrapper for waypoint_count_send
Below is the the instruction that describes the task: ### Input: wrapper for waypoint_count_send ### Response: def waypoint_count_send(self, seq): '''wrapper for waypoint_count_send''' if self.mavlink10(): self.mav.mission_count_send(self.target_system, self.target_component, seq) ...
def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if jan1 == THU or (jan1 == WED and isleap(year)): return 53 else: return 52
Number of ISO weeks in a year
Below is the the instruction that describes the task: ### Input: Number of ISO weeks in a year ### Response: def weeks_per_year(year): '''Number of ISO weeks in a year''' # 53 weeks: any year starting on Thursday and any leap year starting on Wednesday jan1 = jwday(gregorian.to_jd(year, 1, 1)) if ...
def default_unit_label(axis, unit): """Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to u...
Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.Unit` the unit to use for the label Returns ------- ...
Below is the the instruction that describes the task: ### Input: Set default label for an axis from a `~astropy.units.Unit` If the axis already has a label, this function does nothing. Parameters ---------- axis : `~matplotlib.axis.Axis` the axis to manipulate unit : `~astropy.units.U...
def distributions_for_instances(self, data): """ Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndar...
Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ndarray
Below is the the instruction that describes the task: ### Input: Peforms predictions, returning the class distributions. :param data: the Instances to get the class distributions for :type data: Instances :return: the class distribution matrix, None if not a batch predictor :rtype: ...
def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs): '''calculate magnetic field strength from raw magnetometer''' import mavutil self = mavutil.mavfile_global m = SERVO_OUTPUT_RAW motor_pwm = m.servo1_raw + m.servo2_raw + m.servo3_raw + m.servo4_raw motor_pwm *= 0.25 rc3_min = self.par...
calculate magnetic field strength from raw magnetometer
Below is the the instruction that describes the task: ### Input: calculate magnetic field strength from raw magnetometer ### Response: def get_motor_offsets(SERVO_OUTPUT_RAW, ofs, motor_ofs): '''calculate magnetic field strength from raw magnetometer''' import mavutil self = mavutil.mavfile_global ...
def convert_jams(jams_file, output_prefix, csv=False, comment_char='#', namespaces=None): '''Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whe...
Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whether to output in csv (True) or lab (False) format comment_char : str The character ...
Below is the the instruction that describes the task: ### Input: Convert jams to labs. Parameters ---------- jams_file : str The path on disk to the jams file in question output_prefix : str The file path prefix of the outputs csv : bool Whether to output in csv (True)...
def fn_ceil(self, value): """ Return the ceiling of a number. :param value: The number. :return: The ceiling of the number. """ if is_ndarray(value) or isinstance(value, (list, tuple)): return numpy.ceil(self._to_ndarray(value)) else: ret...
Return the ceiling of a number. :param value: The number. :return: The ceiling of the number.
Below is the the instruction that describes the task: ### Input: Return the ceiling of a number. :param value: The number. :return: The ceiling of the number. ### Response: def fn_ceil(self, value): """ Return the ceiling of a number. :param value: The number. :ret...
def RelayDirectly(self, inventory): """ Relay the inventory to the remote client. Args: inventory (neo.Network.Inventory): Returns: bool: True if relayed successfully. False otherwise. """ relayed = False self.RelayCache[inventory.Hash.T...
Relay the inventory to the remote client. Args: inventory (neo.Network.Inventory): Returns: bool: True if relayed successfully. False otherwise.
Below is the the instruction that describes the task: ### Input: Relay the inventory to the remote client. Args: inventory (neo.Network.Inventory): Returns: bool: True if relayed successfully. False otherwise. ### Response: def RelayDirectly(self, inventory): """ ...
def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize): """Show a colorbar right of the plot.""" fig = ax.get_figure() mappable = cm.ScalarMappable(cmap=cmap, norm=norm) mappable.set_array(cmap_data) # TODO: Or what??? fig.colorbar(mappable, ax=ax)
Show a colorbar right of the plot.
Below is the the instruction that describes the task: ### Input: Show a colorbar right of the plot. ### Response: def _add_colorbar(ax: Axes, cmap: colors.Colormap, cmap_data: np.ndarray, norm: colors.Normalize): """Show a colorbar right of the plot.""" fig = ax.get_figure() mappable = cm.ScalarMappabl...
def _skew_symmetric_translation(pos_A_in_B): """ Helper function to get a skew symmetric translation matrix for converting quantities between frames. """ return np.array( [ 0., -pos_A_in_B[2], pos_A_in_B[1], pos_A_in_B[2], 0., ...
Helper function to get a skew symmetric translation matrix for converting quantities between frames.
Below is the the instruction that describes the task: ### Input: Helper function to get a skew symmetric translation matrix for converting quantities between frames. ### Response: def _skew_symmetric_translation(pos_A_in_B): """ Helper function to get a skew symmetric translation matrix for converting ...
def close(self): """Close the notification.""" with self.selenium.context(self.selenium.CONTEXT_CHROME): if self.window.firefox_version > 63: self.find_primary_button().click() self.window.wait_for_notification(None) else: BaseNotif...
Close the notification.
Below is the the instruction that describes the task: ### Input: Close the notification. ### Response: def close(self): """Close the notification.""" with self.selenium.context(self.selenium.CONTEXT_CHROME): if self.window.firefox_version > 63: self.find_primary_button()...
def equals(self, other): """ Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels """ if self.is_(other): return True if ...
Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels
Below is the the instruction that describes the task: ### Input: Determines if two MultiIndex objects have the same labeling information (the levels themselves do not necessarily have to be the same) See Also -------- equal_levels ### Response: def equals(self, other): """ ...
def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B', asbytes(s)) for i in range_g(len(a)): self._buf[addr+i] = a[i]
Put string of bytes at given address. Will overwrite any previous entries.
Below is the the instruction that describes the task: ### Input: Put string of bytes at given address. Will overwrite any previous entries. ### Response: def puts(self, addr, s): """Put string of bytes at given address. Will overwrite any previous entries. """ a = array('B',...
def show_workspace(self, name): """Show specific workspace.""" if not self.workspace.exists(name): raise ValueError("Workspace `%s` doesn't exists." % name) color = Color() workspaces = self.workspace.list() self.logger.info("<== %s workspace ==>" % color.colored(na...
Show specific workspace.
Below is the the instruction that describes the task: ### Input: Show specific workspace. ### Response: def show_workspace(self, name): """Show specific workspace.""" if not self.workspace.exists(name): raise ValueError("Workspace `%s` doesn't exists." % name) color = Color() ...
def generate_image_beacon(self, event_collection, event_body, timestamp=None): """ Generates an image beacon URL. :param event_collection: the name of the collection to insert the event to :param event_body: dict, the body of the event to insert the event to :param timestamp: da...
Generates an image beacon URL. :param event_collection: the name of the collection to insert the event to :param event_body: dict, the body of the event to insert the event to :param timestamp: datetime, optional, the timestamp of the event
Below is the the instruction that describes the task: ### Input: Generates an image beacon URL. :param event_collection: the name of the collection to insert the event to :param event_body: dict, the body of the event to insert the event to :param timestamp: datetime, optional, the ...
def main(command_line=True, **kwargs): """ NAME utrecht_magic.py DESCRIPTION converts Utrecht magnetometer data files to magic_measurements files SYNTAX utrecht_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify ...
NAME utrecht_magic.py DESCRIPTION converts Utrecht magnetometer data files to magic_measurements files SYNTAX utrecht_magic.py [command line options] OPTIONS -h: prints the help message and quits. -f FILE: specify input file, or -F FILE: specify output fil...
Below is the the instruction that describes the task: ### Input: NAME utrecht_magic.py DESCRIPTION converts Utrecht magnetometer data files to magic_measurements files SYNTAX utrecht_magic.py [command line options] OPTIONS -h: prints the help message and quits. ...
def slice_by_component( self, component_index, start, end ): """ Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desi...
Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desired component a component start and end are relative to the ...
Below is the the instruction that describes the task: ### Input: Return a slice of the alignment, corresponding to an coordinate interval in a specific component. component_index is one of an integer offset into the components list a string indicating the src of the desired componen...
def summarize_dataframe(self): """Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs """ if self.dataframe_hash: return(self.dataframe_hash) else: df = self._as_...
Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs
Below is the the instruction that describes the task: ### Input: Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs ### Response: def summarize_dataframe(self): """Summarize default dataframe for this coh...
def Query(self, query, parameters=None): """Queries the database file. Args: query (str): SQL query. parameters (Optional[dict|tuple]): query parameters. Returns: list[sqlite3.Row]: rows resulting from the query. """ # TODO: catch Warning and return None. # Note that we canno...
Queries the database file. Args: query (str): SQL query. parameters (Optional[dict|tuple]): query parameters. Returns: list[sqlite3.Row]: rows resulting from the query.
Below is the the instruction that describes the task: ### Input: Queries the database file. Args: query (str): SQL query. parameters (Optional[dict|tuple]): query parameters. Returns: list[sqlite3.Row]: rows resulting from the query. ### Response: def Query(self, query, parameters=None)...
def file_uptodate(fname, cmp_fname): """Check if a file exists, is non-empty and is more recent than cmp_fname. """ try: return (file_exists(fname) and file_exists(cmp_fname) and getmtime(fname) >= getmtime(cmp_fname)) except OSError: return False
Check if a file exists, is non-empty and is more recent than cmp_fname.
Below is the the instruction that describes the task: ### Input: Check if a file exists, is non-empty and is more recent than cmp_fname. ### Response: def file_uptodate(fname, cmp_fname): """Check if a file exists, is non-empty and is more recent than cmp_fname. """ try: return (file_exists(fna...
def current_version(self, object, relations_as_of=None, check_db=False): """ Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so ...
Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current version available. In this case the function returns None. ...
Below is the the instruction that describes the task: ### Input: Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current vers...
def axes_off(ax): """Get rid of all axis ticks, lines, etc. """ ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False)
Get rid of all axis ticks, lines, etc.
Below is the the instruction that describes the task: ### Input: Get rid of all axis ticks, lines, etc. ### Response: def axes_off(ax): """Get rid of all axis ticks, lines, etc. """ ax.set_frame_on(False) ax.axes.get_yaxis().set_visible(False) ax.axes.get_xaxis().set_visible(False)
def rewrite_to_secure_url(url, secure_base=None): """ Rewrite URL to a Secure URL @param url URL to be rewritten to a secure URL. @param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL). """ if secure_base is None: secure_base = cfg.get('CFG_SITE_SECURE_URL') u...
Rewrite URL to a Secure URL @param url URL to be rewritten to a secure URL. @param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL).
Below is the the instruction that describes the task: ### Input: Rewrite URL to a Secure URL @param url URL to be rewritten to a secure URL. @param secure_base: Base URL of secure site (defaults to CFG_SITE_SECURE_URL). ### Response: def rewrite_to_secure_url(url, secure_base=None): """ Rewrite UR...
def finalize_filename(filename, file_format=None): """ Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extension ...
Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extension :type file_format: MimeType :return: Final filena...
Below is the the instruction that describes the task: ### Input: Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extens...
def _check_cpd_inputs(X, rank): """Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError: If inputs are not suited for ...
Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError: If inputs are not suited for CP decomposition.
Below is the the instruction that describes the task: ### Input: Checks that inputs to optimization function are appropriate. Parameters ---------- X : ndarray Tensor used for fitting CP decomposition. rank : int Rank of low rank decomposition. Raises ------ ValueError:...
def get_dip(self): """ Compute dip of each surface element and return area-weighted average value (in range ``(0, 90]``). Given that dip values are constrained in the range (0, 90], the simple formula for weighted mean is used. """ areas = self._get_areas() ...
Compute dip of each surface element and return area-weighted average value (in range ``(0, 90]``). Given that dip values are constrained in the range (0, 90], the simple formula for weighted mean is used.
Below is the the instruction that describes the task: ### Input: Compute dip of each surface element and return area-weighted average value (in range ``(0, 90]``). Given that dip values are constrained in the range (0, 90], the simple formula for weighted mean is used. ### Response: def ge...
def listFiles(self, dataset = "", block_name = "", logical_file_name = "", release_version="", pset_hash="", app_name="", output_module_label="", run_num=-1, origin_site_name="", lumi_list="", detail=False, validFileOnly=0, sumOverLumi=0): """ API to list files in DBS. Either non-wildcar...
API to list files in DBS. Either non-wildcarded logical_file_name, non-wildcarded dataset or non-wildcarded block_name is required. The combination of a non-wildcarded dataset or block_name with an wildcarded logical_file_name is supported. * For lumi_list the following two json formats are supported: ...
Below is the the instruction that describes the task: ### Input: API to list files in DBS. Either non-wildcarded logical_file_name, non-wildcarded dataset or non-wildcarded block_name is required. The combination of a non-wildcarded dataset or block_name with an wildcarded logical_file_name is supported. ...
def _rebuild_entries(self): """ Recreates the entries master list based on the groups hierarchy (order matters here, since the parser uses order to determine lineage). """ self.entries = [] def collapse_entries(group): for entry in group.entries: ...
Recreates the entries master list based on the groups hierarchy (order matters here, since the parser uses order to determine lineage).
Below is the the instruction that describes the task: ### Input: Recreates the entries master list based on the groups hierarchy (order matters here, since the parser uses order to determine lineage). ### Response: def _rebuild_entries(self): """ Recreates the entries master list based on t...
def getDescriptor(self, desc_type, desc_index, length, endpoint = -1): r"""Retrieves a descriptor from the device identified by the type and index of the descriptor. Arguments: desc_type: descriptor type. desc_index: index of the descriptor. len: descriptor l...
r"""Retrieves a descriptor from the device identified by the type and index of the descriptor. Arguments: desc_type: descriptor type. desc_index: index of the descriptor. len: descriptor length. endpoint: ignored.
Below is the the instruction that describes the task: ### Input: r"""Retrieves a descriptor from the device identified by the type and index of the descriptor. Arguments: desc_type: descriptor type. desc_index: index of the descriptor. len: descriptor length. ...
def geo_shape(self, sides=5, center=None, distance=None): """ Return a WKT string for a POLYGON with given amount of sides. The polygon is defined by its center (random point if not provided) and the distance (random distance if not provided; in km) of the points to its center. ...
Return a WKT string for a POLYGON with given amount of sides. The polygon is defined by its center (random point if not provided) and the distance (random distance if not provided; in km) of the points to its center.
Below is the the instruction that describes the task: ### Input: Return a WKT string for a POLYGON with given amount of sides. The polygon is defined by its center (random point if not provided) and the distance (random distance if not provided; in km) of the points to its center. ### Respon...
def share(self, accounts): """ Create a share """ if not isinstance(accounts, (list, tuple)): msg = "Video.share expects an iterable argument" raise exceptions.PyBrightcoveError(msg) raise exceptions.PyBrightcoveError("Not yet implemented")
Create a share
Below is the the instruction that describes the task: ### Input: Create a share ### Response: def share(self, accounts): """ Create a share """ if not isinstance(accounts, (list, tuple)): msg = "Video.share expects an iterable argument" raise exceptions.PyBri...
def poly2poly(line): """ Parse a string of text containing a DS9 description of a polygon. This function works but is not very robust due to the constraints of healpy. Parameters ---------- line : str A string containing a DS9 region command for a polygon. Returns ------- ...
Parse a string of text containing a DS9 description of a polygon. This function works but is not very robust due to the constraints of healpy. Parameters ---------- line : str A string containing a DS9 region command for a polygon. Returns ------- poly : [ra, dec, ...] The...
Below is the the instruction that describes the task: ### Input: Parse a string of text containing a DS9 description of a polygon. This function works but is not very robust due to the constraints of healpy. Parameters ---------- line : str A string containing a DS9 region command for a po...