code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def gen_primes(): """ Generate an infinite sequence of prime numbers. """ D = {} q = 2 while True: if q not in D: yield q D[q * q] = [q] else: for p in D[q]: D.setdefault(p + q, []).append(p) del D[q] q += 1
Generate an infinite sequence of prime numbers.
def get_signed_area(self): """ Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up. """ accum = 0.0 for i in range(len(self.verts)): j = (i + 1) % len(self.v...
Return area of a simple (ie. non-self-intersecting) polygon. If verts wind anti-clockwise, this returns a negative number. Assume y-axis points up.
def find_dependencies_with_parent(self, dependent, parent): """Find all dependencies of the given revision caused by the given parent commit. This will be called multiple times for merge commits which have multiple parents. """ self.logger.info(" Finding dependencies of %s vi...
Find all dependencies of the given revision caused by the given parent commit. This will be called multiple times for merge commits which have multiple parents.
def newEntity(self, name, type, ExternalID, SystemID, content): """Create a new entity, this differs from xmlAddDocEntity() that if the document is None or has no internal subset defined, then an unlinked entity structure will be returned, it is then the responsability of the calle...
Create a new entity, this differs from xmlAddDocEntity() that if the document is None or has no internal subset defined, then an unlinked entity structure will be returned, it is then the responsability of the caller to link it to the document later or free it when not needed ...
def _get_manifest_string(self): """Returns the nextflow manifest config string to include in the config file from the information on the pipeline. Returns ------- str Nextflow manifest configuration string """ config_str = "" config_str += '...
Returns the nextflow manifest config string to include in the config file from the information on the pipeline. Returns ------- str Nextflow manifest configuration string
def get_next_base26(prev=None): """Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID. """ if not prev: return 'a' r = re.compile("^[a-z]*$") if not r.match(prev): raise ValueError("Inv...
Increment letter-based IDs. Generates IDs like ['a', 'b', ..., 'z', 'aa', ab', ..., 'az', 'ba', ...] Returns: str: Next base-26 ID.
def sync(self, videoQuality, limit=None, unwatched=False, **kwargs): """ Add current Movie library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection...
Add current Movie library section as sync item for specified device. See description of :func:`plexapi.library.LibrarySection.search()` for details about filtering / sorting and :func:`plexapi.library.LibrarySection.sync()` for details on syncing libraries and possible exceptions. P...
def _on_timeout(self, info: str = None) -> None: """Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information. """ self._timeout = None error_message = "Timeout {0}".format(info) i...
Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information.
def get(search="unsigned"): """ List all available plugins""" plugins = [] for i in os.walk('/usr/lib/nagios/plugins'): for f in i[2]: plugins.append(f) return plugins
List all available plugins
def filter_results(self, boxlist, num_classes): """Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS). """ # unwrap the boxlist to avoid additional overhead. # if we had multi-class NMS, we could perform this directly on th...
Returns bounding-box detection results by thresholding on scores and applying non-maximum suppression (NMS).
def privmsg(self, target, message): """ Sends a PRIVMSG to someone. Required arguments: * target - Who to send the message to. * message - Message to send. """ with self.lock: self.send('PRIVMSG ' + target + ' :' + message) if self.readable...
Sends a PRIVMSG to someone. Required arguments: * target - Who to send the message to. * message - Message to send.
def _LowerBoundSearch(partitions, hash_value): """Searches the partition in the partition array using hashValue. """ for i in xrange(0, len(partitions) - 1): if partitions[i].CompareTo(hash_value) <= 0 and partitions[i+1].CompareTo(hash_value) > 0: return i r...
Searches the partition in the partition array using hashValue.
def _flatten(lst): """ Flatten a nested list. """ if not isinstance(lst, (list, tuple)): return [lst] result = [] for item in lst: result.extend(_flatten(item)) return result
Flatten a nested list.
def get_synset_1000(self): """ Returns: dict: {cls_number: synset_id} """ fname = os.path.join(self.dir, 'synsets.txt') assert os.path.isfile(fname) lines = [x.strip() for x in open(fname).readlines()] return dict(enumerate(lines))
Returns: dict: {cls_number: synset_id}
def format_currency_field(__, prec, number, locale): """Formats a currency field.""" locale = Locale.parse(locale) currency = get_territory_currencies(locale.territory)[0] if prec is None: pattern, currency_digits = None, True else: prec = int(prec) pattern = locale.currency_...
Formats a currency field.
def tagAttributes(fdef_master_list,node,depth=0): '''recursively tag objects with sizes, depths and path names ''' if type(node)==list: for i in node: depth+=1 tagAttributes(fdef_master_list,i,depth) if type(node)==dict: for x in fdef_master_list: if jsNam...
recursively tag objects with sizes, depths and path names
def data(link): '''Returns a dictionary from requested link''' link = _remove_api_url_from_link(link) req = _get_from_dapi_or_mirror(link) return _process_req(req)
Returns a dictionary from requested link
def iterate_similarity_datasets(args): """Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset. """ for dataset_name in args.similarity_datasets: parameters = nlp.data.list_datasets(dataset_name) ...
Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the created dataset.
def get_encoder_from_vocab(vocab_filepath): """Get encoder from vocab file. If vocab is not found in output dir, it will be copied there by copy_vocab_to_output_dir to clarify the vocab used to generate the data. Args: vocab_filepath: path to vocab, either local or cns Returns: A SubwordTextEncoder...
Get encoder from vocab file. If vocab is not found in output dir, it will be copied there by copy_vocab_to_output_dir to clarify the vocab used to generate the data. Args: vocab_filepath: path to vocab, either local or cns Returns: A SubwordTextEncoder vocabulary object. None if the output_parallel_t...
def ap_state(value, failure_string=None): """ Converts a state's name, postal abbreviation or FIPS to A.P. style. Example usage: >> ap_state("California") 'Calif.' """ try: return statestyle.get(value).ap except: if failure_string: retur...
Converts a state's name, postal abbreviation or FIPS to A.P. style. Example usage: >> ap_state("California") 'Calif.'
def modify_ip_prefixes( config, config_file, variable_name, dummy_ip_prefix, reconfigure_cmd, keep_changes, changes_counter, ip_version): """Modify IP prefixes in Bird configuration. Depending on the configuration either removes or reports IP pref...
Modify IP prefixes in Bird configuration. Depending on the configuration either removes or reports IP prefixes found in Bird configuration for which we don't have a service check associated with them. Moreover, it adds the dummy IP prefix if it isn't present and ensures that the correct variable name i...
def available_edbg_ports(self): """ Finds available EDBG COM ports. :return: list of available ports """ ports_available = sorted(list(list_ports.comports())) edbg_ports = [] for iport in ports_available: port = iport[0] desc = iport[1] ...
Finds available EDBG COM ports. :return: list of available ports
def _load_types(root): """Returns {name: Type}""" def text(t): if t.tag == 'name': return '{name}' elif t.tag == 'apientry': return '{apientry}' out = [] if t.text: out.append(_escape_tpl_str(t.text)) for x in t: out.append(...
Returns {name: Type}
def remove_group_from_favorites(self, id): """ Remove group from favorites. Remove a group from the current user's favorites. """ path = {} data = {} params = {} # REQUIRED - PATH - id """the ID or SIS ID of the group to remove""" ...
Remove group from favorites. Remove a group from the current user's favorites.
def array_dualmap(ol,value_map_func,**kwargs): ''' from elist.elist import * ol = ['a','b','c','d'] def index_map_func(index,prefix,suffix): s = prefix +str(index+97)+ suffix return(s) def value_map_func(mapped_index,ele,prefix,suffix): s ...
from elist.elist import * ol = ['a','b','c','d'] def index_map_func(index,prefix,suffix): s = prefix +str(index+97)+ suffix return(s) def value_map_func(mapped_index,ele,prefix,suffix): s = prefix+mapped_index+': ' + str(ele) + suffix retu...
def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word)
Converts 'bad' characters in a string to underscores so they can be used as Ansible groups
def make_tx(version, tx_ins, tx_outs, lock_time, expiry=None, value_balance=0, tx_shielded_spends=None, tx_shielded_outputs=None, tx_witnesses=None, tx_joinsplits=None, joinsplit_pubkey=None, joinsplit_sig=None, binding_sig=None): ''' int, list(TxIn), list(TxOut), int, list(I...
int, list(TxIn), list(TxOut), int, list(InputWitness) -> Tx
def download(self, packageName, versionCode=None, offerType=1, expansion_files=False): """Download an app and return its raw data (APK file). Free apps need to be "purchased" first, in order to retrieve the download cookie. If you want to download an already purchased app, use *delivery* method....
Download an app and return its raw data (APK file). Free apps need to be "purchased" first, in order to retrieve the download cookie. If you want to download an already purchased app, use *delivery* method. Args: packageName (str): app unique ID (usually starting with 'com.') ...
def edit_standard_fwl_rules(self, firewall_id, rules): """Edit the rules for standard firewall. :param integer firewall_id: the instance ID of the standard firewall :param dict rules: the rules to be pushed on the firewall """ rule_svc = self.client['Network_Firewall_Update_Req...
Edit the rules for standard firewall. :param integer firewall_id: the instance ID of the standard firewall :param dict rules: the rules to be pushed on the firewall
def get_mode(self, gpio): """ Returns the gpio mode. gpio:= 0-53. Returns a value as follows . . 0 = INPUT 1 = OUTPUT 2 = ALT5 3 = ALT4 4 = ALT0 5 = ALT1 6 = ALT2 7 = ALT3 . . ... print(pi...
Returns the gpio mode. gpio:= 0-53. Returns a value as follows . . 0 = INPUT 1 = OUTPUT 2 = ALT5 3 = ALT4 4 = ALT0 5 = ALT1 6 = ALT2 7 = ALT3 . . ... print(pi.get_mode(0)) 4 ...
def open_connection(self): """Open an sqlite connection to the metadata database. By default the metadata database will be used in the plugin dir, unless an explicit path has been set using setmetadataDbPath, or overridden in QSettings. If the db does not exist it will be create...
Open an sqlite connection to the metadata database. By default the metadata database will be used in the plugin dir, unless an explicit path has been set using setmetadataDbPath, or overridden in QSettings. If the db does not exist it will be created. :raises: An sqlite.Error i...
def _format_args(): """Get JSON dump indentation and separates.""" # Ensure we can run outside a application/request context. try: pretty_format = \ current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] and \ not request.is_xhr except RuntimeError: pretty_format = Fal...
Get JSON dump indentation and separates.
def get_exif_tags(data, datetime_format='%c'): """Make a simplified version with common tags from raw EXIF data.""" logger = logging.getLogger(__name__) simple = {} for tag in ('Model', 'Make', 'LensModel'): if tag in data: if isinstance(data[tag], tuple): simple[ta...
Make a simplified version with common tags from raw EXIF data.
def read(filename, file_format=None): """Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data. """ # https://stackoverflow.com/q/4843173/353337 assert isinstance(filename, str) if not file_format:...
Reads an unstructured mesh with added data. :param filenames: The files to read from. :type filenames: str :returns mesh{2,3}d: The mesh data.
def poe_map(self, src, s_sites, imtls, trunclevel, rup_indep=True): """ :param src: a source object :param s_sites: a filtered SiteCollection of sites around the source :param imtls: intensity measure and levels :param trunclevel: truncation level :param rup_indep: True i...
:param src: a source object :param s_sites: a filtered SiteCollection of sites around the source :param imtls: intensity measure and levels :param trunclevel: truncation level :param rup_indep: True if the ruptures are independent :returns: a ProbabilityMap instance
def encode(arg, delimiter=None, encodeseq=None, encoded=tuple()): '''Encode a single argument for the file-system''' arg = coerce_unicode(arg, _c.FSQ_CHARSET) new_arg = sep = u'' delimiter, encodeseq = delimiter_encodeseq( _c.FSQ_DELIMITER if delimiter is None else delimiter, _c.FSQ_ENCO...
Encode a single argument for the file-system
def bind(context, block=False): """ Given the context, returns a decorator wrapper; the binder replaces the wrapped func with the value from the context OR puts this function in the context with the name. """ if block: def decorate(func): name = func.__name__.replace('__...
Given the context, returns a decorator wrapper; the binder replaces the wrapped func with the value from the context OR puts this function in the context with the name.
def get_item_bank_id_metadata(self): """get the metadata for item bank""" metadata = dict(self._item_bank_id_metadata) metadata.update({'existing_id_values': self.my_osid_object_form._my_map['itemBankId']}) return Metadata(**metadata)
get the metadata for item bank
def _finish(self): """ Closes and waits for subprocess to exit. """ if self._process.returncode is None: self._process.stdin.flush() self._process.stdin.close() self._process.wait() self.closed = True
Closes and waits for subprocess to exit.
def run(self): ''' Fire up halite! ''' salt.utils.process.appendproctitle(self.__class__.__name__) halite.start(self.hopts)
Fire up halite!
def add_error_class(klass, code): """ Maps an exception class to a string code. Used to map remoting C{onStatus} objects to an exception class so that an exception can be built to represent that error. An example:: >>> class AuthenticationError(Exception): ... pass ... ...
Maps an exception class to a string code. Used to map remoting C{onStatus} objects to an exception class so that an exception can be built to represent that error. An example:: >>> class AuthenticationError(Exception): ... pass ... >>> pyamf.add_error_class(Authenticati...
def clean(self): """ Validates the current instance. """ super().clean() if ( (self.user is None and not self.anonymous_user) or (self.user and self.anonymous_user) ): raise ValidationError( _('A permission should target either a user o...
Validates the current instance.
def _base_get_list(self, url, limit=None, *, query=None, order_by=None, batch=None): """ Returns a collection of drive items """ if limit is None or limit > self.protocol.max_top_value: batch = self.protocol.max_top_value params = {'$top': batch if batch else...
Returns a collection of drive items
def config_(dev=None, **kwargs): ''' Show or update config of a bcache device. If no device is given, operate on the cache set itself. CLI example: .. code-block:: bash salt '*' bcache.config salt '*' bcache.config bcache1 salt '*' bcache.config errors=panic journal_delay...
Show or update config of a bcache device. If no device is given, operate on the cache set itself. CLI example: .. code-block:: bash salt '*' bcache.config salt '*' bcache.config bcache1 salt '*' bcache.config errors=panic journal_delay_ms=150 salt '*' bcache.config bcache...
def serialize_rdf(update_graph, signing): '''Tweak rdflib's pretty-xml serialization of update_graph into the "indentical" representation as defined in http://mzl.la/x4XF6o ''' unsorted_s = update_graph.serialize(format = 'pretty-xml') unsorted_s = unsorted_s.replace('xmlns:rdf', 'xmlns:RDF') un...
Tweak rdflib's pretty-xml serialization of update_graph into the "indentical" representation as defined in http://mzl.la/x4XF6o
def execute(self): """ migrate storage """ repo = repository.PickleRepository(self.params.storage_path) clusters = [i[:-7] for i in os.listdir(self.params.storage_path) if i.endswith('.pickle')] if self.params.cluster: clusters = [x for x in clusters if x in...
migrate storage
def to_text_string(obj, encoding=None): """Convert `obj` to (unicode) text string""" if PY2: # Python 2 if encoding is None: return unicode(obj) else: return unicode(obj, encoding) else: # Python 3 if encoding is None: return str(ob...
Convert `obj` to (unicode) text string
def format_duration(seconds): """Formats a number of seconds using the best units.""" units, divider = get_time_units_and_multiplier(seconds) seconds *= divider return "%.3f %s" % (seconds, units)
Formats a number of seconds using the best units.
def get_bucket(): """ Get listing of S3 Bucket """ args = parser.parse_args() bucket = s3_bucket(args.aws_access_key_id, args.aws_secret_access_key, args.bucket_name) for b in bucket.list(): print(''.join([i if ord(i) < 128 else ' ' for i in b.name]))
Get listing of S3 Bucket
def generate(input_path, output_path=None, in_memory=False, safe_mode=False, error_context=None): """Executes the Statik site generator using the given parameters. """ project = StatikProject(input_path, safe_mode=safe_mode, error_context=error_context) return project.generate(output_path=output_path, i...
Executes the Statik site generator using the given parameters.
def getCatalogPixels(self): """ Return the catalog pixels spanned by this ROI. """ filenames = self.config.getFilenames() nside_catalog = self.config.params['coords']['nside_catalog'] nside_pixel = self.config.params['coords']['nside_pixel'] # All possible catalo...
Return the catalog pixels spanned by this ROI.
def lstm_seq2seq_internal_attention(inputs, targets, hparams, train, inputs_length, targets_length): """LSTM seq2seq model with attention, main step used for training.""" with tf.variable_scope("lstm_seq2seq_attention"): # Flatten inputs. inputs = common_layers.flatten4d3...
LSTM seq2seq model with attention, main step used for training.
def _is_valid(self, log: Optional[Logger] = None) -> bool: """ Determine whether the current contents are valid """ return self._validate(self, log)[0]
Determine whether the current contents are valid
def get_exif_data(filename): """Return a dict with the raw EXIF data.""" logger = logging.getLogger(__name__) img = _read_image(filename) try: exif = img._getexif() or {} except ZeroDivisionError: logger.warning('Failed to read EXIF data.') return None data = {TAGS.ge...
Return a dict with the raw EXIF data.
def _update_self_link(self, link, headers): '''Update the self link of this navigator''' self.self.props.update(link) # Set the self.type to the content_type of the returned document self.self.props['type'] = headers.get( 'Content-Type', self.DEFAULT_CONTENT_TYPE) sel...
Update the self link of this navigator
def _init_filename(self, filename=None, ext=None): """Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_extension` ...
Initialize the current filename :attr:`FileUtils.real_filename` of the object. Bit of a hack. - The first invocation must have ``filename != None``; this will set a default filename with suffix :attr:`FileUtils.default_extension` unless another one was supplied. - Subseque...
def ListingBox(listing, *args, **kwargs): " Delegate the boxing to the target's Box class. " obj = listing.publishable return obj.box_class(obj, *args, **kwargs)
Delegate the boxing to the target's Box class.
def channel_info(self, channel): """Fetch information about a channel.""" resource = self.RCHANNEL_INFO params = { self.PCHANNEL: channel, } response = self._fetch(resource, params) return response
Fetch information about a channel.
def gradient(self, q, t=0.): """ Compute the gradient of the potential at the given position(s). Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like The position to compute the value of the potential. If the ...
Compute the gradient of the potential at the given position(s). Parameters ---------- q : `~gala.dynamics.PhaseSpacePosition`, `~astropy.units.Quantity`, array_like The position to compute the value of the potential. If the input position object has no units (i.e. is an ...
def create_ticket_from_albaran(pk, list_lines): MODEL_SOURCE = SalesAlbaran MODEL_FINAL = SalesTicket url_reverse = 'CDNX_invoicing_ticketsaless_list' # type_doc msg_error_relation = _("Hay lineas asignadas a ticket") msg_error_not_found = _('Sales albaran not found') ...
context = {} if list_lines: new_list_lines = SalesLines.objects.filter( pk__in=[int(x) for x in list_lines] ).exclude( invoice__isnull=True ).values_list('pk') if new_list_lines: new_pk = SalesLines.objects.values_l...
def connect(self): """ Connect the instance to redis by checking the existence of its primary key. Do nothing if already connected. """ if self.connected: return pk = self._pk if self.exists(pk=pk): self._connected = True else: ...
Connect the instance to redis by checking the existence of its primary key. Do nothing if already connected.
def write_string(value, buff, byteorder='big'): """Write a string to a file-like object.""" data = value.encode('utf-8') write_numeric(USHORT, len(data), buff, byteorder) buff.write(data)
Write a string to a file-like object.
def run(self): ''' Execute salt-run ''' import salt.runner self.parse_args() # Setup file logging! self.setup_logfile_logger() verify_log(self.config) profiling_enabled = self.options.profiling_enabled runner = salt.runner.Runner(self.con...
Execute salt-run
def extract_status(self, status_headers): """ Extract status code only from status line """ self['status'] = status_headers.get_statuscode() if not self['status']: self['status'] = '-' elif self['status'] == '204' and 'Error' in status_headers.statusline: ...
Extract status code only from status line
def NumExpr(ex, signature=(), **kwargs): """ Compile an expression built using E.<variable> variables to a function. ex can also be specified as a string "2*a+3*b". The order of the input variables and their types can be specified using the signature parameter, which is a list of (name, type) pair...
Compile an expression built using E.<variable> variables to a function. ex can also be specified as a string "2*a+3*b". The order of the input variables and their types can be specified using the signature parameter, which is a list of (name, type) pairs. Returns a `NumExpr` object containing the com...
def pwarning(*args, **kwargs): """print formatted output to stderr with indentation control""" if should_msg(kwargs.get("groups", ["warning"])): # initialize colorama only if uninitialized global colorama_init if not colorama_init: colorama_init = True colorama.i...
print formatted output to stderr with indentation control
def get_holdings(self, account: SEPAAccount): """ Retrieve holdings of an account. :param account: SEPAAccount to retrieve holdings for. :return: List of Holding objects """ # init dialog with self._get_dialog() as dialog: hkwpd = self._find_highest_s...
Retrieve holdings of an account. :param account: SEPAAccount to retrieve holdings for. :return: List of Holding objects
def parse(json, query_path, expected_vars=NO_VARS): """ INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATIN...
INTENDED TO TREAT JSON AS A STREAM; USING MINIMAL MEMORY WHILE IT ITERATES THROUGH THE STRUCTURE. ASSUMING THE JSON IS LARGE, AND HAS A HIGH LEVEL ARRAY STRUCTURE, IT WILL yield EACH OBJECT IN THAT ARRAY. NESTED ARRAYS ARE HANDLED BY REPEATING THE PARENT PROPERTIES FOR EACH MEMBER OF THE NESTED ARRAY....
def start(check_time: int = 500) -> None: """Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed. """ io_loop = ioloop.IOLoop.current() if io_loop in _io_loops: return _io_loops[io_loop] = True...
Begins watching source files for changes. .. versionchanged:: 5.0 The ``io_loop`` argument (deprecated since version 4.1) has been removed.
async def run_task(self) -> None: '''Initialize the queue and spawn extra worker tasks if this if the first task. Then wait for work items to enter the task queue, and execute the `run()` method with the current work item.''' while self.running: try: item = ...
Initialize the queue and spawn extra worker tasks if this if the first task. Then wait for work items to enter the task queue, and execute the `run()` method with the current work item.
def profile_write(self, profile, outfile=None): """Write the profile to the output directory. Args: profile (dict): The dictionary containting the profile settings. outfile (str, optional): Defaults to None. The filename for the profile. """ # fully qualified ou...
Write the profile to the output directory. Args: profile (dict): The dictionary containting the profile settings. outfile (str, optional): Defaults to None. The filename for the profile.
def cleanup(self): "Purpose: Frees the GL resources for a render model" if self.m_glVertBuffer != 0: glDeleteBuffers(1, (self.m_glIndexBuffer,)) glDeleteVertexArrays( 1, (self.m_glVertArray,) ) glDeleteBuffers(1, (self.m_glVertBuffer,)) self.m_glInde...
Purpose: Frees the GL resources for a render model
def _read_configfile(self): """Read the config file and store it (when valid)""" rc = self.config_filename if not os.path.isabs(rc): rc = os.path.join(os.path.expanduser('~'), self.config_filename) # If there is a setup.cfg in the package, parse it files = [f for f in...
Read the config file and store it (when valid)
def render_context_with_title(self, context): """Render a page title and insert it into the context. This function takes in a context dict and uses it to render the page_title variable. It then appends this title to the context using the 'page_title' key. If there is already a page_titl...
Render a page title and insert it into the context. This function takes in a context dict and uses it to render the page_title variable. It then appends this title to the context using the 'page_title' key. If there is already a page_title key defined in context received then this funct...
def account_setup(remote, token=None, response=None, account_setup=None): """Setup user account.""" gh = GitHubAPI(user_id=token.remote_account.user_id) with db.session.begin_nested(): gh.init_account() # Create user <-> external id link. oauth_link_external_id( ...
Setup user account.
def truepath_relative(path, otherpath=None): """ Normalizes and returns absolute path with so specs Args: path (str): path to file or directory otherpath (None): (default = None) Returns: str: path_ CommandLine: python -m utool.util_path --exec-truepath_relative --sho...
Normalizes and returns absolute path with so specs Args: path (str): path to file or directory otherpath (None): (default = None) Returns: str: path_ CommandLine: python -m utool.util_path --exec-truepath_relative --show Example: >>> # ENABLE_DOCTEST ...
def get_publication_date(self, **kwargs): """Determine the creation date for the publication date.""" date_string = kwargs.get('content', '') date_match = CREATION_DATE_REGEX.match(date_string) month_match = CREATION_MONTH_REGEX.match(date_string) year_match = CREATION_YEAR_REGEX...
Determine the creation date for the publication date.
def post_values(self, values): """ Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint. :param values: Values to post, see M2X API docs for details :type values: dict :return: The API response, see M2X API docs ...
Method for `Post Data Stream Values <https://m2x.att.com/developer/documentation/v2/device#Post-Data-Stream-Values>`_ endpoint. :param values: Values to post, see M2X API docs for details :type values: dict :return: The API response, see M2X API docs for details :rtype: dict :...
def readline(self, timeout=1): # pylint: disable=unused-argument """ Readline implementation. :param timeout: Timeout, not used :return: Line read or None """ data = None if self.read_thread: # Ignore the timeout value, return imediately if no lines ...
Readline implementation. :param timeout: Timeout, not used :return: Line read or None
def sample_less_than_condition(choices_in, condition): """Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order. """ output = np....
Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order.
def write(self, output=None): """ Write association table to a file. """ if not output: outfile = self['output']+'_asn.fits' output = self['output'] else: outfile = output # Delete the file if it exists. if os.path.exists(outf...
Write association table to a file.
def input(self, data): """ 小数据片段拼接成完整数据包 如果内容足够则yield数据包 """ self.buf += data while len(self.buf) > HEADER_SIZE: data_len = struct.unpack('i', self.buf[0:HEADER_SIZE])[0] if len(self.buf) >= data_len + HEADER_SIZE: content = self.buf[HE...
小数据片段拼接成完整数据包 如果内容足够则yield数据包
def guess_external_url(local_host, port): """Return a URL that is most likely to route to `local_host` from outside. The point is that we may be running on a remote host from the user's point of view, so they can't access `local_host` from a Web browser just by typing ``http://localhost:12345/``. "...
Return a URL that is most likely to route to `local_host` from outside. The point is that we may be running on a remote host from the user's point of view, so they can't access `local_host` from a Web browser just by typing ``http://localhost:12345/``.
def join(self, word_blocks, float_part): """ join the words by first join lists in the tuple :param word_blocks: tuple :rtype: str """ word_list = [] length = len(word_blocks) - 1 first_block = word_blocks[0], start = 0 if length == 1 and ...
join the words by first join lists in the tuple :param word_blocks: tuple :rtype: str
def apply_augments(self, auglist, p_elem, pset): """Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants. """ for a in auglist: pa...
Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants.
def logged_api_call(func): """ Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): ...
Function decorator that causes the decorated API function or method to log calls to itself to a logger. The logger's name is the dotted module name of the module defining the decorated function (e.g. 'zhmcclient._cpc'). Parameters: func (function object): The original function being decorated. ...
def attempt_file_write( path: str, contents: typing.Union[str, bytes], mode: str = 'w', offset: int = 0 ) -> typing.Union[None, Exception]: """ Attempts to write the specified contents to a file and returns None if successful, or the raised exception if writing failed. ...
Attempts to write the specified contents to a file and returns None if successful, or the raised exception if writing failed. :param path: The path to the file that will be written :param contents: The contents of the file to write :param mode: The mode in which the file wil...
def close(self): """ Closing a cursor just exhausts all remaining data. """ conn = self.connection if conn is None: return try: while self.nextset(): pass finally: self.connection = None
Closing a cursor just exhausts all remaining data.
def _find_base_tds_url(catalog_url): """Identify the base URL of the THREDDS server from the catalog URL. Will retain URL scheme, host, port and username/password when present. """ url_components = urlparse(catalog_url) if url_components.path: return catalog_url.split(url_components.path)[0...
Identify the base URL of the THREDDS server from the catalog URL. Will retain URL scheme, host, port and username/password when present.
def __do_query_into_hash(conn, sql_str): ''' Perform the query that is passed to it (sql_str). Returns: results in a dict. ''' mod = sys._getframe().f_code.co_name log.debug('%s<--(%s)', mod, sql_str) rtn_results = [] try: cursor = conn.cursor() except MySQLdb.MySQ...
Perform the query that is passed to it (sql_str). Returns: results in a dict.
def _CronJobFromRow(self, row): """Creates a cronjob object from a database result row.""" (job, create_time, enabled, forced_run_requested, last_run_status, last_run_time, current_run_id, state, leased_until, leased_by) = row job = rdf_cronjobs.CronJob.FromSerializedString(job) job.current_run_id...
Creates a cronjob object from a database result row.
def checks(similarities, verbose = False): """Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-se...
Check that a matrix is a proper similarity matrix and bring appropriate changes if applicable. Parameters ---------- similarities : array of shape (n_samples, n_samples) A matrix of pairwise similarities between (sub)-samples of the data-set. verbose : Boolean, optional (default = Fa...
def _get_service_instance(host, username, password, protocol, port, mechanism, principal, domain): ''' Internal method to authenticate with a vCenter server or ESX/ESXi host and return the service instance object. ''' log.trace('Retrieving new service instance') token =...
Internal method to authenticate with a vCenter server or ESX/ESXi host and return the service instance object.
def get_vardict_command(data): """ convert variantcaller specification to proper vardict command, handling string or list specification """ vcaller = dd.get_variantcaller(data) if isinstance(vcaller, list): vardict = [x for x in vcaller if "vardict" in x] if not vardict: ...
convert variantcaller specification to proper vardict command, handling string or list specification
def find_action(self, action_name): """Find an action by name. Convenience method that searches through all the services offered by the Server for an action and returns an Action instance. If the action is not found, returns None. If multiple actions with the same name are found ...
Find an action by name. Convenience method that searches through all the services offered by the Server for an action and returns an Action instance. If the action is not found, returns None. If multiple actions with the same name are found it returns the first one.
def get_photo_url(photo_id): """Request the photo download url with the photo id :param photo_id: The photo id of flickr :type photo_id: str :return: Photo download url :rtype: str """ args = _get_request_args( 'flickr.photos.getSizes', photo_id=photo_id ) resp = requ...
Request the photo download url with the photo id :param photo_id: The photo id of flickr :type photo_id: str :return: Photo download url :rtype: str
def verify(backup_path, fast): """Verify a existing backup""" from PyHardLinkBackup.phlb.verify import verify_backup verify_backup(backup_path, fast)
Verify a existing backup
def fit(self, X, y=None, **kwargs): """Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-...
Fit encoder according to X and y. Parameters ---------- X : array-like, shape = [n_samples, n_features] Training vectors, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape = [n_samples] Target va...
def num2term(num, fs, conj=False): """Convert *num* into a min/max term in an N-dimensional Boolean space. The *fs* argument is a sequence of :math:`N` Boolean functions. There are :math:`2^N` points in the corresponding Boolean space. The dimension number of each function is its index in the sequence....
Convert *num* into a min/max term in an N-dimensional Boolean space. The *fs* argument is a sequence of :math:`N` Boolean functions. There are :math:`2^N` points in the corresponding Boolean space. The dimension number of each function is its index in the sequence. The *num* argument is an int in rang...
def predecessors(self, node): """Returns list of the predecessors of a node as DAGNodes.""" if isinstance(node, int): warnings.warn('Calling predecessors() with a node id is deprecated,' ' use a DAGNode instead', DeprecationWarning, 2) ...
Returns list of the predecessors of a node as DAGNodes.