text
stringlengths
78
104k
score
float64
0
0.18
def get_instance( model, method="file", img_dir=None, data_dir=None, bucket=None ): """Return an instance of ConsumeStore.""" global _instances if not isinstance(model, ConsumeModel): raise TypeError( "get_instance() expects a parker.ConsumeModel derivative." ) i...
0.001156
def find_articulation_vertices(graph): """Finds all of the articulation vertices within a graph. Returns a list of all articulation vertices within the graph. Returns an empty list for an empty graph. """ articulation_vertices = [] all_nodes = graph.get_all_node_ids() if len(all_nodes) == ...
0.001235
def compute(self, text, # text for which to find the most similar event lang = "eng"): # language in which the text is written """ compute the list of most similar events for the given text """ params = { "lang": lang, "text": text, "topClusters...
0.017327
def formula_1980(household, period, parameters): ''' To compute this allowance, the 'rent' value must be provided for the same month, but 'housing_occupancy_status' is not necessary. ''' return household('rent', period) * parameters(period).benefits.housing_allowance
0.013378
def open(self, url, method='get', **kwargs): """Open a URL. :param str url: URL to open :param str method: Optional method; defaults to `'get'` :param kwargs: Keyword arguments to `Session::request` """ response = self.session.request(method, url, **self._build_send_arg...
0.00813
def _TypecheckDecorator(subject=None, **kwargs): """Dispatches type checks based on what the subject is. Functions or methods are annotated directly. If this method is called with keyword arguments only, return a decorator. """ if subject is None: return _TypecheckDecoratorFactory(kwargs) elif inspect....
0.011086
def get_fields(self): """ Return all field objects :rtype: a list of :class:`EncodedField` objects """ l = [] for i in self.classes.class_def: for j in i.get_fields(): l.append(j) return l
0.01083
def generate_map_chart_file(qtl_matrix, lod_threshold, map_chart_file='MapChart.map'): """ This function converts our QTL matrix file into a MapChart input file. :arg qtl_matrix: the path to the QTL matrix file generated by the plugin. :arg lod_threshold: threshold u...
0.000768
def _convert_size(self, size_str): """Convert units to GB""" suffix = size_str[-1] if suffix == 'K': multiplier = 1.0 / (1024.0 * 1024.0) elif suffix == 'M': multiplier = 1.0 / 1024.0 elif suffix == 'T': multiplier = 1024.0 else: ...
0.004098
def _ensure_format(rule, attribute, res_dict): """Verifies that attribute in res_dict is properly formatted. Since, in the .ini-files, lists are specified as ':' separated text and UUID values can be plain integers we need to transform any such values into proper format. Empty strings are converted to ...
0.001025
def get_elasticache_clusters_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would...
0.001817
def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument ''' Remove packages using ``apk del``. name The name of the package to be deleted. Multiple Package Options: pkgs A list of packages to delete. Must be passed as a python list. The ...
0.001288
def _AssAttr(self, t): """ Handle assigning an attribute of an object """ self._dispatch(t.expr) self._write('.'+t.attrname)
0.012821
def add_field(self, fieldname, fieldspec=whoosh_module_fields.TEXT): """Add a field in the index of the model. Args: fieldname (Text): This parameters register a new field in specified model. fieldspec (Name, optional): This option adds various options as were described before. Returns: ...
0.006508
def longest_non_repeat_v1(string): """ Find the length of the longest substring without repeating characters. """ if string is None: return 0 dict = {} max_length = 0 j = 0 for i in range(len(string)): if string[i] in dict: j = max(dict[string[i]], j) ...
0.002398
def start_blocking(self): """ Start the advertiser in the background, but wait until it is ready """ self._cav_started.clear() self.start() self._cav_started.wait()
0.015228
def fullcompare(self, other): """Compare two names, returning a 3-tuple (relation, order, nlabels). I{relation} describes the relation ship beween the names, and is one of: dns.name.NAMERELN_NONE, dns.name.NAMERELN_SUPERDOMAIN, dns.name.NAMERELN_SUBDOMAIN, dns.name.NAMERELN_EQUA...
0.002468
def hot_plug_cpu(self, cpu): """Plugs a CPU into the machine. in cpu of type int The CPU id to insert. """ if not isinstance(cpu, baseinteger): raise TypeError("cpu can only be an instance of type baseinteger") self._call("hotPlugCPU", ...
0.008982
def update(self, new_val): """Update the estimate. Parameters ---------- new_val: float new observated value of estimated quantity. """ if self._value is None: self._value = new_val else: self._value = self._gamma * self._value...
0.008523
def award_group_principal_award_recipient(tag): """ Find the award group principal award recipient, one for each item found in the get_funding_group section """ award_group_principal_award_recipient = [] principal_award_recipients = extract_nodes(tag, "principal-award-recipient") for t in p...
0.002252
def declallvars(self): """generator on all declaration of variable""" for f in self.body: if (hasattr(f, '_ctype') and not isinstance(f._ctype, FuncType)): yield f
0.008811
def perform_permissions_check(self, user, obj, perms): """ Performs the permissions check. """ return self.request.forum_permission_handler.can_move_topics(obj, user)
0.010989
def replace_entities(self, html): """ Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced """ def fixup(text): """replace the htmlentities in some text""" ...
0.00207
def get_passphrase(self, prompt='Passphrase:'): """Ask the user for passphrase.""" passphrase = None if self.cached_passphrase_ack: passphrase = self.cached_passphrase_ack.get() if passphrase is None: passphrase = interact( title='{} passphrase'.fo...
0.003185
def fetchone(self): """ Fetch next row """ self._check_executed() row = yield self.read_next() if row is None: raise gen.Return(None) self.rownumber += 1 raise gen.Return(row)
0.008511
def publish(self, message, properties=None, mandatory=False): """ Publish a message to an AMQP exchange. Parameters ---------- message: string Message to publish. properties: dict Properties to set on message. This parameter is optional, but if set, at least the following options must be set: con...
0.026685
def guard(func): """ Prevents the decorated function from parallel execution. Internally, this decorator creates a Lock object and transparently obtains/releases it when calling the function. """ semaphore = threading.Lock() @functools.wraps(func) def wrapper(*args, **kwargs): s...
0.002169
def _dispatch(self, func, args=None): """Send message to parent process Arguments: func (str): Name of function for parent to call args (list, optional): Arguments passed to function when called """ data = json.dumps( { "header": "py...
0.001497
def list(self, status=values.unset, phone_number=values.unset, incoming_phone_number_sid=values.unset, friendly_name=values.unset, unique_name=values.unset, limit=None, page_size=None): """ Lists DependentHostedNumberOrderInstance records from the API as a list. Unlike ...
0.008338
def getColumnName(self, attribute): """ Retreive the fully qualified column name for a particular attribute in this store. The attribute must be bound to an Item subclass (its type must be valid). If the underlying table does not exist in the database, it will be created as a ...
0.002861
def get_object(pid_type, pid_value): """Get an object behind persistent identifier.""" from .models import PersistentIdentifier obj = PersistentIdentifier.get(pid_type, pid_value) if obj.has_object(): click.echo('{0.object_type} {0.object_uuid} {0.status}'.format(obj))
0.003401
def choicerank( digraph, traffic_in, traffic_out, weight=None, initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8): """Compute the MAP estimate of a network choice model's parameters. This function computes the maximum-a-posteriori (MAP) estimate of model parameters given a network st...
0.000497
def _serialize_function(obj): """ Still needing this much try-except stuff. We should find a way to get rid of this. :param obj: :return: """ try: obj = inspect.getsource(obj) except (TypeError, IOError): try: obj = marshal.dumps(obj) except ValueError: ...
0.004706
def min_max_temp(temp: str, unit: str = 'C') -> str: """ Format the Min and Max temp elemets into a readable string Ex: Maximum temperature of 23°C (73°F) at 18-15:00Z """ if not temp or len(temp) < 7: return '' if temp[:2] == 'TX': temp_type = 'Maximum' elif temp[:2] == 'TN...
0.002915
def point_sets(script, neighbors=10, smooth_iteration=0, flip=False, viewpoint_pos=(0.0, 0.0, 0.0)): """ Compute the normals of the vertices of a mesh without exploiting the triangle connectivity, useful for dataset with no faces. Args: script: the FilterScript object or script f...
0.000498
def recv(self, timeout=None): """Receive a handover select message from the remote server.""" message = self._recv(timeout) if message and message.type == "urn:nfc:wkt:Hs": log.debug("received '{0}' message".format(message.type)) return nfc.ndef.HandoverSelectMessage(mess...
0.004525
def Process(self, parser_mediator, root_item=None, **kwargs): """Parses a document summary information OLECF item. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. root_item (Optional[pyolecf.item]): root item o...
0.005282
def check(cls, status): """Checks if a status enum matches the trigger originally set, and if so, raises the appropriate error. Args: status (int, enum): A protobuf enum response status to check. Raises: AssertionError: If trigger or error were not set. ...
0.002587
def tell(self): """Returns the current position of read head. """ pos = ctypes.c_size_t() check_call(_LIB.MXRecordIOReaderTell(self.handle, ctypes.byref(pos))) return pos.value
0.009259
def get_avatar_url(self, size=2): """Get URL to avatar picture :param size: possible values are ``0``, ``1``, or ``2`` corresponding to small, medium, large :type size: :class:`int` :return: url to avatar :rtype: :class:`str` """ hashbytes = self.get_ps('avatar_h...
0.00612
def echo(text, **kwargs): """ Print results to the console :param text: the text string to print :type text: str :return: a string :rtype: str """ if shakedown.cli.quiet: return if not 'n' in kwargs: kwargs['n'] = True if 'd' in kwargs: te...
0.003431
def plot(self, plot_cmd=None, tf=lambda y: y): """plot the data we have, return ``self``""" if not plot_cmd: plot_cmd = self.plot_cmd colors = 'bgrcmyk' pyplot.hold(False) res = self.res flatx, flatf = self.flattened() minf = np.inf for i in f...
0.002844
def check_port(port, host, timeout=10): """ connect to port on host and return True on success :param port: int, port to check :param host: string, host address :param timeout: int, number of seconds spent trying :return: bool """ logger.info("trying to open connection to %s:%s", host, ...
0.001259
def iter(self, start=0, stop=-1, withscores=False, reverse=None): """ Return a range of values from sorted set name between @start and @end sorted in ascending order unless @reverse or :prop:reversed. @start and @end: #int, can be negative, indicating the end of ...
0.001918
def from_any(cls, params, **ctor_opts): """ Creates a new Query object from input. :param params: Parameter to convert to query :type params: dict, string, or :class:`Query` If ``params`` is a :class:`Query` object already, a deep copy is made and a new :class:`Query` o...
0.001881
def is_good_age_ratios(self): """Method to check the sum of age ratio is 1. :returns: True if the sum is 1 or the sum less than 1 but there is None. :rtype: bool """ ratios = self.age_ratios() if None in ratios: # If there is None, just check to ...
0.003361
def import_from_path(path): """ Imports a package, module or attribute from path Thanks http://stackoverflow.com/a/14050282/1267398 >>> import_from_path('os.path') <module 'posixpath' ... >>> import_from_path('os.path.basename') <function basename at ... >>> import_from_path('os') <...
0.000876
def _GetNormalizedTimestamp(self): """Retrieves the normalized timestamp. Returns: decimal.Decimal: normalized timestamp, which contains the number of seconds since January 1, 1970 00:00:00 and a fraction of second used for increased precision, or None if the normalized timestamp cann...
0.004918
def _plot_prepare(self, components, units): """ Prepare the ``PhaseSpacePosition`` or subclass for passing to a plotting routine to plot all projections of the object. """ # components to plot if components is None: components = self.pos.components n_...
0.003608
def spoolable(*, pre_condition=True, body_params=()): """ Decorates a function to make it spoolable using uWSGI, but if no spooling mechanism is available, the function is called synchronously. All decorated function arguments must be picklable and the first annotated with `Context` will receive an obje...
0.006131
def is_predecessor_of_other(self, predecessor, others): """Returns whether the predecessor is a predecessor or a predecessor of a predecessor...of any of the others. Args: predecessor (str): The txn id of the predecessor. others (list(str)): The txn id of the successor. ...
0.004454
def hist(self, by=None, bins=10, **kwds): """ Draw one histogram of the DataFrame's columns. A histogram is a representation of the distribution of data. This function groups the values of all given Series in the DataFrame into bins and draws all bins in one :class:`matplotlib.a...
0.001213
def grid_track(lat,lon,sla,remove_edges=None,backbone=None,interp_over_continents=True): """ # GRID_TRACK # @summary: This function allow detecting gaps in a set of altimetry data and rebin this data regularly, with informations on gaps. # @param lat {type:numeric} : latitude # @param lon {type...
0.035405
def session_demo_alert_callback(n_clicks, session_state=None, **kwargs): 'Output text based on both app state and session state' if session_state is None: raise NotImplementedError("Cannot handle a missing session state") csf = session_state.get('bootstrap_demo_state', None) if not csf: ...
0.00578
def get_current_state_m(self): """Returns the state model of the currently open tab""" page_id = self.view.notebook.get_current_page() if page_id == -1: return None page = self.view.notebook.get_nth_page(page_id) state_identifier = self.get_state_identifier_for_page(p...
0.005291
def boolean(meshes, operation='difference'): """ Run an operation on a set of meshes """ script = operation + '(){' for i in range(len(meshes)): script += 'import(\"$mesh_' + str(i) + '\");' script += '}' return interface_scad(meshes, script)
0.003597
def write(self, data: bytes) -> int: """Returns the number of (encrypted) bytes sent. """ if self._sock is None: raise IOError('Internal socket set to None; cannot perform handshake.') if not self._is_handshake_completed: raise IOError('SSL Handshake was not compl...
0.005386
def winning_abbr(self): """ Returns a ``string`` of the winning team's abbreviation, such as 'HOU' for the Houston Astros. """ if self.winner == HOME: return utils._parse_abbreviation(self._home_name) return utils._parse_abbreviation(self._away_name)
0.006452
def multiifo_noise_coinc_rate(rates, slop): """ Calculate the expected rate of noise coincidences for multiple detectors Parameters ---------- rates: dict Dictionary keyed on ifo string Value is a sequence of single-detector trigger rates, units assumed to be Hz slop: fl...
0.000561
def autoload_static(model, resources, script_path): ''' Return JavaScript code and a script tag that can be used to embed Bokeh Plots. The data for the plot is stored directly in the returned JavaScript code. Args: model (Model or Document) : resources (Resources) : script_pa...
0.0105
def exists(name=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None, group_id=None): ''' Check to see if a security group exists. CLI example:: salt myminion boto_secgroup.exists mysecgroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, p...
0.001684
def _get_national_number_groups(numobj, formatting_pattern): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that should be formatted together according to the formatting pattern passed in.""" # If a format is pr...
0.006897
def length(self): """Gets the length of the Vector""" return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w))
0.018182
def mesh2fc(script, all_visible_layers=False): """Transfer mesh colors to face colors Args: script: the FilterScript object or script filename to write the filter to. all_visible_layers (bool): If true the color mapping is applied to all the meshes """ filter_xml = ''.join([...
0.003049
def _changes(plays): ''' Find changes in ansible return data ''' changes = {} for play in plays['plays']: task_changes = {} for task in play['tasks']: host_changes = {} for host, data in six.iteritems(task['hosts']): if data['changed'] is True:...
0.003339
def load_imdb_dataset( path='data', nb_words=None, skip_top=0, maxlen=None, test_split=0.2, seed=113, start_char=1, oov_char=2, index_from=3 ): """Load IMDB dataset. Parameters ---------- path : str The path that the data is downloaded to, defaults is ``data/imdb/``. nb_word...
0.002653
def u64(self, name, value=None, align=None): """Add an unsigned 8 byte integer field to template. This is an convenience method that simply calls `Uint` keyword with predefined length.""" self.uint(8, name, value, align)
0.012245
def _highlight_block(self, block): """ Highlights the current fold scope. :param block: Block that starts the current fold scope. """ scope = FoldScope(block) if (self._current_scope is None or self._current_scope.get_range() != scope.get_range()): ...
0.0033
async def connect(self): """ Connect to target. """ self.tls_context = None if self.tls: self.tls_context = self.create_tls_context() (self.reader, self.writer) = await asyncio.open_connection( host=self.hostname, port=self.port, local_ad...
0.004773
def remove_tweet(self, id): """ Delete a tweet. :param id: ID of the tweet in question :return: True if success, False otherwise """ try: self._client.destroy_status(id=id) return True except TweepError as e: if e.api_code in [...
0.006881
def divide_1Darray_equally(ind, nsub): """Divide an array into equal chunks to be used for instance in OSEM. Parameters ---------- ind : ndarray input array nsubsets : int number of subsets to be divided into Returns ------- sub2ind : list list of indices for ea...
0.001481
def _safe_output(line): ''' Looks for rabbitmqctl warning, or general formatting, strings that aren't intended to be parsed as output. Returns a boolean whether the line can be parsed as rabbitmqctl output. ''' return not any([ line.startswith('Listing') and line.endswith('...'), ...
0.002278
def export_users(path_prefix='/', region=None, key=None, keyid=None, profile=None): ''' Get all IAM user details. Produces results that can be used to create an sls file. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.export_users --out=txt | sed "s/local: //"...
0.00277
def get_values(self, dtype=None): """ return an internal format, currently just the ndarray this is often overridden to handle to_dense like operations """ if is_object_dtype(dtype): return self.values.astype(object) return self.values
0.00678
def _get_websocket(self, reuse=True): """ Reuse existing connection or create a new connection. """ # Check if still connected if self.ws and reuse: if self.ws.connected: return self.ws logging.debug("Stale connection, reconnecting.") ...
0.005222
def find(cls, text): """This method should return an iterable containing matches of this element.""" if isinstance(cls.pattern, string_types): cls.pattern = re.compile(cls.pattern) return cls.pattern.finditer(text)
0.012
def slice_pdf(input_filename: str, output_filename: str, slice_horiz: int, slice_vert: int) -> str: """ Slice each page of the original, to convert to "one real page per PDF page". Return the output filename. """ if slice_horiz == 1 and slice_vert == 1: log.debug("No slicing re...
0.002513
def findStylesForEach(self, element, attrNames, default=NotImplemented): """Attempts to find the style setting for attrName in the CSSRulesets. Note: This method does not attempt to resolve rules that return "inherited", "default", or values that have units (including "%"). This is left...
0.003226
def triads(key): """Return all the triads in key. Implemented using a cache. """ if _triads_cache.has_key(key): return _triads_cache[key] res = map(lambda x: triad(x, key), keys.get_notes(key)) _triads_cache[key] = res return res
0.007519
def trim_snapshots(self, hourly_backups = 8, daily_backups = 7, weekly_backups = 4): """ Trim excess snapshots, based on when they were taken. More current snapshots are retained, with the number retained decreasing as you move back in time. If ebs volumes...
0.004606
def _arg_parser(): """Factory for creating the argument parser""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('xml', nargs='*') return parser
0.005348
def get_time_offset(): """Get time offset from steam server time via WebAPI :return: time offset (``None`` when Steam WebAPI fails to respond) :rtype: :class:`int`, :class:`None` """ try: resp = webapi.post('ITwoFactorService', 'QueryTime', 1, params={'http_timeout': 10}) except: ...
0.007075
def shear_vel_at_depth(self, y_c): """ Get the shear wave velocity at a depth. :param y_c: float, depth from surface :return: """ sl = self.get_soil_at_depth(y_c) if y_c <= self.gwl: saturation = False else: saturation = True ...
0.003484
def get_version(brain_or_object): """Get the version of the current object :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The current version of the object, or None if not available :rtype: int or Non...
0.002132
def correlation_plot(self, x_analyte, y_analyte, window=15, filt=True, recalc=False): """ Plot the local correlation between two analytes. Parameters ---------- x_analyte, y_analyte : str The names of the x and y analytes to correlate. window : int, None ...
0.007898
def parse_frog(lines): """ Interpret the output of the frog parser. Input should be an iterable of lines (i.e. the output of call_frog) Result is a sequence of dicts representing the tokens """ sid = 0 for i, line in enumerate(lines): if not line: # end of sentence marker...
0.001148
def cmd_iter( self, tgt, fun, arg=(), timeout=None, tgt_type='glob', ret='', kwarg=None, **kwargs): ''' Yields the individual minion returns as they come in The function signature is the ...
0.001441
def resolve_sid(sid): """Get the PID to which the ``sid`` currently maps. Preconditions: - ``sid`` is verified to exist. E.g., with d1_gmn.app.views.asserts.is_sid(). """ return d1_gmn.app.models.Chain.objects.get(sid__did=sid).head_pid.did
0.007634
def unregister(self, slug): """ Unregisters the given url. If a slug isn't already registered, this will raise NotRegistered. """ if slug not in self._registry: raise NotRegistered('The slug %s is not registered' % slug) bundle = self._registry[slug] ...
0.004008
def remove_child(self, child): """Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None :raises: ValueError """ child.set_model(None) if self._model: row = self....
0.003929
def cmdloop(self): """Start the main loop of the interactive shell. The preloop() and postloop() methods are always run before and after the main loop, respectively. Returns: 'root': Inform the parent shell to to keep exiting until the root shell is reached....
0.001983
def set_gmxrc_environment(gmxrc): """Set the environment from ``GMXRC`` provided in *gmxrc*. Runs ``GMXRC`` in a subprocess and puts environment variables loaded by it into this Python environment. If *gmxrc* evaluates to ``False`` then nothing is done. If errors occur then only a warning will be ...
0.00136
def write_tsv(self, file_path: str, encoding: str = 'UTF-8', sep: str = '\t'): """Write expression matrix to a tab-delimited text file. Parameters ---------- file_path: str The path of the output file. encoding: str, optional The file en...
0.006974
def ignore_stops_before_now(self): """Ignore any stops received before this point""" self._sentinel_stop = object() self._q.put(self._sentinel_stop)
0.011628
def pollNextEvent(self, pEvent): """ Returns true and fills the event with the next event on the queue if there is one. If there are no events this method returns false. uncbVREvent should be the size in bytes of the VREvent_t struct """ fn = self.function_table.pollNextEvent ...
0.01005
def natsort(string): '''按照语言里的意义对字符串进行排序. 这个方法用于替换按照字符编码顺序对字符串进行排序. 相关链接: http://stackoverflow.com/questions/2545532/python-analog-of-natsort-function-sort-a-list-using-a-natural-order-algorithm http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html ''' return [...
0.005208
def pasteprepare(args): """ %prog pasteprepare bacs.fasta Prepare sequences for paste. """ p = OptionParser(pasteprepare.__doc__) p.add_option("--flank", default=5000, type="int", help="Get the seq of size on two ends [default: %default]") opts, args = p.parse_args(args) ...
0.006652
def project_users_with_administrator_permissions(self, key): """ Get project administrators for project :param key: project key :return: project administrators """ project_administrators = [user['user'] for user in self.project_users(key) ...
0.005164
def _custom_init_(self, model_name, other_name=None,log_interp = True): """ Custom initialization for this model :param model_name: the name of the model, corresponding to the root of the .h5 file in the data directory :param other_name: (optional) the name to be used as name of...
0.005196
def _add_parsley_ns(cls, namespace_dict): """ Extend XPath evaluation with Parsley extensions' namespace """ namespace_dict.update({ 'parslepy' : cls.LOCAL_NAMESPACE, 'parsley' : cls.LOCAL_NAMESPACE, }) return namespace_dict
0.013468