text
stringlengths
78
104k
score
float64
0
0.18
def _results(self, product, path, cls=Results, **kwargs): """Returns _results for the specified API path with the specified **kwargs parameters""" if product != 'account-information' and self.rate_limit and not self.limits_set and not self.limits: self._rate_limit() uri = '/'.join((...
0.008313
def get_file_properties( client, fileshare, prefix, timeout=None, snapshot=None): # type: (azure.storage.file.FileService, str, str, int, str) -> # azure.storage.file.models.File """Get file properties :param FileService client: blob client :param str fileshare: file share name :p...
0.000917
def _get_ann_labels_data(self, order_ann, bins_ann): """Generate ColumnDataSource dictionary for annular labels. """ if self.yticks is None: return dict(x=[], y=[], text=[], angle=[]) mapping = self._compute_tick_mapping("radius", order_ann, bins_ann) values = [(la...
0.002681
def is_valid_file(parser,arg): """verify the validity of the given file. Never trust the End-User""" if not os.path.exists(arg): parser.error("File %s not found"%arg) else: return arg
0.058824
def _alpha_eff(self, r_eff, n_sersic, k_eff): """ deflection angle at r_eff :param r_eff: :param n_sersic: :param k_eff: :return: """ b = self.b_n(n_sersic) alpha_eff = n_sersic * r_eff * k_eff * b**(-2*n_sersic) * np.exp(b) * special.gamma(2*n_ser...
0.008571
def split_taf(txt: str) -> [str]: # type: ignore """ Splits a TAF report into each distinct time period """ lines = [] split = txt.split() last_index = 0 for i, item in enumerate(split): if starts_new_line(item) and i != 0 and not split[i - 1].startswith('PROB'): lines.a...
0.004474
def intersect(self, other): """Constructs an unminimized DFA recognizing the intersection of the languages of two given DFAs. Args: other (DFA): The other DFA that will be used for the intersect operation Returns: Returns: DFA: The...
0.006742
def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin """Download a device's attachment. :param id: Device ID as an int. :param attid: Attachment ID as an int. :rtype: tuple `(io.BytesIO, 'filename')` """ resp = self.service.get_id(self._base(id...
0.007435
def editProtocol(self, clusterProtocolObj): """ Updates the Cluster Protocol. This will cause the cluster to be restarted with updated protocol configuration. """ if isinstance(clusterProtocolObj, ClusterProtocol): pass else: raise AttributeError("Invalid Inpu...
0.012531
def results_class_wise_metrics(self): """Class-wise metrics Returns ------- dict results in a dictionary format """ results = {} for scene_id, scene_label in enumerate(self.scene_label_list): if scene_label not in results: ...
0.005302
def get_objective_query_session(self, proxy): """Gets the ``OsidSession`` associated with the objective query service. :param proxy: a proxy :type proxy: ``osid.proxy.Proxy`` :return: an ``ObjectiveQuerySession`` :rtype: ``osid.learning.ObjectiveQuerySession`` :raise: ``...
0.00565
def get(self, reg, ty): """ Load a value from a machine register into a VEX temporary register. All values must be loaded out of registers before they can be used with operations, etc and stored back into them when the instruction is over. See Put(). :param reg: Register number...
0.004225
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]: """ A random string. Not unique, but has around 1 in a million chance of collision (with the default 8 character length). e.g. 'fubui5e6' Args: length: Length of the random string. chars: The chara...
0.006881
def aimport_module(self, module_name): """Import a module, and mark it reloadable Returns ------- top_module : module The imported module if it is top-level, or the top-level top_name : module Name of top_module """ self.mark_module_reloa...
0.004016
def create_class(request): """Create new class POST parameters (JSON): name: Human readable name of class code (optional): unique code of class used for joining to class """ if request.method == 'GET': return render(request, 'classes_create.html', {}, he...
0.003674
def run(self, result): """Run tests in suite inside of suite fixtures. """ # proxy the result for myself log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests) #import pdb #pdb.set_trace() if self.resultProxy: result, orig = self...
0.005551
def update_email_asset(self, asset_id, name, asset_type): """ Updates a Email Asset Args: name: The name provided to the email asset asset_type: The type provided to the email asset asset_id: Returns: """ self.update_asset('EMAIL', as...
0.005797
def parse_requests_response(response, **kwargs): """Build a ContentDisposition from a requests (PyPI) response. """ return parse_headers( response.headers.get('content-disposition'), response.url, **kwargs)
0.004405
def delete_collection_namespaced_daemon_set(self, namespace, **kwargs): """ delete collection of DaemonSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_daemo...
0.002748
def average_true_range_percent(close_data, period): """ Average True Range Percent. Formula: ATRP = (ATR / CLOSE) * 100 """ catch_errors.check_for_period_error(close_data, period) atrp = (atr(close_data, period) / np.array(close_data)) * 100 return atrp
0.003497
def on_capacity(self, connection, command, query_kwargs, response, capacity): """ Hook that runs in response to a 'returned capacity' event """ now = time.time() args = (connection, command, query_kwargs, response, capacity) # Check total against the total_cap ...
0.001519
def get_structure_with_only_magnetic_atoms(self, make_primitive=True): """ Returns a Structure with only magnetic atoms present. :return: Structure """ sites = [site for site in self.structure if abs(site.properties["magmom"]) > 0] structure = Structure.from_sites(sites...
0.006608
def run(command, verbose=False): """ Run a shell command. Capture the stdout and stderr as a single stream. Capture the status code. If verbose=True, then print command and the output to the terminal as it comes in. """ def do_nothing(*args, **kwargs): return None v_print = p...
0.001085
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv # setup command line parser parser = U.OptionParser(version="%prog version: $Id$", usage=usage, ...
0.000981
def _get_xk(self, yk): '''Compute approximate solution from initial guess and approximate solution of the preconditioned linear system.''' if yk is not None: return self.x0 + self.linear_system.Mr * yk return self.x0
0.007692
def copy_to_clipboard(self): """ Copies selected items to clipboard. """ tree = self.treeview # get the selected item: selection = tree.selection() if selection: self.filter_remove(remember=True) root = ET.Element('selection') f...
0.002717
def create_307_response(self): """ Creates a 307 "Temporary Redirect" response including a HTTP Warning header with code 299 that contains the user message received during processing the request. """ request = get_current_request() msg_mb = UserMessageMember(self....
0.003061
def image_function(f='sin(5*x)*cos(5*y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p='x,y', g=None, **kwargs): """ Plots a 2-d function over the specified range Parameters ---------- f='sin(5*x)*cos(5*y)' Takes two inputs and returns one value. Can also ...
0.008264
def scan_in_memory(node, env, path=()): """ "Scans" a Node.FS.Dir for its in-memory entries. """ try: entries = node.entries except AttributeError: # It's not a Node.FS.Dir (or doesn't look enough like one for # our purposes), which can happen if a target list containing ...
0.001848
def cell_normalize(data): """ Returns the data where the expression is normalized so that the total count per cell is equal. """ if sparse.issparse(data): data = sparse.csc_matrix(data.astype(float)) # normalize in-place sparse_cell_normalize(data.data, data.i...
0.007205
def move_item(self, token, item_id, src_folder_id, dest_folder_id): """ Move an item from the source folder to the destination folder. :param token: A valid token for the user in question. :type token: string :param item_id: The id of the item to be moved :type item_id: ...
0.002041
def find_by_id(self, team, params={}, **options): """Returns the full record for a single team. Parameters ---------- team : {Id} Globally unique identifier for the team. [params] : {Object} Parameters for the request """ path = "/teams/%s" % (team) retu...
0.008264
def get_watchlist_ttl(self, item: str) -> int: """ Get the amount of time a specific item will remain on the watchlist. :param str item: The item to get the TTL for on the watchlist :return: Time in seconds. Returns None for a non-existing element :rtype: int """ ...
0.006424
def _clean_key_type(key_name, escape_char=ESCAPE_SEQ): """Removes type specifier returning detected type and a key name without type specifier. :param str key_name: A key name containing type postfix. :rtype: tuple[type|None, str] :returns: Type definition and cleaned key name. """ for i i...
0.001073
def fill_auth_list(self, auth_provider, name, groups, auth_list=None, permissive=None): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' ...
0.002804
def randomizer_bin_und(R, alpha, seed=None): ''' This function randomizes a binary undirected network, while preserving the degree distribution. The function directly searches for rewirable edge pairs (rather than trying to rewire edge pairs at random), and hence avoids long loops and works especial...
0.000748
def single(self, trigger_id, full=False): """ Get an existing (full) trigger definition. :param trigger_id: Trigger definition id to be retrieved. :param full: Fetch the full definition, default is False. :return: Trigger of FullTrigger depending on the full parameter value. ...
0.00641
def _check_infinite_flows(self, steps, flows=None): """ Recursively loop through the flow_config and check if there are any cycles. :param steps: Set of step definitions to loop through :param flows: Flows already visited. :return: None """ if flows is None: ...
0.003509
def get_is_authorized(request, pid): """MNAuthorization.isAuthorized(did, action) -> Boolean.""" if 'action' not in request.GET: raise d1_common.types.exceptions.InvalidRequest( 0, 'Missing required parameter. required="action"' ) # Convert action string to action level. Raises I...
0.001757
def refresh(self, id_or_uri, timeout=-1): """ The Refresh action reclaims the top-of-rack switches in a logical switch. Args: id_or_uri: Can be either the Logical Switch ID or URI timeout: Timeout in seconds. Wait for task completion by de...
0.006319
def _rgetattr(obj, key): """Recursive getattr for handling dots in keys.""" for k in key.split("."): obj = getattr(obj, k) return obj
0.006536
def dt_from_rfc8601(date_str): """Convert 8601 (ISO) date string to datetime object. Handles "Z" and milliseconds transparently. :param date_str: Date string. :type date_str: ``string`` :return: Date time. :rtype: :class:`datetime.datetime` """ # Normalize string and adjust for milli...
0.001393
def _complete_values(self, symbol = ""): """Compiles a list of possible symbols that can hold a value in place. These consist of local vars, global vars, and functions.""" result = {} #Also add the subroutines from the module and its dependencies. moddict = self._generic_filter_e...
0.010354
def number_to_string(n, alphabet): """ Given an non-negative integer ``n``, convert it to a string composed of the given ``alphabet`` mapping, where the position of each element in ``alphabet`` is its radix value. Examples:: >>> number_to_string(12345678, '01') '1011110001100001010...
0.002114
def list_from_json(source_list_json): """ Deserialise all the items in source_list from json """ result = [] if source_list_json == [] or source_list_json == None: return result for list_item in source_list_json: item = json.loads(list_item) try: if item['clas...
0.002461
def install_handler(self, app): """Install logging handler.""" # Configure python logging if app.config['LOGGING_CONSOLE_PYWARNINGS']: self.capture_pywarnings(logging.StreamHandler()) if app.config['LOGGING_CONSOLE_LEVEL'] is not None: for h in app.logger.handler...
0.004184
def t(root, children=None, debug=False, root_id=None): "Create (DGParented)Tree from a root (str) and a list of (str, list) tuples." if isinstance(root, Tree): if children is None: return root return root.__class__(root, children, root_id) elif isinstance(root, basestring): ...
0.001259
def get_cf_files(path, queue): """Get rule files in a directory and put them in a queue""" for root, _, files in os.walk(os.path.abspath(path)): if not files: continue for filename in files: fullname = os.path.join(root, filename) if os.path.isfile(fullname) a...
0.002294
def get_image(self): """Get the image currently being displayed. Returns ------- image : `~ginga.AstroImage.AstroImage` or `~ginga.RGBImage.RGBImage` Image object. """ if self._imgobj is not None: # quick optomization return self._img...
0.004773
def img2img_transformer_tiny(): """Tiny params.""" hparams = img2img_transformer2d_base() hparams.num_hidden_layers = 2 hparams.hidden_size = 128 hparams.batch_size = 4 hparams.max_length = 128 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.filter_size = 128 hparams.num_...
0.032345
def rpcproxy(spec): """Decorator to enable this class to proxy RPC client calls The decorated class constructor takes two additional arguments, `context=` is required to be a :class:`~p4p.client.thread.Context`. `format`= can be a string, tuple, or dictionary and is applied to PV name strings given...
0.002421
def resolve_weak_types(storage, debug=False): """Reslove weak type rules W1 - W3. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types """ for run in storage['runs']: prev_strong = prev_type = run['sor'] start, length = run['start'], run['length'] chars = storage['chars']...
0.000594
def verify_upload(self): """ Confirm that the last upload was sucessful. Raises TusUploadFailed exception if the upload was not sucessful. """ if self.request.status_code == 204: return True else: raise TusUploadFailed('', self.request.status_code,...
0.008547
def copy_artifact(src_path: str, artifact_hash: str, conf: Config): """Copy the artifact at `src_path` with hash `artifact_hash` to artifacts cache dir. If an artifact already exists at that location, it is assumed to be identical (since it's based on hash), and the copy is skipped. TODO: pruni...
0.001066
def set_user_agent_component(self, key, value, sanitize=True): """Add or replace new user-agent component strings. Given strings are formatted along the format agreed upon by Mollie and implementers: - key and values are separated by a forward slash ("/"). - multiple key/values are sepa...
0.005025
def split_url(url): """ Split the given URL ``base#anchor`` into ``(base, anchor)``, or ``(base, None)`` if no anchor is present. In case there are two or more ``#`` characters, return only the first two tokens: ``a#b#c => (a, b)``. :param string url: the url :rtype: list of str """ ...
0.002119
def get_logging_level(debug): """Returns logging level based on boolean""" level = logging.INFO if debug: level = logging.DEBUG return level
0.006098
def done(self, result, noraise=False): """This method is called when a task has finished executing. Subclass can override this method if desired, but should call superclass method at the end. """ # [??] Should this be in a critical section? # Has done() already been call...
0.001606
def quote_value(value): """ convert values to mysql code for the same mostly delegate directly to the mysql lib, but some exceptions exist """ try: if value == None: return SQL_NULL elif isinstance(value, SQL): return quote_sql(value.template, value.param) ...
0.00446
def recall_score(gold, pred, pos_label=1, ignore_in_gold=[], ignore_in_pred=[]): """ Calculate recall for a single class. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements ha...
0.002043
def view_decorator(function_decorator): """Convert a function based decorator into a class based decorator usable on class based Views. Can't subclass the `View` as it breaks inheritance (super in particular), so we monkey-patch instead. Based on http://stackoverflow.com/a/8429311 """ def simple_decorator(Vie...
0.025404
def send_request(self, request): """ Add itself to the observing list :param request: the request :return: the request unmodified """ if request.observe == 0: # Observe request host, port = request.destination key_token = hash(str(host...
0.006466
def tomorrow(hour=None, minute=None): """ Gives the ``datetime.datetime`` object corresponding to tomorrow. The default value for optional parameters is the current value of hour and minute. I.e: when called without specifying values for parameters, the resulting object will refer to the time = now ...
0.000905
def splitlines(self, keepends=False): """ B.splitlines([keepends]) -> list of lines Return a list of the lines in B, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ # Py2 str.splitlines() take...
0.003824
def distance(self, y, measure=None): """ Compute a pairwise distance measure between all rows of two numeric H2OFrames. :param H2OFrame y: Frame containing queries (small) :param str use: A string indicating what distance measure to use. Must be one of: - ``"l1"``: A...
0.006969
def correct_peaks(sig, peak_inds, search_radius, smooth_window_size, peak_dir='compare'): """ Adjust a set of detected peaks to coincide with local signal maxima, and Parameters ---------- sig : numpy array The 1d signal array peak_inds : np array Array of ...
0.000629
def call(self, name, options=None, o=None): """ Call another command. :param name: The command name :type name: str :param options: The options :type options: list or None :param o: The output :type o: cleo.outputs.output.Output """ if o...
0.003795
def handle(self, t_input: inference.TranslatorInput, t_output: inference.TranslatorOutput, t_walltime: float = 0.): """ :param t_input: Translator input. :param t_output: Translator output. :param t_walltime: Total walltime for translation. ...
0.008487
def __calculate_score(self, index_point, index_cluster): """! @brief Calculates Silhouette score for the specific object defined by index_point. @param[in] index_point (uint): Index point from input data for which Silhouette score should be calculated. @param[in] index_cluster (uin...
0.009259
def pos(self, p_x=None, y=None, z=None): """Set/Get actor position.""" if p_x is None: return np.array(self.GetPosition()) if z is None: # assume p_x is of the form (x,y,z) self.SetPosition(p_x) else: self.SetPosition(p_x, y, z) if self.trail:...
0.005391
def Ntubes_Phadkeb(DBundle, Do, pitch, Ntp, angle=30): r'''Using tabulated values and correction factors for number of passes, the highly accurate method of [1]_ is used to obtain the tube count of a given tube bundle outer diameter for a given tube size and pitch. Parameters ---------- DBundle...
0.003758
def binarize_percent(netin, level, sign='pos', axis='time'): """ Binarizes a network proprtionally. When axis='time' (only one available at the moment) then the top values for each edge time series are considered. Parameters ---------- netin : array or dict network (graphlet or contact rep...
0.002304
def begin(self, service_endpoint): """Create an AuthRequest object for the specified service_endpoint. This method will create an association if necessary.""" if self.store is None: assoc = None else: assoc = self._getAssociation(service_endpoint) ...
0.00316
def scan_videopath(videopath, callback, recursive=False): """ Scan the videopath string for video files. :param videopath: Path object :param callback: Instance of ProgressCallback :param recursive: True if the scanning should happen recursive :return: tuple with list of videos and list of subti...
0.004147
def striptags(self): r"""Unescape markup into an unicode string and strip all tags. This also resolves known HTML4 and XHTML entities. Whitespace is normalized to one: >>> Markup("Main &raquo; <em>About</em>").striptags() u'Main \xbb About' """ stripped = u' '...
0.004938
def _set_siteinfo(self): """ capture API sitematrix data in data attribute """ data = self._load_response('siteinfo').get('query') mostviewed = data.get('mostviewed') self.data['mostviewed'] = [] for item in mostviewed[1:]: if item['ns'] == 0: ...
0.001754
def compose(self, to, subject, text): """Login required. Sends POST to send a message to a user. Returns True or raises :class:`exceptions.UnexpectedResponse` if non-"truthy" value in response. URL: ``http://www.reddit.com/api/compose/`` :param to: username or :class`things.A...
0.007825
def list(self, request, *args, **kwargs): """ To get a list of price list items, run **GET** against */api/merged-price-list-items/* as authenticated user. If service is not specified default price list items are displayed. Otherwise service specific price list items are display...
0.006579
def parse_theta2_report (self, fh): """ Parse the final THetA2 log file. """ parsed_data = {} for l in fh: if l.startswith('#'): continue else: s = l.split("\t") purities = s[1].split(',') parsed_data['propor...
0.008086
def get_login_button_url(self, button_color=None, caption_color=None, button_size=None): """Return URL for image used for RunKeeper Login button. @param button_color: Button color. Either 'blue', 'grey' or 'black'. Default: 'blue'. @param caption_color: Bu...
0.008013
def get_annotations(self, min_rho=None): ''' Get the list of annotations found. :param min_rho: if set, only get entities with a rho-score (confidence) higher than this. ''' return (a for a in self.annotations if min_rho is None or a.score > min_rho)
0.013793
def stationary_coefficients(self, j, coeff_type='ma'): """ Wold representation moving average or VAR coefficients for the steady state Kalman filter. Parameters ---------- j : int The lag length coeff_type : string, either 'ma' or 'var' (default='ma')...
0.001679
def notifyPop(self, queue, length = 1): ''' Internal notify for sub-queues been poped :returns: List of any events generated by this pop ''' self.totalSize = self.totalSize - length ret1 = [] ret2 = [] if self.isWaited and self.canAppend(): ...
0.007701
def actuator_on(self, service_location_id, actuator_id, duration=None): """ Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator ...
0.00299
def overfit(self, tau=None, plot=True, clobber=False, w=9, **kwargs): r""" Compute the masked & unmasked overfitting metrics for the light curve. This routine injects a transit model given by `tau` at every cadence in the light curve and recovers the transit depth when (1) leaving ...
0.00018
def run(self, scenario): """Run the algorithm, utilizing a classifier set to choose the most appropriate action for each situation produced by the scenario. Improve the situation/action mapping on each reward cycle to maximize reward. Return the classifier set that was created. ...
0.002747
def __presence_unavailable(self,stanza): """Process an unavailable presence from a MUC room. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `Presence` :return: `True` if the stanza was properly recognized as generated by one of the...
0.009917
async def create( cls, fabric: Union[Fabric, int], vid: int, *, name: str = None, description: str = None, mtu: int = None, relay_vlan: Union[Vlan, int] = None, dhcp_on: bool = False, primary_rack: Union[RackController, str] = None, secondary_rack: Union[RackC...
0.000515
def assert_no_text(self, *args, **kwargs): """ Asserts that the page or current node doesn't have the given text content, ignoring any HTML tags. Args: *args: Variable length argument list for :class:`TextQuery`. **kwargs: Arbitrary keyword arguments for :class:`...
0.004474
def _get_password(params): """Get the password for a database connection from :mod:`keyring` Args: params (dict): database configuration, as defined in :mod:`ozelot.config` Returns: str: password """ user_name = params['user'] service_name = para...
0.006329
def create_organisation(self, organisation_json): ''' Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`. ''' return trolly.organisation.Organisation( trello_client=self, ...
0.004435
def free_parameter(self, name, par, free=True): """Free/Fix a parameter of a source by name. Parameters ---------- name : str Source name. par : str Parameter name. """ name = self.get_source_name(name) if par in self._lck_params....
0.004283
def get_task_cache(self, username, courseid, taskid): """ Shorthand for get_task_caches([username], courseid, taskid)[username] """ return self.get_task_caches([username], courseid, taskid)[username]
0.008658
def set_cursor(self, col, row): """Move the cursor to an explicit column and row position.""" # Clamp row to the last row of the display. if row > self._lines: row = self._lines - 1 # Set location. self.write8(LCD_SETDDRAMADDR | (col + LCD_ROW_OFFSETS[row]))
0.006452
def get(self): """ get method """ try: cluster = self.get_argument_cluster() role = self.get_argument_role() environ = self.get_argument_environ() topology_name = self.get_argument_topology() component = self.get_argument_component() metric_names = self.get_required_arguments...
0.017225
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
0.002201
def indices2one_hot(indices, nb_classes): """ Convert an iterable of indices to one-hot encoded list. You might also be interested in sklearn.preprocessing.OneHotEncoder Parameters ---------- indices : iterable iterable of indices nb_classes : int Number of classes dtyp...
0.001212
def get_unique_constraint_declaration_sql(self, name, index): """ Obtains DBMS specific SQL code portion needed to set a unique constraint declaration to be used in statements like CREATE TABLE. :param name: The name of the unique constraint. :type name: str :param inde...
0.002288
def confidence_intervals(self, X, width=.95, quantiles=None): """estimate confidence intervals for the model. Parameters ---------- X : array-like of shape (n_samples, m_features) Input data matrix width : float on [0,1], optional quantiles : array-like of fl...
0.003834
def get_draft_page_by_id(self, page_id, status='draft'): """ Provide content by id with status = draft :param page_id: :param status: :return: """ url = 'rest/api/content/{page_id}?status={status}'.format(page_id=page_id, status=status) return self.get(url...
0.009346