text
stringlengths
78
104k
score
float64
0
0.18
def sample(self, iter, length=None, verbose=0): """ Draws iter samples from the posterior. """ self._cur_trace_index = 0 self.max_trace_length = iter self._iter = iter self.verbose = verbose or 0 self.seed() # Assign Trace instances to tallyable o...
0.002685
def _calc_fourier_spectrum(self, fa_length=None): """Compute the Fourier Amplitude Spectrum of the time series.""" if fa_length is None: # Use the next power of 2 for the length n = 1 while n < self.accels.size: n <<= 1 else: n = f...
0.004
def show(self,index=None): """Show a single block on screen""" index = self._get_index(index) if index is None: return print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' % (self.title,index,self.nblocks-index-1)) print >>io.s...
0.018182
def _put(self, url_suffix, data, content_type=ContentType.json): """ Send PUT request to API at url_suffix with post_data. Raises error if x-total-pages is contained in the response. :param url_suffix: str URL path we are sending a PUT to :param data: object data we are sending ...
0.005618
def _is_null(instance, name): ''' Determine if an attribute of an *instance* with a specific *name* is null. ''' if name in instance.__dict__: value = instance.__dict__[name] else: value = getattr(instance, name) if value: return False elif value is None: ...
0.004484
def get_instance(self, payload): """ Build an instance of ModelBuildInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance :rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildInstance ...
0.011416
def get_containers(config, all=True, trunc=False, since=None, before=None, limit=-1, *args, **kwargs): ''' Get a list of mappings representing all containers all Retu...
0.002326
def set_default_preferences(self): """ Defines the default settings file content. :return: Method success. :rtype: bool """ LOGGER.debug("> Initializing default settings!") for key in self.__default_settings.allKeys(): self.__settings.setValue(key, ...
0.004866
def tf_optimization(self, states, internals, actions, terminal, reward, next_states=None, next_internals=None): """ Creates the TensorFlow operations for performing an optimization update step based on the given input states and actions batch. Args: states: Dict of state ten...
0.003828
def _highlight_caret_scope(self): """ Highlight the scope of the current caret position. This get called only if :attr:` spyder.widgets.panels.FoldingPanel.highlight_care_scope` is True. """ cursor = self.editor.textCursor() block_nbr = cursor.blockNumber() ...
0.002491
def iter_leaf_names(self, is_leaf_fn=None): """Returns an iterator over the leaf names under this node.""" for n in self.iter_leaves(is_leaf_fn=is_leaf_fn): yield n.name
0.010152
def histogram(ratings, min_rating=None, max_rating=None): """ Generates a frequency count of each rating on the scale ratings is a list of scores Returns a list of frequencies """ ratings = [int(r) for r in ratings] if min_rating is None: min_rating = min(ratings) if max_rating i...
0.001815
def _assemble_complex(stmt): """Assemble Complex statements into text.""" member_strs = [_assemble_agent_str(m) for m in stmt.members] stmt_str = member_strs[0] + ' binds ' + _join_list(member_strs[1:]) return _make_sentence(stmt_str)
0.004
def _scale_tdb_minus_tt(self, mjd, eop): """Definition of the Barycentric Dynamic Time scale relatively to Terrestrial Time """ jd = mjd + Date.JD_MJD jj = Date._julian_century(jd) m = radians(357.5277233 + 35999.05034 * jj) delta_lambda = radians(246.11 + 0.90251792 * (j...
0.007538
def avg(self, func=lambda x: x): """ Returns the average value of data elements :param func: lambda expression to transform data :return: average value as float object """ count = self.count() if count == 0: raise NoElementsError(u"Iterable contains no...
0.005222
def polygon_to_points(coords, z=None): """ Given a list of pairs of points which define a polygon, return a list of points interior to the polygon """ bounds = array(coords).astype('int') bmax = bounds.max(0) bmin = bounds.min(0) path = Path(bounds) grid = meshgrid(range(bmin[0],...
0.002886
def modify(self, order_id, approver_email=None, domain_validation_methods=None): """Modify an ordered SSL certificate.""" response = self.request(E.modifySslCertRequest( E.id(order_id), OE('approverEmail', approver_email), OE('domainValidationMethods', domain_validat...
0.009709
def parse_reports(self): """ Find RSeQC read_distribution reports and parse their data """ # Set up vars self.read_dist = dict() first_regexes = { 'total_reads': r"Total Reads\s+(\d+)\s*", 'total_tags': r"Total Tags\s+(\d+)\s*", 'total_assigned_tags': r"Total Assigned Tags\s+(\d...
0.00383
def services(self, *args, **kwargs): """Retrieve services belonging to this scope. See :class:`pykechain.Client.services` for available parameters. .. versionadded:: 1.13 """ return self._client.services(*args, scope=self.id, **kwargs)
0.00722
def export(self, composite=False): """Export this name as a token. This method exports the name into a byte string which can then be imported by using the `token` argument of the constructor. Args: composite (bool): whether or not use to a composite token -- ...
0.002141
def apply(self, strain, detector_name, f_lower=None, distance_scale=1, simulation_ids=None, inj_filter_rejector=None): """Add injections (as seen by a particular detector) to a time series. Parameters ---------- strain : TimeSeries Time series to inject signals...
0.00193
def send_wrapped(self, text): """ Send text padded and wrapped to the user's screen width. """ lines = word_wrap(text, self.columns) for line in lines: self.send_cc(line + '\n')
0.008734
async def delete_entries(cls, db, query): ''' Delete documents by given query. ''' query = cls.process_query(query) for i in cls.connection_retries(): try: result = await db[cls.get_collection_name()].delete_many(query) return result except...
0.006148
def _generate_random_leaf_count(height): """Return a random leaf count for building binary trees. :param height: Height of the binary tree. :type height: int :return: Random leaf count. :rtype: int """ max_leaf_count = 2 ** height half_leaf_count = max_leaf_count // 2 # A very naiv...
0.001934
def _add_new_state(self, *event, **kwargs): """Triggered when shortcut keys for adding a new state are pressed, or Menu Bar "Edit, Add State" is clicked. Adds a new state only if the the state machine tree is in focus. """ if react_to_event(self.view, self.view['state_machine_tree_view'...
0.01105
def second_order_score(y, mean, scale, shape, skewness): """ GAS Poisson Update term potentially using second-order information - native Python function Parameters ---------- y : float datapoint for the time series mean : float location parameter for the...
0.004127
def _sincedb_init(self): """Initializes the sincedb schema in an sqlite db""" if not self._sincedb_path: return if not os.path.exists(self._sincedb_path): self._log_debug('initializing sincedb sqlite schema') conn = sqlite3.connect(self._sincedb_path, isolati...
0.003497
def del_property(self, t_property_name, sync=True): """ delete property from this transport. if this transport has no id then it's like sync=False. :param t_property_name: property name to remove :param sync: If sync=True(default) synchronize with Ariane server. If sync=False, ad...
0.004656
def filter_geometry(queryset, **filters): """Helper function for spatial lookups filters. Provide spatial lookup types as keywords without underscores instead of the usual "geometryfield__lookuptype" format. """ fieldname = geo_field(queryset).name query = {'%s__%s' % (fieldname, k): v for k, v...
0.00266
def add_event(cls, event, event_name=None): """Add events""" # setattr(cls, event_name, event) event_name = event_name or event.__name__ setattr(cls, event_name, types.MethodType(event, cls))
0.008969
def NewType(name, tp): """NewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy function that simply returns its argument. Usage:: UserId = NewType('UserId', i...
0.001422
def _add_arg_python(self, key, value=None, mask=False): """Add CLI Arg formatted specifically for Python. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask val...
0.002513
def process_agreement_events_publisher(publisher_account, agreement_id, did, service_agreement, price, consumer_address, condition_ids): """ Process the agreement events during the register of the service agreement for the publisher side :param publisher_account: Acco...
0.002323
def fn_getds(fn): """Wrapper around gdal.Open() """ ds = None if fn_check(fn): ds = gdal.Open(fn, gdal.GA_ReadOnly) else: print("Unable to find %s" % fn) return ds
0.004926
def download_files(self, files): """This method uses the `download_file` task to retrieve binary files such as attachments, images and videos. Notice that this method does not wait for the tasks it creates to return a result synchronously. """ utils.pending_message( ...
0.004248
def to_csv(self, file): """ Write all the trajectories of a collection to a csv file with the headers 'description', 'time' and 'value'. :param file: a file object to write to :type file: :class:`file` :return: """ file.write("description,time,value\n") f...
0.01139
def sync_update_current_price_info(self): """Update current price info.""" loop = asyncio.get_event_loop() task = loop.create_task(self.update_current_price_info()) loop.run_until_complete(task)
0.00885
def slugify(text, sep='-'): """A simple slug generator.""" text = stringify(text) if text is None: return None text = text.replace(sep, WS) text = normalize(text, ascii=True) if text is None: return None return text.replace(WS, sep)
0.003623
def init_perfect_ttable(words): """initialize (normalized) theta according to whether words rhyme""" d = read_celex() not_in_dict = 0 n = len(words) t_table = numpy.zeros((n, n + 1)) # initialize P(c|r) accordingly for r, w in enumerate(words): if w not in d: not_in_di...
0.001087
def collect_s3(self): """ Collect and download build-artifacts from S3 based on git reference """ print('Collecting artifacts matching tag/sha %s from S3 bucket %s' % (self.gitref, s3_bucket)) self.s3 = boto3.resource('s3') self.s3_bucket = self.s3.Bucket(s3_bucket) self.s3.meta....
0.007707
def _compute_nonlinear_magnitude_term(self, C, mag): """ Computes the non-linear magnitude term """ return self._compute_linear_magnitude_term(C, mag) +\ C["b3"] * ((mag - 7.0) ** 2.)
0.008811
def write_to(self, group, append=False): """Write the data to the given group. :param h5py.Group group: The group to write the data on. It is assumed that the group is already existing or initialized to store h5features data (i.e. the method ``Data.init_group`` have ...
0.002265
def run(self, message_id, **kwargs): """ Load and contruct message and send them off """ log = self.get_logger(**kwargs) error_retry_count = kwargs.get("error_retry_count", 0) if error_retry_count >= self.max_error_retries: raise MaxRetriesExceededError( ...
0.001588
def cumulative_max(self): """ Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int,...
0.0058
def get(self, name): """ Gets an image. Args: name (str): The name of the image. Returns: (:py:class:`Image`): The image. Raises: :py:class:`docker.errors.ImageNotFound` If the image does not exist. :py:class:`doc...
0.004246
def canonical_fix_name(fix, avail_fixes): """ Examples: >>> canonical_fix_name('fix_wrap_text_literals') 'libfuturize.fixes.fix_wrap_text_literals' >>> canonical_fix_name('wrap_text_literals') 'libfuturize.fixes.fix_wrap_text_literals' >>> canonical_fix_name('wrap_te') ValueError("unknow...
0.002616
def load_weights_from_json_hdf5(def_json, weights_hdf5, by_name=False): """ The file path can be stored in a local file system, HDFS, S3, or any Hadoop-supported file system. """ bmodel = DefinitionLoader.from_json_path(def_json) def_value = BCommon.text_from_path(def_jso...
0.006369
def clean_worksheet(wks, gfile_id, wks_name, credentials): """DOCS...""" values = wks.get_all_values() if values: df_ = pd.DataFrame(index=range(len(values)), columns=range(len(values[0]))) df_ = df_.fillna('') wks = upload(df_, gfile_id, wks_name=wks_name...
0.002222
def put_subsegment(self, subsegment): """ Refresh the facade segment every time this function is invoked to prevent a new subsegment from being attached to a leaked segment/subsegment. """ current_entity = self.get_trace_entity() if not self._is_subsegment(current_entity...
0.007899
def render(self, path, **context): """ Render a template with context. """ funcs = self.functions ctx = dict(self.functions, jdebug=lambda: dict( (k, v) for k, v in ctx.items() if k not in funcs and k != 'jdebug')) for provider in self.providers: _ctx = yield from...
0.006211
def components(channel, channel_name, unique_names, prefix="", master=None): """ yield pandas Series and unique name based on the ndarray object Parameters ---------- channel : numpy.ndarray channel to be used foir Series channel_name : str channel name unique_names : UniqueDB ...
0.001276
def crypto_secretstream_xchacha20poly1305_push( state, m, ad=None, tag=crypto_secretstream_xchacha20poly1305_TAG_MESSAGE, ): """ Add an encrypted message to the secret stream. :param state: a secretstream state object :type state: crypto_secretstream_xchacha20poly1305_state :param m...
0.000501
def getParameterByValue(self, value): """Searchs a parameter by value and returns it.""" result = None for parameter in self.getParameters(): valueParam = parameter.getValue() if valueParam == value: result = parameter break return ...
0.006135
def collect_publications(self): """ Recursively collect list of all publications referenced in this tree and all sub-trees. Returns: list: List of UUID strings. """ pubs = list(self.sub_publications) for sub_tree in self.sub_trees: pubs.e...
0.005277
def ramping_values(period=360): """ Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats every *period* values. For example, to pulse an LED once a second:: from gpiozero import PWMLED from gpiozero.tools import ramping_values ...
0.001111
def get_coordinates_by_nickname(self, nickname): """Retrieves a person's coordinates by nickname""" person = self.get_person_by_nickname(nickname) if not person: return '', '' return person.latitude, person.longitude
0.007692
def set_deltatime(self, delta_time): """Set the delta_time. Can be an integer or a variable length byte. """ if type(delta_time) == int: delta_time = self.int_to_varbyte(delta_time) self.delta_time = delta_time
0.007605
def compose_capability(base, *classes): """Create a new class starting with the base and adding capabilities.""" if _debug: compose_capability._debug("compose_capability %r %r", base, classes) # make sure the base is a Collector if not issubclass(base, Collector): raise TypeError("base must be ...
0.003812
def encode_kanji(self): """This method encodes the QR code's data if its mode is kanji. It returns the data encoded as a binary string. """ def two_bytes(data): """Output two byte character code as a single integer.""" def next_byte(b): """Make sur...
0.005767
def set_val_summary(self, summary): """ Set validation summary. A ValidationSummary object contains information necessary for the optimizer to know how often the logs are recorded, where to store the logs and how to retrieve them, etc. For details, refer to the docs of Validation...
0.003891
def on_mouse_press(self, x, y, buttons, modifiers): """ Set the start point of the drag. """ self.view['ball'].set_state(Trackball.STATE_ROTATE) if (buttons == pyglet.window.mouse.LEFT): ctrl = (modifiers & pyglet.window.key.MOD_CTRL) shift = (modifiers & ...
0.00207
def label(self, name, internal=False, definition=False): """Generates label name (helper function) name - label name internal - boolean value, adds "@" prefix to label definition - boolean value, adds ":" suffix to label """ return "{0}{1}{2}".format(self.i...
0.007634
def update(self, **kwargs): """ Explicitly reload context with DB usage to get access to complete DB object. """ self.reload_context(es_based=False, **kwargs) return super(ESCollectionView, self).update(**kwargs)
0.007937
def get_current_course_run(course, users_active_course_runs): """ Return the current course run on the following conditions. - If user has active course runs (already enrolled) then return course run with closest start date Otherwise it will check the following logic: - Course run is enrollable (se...
0.004415
def transform_data_word2vec(data, vocab, idx_to_counts, cbow, batch_size, window_size, frequent_token_subsampling=1E-4, dtype='float32', index_dtype='int64'): """Transform a DataStream of coded DataSets to a DataStream of batches. Parameters ---------...
0.000394
async def get_version(self, timeout: int = 15) -> Optional[str]: """Execute FFmpeg process and parse the version information. Return full FFmpeg version string. Such as 3.4.2-tessus """ command = ["-version"] # open input for capture 1 frame is_open = await self.open(cm...
0.003049
def parse(self, text): """The parser entry point. Parse the provided text to check for its validity. On success, the parsing tree is available into the result attribute. It is a list of sievecommands.Command objects (see the module documentation for specific information). ...
0.001236
def getClassDirectSubs(self, aURI): """ 2015-06-03: currenlty not used, inferred from above """ aURI = aURI qres = self.rdflib_graph.query("""SELECT DISTINCT ?x WHERE { { ?x rdfs:subClassOf <%s> } FILTER (!isBlank(?x)) ...
0.005089
def show_in_notebook(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an e...
0.009174
def status(app_name=None, only_cozy=False, as_boolean=False): '''Get apps status :param app_name: If pass app name return this app status :return: dict with all apps status or str with one app status ''' apps = {} # Get all apps status & slip them apps_status = subprocess.Popen('cozy-monito...
0.000764
def send_status_message(self, device_type, device_id, user_id, msg_type, device_status): """ 第三方主动发送设备状态消息给微信终端 详情请参考 https://iot.weixin.qq.com/wiki/document-2_10.html :param device_type: 设备类型,目前为“公众账号原始ID” :param device_id: 设备ID :param user_id: 微信用户账号的openid ...
0.004049
def reset(self, indices=None): """Resets environments at given indices. Subclasses should override _reset to do the actual reset if something other than the default implementation is desired. Args: indices: Indices of environments to reset. If None all envs are reset. Returns: Batch o...
0.004494
def Run(self, args): """Search the file for the pattern. This implements the grep algorithm used to scan files. It reads the data in chunks of BUFF_SIZE (10 MB currently) and can use different functions to search for matching patterns. In every step, a buffer that is a bit bigger than the block siz...
0.005163
def fetch_turbine_data(self, fetch_curve, data_source): r""" Fetches data of the requested wind turbine. Method fetches nominal power as well as power coefficient curve or power curve from a data set provided in the OpenEnergy Database (oedb). You can also import your own power ...
0.000706
def get_user_pubkeys(users): ''' Retrieve a set of public keys from GitHub for the specified list of users. Expects input in list format. Optionally, a value in the list may be a dict whose value is a list of key IDs to be returned. If this is not done, then all keys will be returned. Some exam...
0.000702
def eccentricity(self, **kw): r""" Returns the eccentricity computed from the mean apocenter and mean pericenter. .. math:: e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}} Parameters ---------- **kw Any keyword arguments ...
0.003205
def tag_to_version(tag, config=None): """ take a tag that might be prefixed with a keyword and return only the version part :param config: optional configuration object """ trace("tag", tag) if not config: config = Configuration() tagdict = _parse_version_tag(tag, config) if no...
0.003623
def _matrix_sigma_eta(self, donor_catchments): """ Return model error coveriance matrix Sigma eta Methodology source: Kjelsen, Jones & Morris 2014, eqs 2 and 3 :param donor_catchments: Catchments to use as donors :type donor_catchments: list of :class:`Catchment` :retur...
0.004304
def update(args): """Update a record. Argument: args: arguments object Firstly call delete(), then create(). """ # Check specifying some new values if ((not args.__dict__.get('new_type') and not args.__dict__.get('new_content') and not args.__dict__.get('new_ttl') an...
0.000609
def __initialize_node(self, attributes_flags=int(Qt.ItemIsSelectable | Qt.ItemIsEnabled)): """ Initializes the node. :param attributes_flags: Attributes flags. :type attributes_flags: int """ attributes = dir(self.__component) for attribute in attributes: ...
0.004813
def _initialize(self): """Initialize the object from the request""" self.log.debug("Start initializing data from %s", self.url) resp = self.get(self.url, verify=False, proxies=self.rtc_obj.proxies, he...
0.00404
def container_search(self, query, across_collections=False): '''search for a specific container. If across collections is False, the query is parsed as a full container name and a specific container is returned. If across_collections is True, the container is searched for across collections. If across c...
0.00542
def update(self, key: bytes, value: bytes, node_updates: Sequence[Hash32]): """ Merge an update for another key with the one we are tracking internally. :param key: keypath of the update we are processing :param value: value of the update we are processing :param node_updates: s...
0.001914
def cancel(self, id, **kwargs): """ Cancel running build. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(respo...
0.003099
def api_call(method, end_point, params=None, client_id=None, access_token=None): """Call given API end_point with API keys. :param method: HTTP method (e.g. 'get', 'delete'). :param end_point: API endpoint (e.g. 'users/john/sets'). :param params: Dictionary to be sent in the query string (e.g. {'myparam...
0.002859
def get_header(self, elem, style, node): """Returns HTML tag representing specific header for this element. :Returns: String representation of HTML tag. """ font_size = style if hasattr(elem, 'possible_header'): if elem.possible_header: ret...
0.003927
def ValidatePassword(self, password): """ Validates if the provided password matches with the stored password. Args: password (string): a password. Returns: bool: the provided password matches with the stored password. """ password = to_aes_key(p...
0.007212
def _flatten(v, val): """Recursively flatten vectorized var => {0, 1} mappings.""" if isinstance(v, Variable): yield v, int(val) else: if len(v) != len(val): raise ValueError("expected 1:1 mapping from Variable => {0, 1}") for _var, _val in zip(v, val): yield ...
0.002899
def exclusive_ns(guard: StateGuard[A], desc: str, thunk: Callable[..., NS[A, B]], *a: Any) -> Do: '''this is the central unsafe function, using a lock and updating the state in `guard` in-place. ''' yield guard.acquire() log.debug2(lambda: f'exclusive: {desc}') state, response = yield N.ensure_failu...
0.007634
def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1): """Get affine transform matrix for zooming/scaling that height and width are changed independently. OpenCV format, x is width. Parameters ----------- w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greater...
0.004298
def ajax_request(func): """ If view returned serializable dict, returns response in a format requested by HTTP_ACCEPT header. Defaults to JSON if none requested or match. Currently supports JSON or YAML (if installed), but can easily be extended. example: @ajax_request def my_view...
0.000587
async def email(self, *args, **kwargs): """ Send an Email Send an email to `address`. The content is markdown and will be rendered to HTML, but both the HTML and raw markdown text will be sent in the email. If a link is included, it will be rendered to a nice button in the ...
0.007366
def name_to_jsonld(title_in): """ Convert formal titles to camelcase json_ld text that matches our context file Keep a growing list of all titles that are being used in the json_ld context :param str title_in: :return str: """ title_out = '' try: title_in = title_in.lower() ...
0.004219
def bytes_to_str(self, b): "convert bytes array to raw string" if PYTHON_MAJOR_VER == 3: return b.decode(charset_map.get(self.charset, self.charset)) return b
0.010309
def check_candidate_exists(self, basepath, candidates): """ Check that at least one candidate exist into a directory. Args: basepath (str): Directory path where to search for candidate. candidates (list): List of candidate file paths. Returns: list: ...
0.003521
async def connect(self, client_id, conn_string): """Connect to a device on behalf of a client. See :meth:`AbstractDeviceAdapter.connect`. Args: client_id (str): The client we are working for. conn_string (str): A connection string that will be passed to ...
0.002729
def _populate_tournament_payoff_array0(payoff_array, k, indices, indptr): """ Populate `payoff_array` with the payoff values for player 0 in the tournament game given a random tournament graph in CSR format. Parameters ---------- payoff_array : ndarray(float, ndim=2) ndarray of shape (n...
0.000864
def _execute(self, stmt, *values): """ Gets a cursor, executes `stmt` and closes the cursor, fetching one row afterwards and returning its result. """ c = self._cursor() try: return c.execute(stmt, values).fetchone() finally: c.close()
0.006349
def clone(self, substitutions, commit=True, **kwargs): """ Clone a DAG, optionally skipping the commit. """ return self.store.clone(substitutions, **kwargs)
0.010582
def newKernel(self, nb): """ generate a new kernel """ manager, kernel = utils.start_new_kernel( kernel_name=nb.metadata.kernelspec.name ) return kernel
0.009434