text
stringlengths
78
104k
score
float64
0
0.18
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain): """Run the event loop, ask the user if we should continue if an exception is caught. Use this function instead of NSApplicationMain(). """ if argv is None: argv = sys.argv if pdb...
0.002096
def from_config(cls, filename): """ Create a TelegramObserver from a given configuration file. The file can be in any format supported by Sacred (.json, .pickle, [.yaml]). It has to specify a ``token`` and a ``chat_id`` and can optionally set ``silent_completion``,``comp...
0.002051
def session(self, create=True): """ Used to created default session """ if hasattr(self.local, 'session'): return self.local.session else: if create: s = Session(self.name) self.local.session = s return s
0.006329
def _get_result(self) -> float: """Return current measurement result in lx.""" try: data = self._bus.read_word_data(self._i2c_add, self._mode) self._ok = True except OSError as exc: self.log_error("Bad reading in bus: %s", exc) self._ok = False ...
0.00381
def validate_and_get_warnings(self): """ Validates/checks a given GTFS feed with respect to a number of different issues. The set of warnings that are checked for, can be found in the gtfs_validator.ALL_WARNINGS Returns ------- warnings: WarningsContainer """ ...
0.006525
def parse_data(self, logfile): """Parse data from data stream and replace object lines. :param logfile: [required] Log file data stream. :type logfile: str """ for line in logfile: stripped_line = line.strip() parsed_line = Line(stripped_line) ...
0.00363
def variables(self): '''Generator which returns all of the statements in all of the variables tables''' for table in self.tables: if isinstance(table, VariableTable): # FIXME: settings have statements, variables have rows WTF? :-( for statement in table.rows: ...
0.007463
def check_initializers(initializers, keys): """Checks the given initializers. This checks that `initializers` is a dictionary that only contains keys in `keys`, and furthermore the entries in `initializers` are functions or further dictionaries (the latter used, for example, in passing initializers to module...
0.006545
def p_chr(p): """ string : CHR arg_list """ if len(p[2]) < 1: syntax_error(p.lineno(1), "CHR$ function need at less 1 parameter") p[0] = None return for i in range(len(p[2])): # Convert every argument to 8bit unsigned p[2][i].value = make_typecast(TYPE.ubyte, p[2][i].va...
0.002457
def application(self, func): """Parse the function application subgrammar. Function application can, conceptually, be thought of as a mixfix operator, similar to the way array subscripting works. However, it is not clear at this point whether we want to allow it to work as such, ...
0.001349
def load_config(self, config_path=None): """ Load application configuration from a file and merge it with the default configuration. If the ``FEDORA_MESSAGING_CONF`` environment variable is set to a filesystem path, the configuration will be loaded from that location. Ot...
0.003327
def edit_config_input_with_inactive(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") edit_config = ET.Element("edit_config") config = edit_config input = ET.SubElement(edit_config, "input") with_inactive = ET.SubElement(input, "with-inacti...
0.006438
def delete_activity(self, activity_id=None): """Deletes the Activity identified by the given Id. arg: activityId (osid.id.Id): the Id of the Activity to delete raise: NotFound - an Activity was not found identified by the given Id raise: NullArgument...
0.00207
def register_workflow(self, name, workflow): """Register an workflow to be showed in the workflows list.""" assert name not in self.workflows self.workflows[name] = workflow
0.010152
def click_window_multiple(self, window, button, repeat=2, delay=100000): """ Send a one or more clicks for a specific mouse button at the current mouse location. :param window: The window you want to send the event to or CURRENTWINDOW :param button: The m...
0.003003
def child_set(self, child, **kwargs): """Set a child properties on the given child to key/value pairs.""" for name, value in kwargs.items(): name = name.replace('_', '-') self.child_set_property(child, name, value)
0.007843
def load_sparql(self, sparql_endpoint, verbose=False, hide_base_schemas=True, hide_implicit_types=True, hide_implicit_preds=True, credentials=None): """ Set up a SPARQLStore backend as a virtual ontospy g...
0.007218
def deserialize(cls, raw_bytes): """ Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other subclass of ``Part`` would have a ``Response`` as a part) this merely has to parse the raw bytes and discard the result...
0.004751
def user_getmedia(userids=None, **kwargs): ''' .. versionadded:: 2016.3.0 Retrieve media according to the given parameters .. note:: This function accepts all standard usermedia.get properties: keyword argument names differ depending on your zabbix version, see here__. .. __: ...
0.003465
def hurst(X): """ Compute the Hurst exponent of X. If the output H=0.5,the behavior of the time-series is similar to random walk. If H<0.5, the time-series cover less "distance" than a random walk, vice verse. Parameters ---------- X list a time series Returns ------...
0.00093
def auto_unit(self, number, low_precision=False, min_symbol='K' ): """Make a nice human-readable string out of number. Number of decimal places increases as quantity approaches 1. CASE: 613421788 RESULT: 585M low_precision: ...
0.002691
def show_context_menu(self, item, mouse_pos=None): "Open a popup menu with options regarding the selected object" if item: d = self.tree.GetItemData(item) if d: obj = d.GetData() if obj: # highligh and store the selected object:...
0.005157
def get_accessibility_type_metadata(self): """Gets the metadata for an accessibility type. return: (osid.Metadata) - metadata for the accessibility types *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.logging.LogEntryForm.ge...
0.007678
def validate_args(func: Method, *args: Any, **kwargs: Any) -> Method: """ Check if the request's arguments match a function's signature. Raises TypeError exception if arguments cannot be passed to a function. Args: func: The function to check. args: Positional arguments. kwargs...
0.002045
def set_property_batch(self, remote_path, option): """Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: ...
0.008307
def init(i): # pragma: no cover """ Input: {} Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ global cfg, work, initialized, paths_repos, type_lon...
0.030906
def avail_images(call=None): ''' Return a dict of all available images on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The avail_images function must be called with ' '-f or --function, or with the --list-images option' ) compconn = get_co...
0.000368
def get_external_references(self): """ Iterator that returns all the external references of the markable @rtype: L{CexternalReference} @return: the external references """ for ext_ref_node in self.node.findall('externalReferences'): ext_refs_obj = CexternalRef...
0.00495
def apply_transform(self, transform): """ Apply a homogenous transformation to the PointCloud object in- place. Parameters -------------- transform : (4, 4) float Homogenous transformation to apply to PointCloud """ self.vertices = transformatio...
0.004662
def oom_components(Ct, C2t, rank_ind=None, lcc=None, tol_one=1e-2): """ Compute OOM components and eigenvalues from count matrices: Parameters ---------- Ct : ndarray(N, N) count matrix from data C2t : sparse csc-matrix (N*N, N) two-step count matrix from data for all states, co...
0.001171
def truncate(self, size): """ Change the size of this file. This usually extends or shrinks the size of the file, just like the ``truncate()`` method on Python file objects. :param size: the new size of the file """ self.sftp._log( DEBUG, "truncate({...
0.004049
def do_youtube_dl(worker, site, page): ''' Runs youtube-dl configured for `worker` and `site` to download videos from `page`. Args: worker (brozzler.BrozzlerWorker): the calling brozzler worker site (brozzler.Site): the site we are brozzling page (brozzler.Page): the page we are...
0.000806
def delete_group(self, group_id, keep_non_orphans=False, keep_orphans=False): """ Delete a group trigger :param group_id: ID of the group trigger to delete :param keep_non_orphans: if True converts the non-orphan member triggers to standard triggers :param keep_orphans: if True ...
0.010239
def send_contributor_email(self, contributor): """Send an EmailMessage object for a given contributor.""" ContributorReport( contributor, month=self.month, year=self.year, deadline=self._deadline, start=self._start, end=self._end ...
0.005988
def allow_pgcodes(cr, *codes): """Context manager that will omit specified error codes. E.g., suppose you expect a migration to produce unique constraint violations and you want to ignore them. Then you could just do:: with allow_pgcodes(cr, psycopg2.errorcodes.UNIQUE_VIOLATION): cr.ex...
0.00058
def getContinuousSet(self, id_): """ Returns the ContinuousSet with the specified id, or raises a ContinuousSetNotFoundException otherwise. """ if id_ not in self._continuousSetIdMap: raise exceptions.ContinuousSetNotFoundException(id_) return self._continuous...
0.006006
def _reduce_logsumexp(input_tensor, axis=None, keepdims=False, name=None): # pylint: disable=unused-argument """Computes `log(sum(exp(input_tensor))) along the specified axis.""" try: return scipy_special.logsumexp( input_tensor, axis=_astuple(axis), keepdims=keepdims) except NotImplementedError: ...
0.008065
def predict_is(self, h): """ Outputs predictions for the Aggregate algorithm on the in-sample data Parameters ---------- h : int How many steps to run the aggregating algorithm on Returns ---------- - pd.DataFrame of ensemble predictions """...
0.011494
async def get_messages(self, name): """Get stored messages for a service. Args: name (string): The name of the service to get messages from. Returns: list(ServiceMessage): A list of the messages stored for this service """ resp = await self.send_command...
0.00956
def parse_markdown_readme(): """ Convert README.md to RST via pandoc, and load into memory (fallback to LONG_DESCRIPTION on failure) """ # Attempt to run pandoc on markdown file import subprocess try: subprocess.call( ['pandoc', '-t', 'rst', '-o', 'README.rst', 'README.md...
0.001637
def get_nfd_quick_check_property(value, is_bytes=False): """Get `NFD QUICK CHECK` property.""" obj = unidata.ascii_nfd_quick_check if is_bytes else unidata.unicode_nfd_quick_check if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['nfdquickcheck'].get(negated...
0.006881
def capture_events(receiver, dest): """ Capture all events sent to `receiver` in the sequence `dest`. This is a generator, and it is best used with ``yield from``. The observable effect of using this generator with ``yield from`` is identical to the effect of using `receiver` with ``yield from`` dir...
0.000484
def best_value(Y,sign=1): ''' Returns a vector whose components i are the minimum (default) or maximum of Y[:i] ''' n = Y.shape[0] Y_best = np.ones(n) for i in range(n): if sign == 1: Y_best[i]=Y[:(i+1)].min() else: Y_best[i]=Y[:(i+1)].max() return Y_b...
0.01548
def inverted(arg): """Yield the inverse items of the provided object. If *arg* has a :func:`callable` ``__inverted__`` attribute, return the result of calling it. Otherwise, return an iterator over the items in `arg`, inverting each item on the fly. *See also* :attr:`bidict.BidirectionalMappi...
0.001961
def _parse_subnet(self, subnet_dict): """Return the subnet, start, end, gateway of a subnet. """ if not subnet_dict: return alloc_pool = subnet_dict.get('allocation_pools') cidr = subnet_dict.get('cidr') subnet = cidr.split('/')[0] start = alloc_pool[0].get('s...
0.003373
def is_binary(filename): """ :param filename: File to check. :returns: True if it's a binary file, otherwise False. """ logger.debug('is_binary: %(filename)r', locals()) # Check if the file extension is in a list of known binary types binary_extensions = ['pyc', 'iso', 'zip', 'pdf'] for...
0.001869
def was_suicide(self): ''' Checks if the king of the other side is attacked. Such a position is not valid and could only be reached by an illegal move. ''' return self.is_attacked_by(self.turn, self.king_squares[self.turn ^ 1])
0.011236
def _get_database(self, options): """Get the database to restore.""" database_name = options.get('database') if not database_name: if len(settings.DATABASES) > 1: errmsg = "Because this project contains more than one database, you"\ " must specify ...
0.004666
async def fetch_data(self): """Get the latest data from EBox.""" # Get http session await self._get_httpsession() # Get login page token = await self._get_login_page() # Post login page await self._post_login_page(token) # Get home data home_data =...
0.003854
def register_resources(klass, registry, resource_class): """ meta model subscriber on resource registration. We watch for PHD event that provides affected entities and register the health-event filter to the resources. """ services = {'acm-certificate', 'directconnect', 'dms-ins...
0.006678
def get_illegal_targets(part, include): """ Retrieve the illegal parent parts where `Part` can be moved/copied. :param part: `Part` to be moved/copied. :type part: :class:`Part` :param include: `Set` object with id's to be avoided as target parent `Part` :type include: set :return: `List` o...
0.003571
def from_string(cls, key, key_id=None): """Construct an Signer instance from a private key in PEM format. Args: key (str): Private key in PEM format. key_id (str): An optional key id used to identify the private key. Returns: google.auth.crypt.Signer: The co...
0.001455
def root_rhx_gis(self) -> Optional[str]: """rhx_gis string returned in the / query.""" if self.is_logged_in: # At the moment, rhx_gis seems to be required for anonymous requests only. By returning None when logged # in, we can save the root_rhx_gis lookup query. retur...
0.006508
def indexes(self, collection=None): """Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list) """ indexes = [] for collection_name in self.collections...
0.008389
def get_bounding_box(font): """ Returns max and min bbox of given truetype font """ ymin = 0 ymax = 0 if font.sfntVersion == 'OTTO': ymin = font['head'].yMin ymax = font['head'].yMax else: for g in font['glyf'].glyphs: char = font['glyf'][g] if hasattr...
0.001988
def addOutParameter(self, name, type, namespace=None, element_type=0): """Add an output parameter description to the call info.""" parameter = ParameterInfo(name, type, namespace, element_type) self.outparams.append(parameter) return parameter
0.007273
def tokenize_sents(string): """ Tokenize input text to sentences. :param string: Text to tokenize :type string: str or unicode :return: sentences :rtype: list of strings """ string = six.text_type(string) spans = [] for match in re.finditer('[^\s]+', string): spans.appe...
0.001894
def _extract_fund(l, _root): """ Creates flat funding dictionary. :param list l: Funding entries """ logger_ts.info("enter _extract_funding") for idx, i in enumerate(l): for k, v in i.items(): _root['funding' + str(idx + 1) + '_' + k] = v return _root
0.006689
async def _cancel_payloads(self): """Cancel all remaining payloads""" for task in self._tasks: task.cancel() await asyncio.sleep(0) for task in self._tasks: while not task.done(): await asyncio.sleep(0.1) task.cancel()
0.006452
def query(cls, automation=None, package=None, status=None, name=None, created_by=None, created_from=None, created_to=None, order_by=None, order=None, offset=None, limit=None, api=None): """ Query (List) automation runs. :param name: Automation run name :param ...
0.002613
def render(self): """Runs the render until thread flag is set. Returns ------- self """ while not self._stop_spinner.is_set(): self._render_frame() time.sleep(0.001 * self._interval) return self
0.007273
def iteritems(self, **options): '''Return a query interator with (id, object) pairs.''' iter = self.query(**options) while True: obj = iter.next() yield (obj.id, obj)
0.009346
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: ...
0.005272
def display_eventtype(self): """Read the list of event types in the annotations and update widgets. """ if self.annot is not None: event_types = sorted(self.annot.event_types, key=str.lower) else: event_types = [] self.idx_eventtype.clear() evtty...
0.002616
def remove_all_gap_columns( self ): """ Remove any columns containing only gaps from alignment components, text of components is modified IN PLACE. """ seqs = [] for c in self.components: try: seqs.append( list( c.text ) ) except Ty...
0.020471
def _make_gelf_dict(self, record): """Create a dictionary representing a Graylog GELF log from a python :class:`logging.LogRecord` :param record: :class:`logging.LogRecord` to create a Graylog GELF log from. :type record: logging.LogRecord :return: dictionary repres...
0.002278
def iter_teams(self, number=-1, etag=None): """Iterate over teams that are part of this organization. :param int number: (optional), number of teams to return. Default: -1 returns all available teams. :param str etag: (optional), ETag from a previous request to the same ...
0.005825
def select(self): """ generate the selection """ if self.condition is not None: return self.table.table.read_where(self.condition.format(), start=self.start, stop=self.stop) ...
0.004032
def storeToXML(self, out, comment=None, encoding='UTF-8'): """ Write the `Properties` object's entries (in unspecified order) in XML properties format to ``out``. :param out: a file-like object to write the properties to :type out: binary file-like object :param comment:...
0.002782
def rule_command_cmdlist_interface_h_interface_ge_leaf_interface_gigabitethernet_leaf(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index_key = ET.SubElement(rule, "index") ...
0.0044
def makedoedict(str1): """makedoedict""" blocklist = str1.split('..') blocklist = blocklist[:-1]#remove empty item after last '..' blockdict = {} belongsdict = {} for num in range(0, len(blocklist)): blocklist[num] = blocklist[num].strip() linelist = blocklist[num].split(os.lines...
0.006579
def make_value_from_env(self, param, value_type, function): """ get environment variable """ value = os.getenv(param) if value is None: self.notify_user("Environment variable `%s` undefined" % param) return self.value_convert(value, value_type)
0.006579
def register_deregister(notifier, event_type, callback=None, args=None, kwargs=None, details_filter=None, weak=False): """Context manager that registers a callback, then deregisters on exit. NOTE(harlowja): if the callback is none, then this registers nothing, wh...
0.001122
def run(self): """ Run the server. Returns with system error code. """ normalized = os.path.normpath(self.path) + ("/" if self.path.endswith("/") else "") if self.path != normalized: sys.stderr.write("Please use full path '%s'" % (normalized,)) return -1 self.bu...
0.005602
def list_handler(args): """usage: {program} list List the anchors for a file. """ repo = open_repository(None) for anchor_id, anchor in repo.items(): print("{} {}:{} => {}".format(anchor_id, anchor.file_path.relative_to(repo.root), ...
0.002494
def complete_block(self): """Return code lines **with** bootstrap""" return "".join(line[SOURCE] for line in self._boot_lines + self._source_lines)
0.018405
def set_frequencies(self, freq, rg=None, setMaxfeq=True, setMinfreq=True, setSpeed=True): ''' Set cores frequencies freq: int frequency in KHz rg: list of range of cores setMaxfeq: set the maximum frequency, default to true setMinfreq: set the minimum frequency, default ...
0.013711
def create_class_instance(element, element_id, doc_id): """ given an Salt XML element, returns a corresponding `SaltElement` class instance, i.e. a SaltXML `SToken` node will be converted into a `TokenNode`. Parameters ---------- element : lxml.etree._Element an `etree._Element` is ...
0.001161
def fasta_file_to_dict(fasta_file, id=True, header=False, seq=False): """Returns a dict from a fasta file and the number of sequences as the second return value. fasta_file can be a string path or a file object. The key of fasta_dict can be set using the keyword arguments and results in a combination of...
0.003413
def _get_files_recursively(rootdir): """Sometimes, we want to use this tool with non-git repositories. This function allows us to do so. """ output = [] for root, dirs, files in os.walk(rootdir): for filename in files: output.append(os.path.join(root, filename)) return outpu...
0.003115
def get_line_indent(token): """Finds the indent of the line the token starts in.""" start = token.start_mark.buffer.rfind('\n', 0, token.start_mark.pointer) + 1 content = start while token.start_mark.buffer[content] == ' ': content += 1 return conten...
0.00304
def pre_serialize(self, raw, pkt, i): ''' Set length of the header based on ''' self.length = len(raw) + OpenflowHeader._MINLEN
0.012579
def name(self): """Returns the real name of the franchise given the team ID. Examples: 'nwe' -> 'New England Patriots' 'sea' -> 'Seattle Seahawks' :returns: A string corresponding to the team's full name. """ doc = self.get_main_doc() headerwords = doc('...
0.004124
def lookups(self): "Yields (lookup, display, no_argument) pairs" for filter in self._filters: yield filter.key, filter.display, filter.no_argument
0.011494
def run_per_switch_cmds(self, switch_cmds): """Applies cmds to appropriate switches This takes in a switch->cmds mapping and runs only the set of cmds specified for a switch on that switch. This helper is used for applying/removing ACLs to/from interfaces as this config will vary ...
0.003906
def convert_cidr(cidr): ''' returns the network address, subnet mask and broadcast address of a cidr address .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' network.convert_cidr 172.31.0.0/16 ''' ret = {'network': None, 'netmask': None, ...
0.003241
def safe_call(request: Request, methods: Methods, *, debug: bool) -> Response: """ Call a Request, catching exceptions to ensure we always return a Response. Args: request: The Request object. methods: The list of methods that can be called. debug: Include more information in error ...
0.003221
def conf_budget(self, budget): """ Set limit on the number of conflicts. """ if self.maplesat: pysolvers.maplecm_cbudget(self.maplesat, budget)
0.010417
def import_data(self, data): """Import additional data for tuning Parameters ---------- data: a list of dictionarys, each of which has at least two keys, 'parameter' and 'value' """ _completed_num = 0 for trial_info in data: logger.info("Im...
0.008295
def process_text(text, pmid=None, python2_path=None): """Processes the specified plain text with TEES and converts output to supported INDRA statements. Check for the TEES installation is the TEES_PATH environment variable, and configuration file; if not found, checks candidate paths in tees_candidate_p...
0.001442
def save_ndarray_to_fits(array=None, file_name=None, main_header=None, cast_to_float=True, crpix1=None, crval1=None, cdelt1=None, overwrite=True): """Save numpy array(s) into a FITS file with the provided filename. ...
0.000202
def _Rzderiv(self,R,z,phi=0.,t=0.): #pragma: no cover """ NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time...
0.023991
def save_inst(self, obj): """Inner logic to save instance. Based off pickle.save_inst""" cls = obj.__class__ # Try the dispatch table (pickle module doesn't do it) f = self.dispatch.get(cls) if f: f(self, obj) # Call unbound method with explicit self ret...
0.001663
def decode_id_token(token, client): """ Represent the ID Token as a JSON Web Token (JWT). Return a hash. """ keys = get_client_alg_keys(client) return JWS().verify_compact(token, keys=keys)
0.004695
def __configure_canvas(self, *args): """ Private function to configure the internal Canvas. Changes the width of the canvas to fit the interior Frame :param args: Tkinter event """ if self.interior.winfo_reqwidth() is not self._canvas.winfo_width(): ...
0.010309
def get_short_uid_dict(self, query=None): """Create a dictionary of shortend UIDs for all contacts. All arguments are only used if the address book is not yet initialized and will just be handed to self.load(). :param query: see self.load() :type query: str :returns: th...
0.001136
def _read_dict(self, f): """ Converts h5 groups to dictionaries """ d = {} for k, item in f.items(): if type(item) == h5py._hl.dataset.Dataset: v = item.value if type(v) == np.string_: v = str(v) if type(v) =...
0.002326
def restrict_joins(self, q, bindings): """ Restrict the joins across all tables referenced in the database query to those specified in the model for the relevant dimensions. If a single table is used for the query, no unnecessary joins are performed. If more than one table are re...
0.004644
def read_file(self, file_name, section=None): """Read settings from specified ``section`` of config file.""" file_name, section = self.parse_file_name_and_section(file_name, section) if not os.path.isfile(file_name): raise SettingsFileNotFoundError(file_name) parser = self.ma...
0.002629
def max_end(self): """ Retrieves the maximum index. :return: """ return max(len(self.input_string), self._max_end) if self.input_string else self._max_end
0.015464