text
stringlengths
78
104k
score
float64
0
0.18
def _find_valid_index(self, how): """ Retrieves the index of the first valid value. Parameters ---------- how : {'first', 'last'} Use this parameter to change between the first or last valid index. Returns ------- idx_first_valid : type of in...
0.002286
def present(name, Name=None, ScheduleExpression=None, EventPattern=None, Description=None, RoleArn=None, State=None, Targets=None, region=None, key=None, keyid=None, profile=None): ''' Ensure trail exists. name The name of...
0.006122
def priority(s): """Return priority for a given object.""" # REZ: Previously this value was calculated in place many times which is # expensive. Do it once early. # REZ: Changed this to output a list, so that can nicely sort "validate" # items by the sub-priority of their schema type_...
0.001335
def is_filtered(self, require=None, ignore=None): """Return ``True`` for filtered calls :param iterable ignore: if set, the filters to ignore, make sure to include 'PASS', when setting, default is ``['PASS']`` :param iterable require: if set, the filters to require for returning ...
0.002853
def gridnet(np, pfile, plenfile, tlenfile, gordfile, outlet=None, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run gridnet""" fname = TauDEM.func_name('gridnet') return TauDEM.run(FileClass.get_executable_fullpath(fname, exedi...
0.010511
def head(self, lines=10): """ Return the top lines of the file. """ self.file.seek(0) for i in range(lines): if self.seek_next_line() == -1: break end_pos = self.file.tell() self.file.seek(0) data = self.file.read...
0.006784
def pokeStorable(self, storable, objname, obj, container, visited=None, _stack=None, **kwargs): """ Arguments: storable (StorableHandler): storable instance. objname (any): record reference. obj (any): object to be serialized. container (any): containe...
0.005848
def vhost_remove(cls, name): """ Delete a vhost in a webaccelerator """ oper = cls.call('hosting.rproxy.vhost.delete', name) cls.echo('Deleting your virtual host %s' % name) cls.display_progress(oper) cls.echo('Your virtual host have been removed') return oper
0.006494
def relationship(self, node): """ Retrieve the relationship object for this first relationship between self and node. :param node: :return: StructuredRel """ self._check_node(node) my_rel = _rel_helper(lhs='us', rhs='them', ident='r', **self.definition) q...
0.007752
def batch(samples): """CWL: batch together per sample, joint and germline calls for ensemble combination. Sets up groups of same sample/batch variant calls for ensemble calling, as long as we have more than one caller per group. """ samples = [utils.to_single_data(x) for x in samples] sample_or...
0.004759
def return_daily_messages_count(self, sender): """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """ h24 = now() - timedelta(days=1) return Message.objects.filter(sender=sender, sent_at__gte=h24).count()
0.009967
def send_command(self, cmd, priority=False): """ Flushes a command to the server as a bytes payload. """ if priority: self._pending.insert(0, cmd) else: self._pending.append(cmd) self._pending_size += len(cmd) if self._pending_size > DEFAU...
0.005319
def _eval(self, memory, addr, n, **kwargs): """ Gets n solutions for an address. """ return memory.state.solver.eval_upto(addr, n, exact=kwargs.pop('exact', self._exact), **kwargs)
0.014151
def _commit_run_log(self): """" Commit the current run log to the backend. """ logger.debug('Committing run log for job {0}'.format(self.name)) self.backend.commit_log(self.run_log)
0.009756
def nt_quote_arg(arg): """Quote a command line argument according to Windows parsing rules""" result = [] needquote = False nb = 0 needquote = (" " in arg) or ("\t" in arg) if needquote: result.append('"') for c in arg: if c == '\\': nb += 1 elif c == '...
0.001309
def get_interface_detail_output_interface_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail output = ET.SubElement(get_interface_detail, "output"...
0.002743
def jsonHook(encoded): """Custom JSON decoder that allows construction of a new ``Smi`` instance from a decoded JSON object. :param encoded: a JSON decoded object literal (a dict) :returns: "encoded" or one of the these objects: :class:`Smi`, :class:`MzmlScan`, :class:`Mzml...
0.002427
def rebuildSmooth(self): """ Rebuilds a smooth path based on the inputed points and set \ parameters for this item. :return <QPainterPath> """ # collect the control points points = self.controlPoints() # create the path path = QPainte...
0.002237
def _ClientPathToString(client_path, prefix=""): """Returns a path-like String of client_path with optional prefix.""" return os.path.join(prefix, client_path.client_id, client_path.vfs_path)
0.015385
def set(self, param, value): """ sets the param to the value provided """ self.raw_dict[param] = value self.manifest.set(self.feature_name, param, value)
0.011299
def handle_input(self, smtp_command, data=None): """Processes the given SMTP command with the (optional data). [PUBLIC API] """ self._command_arguments = data self.please_close_connection_after_response(False) # SMTP commands must be treated as case-insensitive co...
0.001157
def remove_ephemeral_listener(self, uid): """Remove ephemeral listener with given uid.""" self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners if listener['uid'] != uid)
0.011905
def addMethod(self, m): """ Adds a L{Method} to the interface """ if m.nargs == -1: m.nargs = len([a for a in marshal.genCompleteTypes(m.sigIn)]) m.nret = len([a for a in marshal.genCompleteTypes(m.sigOut)]) self.methods[m.name] = m self._xml = Non...
0.006231
def pluralize(self, measure, singular, plural): """ Returns a string that contains the measure (amount) and its plural or singular form depending on the amount. Parameters: :param measure: Amount, value, always a numerical value :param singular: The singular form of the ...
0.003419
def _mirror_groups(self): """ Mirrors the user's LDAP groups in the Django database and updates the user's membership. """ target_group_names = frozenset(self._get_groups().get_group_names()) current_group_names = frozenset( self._user.groups.values_list("name...
0.00242
def xpath_on_node(self, node, xpath, **kwargs): """ Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is d...
0.002952
def send_message(self, id: str, message: str) -> Dict[str, Any]: """Send a message to a channel For formatting options, see the documentation: https://discordapp.com/developers/docs/resources/channel#create-message Args: id: channel snowflake id message: you...
0.005102
def get_request_token_secret(self, client_key, token, request): """Get request token secret. The request token object should a ``secret`` attribute. """ log.debug('Get request token secret of %r for %r', token, client_key) tok = request.request_token or self._g...
0.004149
def _manage_child_object(self, nurest_object, method=HTTP_METHOD_GET, async=False, callback=None, handler=None, response_choice=None, commit=False): """ Low level child management. Send given HTTP method with given nurest_object to given ressource of current object Args: nurest_obje...
0.007561
def add_user(self, user_id, custom_properties=None, headers=None, endpoint_url=None): """ Creates a new identified user if he doesn't exist. :param str user_id: identified user's ID :param dict custom_properties: user properties :param dict headers: custom request headers (if is...
0.005727
def _analyze_tree(self, tree): """Analyze given tree and create mapping of indexes to character addresses. """ addresses = [] for text in self._iter_texts(tree): for i, char in enumerate(text.content): if char in whitespace: char = ...
0.003091
def resource_groups(self): """Instance depends on the API version: * 2016-02-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2016_02_01.operations.ResourceGroupsOperations>` * 2016-09-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2016_09_01.operat...
0.007973
def client_factory(self): """ Custom client factory to set proxy options. """ if self._service.production: url = self.production_url else: url = self.testing_url proxy_options = dict() https_proxy_setting = os.environ.get(...
0.011158
def guess_filename(obj): """Tries to guess the filename of the given object.""" name = getattr(obj, 'name', None) if (name and isinstance(name, basestring) and name[0] != '<' and name[-1] != '>'): return os.path.basename(name)
0.003876
def open(self): ''' attempts to open the database. if it gets a locked message, it will wait one second and try again. if it is still locked, it will return an error :return: None, None if successful None, error if error ''' cycle = 2 count = 0 ...
0.006345
def generateUniqueId(context, **kw): """ Generate pretty content IDs. """ # get the config for this portal type from the system setup config = get_config(context, **kw) # get the variables map for later string interpolation variables = get_variables(context, **kw) # The new generate seque...
0.000618
def xcorr(x, y, maxlags): """ Streamlined version of matplotlib's `xcorr`, without the plots. :param x, y: NumPy arrays to cross-correlate :param maxlags: Max number of lags; result will be `2*maxlags+1` in length """ xlen = len(x) ylen = len(y) assert xlen == ylen c = np.correlate...
0.001996
def generate_between_segment_description( self, between_expression, get_between_description_format, get_single_item_description ): """ Generates the between segment description :param between_expression: :param get_between_description_f...
0.006783
def swap(self, key, items): """Set key to a copy of items and return the list that was previously stored if the key was set. If not key was set, returns an empty list. """ if not isinstance(items, list): raise ValueError("items must be a list") return_value = [] ...
0.003322
def pointlist(points, sr): """Convert a list of the form [[x, y] ...] to a list of Point instances with the given x, y coordinates.""" assert all(isinstance(pt, Point) or len(pt) == 2 for pt in points), "Point(s) not in [x, y] form" return [coord if isinstance(coord, Point) ...
0.010101
def do_identity(args): """Executes the config commands subcommands. """ if args.subcommand == 'policy' and args.policy_cmd == 'create': _do_identity_policy_create(args) elif args.subcommand == 'policy' and args.policy_cmd == 'list': _do_identity_policy_list(args) elif args.subcommand...
0.001558
def urlencode2(query, doseq=0, safe="", querydelimiter="&"): """Encode a sequence of two-element tuples or dictionary into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of t...
0.00317
def directoryAdd(self, dir_key, key): '''Adds directory entry `key` to directory at `dir_key`. If the directory `dir_key` does not exist, it is created. ''' key = str(key) dir_items = self.get(dir_key) or [] if key not in dir_items: dir_items.append(key) self.put(dir_key, dir_items...
0.009346
def upload(self, href, vobject_item): """Upload a new or replace an existing item.""" if self.is_fake: return content = vobject_item.serialize() try: item = self.get(href) etesync_item = item.etesync_item etesync_item.content = content ...
0.005814
def delete_project(self, project): '''Delete a project. It will recursively delete all the content. Args: project (str): The UUID of the project to be deleted. Returns: None Raises: StorageArgumentException: Invalid arguments StorageForb...
0.002825
def create_legacy_pad(scope, input_name, output_name, H_in, W_in, k_h, k_w, s_h, s_w, p_h, p_w, padded_value, container): ''' This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of the created Pad operator into Pool operator un...
0.003431
def _reset_page_refs(self): """Invalidate all pages in document dictionary.""" if self.isClosed: return for page in self._page_refs.values(): if page: page._erase() page = None self._page_refs.clear()
0.006944
def angle_wrap(angle, radians=False): '''Wraps the input angle to 360.0 degrees. Parameters ---------- angle : float The angle to wrap around 360.0 deg. radians : bool If True, will assume that the input is in radians. The output will then also be in radians. Returns ...
0.001387
def log(self, level, message, exc_info=None, reference=None): # pylint: disable=W0212 """ Logs a message, possibly with an exception :param level: Severity of the message (Python logging level) :param message: Human readable message :param exc_info: The exception context...
0.003613
def shard_data(source_fnames: List[str], target_fname: str, source_vocabs: List[vocab.Vocab], target_vocab: vocab.Vocab, num_shards: int, buckets: List[Tuple[int, int]], length_ratio_mean: float, length_ratio_std: f...
0.00575
def visit_named_list(self, _, children): """Manage a list, represented by a ``.resources.List`` instance. This list is populated with data from the result of the ``FILTERS``. Arguments --------- _ (node) : parsimonious.nodes.Node. children : list - 0: for ``...
0.002639
def resolve_child_module_registries_lineage(registry): """ For a given child module registry, attempt to resolve the lineage. Return an iterator, yielding from parent down to the input registry, inclusive of the input registry. """ children = [registry] while isinstance(registry, BaseChild...
0.000458
def Print(self, x, data, message, **kwargs): # pylint: disable=invalid-name """Calls tf.Print. Args: x: LaidOutTensor. data: list of LaidOutTensor. message: str. **kwargs: keyword arguments to tf.print. Returns: LaidOutTensor. """ del data, message, kwargs tf.log...
0.004963
def internal_assert(condition, message=None, item=None, extra=None): """Raise InternalException if condition is False. If condition is a function, execute it on DEVELOP only.""" if DEVELOP and callable(condition): condition = condition() if not condition: if message is None: ...
0.002123
def connect(self, *args, **kwargs): """Extend `client.SimpleClient.connect()` with defaults""" defaults = {} for i, k in enumerate(('host', 'port', 'channel', 'use_ssl', 'password')): if i < len(args): defaults[k] = args[i] elif k in kwargs: ...
0.00325
def get_data_link(self, instance, link): """ Gets a single data link. :param str instance: A Yamcs instance name. :param str link: The name of the data link. :rtype: .Link """ response = self.get_proto('/links/{}/{}'.format(instance, link)) message = yamc...
0.004706
def do_refresh(self, line): "refresh {table_name}" table = self.get_table(line) while True: desc = table.describe() status = desc['Table']['TableStatus'] if status == 'ACTIVE': break else: print status, "..." ...
0.005168
def _param_bounds(self, gamma, q): """ bounds parameters :param gamma: :param q: :return: """ if gamma < 1.4: gamma = 1.4 if gamma > 2.9: gamma = 2.9 if q < 0.01: q = 0.01 return float(gamma), q
0.006431
def _to_tonnetz(chromagram): """Project a chromagram on the tonnetz. Returned value is normalized to prevent numerical instabilities. """ if np.sum(np.abs(chromagram)) == 0.: # The input is an empty chord, return zero. return np.zeros(6) _tonnetz = np.dot(__TONNETZ_MATRIX, c...
0.010482
def min_max(obj, val, is_max): """ min/max validator for float and integer """ n = getattr(obj, 'maximum' if is_max else 'minimum', None) if n == None: return _eq = getattr(obj, 'exclusiveMaximum' if is_max else 'exclusiveMinimum', False) if is_max: to_raise = val >= n if _eq el...
0.007449
def GetHistAvg(tag_name, start_time, end_time, period, desc_as_label=False, label=None): """ Retrieves data from eDNA history for a given tag. The data will be averaged over the specified "period". :param tag_name: fully-qualified (site.service.tag) eDNA tag :param start_time:...
0.001161
def validate_wrap(self, value): ''' Checks that ``value`` is a pymongo ``ObjectId`` or a string representation of one''' if (not isinstance(value, ObjectId) and not isinstance(value, basestring) and not isinstance(value, bytes) ): self....
0.004975
def _cropbox(self, image, x, y, x2, y2): """ Crops the image to a set of x,y coordinates (x,y) is top left, (x2,y2) is bottom left """ image['options']['crop'] = '%sx%s+%s+%s' % (x2 - x, y2 - y, x, y) image['size'] = (x2 - x, y2 - y) # update image size return image
0.009524
def LOOPNZ(cpu, target): """ Loops if ECX counter is nonzero. :param cpu: current CPU. :param target: destination operand. """ counter_name = {16: 'CX', 32: 'ECX', 64: 'RCX'}[cpu.address_bit_size] counter = cpu.write_register(counter_name, cpu.read_register(count...
0.00823
def resolve_indirect (data, key, splithosts=False): """Replace name of environment variable with its value.""" value = data[key] env_value = os.environ.get(value) if env_value: if splithosts: data[key] = split_hosts(env_value) else: data[key] = env_value else:...
0.005848
def _init_record(self, record_type_idstr): """Override this from osid.Extensible because Forms use a different attribute in record_type_data.""" record_type_data = self._record_type_data_sets[Id(record_type_idstr).get_identifier()] module = importlib.import_module(record_type_data['modul...
0.005357
def get_thumbnails(self, *args, **kwargs): """ Return an iterator which returns ThumbnailFile instances. """ # First, delete any related thumbnails. source_cache = self.get_source_cache() if source_cache: thumbnail_storage_hash = utils.get_storage_hash( ...
0.002695
def __load_paths(self, base_path=None): """ Set the paths of the different folders """ if base_path is None: base_path = dirname(dirname(dirname(__file__))) if not base_path.endswith(sep): base_path += sep self.__paths = { 'base': base_...
0.004202
def _run_guest(userid, image_path, os_version, profile, cpu, memory, network_info, disks_list): """Deploy and provision a virtual machine. Input parameters: :userid: USERID of the guest, no more than 8. :image_name: path of the image file :os_version: os ve...
0.002833
def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='minion'): r''' Watch Salt's event bus and block until the given tag is matched .. versionadded:: 2016.3.0 .. versionchanged:: 2019.2.0 ``tagmatch`` can now be eith...
0.000838
def ccbox(message="Shall I continue?", title=""): """ Original doc: Display a message box with choices of Continue and Cancel. The default is "Continue". Returns returns 1 if "Continue" is chosen, or if the dialog is cancelled (which is interpreted as choosing the default). Otherwise return...
0.004317
def parse_file(self,filename): """Parse file (helper function)""" try: return self.rProgram.ignore(cStyleComment).parseFile(filename, parseAll=True) except SemanticException as err: print(err) exit(3) except ParseException as err: p...
0.011429
def convert(ast): """Convert BEL1 AST Function to BEL2 AST Function""" if ast and ast.type == "Function": # Activity function conversion if ( ast.name != "molecularActivity" and ast.name in spec["namespaces"]["Activity"]["list"] ): print("name", ast.n...
0.001452
def split_task_parameters(line): """ Split a string of comma separated words.""" if line is None: result = [] else: result = [parameter.strip() for parameter in line.split(",")] return result
0.004484
def team_2_json(self): """ transform ariane_clip3 team object to Ariane server JSON obj :return: Ariane JSON obj """ LOGGER.debug("Team.team_2_json") json_obj = { 'teamID': self.id, 'teamName': self.name, 'teamDescription': self.descrip...
0.003914
def transloadsForPeer(self, peer): """ Returns an iterator of transloads that apply to a particular peer. """ for tl in self.transloads.itervalues(): if peer in tl.peers: yield tl
0.008368
def saveThumbnail(self,fileName,filePath): """ URL to the thumbnail used for the item """ if self._thumbnail is None: self.__init() param_dict = {} if self._thumbnail is not None: imgUrl = self.root + "/info/" + self._thumbnail onlineFileName, file_ex...
0.006764
def sys_set_renderer(renderer: int) -> None: """Change the current rendering mode to renderer. .. deprecated:: 2.0 RENDERER_GLSL and RENDERER_OPENGL are not currently available. """ lib.TCOD_sys_set_renderer(renderer) if tcod.console._root_console is not None: tcod.console.Console._g...
0.00304
def configuration_option(*param_decls, **attrs): """ Adds configuration file support to a click application. This will create an option of type `click.File` expecting the path to a configuration file. When specified, it overwrites the default values for all other click arguments or options with the...
0.001073
def _code_cell(self, source): """Split the source into input and output.""" input, output = self._prompt.to_cell(source) return {'cell_type': 'code', 'input': input, 'output': output}
0.008368
def from_mapping(cls, mapping): """Create a bag from a dict of elem->count. Each key in the dict is added if the value is > 0. Raises: ValueError: If any count is < 0. """ out = cls() for elem, count in mapping.items(): out._set_count(elem, count) return out
0.039286
def checker_from_dict(self, dct): """Return a checker instance from a dict object.""" checker_identifier = list(dct.keys())[0] checker_class = self.get_checker(checker_identifier) if checker_class: return checker_class(**dct[checker_identifier]) return None
0.006472
def post(self, url, data, params=None, headers=None, connection=None): """ Synchronous POST request. ``data`` must be a JSONable value. """ params = params or {} headers = headers or {} endpoint = self._build_endpoint_url(url, None) self._authenticate(params, head...
0.00404
def get(self, project, date): """ Get the cache data for a specified project for the specified date. Returns None if the data cannot be found in the cache. :param project: PyPi project name to get data for :type project: str :param date: date to get data for :typ...
0.002534
def deploy(www_dir, bucket_name): """ Deploy to the configured S3 bucket. """ # Set up the connection to an S3 bucket. conn = boto.connect_s3() bucket = conn.get_bucket(bucket_name) # Deploy each changed file in www_dir os.chdir(www_dir) for root, dirs, files in os.walk('.'): for f...
0.000953
def windowed_df(pos, ac1, ac2, size=None, start=None, stop=None, step=None, windows=None, is_accessible=None, fill=np.nan): """Calculate the density of fixed differences between two populations in windows over a single chromosome/contig. Parameters ---------- pos : array_like, int,...
0.000366
def _convert_fastq(srafn, outdir, single=False): "convert sra to fastq" cmd = "fastq-dump --split-files --gzip {srafn}" cmd = "%s %s" % (utils.local_path_export(), cmd) sraid = os.path.basename(utils.splitext_plus(srafn)[0]) if not srafn: return None if not single: out_file = [os...
0.001148
def user(netease, name, id): """Download a user\'s playlists by id.""" if name: netease.download_user_playlists_by_search(name) if id: netease.download_user_playlists_by_id(id)
0.004878
def sample(self, k=None, with_replacement=True, weights=None): """Return a new table where k rows are randomly sampled from the original table. Args: ``k`` -- specifies the number of rows (``int``) to be sampled from the table. Default is k equal to number of rows in ...
0.001151
def reject(self): """Override Qt method""" if not self.is_fade_running(): key = Qt.Key_Escape self.key_pressed = key self.sig_key_pressed.emit()
0.00995
def fetch_resources(uri, rel): """ Retrieves embeddable resource from given ``uri``. For now only local resources (images, fonts) are supported. :param str uri: path or url to image or font resource :returns: path to local resource file. :rtype: str :raises: :exc:`~easy_pdf.exceptions.Unsu...
0.003049
def generate(self, path, label): """Creates default data from the corpus at `path`, marking all works with `label`. :param path: path to a corpus directory :type path: `str` :param label: label to categorise each work as :type label: `str` """ for filena...
0.005291
def add_contents(self, dest, contents): """Add file contents to the archive under ``dest``. If ``dest`` is a path, it will be added compressed and world-readable (user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for custom behavior. """ assert not self....
0.002985
def normalize(self, expr, operation): """ Return a normalized expression transformed to its normal form in the given AND or OR operation. The new expression arguments will satisfy these conditions: - operation(*args) == expr (here mathematical equality is meant) - the op...
0.002066
def art(artname, number=1, text=""): """ Return 1-line art. :param artname: artname :type artname : str :return: ascii art as str """ if isinstance(artname, str) is False: raise artError(ART_TYPE_ERROR) artname = artname.lower() arts = sorted(art_dic.keys()) if artname =...
0.000789
def get_instance(self, payload): """ Build an instance of NewKeyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.new_key.NewKeyInstance :rtype: twilio.rest.api.v2010.account.new_key.NewKeyInstance """ return New...
0.0075
def report(self, min_confidence=0, sort_by_size=False, make_whitelist=False): """ Print ordered list of Item objects to stdout. """ for item in self.get_unused_code( min_confidence=min_confidence, sort_by_size=sort_by_size): print(item.get_white...
0.005906
def get_plugin_icon(self): """Return widget icon""" path = osp.join(self.PLUGIN_PATH, self.IMG_PATH) return ima.icon('pylint', icon_path=path)
0.011834
def get(self): """Copies file from local filesystem to self.save_dir. Returns: Full path of the copied file. Raises: EnvironmentError if the file can't be found or the save_dir is not writable. """ if self.local_file.endswith('.whl'): ...
0.002401
def resnet_imagenet_34_td_unit_05_05(): """Set of hyperparameters.""" hp = resnet_imagenet_34() hp.use_td = "unit" hp.targeting_rate = 0.5 hp.keep_prob = 0.5 return hp
0.038889