code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def midi_inputs(self): """ :return: A list of MIDI input :class:`Ports`. """ return self.client.get_ports(is_midi=True, is_physical=True, is_input=True)
:return: A list of MIDI input :class:`Ports`.
def full(self): """Return True if the queue is full, False otherwise (not reliable!).""" self.mutex.acquire() n = 0 < self.maxsize == self._qsize() self.mutex.release() return n
Return True if the queue is full, False otherwise (not reliable!).
def partition(cls, iterable, pred): """ Use a predicate to partition items into false and true entries. """ t1, t2 = itertools.tee(iterable) return cls(itertools.filterfalse(pred, t1), filter(pred, t2))
Use a predicate to partition items into false and true entries.
def finish_plot(): """Helper for plotting.""" plt.legend() plt.grid(color='0.7') plt.xlabel('x') plt.ylabel('y') plt.show()
Helper for plotting.
def load_network(self, layers=1): """ Given an Ethernet frame, determine the appropriate sub-protocol; If layers is greater than zerol determine the type of the payload and load the appropriate type of network packet. It is expected that the payload be a hexified string. The laye...
Given an Ethernet frame, determine the appropriate sub-protocol; If layers is greater than zerol determine the type of the payload and load the appropriate type of network packet. It is expected that the payload be a hexified string. The layers argument determines how many layers to desc...
def remove_symbol_add_symbol(string_item, remove_symbol, add_symbol): """ Remove a symbol from a string, and replace it with a different one Args: string_item: String that you want to replace symbols in remove_symbol: Symbol to remove add_symbol: Symbol to add Returns: returns a...
Remove a symbol from a string, and replace it with a different one Args: string_item: String that you want to replace symbols in remove_symbol: Symbol to remove add_symbol: Symbol to add Returns: returns a string with symbols swapped
def GenomicRangeFromString(range_string,payload=None,dir=None): """Constructor for a GenomicRange object that takes a string""" m = re.match('^(.+):(\d+)-(\d+)$',range_string) if not m: sys.stderr.write("ERROR bad genomic range string\n"+range_string+"\n") sys.exit() chr = m.group(1) start = int(m.g...
Constructor for a GenomicRange object that takes a string
def authAddress(val): """ # The C1 Tag extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways. # Parameters _val_: `list[str]` > The raw data from a WOS file # Returns `list[str]` > A lis...
# The C1 Tag extracts the address of the authors as given by WOS. **Warning** the mapping of author to address is not very good and is given in multiple ways. # Parameters _val_: `list[str]` > The raw data from a WOS file # Returns `list[str]` > A list of addresses
def run_chunk(environ, lowstate): ''' Expects a list of lowstate dictionaries that are executed and returned in order ''' client = environ['SALT_APIClient'] for chunk in lowstate: yield client.run(chunk)
Expects a list of lowstate dictionaries that are executed and returned in order
def parse_match_info(self, req: Request, name: str, field: Field) -> typing.Any: """Pull a value from the request's ``match_info``.""" return core.get_value(req.match_info, name, field)
Pull a value from the request's ``match_info``.
def _validate(self): """Validate model data and save errors """ errors = {} for name, validator in self._validators.items(): value = getattr(self, name) try: validator(self, value) except ValidationError as e: errors[n...
Validate model data and save errors
def is_valid(cls, oid): """Checks if a `oid` string is valid or not. :Parameters: - `oid`: the object id to validate .. versionadded:: 2.3 """ if not oid: return False try: ObjectId(oid) return True except (InvalidI...
Checks if a `oid` string is valid or not. :Parameters: - `oid`: the object id to validate .. versionadded:: 2.3
def _parse_use(self, string): """Extracts use dependencies from the innertext of a module.""" result = {} for ruse in self.RE_USE.finditer(string): #We also handle comments for individual use cases, the "only" section #won't pick up any comments. name = ruse.g...
Extracts use dependencies from the innertext of a module.
def make_coursera_absolute_url(url): """ If given url is relative adds coursera netloc, otherwise returns it without any changes. """ if not bool(urlparse(url).netloc): return urljoin(COURSERA_URL, url) return url
If given url is relative adds coursera netloc, otherwise returns it without any changes.
def load(self, name, *, arguments=None, validate_arguments=True, strict_dag=False): """ Import the workflow script and load all known objects. The workflow script is treated like a module and imported into the Python namespace. After the import, the method looks for instances of known c...
Import the workflow script and load all known objects. The workflow script is treated like a module and imported into the Python namespace. After the import, the method looks for instances of known classes and stores a reference for further use in the workflow object. Args: ...
def request(self, message, timeout=False, *args, **kwargs): """Populate connection pool, send message, return BytesIO, and cleanup""" if not self.connection_pool.full(): self.connection_pool.put(self._register_socket()) _socket = self.connection_pool.get() # setting timeout...
Populate connection pool, send message, return BytesIO, and cleanup
def setNonExpert(self): """ Turns off 'expert' status whereby to allow a button to be disabled """ self._expert = False if self._active: self.enable() else: self.disable()
Turns off 'expert' status whereby to allow a button to be disabled
def sample(self, frame): """Samples the given frame.""" frames = self.frame_stack(frame) if frames: frames.pop() parent_stats = self.stats for f in frames: parent_stats = parent_stats.ensure_child(f.f_code, void) stats = parent_stats.ensure_child(f...
Samples the given frame.
def crypto_box(message, nonce, pk, sk): """ Encrypts and returns a message ``message`` using the secret key ``sk``, public key ``pk``, and the nonce ``nonce``. :param message: bytes :param nonce: bytes :param pk: bytes :param sk: bytes :rtype: bytes """ if len(nonce) != crypto_b...
Encrypts and returns a message ``message`` using the secret key ``sk``, public key ``pk``, and the nonce ``nonce``. :param message: bytes :param nonce: bytes :param pk: bytes :param sk: bytes :rtype: bytes
def restore_from_cluster_snapshot(self, cluster_identifier, snapshot_identifier): """ Restores a cluster from its snapshot :param cluster_identifier: unique identifier of a cluster :type cluster_identifier: str :param snapshot_identifier: unique identifier for a snapshot of a cl...
Restores a cluster from its snapshot :param cluster_identifier: unique identifier of a cluster :type cluster_identifier: str :param snapshot_identifier: unique identifier for a snapshot of a cluster :type snapshot_identifier: str
def get_credit_card_payment_by_id(cls, credit_card_payment_id, **kwargs): """Find CreditCardPayment Return single instance of CreditCardPayment by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> th...
Find CreditCardPayment Return single instance of CreditCardPayment by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_credit_card_payment_by_id(credit_card_payment_id, async=True) ...
def demonstrate_colored_logging(): """Interactively demonstrate the :mod:`coloredlogs` package.""" # Determine the available logging levels and order them by numeric value. decorated_levels = [] defined_levels = coloredlogs.find_defined_levels() normalizer = coloredlogs.NameNormalizer() for name...
Interactively demonstrate the :mod:`coloredlogs` package.
def row(self, *args): """ Adds a list of KeyboardButton to the keyboard. This function does not consider row_width. ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param ar...
Adds a list of KeyboardButton to the keyboard. This function does not consider row_width. ReplyKeyboardMarkup#row("A")#row("B", "C")#to_json() outputs '{keyboard: [["A"], ["B", "C"]]}' See https://core.telegram.org/bots/api#inlinekeyboardmarkup :param args: strings :return: self, to allo...
def analysis_question_report(feature, parent): """Retrieve the analysis question section from InaSAFE report. """ _ = feature, parent # NOQA project_context_scope = QgsExpressionContextUtils.projectScope() key = provenance_layer_analysis_impacted['provenance_key'] if not project_context_scope.h...
Retrieve the analysis question section from InaSAFE report.
def info(): ''' Return information about the license, if the license is not correctly activated this will return None. CLI Example: .. code-block:: bash salt '*' license.info ''' cmd = r'cscript C:\Windows\System32\slmgr.vbs /dli' out = __salt__['cmd.run'](cmd) match = re...
Return information about the license, if the license is not correctly activated this will return None. CLI Example: .. code-block:: bash salt '*' license.info
def handle_read_value(self, buff, start, end): ''' handle read of the value based on the expected length :param buff: :param start: :param end: ''' segmenttype = self._state[1].value.segmenttype value = None eventtype = None ft...
handle read of the value based on the expected length :param buff: :param start: :param end:
def select_resample_op(da, op, freq="YS", **indexer): """Apply operation over each period that is part of the index selection. Parameters ---------- da : xarray.DataArray Input data. op : str {'min', 'max', 'mean', 'std', 'var', 'count', 'sum', 'argmax', 'argmin'} or func Reduce operati...
Apply operation over each period that is part of the index selection. Parameters ---------- da : xarray.DataArray Input data. op : str {'min', 'max', 'mean', 'std', 'var', 'count', 'sum', 'argmax', 'argmin'} or func Reduce operation. Can either be a DataArray method or a function that can b...
def links(self): """ list: List of all MediaWiki page links on the page Note: Not settable """ if self._links is None: self._links = list() self.__pull_combined_properties() return self._links
list: List of all MediaWiki page links on the page Note: Not settable
def setup_table(self): """Setup table""" self.horizontalHeader().setStretchLastSection(True) self.adjust_columns() # Sorting columns self.setSortingEnabled(True) self.sortByColumn(0, Qt.AscendingOrder)
Setup table
def run_job(self): """Execute a logdissect job""" try: self.load_parsers() self.load_filters() self.load_outputs() self.config_args() if self.args.list_parsers: self.list_parsers() if self.args.verbosemode: print('Lo...
Execute a logdissect job
def copy_selection(self, _cut=False): """ Copy selected text and return :class:`.ClipboardData` instance. """ new_document, clipboard_data = self.document.cut_selection() if _cut: self.document = new_document self.selection_state = None return clipboa...
Copy selected text and return :class:`.ClipboardData` instance.
def parse_arg(arg): """ Parses arguments for convenience. Argument can be a csv list ('a,b,c'), a string, a list, a tuple. Returns a list. """ # handle string input if type(arg) == str: arg = arg.strip() # parse csv as tickers and create children if ',' in arg: ...
Parses arguments for convenience. Argument can be a csv list ('a,b,c'), a string, a list, a tuple. Returns a list.
def describe_api_model(restApiId, modelName, flatten=True, region=None, key=None, keyid=None, profile=None): ''' Get a model by name for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_model restApiId modelName [True] ''' try: conn = _...
Get a model by name for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_model restApiId modelName [True]
def createMappings(self, name, body, verbose=None): """ Create a new Visual Mapping function and add it to the Visual Style specified by the `name` parameter. Existing mappings in the Visual Style will be overidden by the new mappings created. The types of mapping available in Cytoscape...
Create a new Visual Mapping function and add it to the Visual Style specified by the `name` parameter. Existing mappings in the Visual Style will be overidden by the new mappings created. The types of mapping available in Cytoscape are explained in depth [here](http://manual.cytoscape.org/en/stable/Sty...
def _compare_across(collections, key): """Return whether all the collections return equal values when called with `key`.""" if len(collections) < 2: return True c0 = key(collections[0]) return all(c0 == key(c) for c in collections[1:])
Return whether all the collections return equal values when called with `key`.
def _Open(self, path_spec, mode='rb'): """Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to ...
Opens the file system defined by path specification. Args: path_spec (PathSpec): a path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: if th...
def get_primary_at(source_code, offset, retry=True): """Return Python object in *source_code* at *offset* Periods to the left of the cursor are carried forward e.g. 'functools.par^tial' would yield 'functools.partial' Retry prevents infinite recursion: retry only once """ obj = '' ...
Return Python object in *source_code* at *offset* Periods to the left of the cursor are carried forward e.g. 'functools.par^tial' would yield 'functools.partial' Retry prevents infinite recursion: retry only once
def book(self, name): """Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is gi...
Return an API wrapper for the given order book. :param name: Order book name (e.g. "btc_cad"). :type name: str | unicode :return: Order book API wrapper. :rtype: quadriga.book.OrderBook :raise InvalidOrderBookError: If an invalid order book is given. **Example**: ...
def ion_equals(a, b, timestamps_instants_only=False): """Tests two objects for equivalence under the Ion data model. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equiva...
Tests two objects for equivalence under the Ion data model. There are three important cases: * When neither operand specifies its `ion_type` or `annotations`, this method will only return True when the values of both operands are equivalent under the Ion data model. * When only one of the...
def delete_view(self, request, object_id, extra_context=None): """ Overrides the default to enable redirecting to the directory view after deletion of a folder. we need to fetch the object and find out who the parent is before super, because super will delete the object and make...
Overrides the default to enable redirecting to the directory view after deletion of a folder. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to. The d...
def transfer_from(self, spender_acct: Account, b58_from_address: str, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int, gas_price: int): """ This interface is used to call the Allowance method in ope4 that allow spender to withdraw amount of oep4 token f...
This interface is used to call the Allowance method in ope4 that allow spender to withdraw amount of oep4 token from from-account to to-account. :param spender_acct: an Account class that actually spend oep4 token. :param b58_from_address: an base58 encode address that actually pay oep4 token f...
def findBinomialNsWithExpectedSampleMinimum(desiredValuesSorted, p, numSamples, nMax): """ For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above th...
For each desired value, find an approximate n for which the sample minimum has a expected value equal to this value. For each value, find an adjacent pair of n values whose expected sample minima are below and above the desired value, respectively, and return a linearly-interpolated n between these two values....
def query_by_login(self, login_id, end_time=None, start_time=None): """ Query by login. List authentication events for a given login. """ path = {} data = {} params = {} # REQUIRED - PATH - login_id """ID""" path["login_id"] =...
Query by login. List authentication events for a given login.
def encode(df, encoding='utf8', verbosity=1): """If you try to encode each element individually with python, this would take days!""" if verbosity > 0: # pbar_i = 0 pbar = progressbar.ProgressBar(maxval=df.shape[1]) pbar.start() # encode strings as UTF-8 so they'll work in python2 an...
If you try to encode each element individually with python, this would take days!
def is_conditional(self, include_loop=True): """ Check if the node is a conditional node A conditional node is either a IF or a require/assert or a RETURN bool Returns: bool: True if the node is a conditional node """ if self.contains_if(include_loop) ...
Check if the node is a conditional node A conditional node is either a IF or a require/assert or a RETURN bool Returns: bool: True if the node is a conditional node
def _log(self, x): """Modified version of np.log that manually sets values <=0 to -inf Parameters ---------- x: ndarray of floats Input to the log function Returns ------- log_ma: ndarray of floats log of x, with x<=0 values replaced with...
Modified version of np.log that manually sets values <=0 to -inf Parameters ---------- x: ndarray of floats Input to the log function Returns ------- log_ma: ndarray of floats log of x, with x<=0 values replaced with -inf
def itemAdded(self): """ Called to indicate that a new item of the type monitored by this batch processor is being added to the database. If this processor is not already scheduled to run, this will schedule it. It will also start the batch process if it is not yet running and ...
Called to indicate that a new item of the type monitored by this batch processor is being added to the database. If this processor is not already scheduled to run, this will schedule it. It will also start the batch process if it is not yet running and there are any registered remote l...
def _status_filter_to_query(clause): """ Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as...
Convert a clause querying for an experiment state RUNNING or DEAD. Queries that check for experiment state RUNNING and DEAD need to be replaced by the logic that decides these two states as both of them are stored in the Mongo Database as "RUNNING". We use querying by last heartbeat tim...
def data(self): # pragma: no cover pylint: disable=inconsistent-return-statements """ Management and input of data to the table. :raises: :code:`Exception` When self.data_to_print is not a list. """ if isinstance(self.data_to_print, list): ...
Management and input of data to the table. :raises: :code:`Exception` When self.data_to_print is not a list.
def magic_api(word): """ This is our magic API that we're simulating. It'll return a random number and a cache timer. """ result = sum(ord(x)-65 + randint(1,50) for x in word) delta = timedelta(seconds=result) cached_until = datetime.now() + delta return result, cached_until
This is our magic API that we're simulating. It'll return a random number and a cache timer.
def inherit_docstrings(cls): """Class decorator for inheriting docstrings. Automatically inherits base class doc-strings if not present in the derived class. """ @functools.wraps(cls) def _inherit_docstrings(cls): if not isinstance(cls, (type, colorise.compat.ClassType)): r...
Class decorator for inheriting docstrings. Automatically inherits base class doc-strings if not present in the derived class.
def principal_rotation_axis(gyro_data): """Get the principal rotation axis of angular velocity measurements. Parameters ------------- gyro_data : (3, N) ndarray Angular velocity measurements Returns ------------- v : (3,1) ndarray The principal ro...
Get the principal rotation axis of angular velocity measurements. Parameters ------------- gyro_data : (3, N) ndarray Angular velocity measurements Returns ------------- v : (3,1) ndarray The principal rotation axis for the chosen sequence
def spiro_image(R, r, r_, resolution=2*PI/1000, spins=50, size=[32, 32]): '''Create image with given Spirograph parameters using numpy and scipy. ''' x, y = give_dots(200, r, r_, spins=20) xy = np.array([x, y]).T xy = np.array(np.around(xy), dtype=np.int64) xy = xy[(xy[:, 0] >= -250) & (xy[:, 1]...
Create image with given Spirograph parameters using numpy and scipy.
def convert_msg(self, msg): """ Takes one POEntry object and converts it (adds a dummy translation to it) msg is an instance of polib.POEntry """ source = msg.msgid if not source: # don't translate empty string return plural = msg.msgid_pl...
Takes one POEntry object and converts it (adds a dummy translation to it) msg is an instance of polib.POEntry
def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num, mlm_metric, nsp_metric, trainer, log_interval): """Log training progress.""" end_time = time.time() duration = end_time - begin_time throughput = running_num_tks / duration / 1000.0 running_mlm_loss = running_...
Log training progress.
def displayTriples(triples, qname=qname): """ triples can also be an rdflib Graph instance """ [print(*(e[:5] if isinstance(e, rdflib.BNode) else qname(e) for e in t), '.') for t in sorted(triples)]
triples can also be an rdflib Graph instance
def inline(self) -> str: """ Return endpoint string :return: """ inlined = [str(info) for info in (self.server, self.ipv4, self.ipv6, self.port, self.path) if info] return SecuredBMAEndpoint.API + " " + " ".join(inlined)
Return endpoint string :return:
def get_skype(self): """Returns Skype window ID or None if Skype not running.""" skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if not skype_inst: return type_ret = Atom() format_ret = c_int() nitems_ret = c_ulong() bytes_after_ret = ...
Returns Skype window ID or None if Skype not running.
def get_scan_parameters_table_from_meta_data(meta_data_array, scan_parameters=None): '''Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data . Parameters ---------- meta_data_array : numpy.ndarray The array with the scan pa...
Takes the meta data array and returns the scan parameter values as a view of a numpy array only containing the parameter data . Parameters ---------- meta_data_array : numpy.ndarray The array with the scan parameters. scan_parameters : list of strings The name of the scan parameters to t...
def epiweek_to_date(ew: Epiweek) -> datetime.date: """ Return date from epiweek (starts at Sunday) """ day_one = _start_date_of_year(ew.year) diff = 7 * (ew.week - 1) + (ew.day - 1) return day_one + datetime.timedelta(days=diff)
Return date from epiweek (starts at Sunday)
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string
def get_scrollbar_position_height(self): """Return the pixel span height of the scrollbar area in which the slider handle may move""" vsb = self.editor.verticalScrollBar() style = vsb.style() opt = QStyleOptionSlider() vsb.initStyleOption(opt) # Get the area in w...
Return the pixel span height of the scrollbar area in which the slider handle may move
def first_or_create( self, _attributes=None, _joining=None, _touch=True, **attributes ): """ Get the first related model record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attr...
Get the first related model record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model
def metamodel_from_str(lang_desc, metamodel=None, **kwargs): """ Creates a new metamodel from the textX description given as a string. Args: lang_desc(str): A textX language description. metamodel(TextXMetaModel): A metamodel that should be used. other params: See TextXMetaModel. ...
Creates a new metamodel from the textX description given as a string. Args: lang_desc(str): A textX language description. metamodel(TextXMetaModel): A metamodel that should be used. other params: See TextXMetaModel.
def list_extra_features(self): ''' Returns ------- List of dicts. One dict for each document, keys are metadata, values are counts ''' return FeatureLister(self._mX, self._metadata_idx_store, self.get_num_docs())....
Returns ------- List of dicts. One dict for each document, keys are metadata, values are counts
def updateConfig(self, eleobj, config, type='simu'): """ write new configuration to element :param eleobj: define element object :param config: new configuration for element, string or dict :param type: 'simu' by default, could be online, misc, comm, ctrl """ ...
write new configuration to element :param eleobj: define element object :param config: new configuration for element, string or dict :param type: 'simu' by default, could be online, misc, comm, ctrl
def expression_statement(self): """ expression_statement: assignment ';' """ node = self.assignment() self._process(Nature.SEMI) return node
expression_statement: assignment ';'
def set_ram(self, ram): """ Set the RAM amount for the GNS3 VM. :param ram: amount of memory """ yield from self._execute("modifyvm", [self._vmname, "--memory", str(ram)], timeout=3) log.info("GNS3 VM RAM amount set to {}".format(ram))
Set the RAM amount for the GNS3 VM. :param ram: amount of memory
def create_floating_ip(self, droplet_id=None, region=None, **kwargs): """ Create a new floating IP assigned to a droplet or reserved to a region. Either ``droplet_id`` or ``region`` must be specified, but not both. The returned `FloatingIP` object will represent the IP at the moment of ...
Create a new floating IP assigned to a droplet or reserved to a region. Either ``droplet_id`` or ``region`` must be specified, but not both. The returned `FloatingIP` object will represent the IP at the moment of creation; if the IP address is supposed to be assigned to a droplet, the a...
def _equaBreaks(self, orbit_index_period=24.): """Determine where breaks in an equatorial satellite orbit occur. Looks for negative gradients in local time (or longitude) as well as breaks in UT. Parameters ---------- orbit_index_period : float The change in...
Determine where breaks in an equatorial satellite orbit occur. Looks for negative gradients in local time (or longitude) as well as breaks in UT. Parameters ---------- orbit_index_period : float The change in value of supplied index parameter for a single orbit
def delocalization_analysis(self, defect_entry): """ Do delocalization analysis. To do this, one considers: i) sampling region of planar averaged electrostatic potential (freysoldt approach) ii) sampling region of atomic site averaged potentials (kumagai approach) iii...
Do delocalization analysis. To do this, one considers: i) sampling region of planar averaged electrostatic potential (freysoldt approach) ii) sampling region of atomic site averaged potentials (kumagai approach) iii) structural relaxation amount outside of radius considered in kumaga...
def find_executable(executable, path=None): """Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found. """ if path is None: path = os.environ['PATH'] path...
Tries to find 'executable' in the directories listed in 'path'. A string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']. Returns the complete filename or None if not found.
def parse_posting_id(text, city): """ Parse the posting ID from the Backpage ad. text -> The ad's HTML (or the a substring containing the "Post ID:" section) city -> The Backpage city of the ad """ parts = text.split('Post ID: ') if len(parts) == 2: post_id = parts[1].split(' ')[0] if p...
Parse the posting ID from the Backpage ad. text -> The ad's HTML (or the a substring containing the "Post ID:" section) city -> The Backpage city of the ad
def file_list(*packages, **kwargs): ''' List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*...
List the files that belong to a package. Not specifying any packages will return a list of _every_ file on the system's package database (not generally recommended). CLI Examples: .. code-block:: bash salt '*' pkg.file_list httpd salt '*' pkg.file_list httpd postfix salt '*' p...
def at(self, t): """At time ``t``, compute the target's position relative to the center. If ``t`` is an array of times, then the returned position object will specify as many positions as there were times. The kind of position returned depends on the value of the ``center`` att...
At time ``t``, compute the target's position relative to the center. If ``t`` is an array of times, then the returned position object will specify as many positions as there were times. The kind of position returned depends on the value of the ``center`` attribute: * Solar Sys...
def main(): """Main entry function.""" if len(sys.argv) < 3: print('Usage: <project-name> <filetype> <list-of-path to traverse>') print('\tfiletype can be python/cpp/all') exit(-1) _HELPER.project_name = sys.argv[1] file_type = sys.argv[2] allow_type = [] if file_type == ...
Main entry function.
def library_directories(self) -> typing.List[str]: """ The list of directories to all of the library locations """ def listify(value): return [value] if isinstance(value, str) else list(value) # If this is a project running remotely remove external library # ...
The list of directories to all of the library locations
def doeqdi(x, y, UP=False): """ Takes digitized x,y, data and returns the dec,inc, assuming an equal area projection Parameters __________________ x : array of digitized x from point on equal area projection y : array of igitized y from point on equal area projection UP : if...
Takes digitized x,y, data and returns the dec,inc, assuming an equal area projection Parameters __________________ x : array of digitized x from point on equal area projection y : array of igitized y from point on equal area projection UP : if True, is an upper hemisphere projection...
def jpath_parse(jpath): """ Parse given JPath into chunks. Returns list of dictionaries describing all of the JPath chunks. :param str jpath: JPath to be parsed into chunks :return: JPath chunks as list of dicts :rtype: :py:class:`list` :raises JPathException: in case of invalid JPath synt...
Parse given JPath into chunks. Returns list of dictionaries describing all of the JPath chunks. :param str jpath: JPath to be parsed into chunks :return: JPath chunks as list of dicts :rtype: :py:class:`list` :raises JPathException: in case of invalid JPath syntax
def remove_board(board_id): """remove board. :param board_id: board id (e.g. 'diecimila') :rtype: None """ log.debug('remove %s', board_id) lines = boards_txt().lines() lines = filter(lambda x: not x.strip().startswith(board_id + '.'), lines) boards_txt().write_lines(lines)
remove board. :param board_id: board id (e.g. 'diecimila') :rtype: None
def _load_same_codes(self, refresh=False): """Loads the Same Codes into this object""" if refresh is True: self._get_same_codes() else: self._cached_same_codes()
Loads the Same Codes into this object
def ip_check(*args, func=None): """Check if arguments are IP addresses.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, ipaddress._IPAddressBase): name = type(var).__name__ raise IPError( f'Function {func} expected IP address, {...
Check if arguments are IP addresses.
def build_pattern(body, features): '''Converts body into a pattern i.e. a point in the features space. Applies features to the body lines and sums up the results. Elements of the pattern indicate how many times a certain feature occurred in the last lines of the body. ''' line_patterns = apply_...
Converts body into a pattern i.e. a point in the features space. Applies features to the body lines and sums up the results. Elements of the pattern indicate how many times a certain feature occurred in the last lines of the body.
def input_dataset_from_dataframe(df, delays=(1, 2, 3), inputs=(1, 2, -1), outputs=None, normalize=True, verbosity=1): """ Build a dataset with an empty output/target vector Identical to `dataset_from_dataframe`, except that default values for 2 arguments: outputs: None """ return dataset_from_d...
Build a dataset with an empty output/target vector Identical to `dataset_from_dataframe`, except that default values for 2 arguments: outputs: None
def weapon_cooldown(self) -> Union[int, float]: """ Returns some time (more than game loops) until the unit can fire again, returns -1 for units that can't attack. Usage: if unit.weapon_cooldown == 0: await self.do(unit.attack(target)) elif unit.weapon_cooldown < 0: ...
Returns some time (more than game loops) until the unit can fire again, returns -1 for units that can't attack. Usage: if unit.weapon_cooldown == 0: await self.do(unit.attack(target)) elif unit.weapon_cooldown < 0: await self.do(unit.move(closest_allied_unit_becau...
def dist_location(dist): """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. """ egg_link = egg_link_path(...
Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is.
def bounding_box(self): """Bounding box (`~regions.BoundingBox`).""" xmin = self.center.x - self.radius xmax = self.center.x + self.radius ymin = self.center.y - self.radius ymax = self.center.y + self.radius return BoundingBox.from_float(xmin, xmax, ymin, ymax)
Bounding box (`~regions.BoundingBox`).
def check_frame_id(frame_id): """Check that the provided frame id is valid in Rapids language.""" if frame_id is None: return if frame_id.strip() == "": raise H2OValueError("Frame id cannot be an empty string: %r" % frame_id) for i, ch in enumerate(frame_id): # '$' character has ...
Check that the provided frame id is valid in Rapids language.
def namedb_get_account_diff(current, prior): """ Figure out what the expenditure difference is between two accounts. They must be for the same token type and address. Calculates current - prior """ if current['address'] != prior['address'] or current['type'] != prior['type']: raise Value...
Figure out what the expenditure difference is between two accounts. They must be for the same token type and address. Calculates current - prior
def partition(self, dimension): """ Partition subspace into desired dimension. :type dimension: int :param dimension: Maximum dimension to use. """ # Take leftmost 'dimension' input basis vectors for i, channel in enumerate(self.u): if self.v[i].shape...
Partition subspace into desired dimension. :type dimension: int :param dimension: Maximum dimension to use.
def _get_permission(self, authorizer_name, authorizer_lambda_function_arn): """Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission """ rest_api = ApiGateway...
Constructs and returns the Lambda Permission resource allowing the Authorizer to invoke the function. :returns: the permission resource :rtype: model.lambda_.LambdaPermission
def _fixup_cdef_enums(string, reg=re.compile(r"=\s*(\d+)\s*<<\s*(\d+)")): """Converts some common enum expressions to constants""" def repl_shift(match): shift_by = int(match.group(2)) value = int(match.group(1)) int_value = ctypes.c_int(value << shift_by).value return "= %s" % ...
Converts some common enum expressions to constants
def _report_error(self, request, exp): """When making the request, if an error happens, log it.""" message = ( "Failure to perform %s due to [ %s ]" % (request, exp) ) self.log.fatal(message) raise requests.RequestException(message)
When making the request, if an error happens, log it.
def getserialized(self, key, decoder_func=None, **kwargs): """ Gets the setting value as a :obj:`dict` or :obj:`list` trying :meth:`json.loads`, followed by :meth:`yaml.load`. :rtype: dict, list """ value = self.get(key, cast_func=None, **kwargs) if isinstance(value, (...
Gets the setting value as a :obj:`dict` or :obj:`list` trying :meth:`json.loads`, followed by :meth:`yaml.load`. :rtype: dict, list
def get(self, filepath): """ Get file details for the specified file. """ try: res = self.fs.get_file_details(filepath) res = res.to_dict() self.write(res) except OSError: raise tornado.web.HTTPError(404)
Get file details for the specified file.
def size_str(size_in_bytes): """Returns a human readable size string. If size_in_bytes is None, then returns "?? GiB". For example `size_str(1.5 * tfds.units.GiB) == "1.50 GiB"`. Args: size_in_bytes: `int` or `None`, the size, in bytes, that we want to format as a human-readable size string. """ ...
Returns a human readable size string. If size_in_bytes is None, then returns "?? GiB". For example `size_str(1.5 * tfds.units.GiB) == "1.50 GiB"`. Args: size_in_bytes: `int` or `None`, the size, in bytes, that we want to format as a human-readable size string.
def json_decode(data): """ Decodes the given JSON as primitives """ if isinstance(data, six.binary_type): data = data.decode('utf-8') return json.loads(data)
Decodes the given JSON as primitives
def _get_erred_shared_settings_module(self): """ Returns a LinkList based module which contains link to shared service setting instances in ERRED state. """ result_module = modules.LinkList(title=_('Shared provider settings in erred state')) result_module.template = 'admin/dashbo...
Returns a LinkList based module which contains link to shared service setting instances in ERRED state.
def object_new(self, template=None, **kwargs): """Creates a new object from an IPFS template. By default this creates and returns a new empty merkledag node, but you may pass an optional template argument to create a preformatted node. .. code-block:: python >>> c.object_n...
Creates a new object from an IPFS template. By default this creates and returns a new empty merkledag node, but you may pass an optional template argument to create a preformatted node. .. code-block:: python >>> c.object_new() {'Hash': 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqF...
def entityTriples(self, aURI): """ Builds all triples for an entity Note: if a triple object is a blank node (=a nested definition) we try to extract all relevant data recursively (does not work with sparql endpoins) 2015-10-18: updated """ aURI = aURI qr...
Builds all triples for an entity Note: if a triple object is a blank node (=a nested definition) we try to extract all relevant data recursively (does not work with sparql endpoins) 2015-10-18: updated