text
stringlengths
78
104k
score
float64
0
0.18
def stop(self): """ Stop a node """ try: yield from self.post("/stop", timeout=240, dont_connect=True) # We don't care if a node is down at this step except (ComputeError, aiohttp.ClientError, aiohttp.web.HTTPError): pass except asyncio.Tim...
0.006961
def get_single_file(self, pool, source, target): '''Download a single file or a directory by adding a task into queue''' if source[-1] == PATH_SEP: if self.opt.recursive: basepath = S3URL(source).path for f in (f for f in self.s3walk(source) if not f['is_dir']): pool.download(f['...
0.011765
async def collect(self): """ Create a `self` iterator and collect it into a `TotalList` (a normal list with a `.total` attribute). """ result = helpers.TotalList() async for message in self: result.append(message) result.total = self.total ret...
0.006061
def get_artifact_nexus3(suppress_status=False, nexus_base_url=sample_nexus_base_url, repository=None, timeout_sec=600, overwrite=True, username=None, password=None, **kwargs): """Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress print...
0.003711
def delete(self, obj, matches=None, mt=None, lt=None, eq=None): ''' Delete object from the database. :param obj: :param matches: :param mt: :param lt: :param eq: :return: ''' deleted = False objects = list() for _obj in sel...
0.003049
def _get_dataset_index(catalog, dataset_identifier, dataset_title, logger=None): """Devuelve el índice de un dataset en el catálogo en función de su identificador""" logger = logger or pydj_logger matching_datasets = [] for idx, dataset in enumerate(catalog["catalog_dataset"]...
0.000777
def ready_argument_list(self, arguments): """ready argument list to be passed to the C function :param arguments: List of arguments to be passed to the C function. The order should match the argument list on the C function. Allowed values are numpy.ndarray, and/or numpy.int32, n...
0.005525
def angular_distance(ra1, dec1, ra2, dec2): """ Returns the angular distance between two points, two sets of points, or a set of points and one point. :param ra1: array or float, longitude of first point(s) :param dec1: array or float, latitude of first point(s) :param ra2: array or float, longitud...
0.002876
def get_link_page_text(link_page): """ Construct the dialog box to display a list of links to the user. """ text = '' for i, link in enumerate(link_page): capped_link_text = (link['text'] if len(link['text']) <= 20 else link['text'][:19...
0.004673
def find_repo_by_path(i): """ Input: { path - path to repo } Output: { return - return code = 0, if successful 16, if repo not found (may be warning) > 0, if error ...
0.037722
def rotate(self, clat, clon, coord_degrees=True, dj_matrix=None, nwinrot=None): """" Rotate the spherical-cap windows centered on the North pole to clat and clon, and save the spherical harmonic coefficients in the attribute coeffs. Usage ----- x.r...
0.001112
def Analyze(self, hashes): """Looks up hashes in VirusTotal using the VirusTotal HTTP API. The API is documented here: https://www.virustotal.com/en/documentation/public-api/ Args: hashes (list[str]): hashes to look up. Returns: list[HashAnalysis]: analysis results. Raises: ...
0.006237
def select(self, df, args, inplace=False): """ After joining, selects a subset of arguments df: the result of a call to self.join(left) args: a collcetion of arguments to select, as accepted by drain.util.list_expand: - a tuple corresponding to concat_args, e....
0.003834
def AddFileReadData(self, path, file_data_path): """Adds a "regular" file to the fake file system. Args: path (str): path of the file within the fake file system. file_data_path (str): path of the file to read the file data from. Raises: ValueError: if the path is already set. """ ...
0.004815
def download_from_link(self, link, **kwargs): """ Download torrent using a link. :param link: URL Link or list of. :param savepath: Path to download the torrent. :param category: Label or Category of the torrent(s). :return: Empty JSON data. """ # old:ne...
0.001946
def _get_patches(installed_only=False): ''' List all known patches in repos. ''' patches = {} cmd = [_yum(), '--quiet', 'updateinfo', 'list', 'all'] ret = __salt__['cmd.run_stdout']( cmd, python_shell=False ) for line in salt.utils.itertools.split(ret, os.linesep): ...
0.002963
def send(self, data, room=None, include_self=True, namespace=None, callback=None): """Send a message to one or more connected clients.""" return self.socketio.send(data, room=room, include_self=include_self, namespace=namespace or self.namespace, ...
0.008287
def absent(name, provider): ''' Ensure the named Rackspace queue is deleted. name Name of the Rackspace queue. provider Salt Cloud provider ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} is_present = list(__salt__['cloud.action']('queues_exists', pr...
0.005602
def sha_hash_file(filename): """ Compute the SHA1 hash of filename """ hash_sha = hashlib.sha1() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024*1024), b""): hash_sha.update(chunk) return hash_sha.hexdigest()
0.003731
def comm_all_best_paths(self, peer): """Shares/communicates current best paths with this peers. Can be used to send initial updates after we have established session with `peer`. """ LOG.debug('Communicating current best path for all afi/safi except' ' 1/132') ...
0.002817
def _asciify_list(data): """ Ascii-fies list values """ ret = [] for item in data: if isinstance(item, unicode): item = _remove_accents(item) item = item.encode('utf-8') elif isinstance(item, list): item = _asciify_list(item) elif isinstance(item, ...
0.002469
def get_extension(self, index): """ Get a specific extension of the certificate by index. Extensions on a certificate are kept in order. The index parameter selects which extension will be returned. :param int index: The index of the extension to retrieve. :return: The ...
0.002288
def join_channel(self, partner_address, partner_deposit): """Will be called, when we were selected as channel partner by another node. It will fund the channel with up to the partners deposit, but not more than remaining funds or the initial funding per channel. If the connection manage...
0.00159
def disable_host_flap_detection(self, host): """Disable flap detection for a host Format of the line that triggers function call:: DISABLE_HOST_FLAP_DETECTION;<host_name> :param host: host to edit :type host: alignak.objects.host.Host :return: None """ i...
0.004076
def soundex(self, name, length=8): '''Calculate soundex of given string This function calculates soundex for Indian language string as well as English string. This function is exposed as service method for JSONRPC in SILPA framework. :param name: String ...
0.001438
def __status(self, job_directory, proxy_status): """ Use proxied manager's status to compute the real (stateful) status of job. """ if proxy_status == status.COMPLETE: if not job_directory.has_metadata(JOB_FILE_POSTPROCESSED): job_status = status.POSTPROCESSIN...
0.004329
def get_queryset(self): """The queryset is over-ridden to show only plug events in which the strain matches the breeding strain.""" self.strain = get_object_or_404(Strain, Strain_slug__iexact=self.kwargs['slug']) return PlugEvents.objects.filter(Breeding__Strain=self.strain)
0.013378
def nest(self, node, cls=None): """ Create a new nested scope that is within this instance, binding the provided node to it. """ if cls is None: cls = type(self) nested_scope = cls(node, self) self.children.append(nested_scope) return nested_...
0.006154
def close(self): """ Finalize the GDSII stream library. """ self._outfile.write(struct.pack('>2h', 4, 0x0400)) if self._close: self._outfile.close()
0.01
def succeed(self, instance, action): """Returns if the task for the instance took place successfully """ uid = api.get_uid(instance) return self.objects.get(uid, {}).get(action, {}).get('success', False)
0.008511
def set_title(self, title): """Changes the <meta> title tag.""" self.head.title.attr(content=title) return self
0.014815
def load_variants(self, patients=None, filter_fn=None, **kwargs): """Load a dictionary of patient_id to varcode.VariantCollection Parameters ---------- patients : str, optional Filter to a subset of patients filter_fn : function Takes a FilterableVariant ...
0.006244
def linkify_hd_by_h(self, hosts): """Replace dependent_host_name and host_name in host dependency by the real object :param hosts: host list, used to look for a specific one :type hosts: alignak.objects.host.Hosts :return: None """ for hostdep in self: ...
0.002402
def create_parser(): """ Create the language parser """ select = create_select() scan = create_scan() delete = create_delete() update = create_update() insert = create_insert() create = create_create() drop = create_drop() alter = create_alter() dump = create_dump() load = cr...
0.002548
def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xhtml', {'q', '0.5'}) ...
0.006739
def connect(self, client_id: str = None, client_secret: str = None) -> dict: """Authenticate application and get token bearer. Isogeo API uses oAuth 2.0 protocol (https://tools.ietf.org/html/rfc6749) see: http://help.isogeo.com/api/fr/authentication/groupsapps.html :param str client_id...
0.00225
def buildData(self, key, default=None): """ Returns the build information for the given key. :param key | <str> default | <variant> :return <variant> """ return self._buildData.get(nativestring(key), default)
0.012658
def bootstrap_alert(visitor, items): """ Format: [[alert(class=error)]]: message """ txt = [] for x in items: cls = x['kwargs'].get('class', '') if cls: cls = 'alert-%s' % cls txt.append('<div class="alert %s">' % cls) if 'clos...
0.005357
def perform_pot_corr(self, axis_grid, pureavg, defavg, lattice, q, defect_position, axis, madetol=0.0001, ...
0.005666
def from_source(cls, filename, args=None, unsaved_files=None, options=0, index=None): """Create a TranslationUnit by parsing source. This is capable of processing source code both from files on the filesystem as well as in-memory contents. Command-line arguments tha...
0.001261
def _start_again_message(self, message=None): """Simple method to form a start again message and give the answer in readable form.""" logging.debug("Start again message delivered: {}".format(message)) the_answer = ', '.join( [str(d) for d in self.game.answer][:-1] ) + ', and ...
0.006957
def getbyname(self, name): """Get schemas by given name. :param str name: schema names to retrieve. :rtype: list :raises: KeyError if name is not registered already. """ if name not in self._schbyname: raise KeyError('name {0} not registered'.format(name)) ...
0.005634
def _consumeArgument(self, memberName, positionalArgumentKeyValueList, kwargs, defaultValue): """Returns member's value from kwargs if found or from positionalArgumentKeyValueList if found or default value otherw...
0.008869
def proxyInit(self): """ To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method. """ # Call init() with local XML RPC config and interface_id (the name of # the receiver) to receive events. XML RPC server has to be ru...
0.002425
def action_fluent_variables(self) -> FluentParamsList: '''Returns the instantiated action fluents in canonical order. Returns: Sequence[Tuple[str, List[str]]]: A tuple of pairs of fluent name and a list of instantiated fluents represented as strings. ''' fluents ...
0.004386
def pctile(self,pct,res=1000): """Returns the desired percentile of the distribution. Will only work if properly normalized. Designed to mimic the `ppf` method of the `scipy.stats` random variate objects. Works by gridding the CDF at a given resolution and matching the nearest ...
0.008963
def new(self, name, summary=None, description=None, protected=None, restricted=None, download_restricted=None, contains_phi=None, tags=None, properties=None, bill_to=None, **kwargs): """ :param name: The name of the project :type name: string :param summary: If pr...
0.003909
def normalize(self): """ Sum the values in a Counter, then create a new Counter where each new value (while keeping the original key) is equal to the original value divided by sum of all the original values (this is sometimes referred to as the normalization constant). https://en.wikipedia.org/wiki/No...
0.036403
def _unpickle_panel_compat(self, state): # pragma: no cover """ Unpickle the panel. """ from pandas.io.pickle import _unpickle_array _unpickle = _unpickle_array vals, items, major, minor = state items = _unpickle(items) major = _unpickle(major) ...
0.004396
def not_implemented(self, context, **response_kwargs): ''' If DEBUG: raise NotImplemented Exception. If not, raise 404. :raises:`django.http.Http404` if production environment. :raises:`NotImplementedError` if ``settings.DEBUG`` is True ''' if settings.DEBUG: ...
0.006757
def trace_method(method): """ Decorator to catch and print the exceptions that happen within async tasks. Note: this should be applied to methods of VSphereCheck only! """ def wrapper(*args, **kwargs): try: method(*args, **kwargs) except Exception: args[0].pr...
0.004902
def decode(self, litmap): """Convert the DNF to an expression.""" return Or(*[And(*[litmap[idx] for idx in clause]) for clause in self.clauses])
0.011111
def check_dirty(self): ''' .. versionchanged:: 0.20 Do not log size change. ''' if self._dirty_size is None: if self._dirty_render: self.render() self._dirty_render = False if self._dirty_draw: self.draw(...
0.003413
def get_host_path(root, path, instance=None): """ Generates the host path for a container volume. If the given path is a dictionary, uses the entry of the instance name. :param root: Root path to prepend, if ``path`` does not already describe an absolute path. :type root: unicode | str | AbstractLa...
0.00366
def spawn_new(self, key): """Spawn a new task and save it to the queue.""" # Check if path exists if not os.path.exists(self.queue[key]['path']): self.queue[key]['status'] = 'failed' error_msg = "The directory for this command doesn't exist anymore: {}".format(self.queue[...
0.001678
def RestrictFeedItemToGeoTarget(client, feed_item, location_id): """Restrict a feed item to a geo target location. Args: client: An AdWordsClient instance. feed_item: A FeedItem. location_id: The Id of the location to restrict to. """ # Retrieve the FeedItemTargetService feed_item_target_service ...
0.008648
def native(s): """ Convert :py:class:`bytes` or :py:class:`unicode` to the native :py:class:`str` type, using UTF-8 encoding if conversion is necessary. :raise UnicodeError: The input string is not UTF-8 decodeable. :raise TypeError: The input is neither :py:class:`bytes` nor :py:class:`un...
0.001575
def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = ...
0.007874
def random_draw(self, size=None): """Draw random samples of the hyperparameters. Parameters ---------- size : None, int or array-like, optional The number/shape of samples to draw. If None, only one sample is returned. Default is None. """ ...
0.004085
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key],...
0.006135
def launch_ipython_shell(args): # pylint: disable=unused-argument """Open the SolveBio shell (IPython wrapper)""" try: import IPython # noqa except ImportError: _print("The SolveBio Python shell requires IPython.\n" "To install, type: 'pip install ipython'") return F...
0.0016
def transmogrify(l): """Fit a flat list into a treeable object.""" d = {l[0]: {}} tmp = d for c in l: tmp[c] = {} tmp = tmp[c] return d
0.045752
def _show_traceback(method): """decorator for showing tracebacks in IPython""" def m(self, *args, **kwargs): try: return(method(self, *args, **kwargs)) except Exception as e: ip = get_ipython() if ip is None: self.log.warning("Exception in widg...
0.004651
def run(self): ''' Start a Master Worker ''' salt.utils.process.appendproctitle(self.name) self.clear_funcs = ClearFuncs( self.opts, self.key, ) self.aes_funcs = AESFuncs(self.opts) salt.utils.crypt.reinit_crypto() self.__b...
0.006154
def indel_at( self, position, check_insertions=True, check_deletions=True, one_based=True ): """Does the read contain an indel at the given position? Return True if the read contains an insertion at the given position (position must be the base before the insertion event) or if the read ...
0.008454
def client_for(service, service_module, thrift_service_name=None): """Build a synchronous client class for the given Thrift service. The generated class accepts a TChannelSyncClient and an optional hostport as initialization arguments. Given ``CommentService`` defined in ``comment.thrift`` and registe...
0.000393
def add_blacklisted_directories(self, directories, remove_from_stored_directories=True): """ Adds `directories` to be blacklisted. Blacklisted directories will not be returned or searched recursively when calling the ...
0.003914
def interpolate2dStructuredPointSpreadIDW(grid, mask, kernel=15, power=2, maxIter=1e5, copy=True): ''' same as interpolate2dStructuredIDW but using the point spread method this is faster if there are bigger connected masked areas and the border length is sm...
0.001063
def tar_files(self, path: Path) -> bytes: """ Returns a tar with the git repository. """ tarstream = BytesIO() tar = tarfile.TarFile(fileobj=tarstream, mode='w') tar.add(str(path), arcname="data", recursive=True) tar.close() return tarstream.getvalue()
0.006494
def load_store(cls, store, decoder=None): """Create a new dataset from the contents of a backends.*DataStore object """ variables, attributes = store.load() if decoder: variables, attributes = decoder(variables, attributes) obj = cls(variables, attrs=attribute...
0.005391
def subscribe(object_type: str, subscriber: str, callback_handler: Callable = None) -> EventQueue: """Subscribe to the specified object type. Returns an EventQueue object which can be used to query events associated with the object type for this subscriber. Args: object_type (str...
0.001431
def delete(self, file_id): """Delete a file from GridFS by ``"_id"``. Removes all data belonging to the file with ``"_id"``: `file_id`. .. warning:: Any processes/threads reading from the file while this method is executing will likely see an invalid/corrupt file....
0.002857
def normalize_name(s): """Convert a string into a valid python attribute name. This function is called to convert ASCII strings to something that can pass as python attribute name, to be used with namedtuples. >>> str(normalize_name('class')) 'class_' >>> str(normalize_name('a-name')) 'a_na...
0.002475
def _find_im_paths(self, subj_mp, obs_name, target_polarity, max_paths=1, max_path_length=5): """Check for a source/target path in the influence map. Parameters ---------- subj_mp : pysb.MonomerPattern MonomerPattern corresponding to the subject of the...
0.002073
def toarray(self): """ Converts a ktensor into a dense multidimensional ndarray Returns ------- arr : np.ndarray Fully computed multidimensional array whose shape matches the original ktensor. """ A = dot(self.lmbda, khatrirao(tuple(self.U...
0.005525
def cart_add(self, items, CartId=None, HMAC=None, **kwargs): """CartAdd. :param items: A dictionary containing the items to be added to the cart. Or a list containing these dictionaries. It is not possible to create an empty cart! example: [{'offer_id': 'r...
0.001485
def merge(self, revision=None): """ Merge a revision into the current branch (without committing the result). :param revision: The revision to merge in (a string or :data:`None`, defaults to :attr:`default_revision`). :raises: The following exceptions can be rai...
0.002606
def plot_factor_rank_auto_correlation(factor_autocorrelation, period=1, ax=None): """ Plots factor rank autocorrelation over time. See factor_rank_autocorrelation for more details. Parameters ---------- factor_autocorre...
0.000804
def get_driver_script(driver, script=None): # noqa: E501 """Retrieve the contents of a script Retrieve the contents of a script # noqa: E501 :param driver: The driver to use for the request. ie. github :type driver: str :param script: The script name. :type script: str :rtype: Response ...
0.001538
def sample_colormap(cmap_name, n_samples): """ Sample a colormap from matplotlib """ colors = [] colormap = cm.cmap_d[cmap_name] for i in np.linspace(0, 1, n_samples): colors.append(colormap(i)) return colors
0.004082
def schedule_enable(enable): ''' Enable/disable automatic update scheduling. :param enable: True/On/Yes/1 to turn on automatic updates. False/No/Off/0 to turn off automatic updates. If this value is empty, the current status will be returned. :type: bool str :return: True if sched...
0.001276
def bootstrap_messages(context, *args, **kwargs): """ Show django.contrib.messages Messages in Bootstrap alert containers. In order to make the alerts dismissable (with the close button), we have to set the jquery parameter too when using the bootstrap_javascript tag. Uses the template ``boots...
0.001088
def send_xapi_statements(self, lrs_configuration, days): """ Send xAPI analytics data of the enterprise learners to the given LRS. Arguments: lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations of the LRS where to send xAPI l...
0.006122
def _format_envvar(param): """Format the envvars of a `click.Option` or `click.Argument`.""" yield '.. envvar:: {}'.format(param.envvar) yield ' :noindex:' yield '' if isinstance(param, click.Argument): param_ref = param.human_readable_name else: # if a user has defined an opt ...
0.001838
def is_focused(self): """ Checks that *at least one* matched element is focused. More specifically, it checks whether the element is document.activeElement. If no matching element is focused, this returns `False`. Returns: bool """ active_el = self.br...
0.005566
def post(request): """ method called on POST request on this view :param django.http.HttpRequest request: The current request object :return: ``HttpResponse(u"yes\\n")`` if the POSTed tuple (username, password, service) if valid (i.e. (username, password) is ...
0.004655
def getURL(self, size='Medium', urlType='url'): """Retrieves a url for the photo. (flickr.photos.getSizes) urlType - 'url' or 'source' 'url' - flickr page of photo 'source' - image file """ method = 'flickr.photos.getSizes' data = _doget(method, photo_id=self.id...
0.006148
def capture_stdout(): """Intercept standard output in a with-context :return: cStringIO instance >>> with capture_stdout() as stdout: ... print stdout.getvalue() """ stdout = sys.stdout sys.stdout = six.moves.cStringIO() try: yield sys.stdout finally: ...
0.002941
def generate_control_field(self, revision=None): """ Generate a Debian control file field referring for this repository and revision. :param revision: A reference to a revision, most likely the name of a branch (a string, defaults to :attr:`default_revision`). :...
0.007233
def _get(self, key, section=None, default=_onion_dict_guard): """Try to get the key from each dict in turn. If you specify the optional section it looks there first. """ if section is not None: section_dict = self.__sections.get(section, {}) if key in section_dict...
0.003515
def equals(self, other, equiv=duck_array_ops.array_equiv): """True if two Variables have the same dimensions and values; otherwise False. Variables can still be equal (like pandas objects) if they have NaN values in the same locations. This method is necessary because `v1 == v2...
0.002899
def execute(self): """Run all child tasks concurrently in separate threads. Return 0 after all child tasks have completed execution. """ self.count = 0 self.taskset = [] self.results = {} self.totaltime = time.time() # Register termination callbacks for a...
0.002098
def run_example(path): """ Returns returncode of example """ cmd = "{0} {1}".format(sys.executable, path) proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) res = proc.communicate() if proc.returncode: print(res[1].decode()) return proc.returncode
0.006309
def get_object_or_none(model, *args, **kwargs): """ Like get_object_or_404, but doesn't throw an exception. Allows querying for an object that might not exist without triggering an exception. """ try: return model._default_manager.get(*args, **kwargs) except model.DoesNotExist: ...
0.002985
def isoline_vmag(hemi, isolines=None, surface='midgray', min_length=2, **kw): ''' isoline_vmag(hemi) calculates the visual magnification function f using the default set of iso-lines (as returned by neuropythy.vision.visual_isolines()). The hemi argument may alternately be a mesh object. isoline...
0.022643
def _parse_qcd_segment(self, fptr): """Parse the QCD segment. Parameters ---------- fptr : file Open file object. Returns ------- QCDSegment The current QCD segment. """ offset = fptr.tell() - 2 read_buffer = fptr...
0.004175
def get_proficiencies_by_query(self, proficiency_query): """Gets a list of ``Proficiencies`` matching the given proficiency query. arg: proficiency_query (osid.learning.ProficiencyQuery): the proficiency query return: (osid.learning.ProficiencyList) - the returned ...
0.003329
def period(self): """A Period tuple representing the daily start and end time.""" start_time = self.root.findtext('daily_start_time') if start_time: return Period(text_to_time(start_time), text_to_time(self.root.findtext('daily_end_time'))) return Period(datetime.time(0, 0), ...
0.008772
def _Rforce(self,R,z,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the radial force for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
0.016949
async def send(self, pkt): """Send a packet to the client.""" if not await self.check_ping_timeout(): return if self.upgrading: self.packet_backlog.append(pkt) else: await self.queue.put(pkt) self.server.logger.info('%s: Sending packet %s data ...
0.003781