text
stringlengths
78
104k
score
float64
0
0.18
def cookies(self, url): """ Return cookies that are matching the path and are still valid :param url: :return: """ part = urlparse(url) #if part.port: # _domain = "%s:%s" % (part.hostname, part.port) #else: _domain = part.hostname ...
0.004315
def _format_variants(self, variant, index, case_obj, add_all_info=False): """Return a Variant object Format variant make a variant that includes enough information for the variant view. If add_all_info then all transcripts will be parsed Args: variant (cython2.Varia...
0.0028
def most_by_mask(self, mask, y, mult): """ Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities Arguments: mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contain...
0.006878
def typedef( self, name=None, function=None, header_dir=None, header_file=None, recursive=None): """returns reference to typedef declaration, that is matched defined criteria""" return ( self._find_single( ...
0.003082
def _get_role_arn(): """ Return role arn from X-Role-ARN header, lookup role arn from source IP, or fall back to command line default. """ role_arn = bottle.request.headers.get('X-Role-ARN') if not role_arn: role_arn = _lookup_ip_role_arn(bottle.request.environ.get('REMOTE_ADDR')) ...
0.005168
def _adjust_scrollbars(self): """ Expands the vertical scrollbar beyond the range set by Qt. """ # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp # and qtextedit.cpp. document = self._control.document() scrollbar = self._control.verticalScrollBar() ...
0.001579
def _import(self, name): ''' Import namespace package ''' mod = __import__(name) components = name.split('.') for comp in components[1:]: mod = getattr(mod, comp) return mod
0.008889
def filter_results(source, results, aggressive): """Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712). """ non_docstring_string_line_numbers = multiline_string_lines( source, include_docstrings=False) all_string_line_numbers = ...
0.000503
def add(name, gid=None, **kwargs): ''' Add the specified group CLI Example: .. code-block:: bash salt '*' group.add foo 3456 ''' ### NOTE: **kwargs isn't used here but needs to be included in this ### function for compatibility with the group.present state if info(name): ...
0.00254
def load_cPkl(fpath, verbose=None, n=None): """ Loads a pickled file with optional verbosity. Aims for compatibility between python2 and python3. TestPickleExtentsSimple: >>> def makedata_simple(): >>> data = np.empty((500, 2 ** 20), dtype=np.uint8) + 1 >>> return data ...
0.000853
def _open_dataset(self, urlpath): """Open dataset using dask and use pattern fields to set new columns """ import dask.dataframe if self.pattern is None: self._dataframe = dask.dataframe.read_csv( urlpath, storage_options=self._storage_options, ...
0.004429
def _set_no_advertise(self, v, load=False): """ Setter method for no_advertise, mapped from YANG variable /interface/fortygigabitethernet/ipv6/ipv6_nd_ra/ipv6_intf_cmds/nd/prefix/lifetime/no_advertise (empty) If this variable is read-only (config: false) in the source YANG file, then _set_no_advertise i...
0.005663
def fetch(cls, client, symbol): """ fetch data for stock """ assert(type(symbol) is str) url = ("https://api.robinhood.com/instruments/?symbol={0}". format(symbol)) data = client.get(url) return data["results"][0]
0.007018
def monitoring_plot(ind, shap_values, features, feature_names=None): """ Create a SHAP monitoring plot. (Note this function is preliminary and subject to change!!) A SHAP monitoring plot is meant to display the behavior of a model over time. Often the shap_values given to this plot explain the loss...
0.00762
def iter_links(self): """An iterator over the working links in the machine. Generates a series of (x, y, link) tuples. """ for x in range(self.width): for y in range(self.height): for link in Links: if (x, y, link) in self: ...
0.005764
def get_tripIs_active_in_range(self, start, end): """ Obtain from the (standard) GTFS database, list of trip_IDs (and other trip_related info) that are active between given 'start' and 'end' times. The start time of a trip is determined by the departure time at the last stop of the trip...
0.006554
def identify(self, header): """Identifies a signature and returns the appropriate Signer object. This is done by reading an authorization header and matching it to signature characteristics. None is returned if the authorization header does not match the format of any signature identified by thi...
0.007042
def get_csv_rows_for_installed( old_csv_rows, # type: Iterable[List[str]] installed, # type: Dict[str, str] changed, # type: set generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[InstalledCSVRow] """ :param installed: A map from archive RECORD path to instal...
0.000848
def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained...
0.00243
def start(self): """Start the worker (emits sig_started signal with worker as arg).""" if not self._started: self.sig_started.emit(self) self._started = True
0.010152
def add_user_role(self, user, role): """Add role to given user. Args: user (string): User name. role (string): Role to assign. Raises: requests.HTTPError on failure. """ self.service.add_user_role( user, role, self.url...
0.005305
def undefine(self): """Undefine the Template. Python equivalent of the CLIPS undeftemplate command. The object becomes unusable after this method has been called. """ if lib.EnvUndeftemplate(self._env, self._tpl) != 1: raise CLIPSError(self._env)
0.006645
def get_ISI_ratio(sorting, sampling_frequency, unit_ids=None, save_as_property=True): '''This function calculates the ratio between the frequency of spikes present within 0- to 2-ms (refractory period) interspike interval (ISI) and those at 0- to 20-ms interval. It then returns the ratios and also adds a pr...
0.004228
def heuristic_cost(self, start, target): """ assumes start and target are an (x,y) grid """ (x1, y1) = start (x2, y2) = target return abs(x1 - x2) + abs(y1 - y2)
0.010363
def get_safe(self, section, key, default=None): """ Attempt to get a configuration value from a certain section in a ``cfg`` object but returning None if not found. Avoids the need to be doing try/except {ConfigParser Exceptions} every time. """ try: return se...
0.004535
def estimation_required(func, *args, **kw): """ Decorator checking the self._estimated flag in an Estimator instance, raising a value error if the decorated function is called before estimator.estimate() has been called. If mixed with a property-annotation, this annotation needs to come first in the ch...
0.00542
def get_http_method_arg_name(self): """ Return the HTTP function to call and the params/data argument name """ if self.method == 'get': arg_name = 'params' else: arg_name = 'data' return getattr(requests, self.method), arg_name
0.006689
def plot(self, **kargs): """Plot the data set, using the sampling information to set the x-axis correctly.""" from pylab import plot, linspace, xlabel, ylabel, grid time = linspace(1*self.dt, self.N*self.dt, self.N) plot(time, self.data, **kargs) xlabel('Time') yl...
0.005618
def next(self): """Request next data container. This function call is blocking. Returns ------- data : dict The data for this train, keyed by source name. meta : dict The metadata for this train, keyed by source name. This dictionary...
0.001764
def wikidata_get(identifier): """ https://www.wikidata.org/wiki/Special:EntityData/P248.json """ url = 'https://www.wikidata.org/wiki/Special:EntityData/{}.json'.format(identifier) #logging.info(url) return json.loads(requests.get(url).content)
0.011029
def by_sql(cls, sql, engine_or_session): """ Query with sql statement or texture sql. """ ses, auto_close = ensure_session(engine_or_session) result = ses.query(cls).from_statement(sql).all() if auto_close: ses.close() return result
0.006667
def index_of_item(self, item): """Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of the item :rtype: :class:`QtCore.QModelIndex` :raises: ValueError """ # root has an invalid index...
0.00152
def log_results(): """This is the callback that is run once the Async task is finished. It takes the output from grep and logs it.""" from furious.context import get_current_async # Get the recently finished Async object. async = get_current_async() # Pull out the result data and log it. f...
0.008
def give(self, terrain, num=1): """ Add a certain number of resources to the trade from giver->getter :param terrain: resource type, models.Terrain :param num: number to add, int :return: None """ for _ in range(num): logging.debug('terrain={}'.format(...
0.005435
def get_all_project_owners(project_ids=None, **kwargs): """ Get the project owner entries for all the requested projects. If the project_ids argument is None, return all the owner entries for ALL projects """ projowner_qry = db.DBSession.query(ProjectOwner) if project_ids is n...
0.009259
def __float_window(window_spec): '''Decorator function for windows with fractional input. This function guarantees that for fractional `x`, the following hold: 1. `__float_window(window_function)(x)` has length `np.ceil(x)` 2. all values from `np.floor(x)` are set to 0. For integer-valued `x`, th...
0.00133
def rotate_z(self, angle): """ Rotates mesh about the z-axis. Parameters ---------- angle : float Angle in degrees to rotate about the z-axis. """ axis_rotation(self.points, angle, inplace=True, axis='z')
0.007299
def check(self, var): """Return True if the variable matches this type, and False otherwise.""" if self._class is None: self._init() return self._class and self._checker(var, self._class)
0.018957
def find_serial_devices(serial_matcher="ED"): """ Finds a list of USB devices where the serial number (partially) matches the given string. :param str serial_matcher (optional): only device IDs starting with this string are returned :rtype: List[str] """ objWMIService = win32com.client...
0.006329
def spec(self): """Return a dict with values that can be fed directly into SelectiveRowGenerator""" return dict( headers=self.header_lines, start=self.start_line, comments=self.comment_lines, end=self.end_line )
0.010601
def return_tip(self) -> 'InstrumentContext': """ If a tip is currently attached to the pipette, then it will return the tip to it's location in the tiprack. It will not reset tip tracking so the well flag will remain False. :returns: This instance """ if not sel...
0.002639
def get_user_roles(self, user): """get permissions of a user""" memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups') results = [] for each in memberShipRecords: for group in each.groups: results.append({'role':group.role}) ...
0.011696
def update_share(self, share_id, **kwargs): """Updates a given share :param share_id: (int) Share ID :param perms: (int) update permissions (see share_file_with_user() below) :param password: (string) updated password for public link Share :param public_upload: (boolean) enable/...
0.002681
def LSL(self, a): """ Shifts all bits of accumulator A or B or memory location M one place to the left. Bit zero is loaded with a zero. Bit seven of accumulator A or B or memory location M is shifted into the C (carry) bit. This is a duplicate assembly-language mnemonic for the ...
0.003656
def get_available_palettes(chosen_palette): ''' Given a chosen palette, returns tuple of those available, or None when not found. Because palette support of a particular level is almost always a superset of lower levels, this should return all available palettes. Returns: ...
0.001908
def set_sys(layout): ''' Set current system keyboard setting CLI Example: .. code-block:: bash salt '*' keyboard.set_sys dvorak ''' if salt.utils.path.which('localectl'): __salt__['cmd.run']('localectl set-keymap {0}'.format(layout)) elif 'RedHat' in __grains__['os_family'...
0.001107
def eeg_to_df(eeg, index=None, include="all", exclude=None, hemisphere="both", central=True): """ Convert mne Raw or Epochs object to dataframe or dict of dataframes. DOCS INCOMPLETE :( """ if isinstance(eeg, mne.Epochs): data = {} if index is None: index = range(len(ee...
0.00344
def set_mtime(self, filename, mtime, size): """Store real file mtime in meta data. This is needed on FTP targets, because FTP servers don't allow to set file mtime, but use to the upload time instead. We also record size and upload time, so we can detect if the file was changed ...
0.005051
def countok(self): """ Boolean array showing which stars pass all count constraints. A "count constraint" is a constraint that affects the number of stars. """ ok = np.ones(len(self.stars)).astype(bool) for name in self.constraints: c = self.constraints[name]...
0.004808
def parse_commit(parts): '''Accept a parsed single commit. Some of the named groups require further processing, so parse those groups. Return a dictionary representing the completely parsed commit. ''' commit = {} commit['commit'] = parts['commit'] commit['tree'] = parts['tree'] pare...
0.000993
def boundplot(results, dims, it=None, idx=None, prior_transform=None, periodic=None, ndraws=5000, color='gray', plot_kwargs=None, labels=None, label_kwargs=None, max_n_ticks=5, use_math_text=False, show_live=False, live_color='darkviolet', live_kwargs=None, span=N...
0.000618
def is_empty(self): ''' Return `True` if form is valid and contains an empty lookup. ''' return (self.is_valid() and not self.simple_lookups and not self.complex_conditions and not self.extra_conditions)
0.01845
def client_receives_without_validation(self, *parameters): """Receive a message with template defined using `New Message`. Message template has to be defined with `New Message` before calling this. Optional parameters: - `name` the client name (default is the latest used) examp...
0.006289
def replace_find(self, focus_replace_text=False, replace_all=False): """Replace and find""" if (self.editor is not None): replace_text = to_text_string(self.replace_text.currentText()) search_text = to_text_string(self.search_text.currentText()) re_pattern = None...
0.000702
def readerForDoc(cur, URL, encoding, options): """Create an xmltextReader for an XML in-memory document. The parsing flags @options are a combination of xmlParserOption. """ ret = libxml2mod.xmlReaderForDoc(cur, URL, encoding, options) if ret is None:raise treeError('xmlReaderForDoc() failed') ret...
0.008646
def _parse(self, infile): """Actually parse the config file.""" temp_list_values = self.list_values if self.unrepr: self.list_values = False comment_list = [] done_start = False this_section = self maxline = len(infile) - 1 cur_index = -1 ...
0.001236
def build_method_map(self, prototype, prefix=''): """ Add prototype methods to the dispatcher. Parameters ---------- prototype : object or dict Initial method mapping. If given prototype is a dictionary then all callable objects will be added to dispa...
0.002353
def colorpalette(self, colorpalette): """ Set the colorpalette which should be used """ if isinstance(colorpalette, str): # we assume it's a path to a color file colorpalette = colors.parse_colors(colorpalette) self._colorpalette = colors.sanitize_color_palette(colo...
0.009119
def urlencode(txt): """Url encode a path.""" if isinstance(txt, unicode): txt = txt.encode('utf-8') return urllib.quote_plus(txt)
0.006711
def _format_response(rows, fields, unique_col_names): """This function will look at the data column of rows and extract the specified fields. It will also dedup changes where the specified fields have not changed. The list of rows should be ordered by the compound primary key which versioning pivots around ...
0.005056
def create_driver_script(name, create=None): # noqa: E501 """Create a new script Create a new script # noqa: E501 :param name: Get status of a driver with this name :type name: str :param create: The data needed to create this script :type create: dict | bytes :rtype: Response """ ...
0.001316
def create_default_views(self, create_datastore_views=False): # type: (bool) -> None """Create default resource views for all resources in dataset Args: create_datastore_views (bool): Whether to try to create resource views that point to the datastore Returns: N...
0.007924
def push_record_set(self, **kwargs): """ Push build config set record to Brew. 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 ca...
0.00293
def _preprocess_data(self, data): """ At this point, the data either has a `read` attribute (e.g. a file object or a StringIO) or is a string that is a JSON document. If self.chunksize, we prepare the data for the `__next__` method. Otherwise, we read it into memory for the `rea...
0.00369
def style_ansi(raw_code, lang=None): """ actual code hilite """ lexer = 0 if lang: try: lexer = get_lexer_by_name(lang) except ValueError: print col(R, 'Lexer for %s not found' % lang) lexer = None if not lexer: try: if guess_lexer: ...
0.002766
def squad_v2_f1(y_true: List[List[str]], y_predicted: List[str]) -> float: """ Calculates F-1 score between y_true and y_predicted F-1 score uses the best matching y_true answer The same as in SQuAD-v2.0 Args: y_true: list of correct answers (correct answers are represented by list of stri...
0.001505
def get(name): """ Returns a matcher instance by class or alias name. Arguments: name (str): matcher class name or alias. Returns: matcher: found matcher instance, otherwise ``None``. """ for matcher in matchers: if matcher.__name__ == name or getattr(matcher, 'name', N...
0.002778
def get_pole(continent,age): """ returns rotation poles and angles for specified continents and ages assumes fixed Africa. Parameters __________ continent : aus : Australia eur : Eurasia mad : Madacascar [nwaf,congo] : NW Africa [choose one...
0.17147
def _run_vqsr(in_file, ref_file, vrn_files, sensitivity_cutoff, filter_type, data): """Run variant quality score recalibration. """ cutoffs = ["100.0", "99.99", "99.98", "99.97", "99.96", "99.95", "99.94", "99.93", "99.92", "99.91", "99.9", "99.8", "99.7", "99.6", "99.5", "99.0", "98.0", "90....
0.004906
def delete_after_days(self, bucket, key, days): """更新文件生命周期 Returns: 一个dict变量,返回结果类似: [ { "code": <HttpCode int>, "data": <Data> }, { "code": <HttpCode int> }, { "code": <HttpCode int> }, { "code...
0.004213
def step(self, observation, argmax_sampling=False): """ Select actions based on model's output """ policy_params, q = self(observation) actions = self.action_head.sample(policy_params, argmax_sampling=argmax_sampling) # log probability - we can do that, because we support only discrete ...
0.007143
def get_item_sh_fields(self, identity=None, item_date=None, sh_id=None, rol='author'): """ Get standard SH fields from a SH identity """ eitem_sh = self.__get_item_sh_fields_empty(rol) if identity: # Use the identity to get the SortingHat identity ...
0.002988
def create_git_release(self, tag, name, message, draft=False, prerelease=False, target_commitish=github.GithubObject.NotSet): """ :calls: `POST /repos/:owner/:repo/releases <http://developer.github.com/v3/repos/releases>`_ :param tag: string :param name: string :param message: st...
0.004145
def tag_and_push(context): """Tags your git repo with the new version number""" tag_option = '--annotate' if probe.has_signing_key(context): tag_option = '--sign' shell.dry_run( TAG_TEMPLATE % (tag_option, context.new_version, context.new_version), context.dry_run, ) sh...
0.002725
async def emit(self, name): """ Add a callback to the event named 'name'. Returns this object for chained 'on' calls. """ for cb in self._event_list[name]: if isawaitable(cb): await cb else: cb()
0.006873
def sde(self): """ Return the state space representation of the covariance. Note! For Sparse GP inference too small or two high values of lengthscale lead to instabilities. This is because Qc are too high or too low and P_inf are not full rank. This effect depends on app...
0.021189
def _find_corresponding_multicol_key(key, keys_multicol): """Find the corresponding multicolumn key.""" for mk in keys_multicol: if key.startswith(mk) and 'of' in key: return mk return None
0.004525
def extract_exception(*args): """ Extracts the exception from given arguments or from :func:`sys.exc_info`. :param \*args: Arguments. :type \*args: \* :return: Extracted exception. :rtype: tuple """ cls, instance, trcback = sys.exc_info() exceptions = filter(lambda x: issubclass(t...
0.008224
def RRX_C(value, carry, width): """ The ARM RRX (rotate right with extend and with carry) operation. :param value: Value to shift :type value: int or long or BitVec :param int amount: How many bits to rotate it. :param int width: Width of the value :return: Resultant value and carry result ...
0.002193
def _set_link_fault_signaling(self, v, load=False): """ Setter method for link_fault_signaling, mapped from YANG variable /interface/ethernet/link_fault_signaling (container) If this variable is read-only (config: false) in the source YANG file, then _set_link_fault_signaling is considered as a private ...
0.004873
def imrescale(img, scale, return_scale=False, interpolation='bilinear'): """Resize image while keeping the aspect ratio. Args: img (ndarray): The input image. scale (float or tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by...
0.000678
def detach(self) -> iostream.IOStream: """Take control of the underlying stream. Returns the underlying `.IOStream` object and stops all further HTTP processing. May only be called during `.HTTPMessageDelegate.headers_received`. Intended for implementing protocols like websock...
0.003257
def _check_datetime(self, node): """ Check that a datetime was infered. If so, emit boolean-datetime warning. """ try: infered = next(node.infer()) except astroid.InferenceError: return if isinstance(infered, Instance) and infered.qname() == "datet...
0.007692
def reload(script, input, output): """ reloads the generator script when the script files or the input files changes """ script = Path(script).expand().abspath() output = Path(output).expand().abspath() input = input if isinstance(input, (list, tuple)) else [input] output.makedirs_p() ...
0.002786
def insert_local_var(self, vname, vtype, position): "Inserts a new local variable" index = self.insert_id(vname, SharedData.KINDS.LOCAL_VAR, [SharedData.KINDS.LOCAL_VAR, SharedData.KINDS.PARAMETER], vtype) self.table[index].attribute = position
0.01107
def read_property_from_xml(root, path): """ Get the text from an XML property. Whitespaces, tabs and new lines are trimmed :param root: container in which we search :type root: ElementTree.Element :param path: path to search in root :type path: str :return: the text of the element at t...
0.001992
def drag_and_drop(self, droppable): """ Performs drag a element to another elmenet. Currently works only on Chrome driver. """ self.scroll_to() ActionChains(self.parent.driver).drag_and_drop(self._element, droppable._element).perform()
0.010563
def fqn(o): """Returns the fully qualified class name of an object or a class :param o: object or class :return: class name """ parts = [] if isinstance(o, (str, bytes)): return o if not hasattr(o, '__module__'): raise ValueError('Invalid argument `%s`' % o) parts.append...
0.001842
def get_inventory_text(self): """Return the inventory information from the device.""" inventory_text = None if self.inventory_cmd: try: inventory_text = self.device.send(self.inventory_cmd, timeout=120) self.log('Inventory collected') excep...
0.005894
def next(self): """ This method is deprecated, a holdover from when queries were iterators, rather than iterables. @return: one element of massaged data. """ if self._selfiter is None: warnings.warn( "Calling 'next' directly on a query is depr...
0.003247
def set_variable(self, name, type_, size): """ Register variable of name and type_, with a (multidimensional) size. :param name: variable name as it appears in code :param type_: may be any key from Kernel.datatypes_size (typically float or double) :param size: either None for s...
0.008772
def geometry(obj): """ Apply ``vtkGeometryFilter``. """ gf = vtk.vtkGeometryFilter() gf.SetInputData(obj) gf.Update() return gf.GetOutput()
0.005988
def delete_edge(self, tail_node_or_ID, head_node_or_ID): """ Removes an edge from the graph. Returns the deleted edge or None. """ if isinstance(tail_node_or_ID, Node): tail_node = tail_node_or_ID else: tail_node = self.get_node(tail_node_or_ID) if isinst...
0.002653
def inform(self, reading): """Inform strategy creator of the sensor status.""" try: self._inform_callback(self._sensor, reading) except Exception: log.exception('Unhandled exception trying to send {!r} ' 'for sensor {!r} of type {!r}' ...
0.007692
def noisered(self, profile_path, amount=0.5): '''Reduce noise in the audio signal by profiling and filtering. This effect is moderately effective at removing consistent background noise such as hiss or hum. Parameters ---------- profile_path : str Path to a n...
0.001567
def run_pod(self, pod, startup_timeout=120, get_logs=True): # type: (Pod, int, bool) -> Tuple[State, Optional[str]] """ Launches the pod synchronously and waits for completion. Args: pod (Pod): startup_timeout (int): Timeout for startup of the pod (if pod is pendi...
0.004751
def add_constraint(self, constraint, variables=tuple()): """Add a constraint. Args: constraint (function/iterable/:obj:`.Constraint`): Constraint definition in one of the supported formats: 1. Function, with input arguments matching the order and ...
0.005573
def write_image(self, stream, image_format="svg", **kwargs): """ Writes the phase diagram to an image in a stream. Args: stream: stream to write to. Can be a file stream or a StringIO stream. image_format format for image. Can be any of ma...
0.00314
def indexed_sum_over_const(cls, ops, kwargs): r'''Execute an indexed sum over a term that does not depend on the summation indices .. math:: \sum_{j=1}^{N} a = N a >>> a = symbols('a') >>> i, j = (IdxSym(s) for s in ('i', 'j')) >>> unicode(Sum(i, 1, 2)(a)) '2 a' >>> unicode(S...
0.001239
def _check_panel(self, length): """ Check that given fixed panel length evenly divides index. Parameters ---------- length : int Fixed length with which to subdivide index """ n = len(self.index) if divmod(n, length)[1] != 0: raise...
0.006838