text
stringlengths
78
104k
score
float64
0
0.18
def stage_name(self): """ Get stage name of current job instance. Because instantiating job instance could be performed in different ways and those return different results, we have to check where from to get name of the stage. :return: stage name. """ if 'stage...
0.006438
def get_dir(obj, **kwargs): """Return the type of an object. Do some regex to remove the "<class..." bit.""" attrs = list(filter(filter_dunder, dir(obj))) if not attrs: return "No public attributes." s = "Attributes:" for attr in attrs: s += '\n - {} ({})'.format(attr, extract_type...
0.00831
def delete_event(self, uid): """Delete event and sync calendar Parameters ---------- uid : uid of event to be deleted """ ev_for_deletion = self.calendar.get(uid) ev_for_deletion.delete()
0.008197
def cli_plugin_add_help(help): """ Decorator generator that adds the cli help to the cli plugin based on the decorated function Args: help (str): help string for the cli plugin Returns: function: Decorator that builds or extends the cliplugin for the decorated function,...
0.000919
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] """ Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The ...
0.001229
def to_single_symbol_list(self): """ Convert this HandwrittenData object into a list of HandwrittenData objects. Each element of the list is a single symbol. Returns ------- list of HandwrittenData objects """ symbol_stream = getattr(self, ...
0.002283
def min_branch_length(go_id1, go_id2, godag, branch_dist): ''' Finds the minimum branch length between two terms in the GO DAG. ''' # First get the deepest common ancestor goterm1 = godag[go_id1] goterm2 = godag[go_id2] if goterm1.namespace == goterm2.namespace: dca = deepest_com...
0.002667
def get_by_name(self, name): """ Gets a SAN Manager by name. Args: name: Name of the SAN Manager Returns: dict: SAN Manager. """ san_managers = self._client.get_all() result = [x for x in san_managers if x['name'] == name] return ...
0.005731
def handle(self, *args, **options): """ Iterates over all the CRON_CLASSES (or if passed in as a commandline argument) and runs them. """ cron_classes = options['cron_classes'] if cron_classes: cron_class_names = cron_classes else: cron_cla...
0.004357
def centre_of_atoms(atoms, mass_weighted=True): """ Returns centre point of any list of atoms. Parameters ---------- atoms : list List of AMPAL atom objects. mass_weighted : bool, optional If True returns centre of mass, otherwise just geometric centre of points. Returns --...
0.003328
def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(map(abs, self._values)) if self._values else None) )
0.008439
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = _dict_getitem(self, key.lower()) except KeyError: return [] else: if isinstance(vals, tuple): ...
0.005051
def get_java_remote_console_url(self, ip=None): """ Generates a Single Sign-On (SSO) session for the iLO Java Applet console and returns the URL to launch it. If the server hardware is unmanaged or unsupported, the resulting URL will not use SSO and the iLO Java Applet will prompt for cr...
0.008671
def finish(self, data): """Process success indicator from the server. Process any addiitional data passed with the success. Fail if the server was not authenticated. :Parameters: - `data`: an optional additional data with success. :Types: - `data`: `byte...
0.004209
def cat(prefix="md", dirname=os.path.curdir, partsdir="parts", fulldir="full", resolve_multi="pass"): """Concatenate all parts of a simulation. The xtc, trr, and edr files in *dirname* such as prefix.xtc, prefix.part0002.xtc, prefix.part0003.xtc, ... are 1) moved to the *partsdir* (under *d...
0.0031
def _remove_vm(name, datacenter, service_instance, placement=None, power_off=None): ''' Helper function to remove a virtual machine name Name of the virtual machine service_instance vCenter service instance for connection and configuration datacenter Datacen...
0.000732
def get_records_for_package(self, package_name): """ Get all records identified by package. """ result = [] result.extend(self.package_module_map.get(package_name)) return result
0.008811
def populate(self): """ Populate this list with all views that take no arguments. """ from django.conf import settings from django.core import urlresolvers self.append(("", "")) urlconf = settings.ROOT_URLCONF resolver = urlresolvers.RegexURLResolver(r'^/', urlco...
0.002841
def extract_common(self, keys): """ Return a new segmentlistdict containing only those segmentlists associated with the keys in keys, with each set to their mutual intersection. The offsets are preserved. """ keys = set(keys) new = self.__class__() intersection = self.intersection(keys) for key in ...
0.033113
def get_channel_embeddings(io_depth, targets, hidden_size, name="channel"): """Get separate embedding for each of the channels.""" targets_split = tf.split(targets, io_depth, axis=3) rgb_embedding_var = tf.get_variable("rgb_target_emb_%s" % name, [256 * io_depth, hidden_size]...
0.010778
def is_subpath(path, parent): ''' Returns True if *path* points to the same or a subpath of *parent*. ''' try: relpath = os.path.relpath(path, parent) except ValueError: return False # happens on Windows if drive letters don't match return relpath == os.curdir or not relpath.startswith(os.pardir)
0.015674
def write(self, filename): """ Write a copy of this config object. Parameters: ----------- outfile : output filename Returns: -------- None """ ext = os.path.splitext(filename)[1] writer = open(filename, 'w') if ex...
0.006908
def _termination_callback(self, returncode): """ Called when the process has stopped. :param returncode: Process returncode """ log.info("uBridge process has stopped, return code: %d", returncode) if returncode != 0: self._project.emit("log.error", {"message...
0.007246
def register_press_watcher(self, watcher_name, press_keys, *condition_list): """ The watcher perform *press_keys* action sequentially when conditions match. """ def unicode_to_list(a_unicode): a_list = list() comma_count = a_unicode.count(',') for coun...
0.0033
def last_visible_line(self, before_scroll_offset=False): """ Like `first_visible_line`, but for the last visible line. """ if before_scroll_offset: return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom] else: return self.displayed_lines[-1]
0.009434
def problem_serializing(value, e=None): """ THROW ERROR ABOUT SERIALIZING """ from mo_logs import Log try: typename = type(value).__name__ except Exception: typename = "<error getting name>" try: rep = text_type(repr(value)) except Exception as _: rep = ...
0.003003
def thread_exists(self, thread_id): """Check if a thread exists or has 404'd. Args: thread_id (int): Thread ID Returns: bool: Whether the given thread exists on this board. """ return self._requests_session.head( self._url.thread_api_url( ...
0.005222
def _update_settings(self, X): """ Update the model argument. :param X: The input data of the model. :type X: list of (candidate, features) pair """ self.logger.info("Loading default parameters for Sparse Logistic Regression") config = get_config()["learning"]["...
0.005164
def ne(self, key, value, includeMissing=False): '''Return entries where the key's value is NOT of equal (!=) value. Example of use: >>> test = [ ... {"name": "Jim", "age": 18, "income": 93000, "wigs": 68 }, ... {"name": "Larry", "age": 18, "wigs":...
0.006002
def update_client_secrets(backend, updates, secrets=None, save=True): '''update client secrets will update the data structure for a particular authentication. This should only be used for a (quasi permanent) token or similar. The secrets file, if found, is updated and saved by default. ''' if ...
0.002928
def split_netloc(netloc): """Split netloc into username, password, host and port. >>> split_netloc('foo:bar@www.example.com:8080') ('foo', 'bar', 'www.example.com', '8080') """ username = password = host = port = '' if '@' in netloc: user_pw, netloc = netloc.split('@', 1) if ':'...
0.001592
def load(self, code, setup='', teardown=''): """Prepares a set of setup, test, and teardown code to be run in the console. PARAMETERS: code -- list; processed lines of code. Elements in the list are either strings (input) or CodeAnswer objects (output) se...
0.004016
def mean(self, axis=None, keepdims=False): """ Return the mean of the array over the given axis. Parameters ---------- axis : tuple or int, optional, default=None Axis to compute statistic over, if None will compute over all axes keepdims : boole...
0.004132
def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019...
0.006208
def decorate_class_method(func, classkey=None, skipmain=False): """ Will inject all decorated function as methods of classkey classkey is some identifying string, tuple, or object func can also be a tuple """ #import utool as ut global __CLASSTYPE_ATTRIBUTES__ assert classkey is not No...
0.006237
def WriteArtifact(self, artifact): """Writes new artifact to the database.""" name = str(artifact.name) if name in self.artifacts: raise db.DuplicatedArtifactError(name) self.artifacts[name] = artifact.Copy()
0.008621
def convert_tree(self, element1, element2=None): '''convert_tree High-level api: Convert cxml tree to an internal schema tree. This method is recursive. Parameters ---------- element1 : `Element` The node to be converted. element2 : `Element` ...
0.002049
def validate(self, formats_dir="../formats/"): """checks if the document is valid""" #TODO: download XSD from web if self.inline: xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines())))) xmlschema.assertValid(...
0.010345
def midpoint(self): """ Return a point guranteed to fall within this range, hopefully near the middle. """ minpoint = self.leftedge if self.leftop is gt: minpoint += 1 maxpoint = self.rightedge if self.rightop is lt: maxpoint -= 1 i...
0.011742
def get_receive(self, script_list): """Return a list of received events contained in script_list.""" events = defaultdict(set) for script in script_list: if self.script_start_type(script) == self.HAT_WHEN_I_RECEIVE: event = script.blocks[0].args[0].lower() ...
0.005376
def copyh5(inh5, outh5): """Recursively copy all hdf5 data from one group to another Data from links is copied. Parameters ---------- inh5: str, h5py.File, or h5py.Group The input hdf5 data. This can be either a file name or an hdf5 object. outh5: str, h5py.File, h5py.Group, or...
0.00051
def load_markov(argv, stdin): """Load and return markov algorithm.""" if len(argv) > 3: with open(argv[3]) as input_file: return Algorithm(input_file.readlines()) else: return Algorithm(stdin.readlines())
0.004098
def get_data( dataset, query=None, crs="epsg:4326", bounds=None, sortby=None, pagesize=10000, max_workers=5, ): """Get GeoJSON featurecollection from DataBC WFS """ param_dicts = define_request(dataset, query, crs, bounds, sortby, pagesize) with ThreadPoolExecutor(max_worker...
0.001825
def get_pools(time_span=None, api_code=None): """Get number of blocks mined by each pool. :param str time_span: duration of the chart. Default is 4days (optional) :param str api_code: Blockchain.info API code (optional) :return: an instance of dict:{str,int} """ resource = 'pools' if t...
0.001577
def get_datastream_info(self, dsinfo): '''Use regular expressions to pull datastream [version] details (id, mimetype, size, and checksum) for binary content, in order to sanity check the decoded data. :param dsinfo: text content just before a binaryContent tag :returns: dict wit...
0.001132
def RDirs(self, pathlist): """Search for a list of directories in the Repository list.""" cwd = self.cwd or self.fs._cwd return cwd.Rfindalldirs(pathlist)
0.011236
def _process_json_resp_data(resp, no_custom_fields=False): """ process the response and return a list of BridgeUser """ bridge_users = [] while True: resp_data = json.loads(resp) link_url = None if "meta" in resp_data and\ "next" in resp_data["meta"]: ...
0.001695
def fromSchemaItem(self, item): """set up global elements. """ if item.isElement() is False or item.isLocal() is True: raise TypeError, 'expecting global element declaration: %s' %item.getItemTrace() local = False qName = item.getAttribute('type') if not qNam...
0.013354
def transform_audio(self, y): '''Compute the STFT with phase differentials. Parameters ---------- y : np.ndarray the audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, 1 + n_fft//2) The STF...
0.0033
def mag_to_fnu(self, mag): """Convert a magnitude in this band to a f_ν flux density. It is assumed that the magnitude has been computed in the appropriate photometric system. The definition of "appropriate" will vary from case to case. """ if self.native_flux_kind == '...
0.007366
def escape(self, text, quote = True): """ Escape special characters in HTML """ if isinstance(text, bytes): return escape_b(text, quote) else: return escape(text, quote)
0.017167
def initialize(self): '''List all datasets for a given ...''' fmt = guess_format(self.source.url) # if format can't be guessed from the url # we fallback on the declared Content-Type if not fmt: response = requests.head(self.source.url) mime_type = respons...
0.004848
def _revs_equal(rev1, rev2, rev_type): ''' Shorthand helper function for comparing SHA1s. If rev_type == 'sha1' then the comparison will be done using str.startwith() to allow short SHA1s to compare successfully. NOTE: This means that rev2 must be the short rev. ''' if (rev1 is None and rev...
0.001773
def value(self, value): """ Value to be written on register. :param value: An integer. :raises: IllegalDataValueError when value isn't in range. """ try: struct.pack('>' + conf.TYPE_CHAR, value) except struct.error: raise IllegalDataValueError ...
0.005797
def location(self, relative_alt=False): '''return current location''' self.wait_gps_fix() # wait for another VFR_HUD, to ensure we have correct altitude self.recv_match(type='VFR_HUD', blocking=True) self.recv_match(type='GLOBAL_POSITION_INT', blocking=True) if relative_a...
0.002963
def enable_site(site_name): """Enable an available Nginx site.""" site_available = u'/etc/nginx/sites-available/%s' % site_name site_enabled = u'/etc/nginx/sites-enabled/%s' % site_name if files.exists(site_available): sudo(u'ln -s -f %s %s' % (site_available, site_enabled)) restart_ser...
0.002421
def guest_pause(self, userid): """Pause a virtual machine. :param str userid: the id of the virtual machine to be paused :returns: None """ action = "pause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_pause(useri...
0.006211
def p_list(self, tok): """list : IPV4 | IPV6 | DATETIME | TIMEDELTA | INTEGER | FLOAT | VARIABLE | CONSTANT | IPV4 COMMA list | IPV6 COMMA list | DATETI...
0.002878
def visit_excepthandler(self, node, parent): """visit an ExceptHandler node by returning a fresh instance of it""" newnode = nodes.ExceptHandler(node.lineno, node.col_offset, parent) if node.name: name = self.visit_assignname(node, newnode, node.name) else: name =...
0.003817
def color_str(self): "Return an escape-coded string to write to the terminal." s = self.s for k, v in sorted(self.atts.items()): # (self.atts sorted for the sake of always acting the same.) if k not in xforms: # Unsupported SGR code continu...
0.003945
def coverage(args): """ %prog coverage *.coverage Plot coverage along chromosome. The coverage file can be generated with: $ samtools depth a.bam > a.coverage The plot is a simple line plot using matplotlib. """ from jcvi.graphics.base import savefig p = OptionParser(coverage.__doc__)...
0.001441
def getFileFormat(self, name, args): """ Récupération du contenu d'un fichier via la configuration et interprétation des variables données en argument """ # récupération du nom du fichier template_pathname = self.get(name, "--") if not os.path.isfile(template_pathname): return False # configuration c...
0.03178
def serialize(pca, **kwargs): """ Serialize an orientation object to a dict suitable for JSON """ strike, dip, rake = pca.strike_dip_rake() hyp_axes = sampling_axes(pca) return dict( **kwargs, principal_axes = pca.axes.tolist(), hyperbolic_axes = hyp_axes.tolist(), ...
0.016842
def externalCall(cls, method, url, codes=(200, 201, 204, 207), **kwargs): """ Make a public API call without a connected :class:`.Skype` instance. The obvious implications are that no authenticated calls are possible, though this allows accessing some public APIs such as join URL lookup...
0.004433
def beforeRender(self, ctx): """ Before rendering this page, identify the correct URL for the login to post to, and the error message to display (if any), and fill the 'login action' and 'error' slots in the template accordingly. """ generator = ixmantissa.ISiteURLGenerat...
0.002921
def process_calibration(self, save=True): """processes calibration control signal. Determines transfer function of speaker to get frequency vs. attenuation curve. :param save: Whether to save this calibration data to file :type save: bool :returns: numpy.ndarray, str, int, float...
0.00572
def stop_all_tensorboards(): """Terminate all TensorBoard instances.""" for process in Process.instances: print("Process '%s', running %d" % (process.command[0], process.is_running())) if process.is_running() and process.command[0] == "tensorboard": ...
0.002865
def _get_subelements(self, node): """Gather the sub-elements attached to a node Gather rdf:Bag and and rdf:Seq into set and list respectively. For alternate languages values, take the first language only for simplicity. """ items = node.find('rdf:Alt', self.NS) i...
0.002519
def forwards(self, orm): "Write your forwards methods here." for category in orm['document_library.DocumentCategory'].objects.all(): category.is_published = True category.save()
0.009217
def _validate_address(self, address): """Confirm that supplied address is a valid URL and has an `amqp` or `amqps` scheme. :param address: The endpiont URL. :type address: str :rtype: ~urllib.parse.ParseResult """ parsed = compat.urlparse(address) if not ...
0.004292
def convert_ipynbs(directory): """Recursively converts all ipynb files in a directory into rst files in the same directory.""" # The ipython_examples dir has to be in the same dir as this script for root, subfolders, files in os.walk(os.path.abspath(directory)): for f in files: if "....
0.002309
def setmode(mode): """ You must call this method prior to using all other calls. :param mode: the mode, one of :py:attr:`GPIO.BOARD`, :py:attr:`GPIO.BCM`, :py:attr:`GPIO.SUNXI`, or a `dict` or `object` representing a custom pin mapping. """ if hasattr(mode, '__getitem__'): s...
0.002212
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
0.003483
def annot(self, node): """Add `node` as an annotation of the receiver.""" self.annots.append(node) node.parent = self
0.014184
def diff_for_humans(self, other=None, absolute=False, locale=None): """ Get the difference in a human readable format in the current locale. When comparing a value in the past to default now: 1 day ago 5 months ago When comparing a value in the future to default now: ...
0.001969
def maxcut_qaoa(n_step, edges, minimizer=None, sampler=None, verbose=True): """Setup QAOA. :param n_step: The number of step of QAOA :param n_sample: The number of sampling time of each measurement in VQE. If None, use calculated ideal value. :param edges: The edges list of the gra...
0.001333
def receive(self, request, wait=True, timeout=None): """ Polls the message buffer of the TCP connection and waits until a valid message is received based on the message_id passed in. :param request: The Request object to wait get the response for :param wait: Wait for the final ...
0.001058
def close(self): """ Log disconnects. """ time_spent = time.time() - self.time_start logger.debug( '<{}> Disconnect from [{}]:{}, time spent {:.3f} seconds'.format( self.id, self.client_ip, self.client_port, time_spent)) return Milter.CONTINUE
0.00625
def format_output(data, headers, format_name, **kwargs): """Format output using *format_name*. This is a wrapper around the :class:`TabularOutputFormatter` class. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. :param str format_name: The...
0.005119
def sci(x, digs): """Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point and exactly one digit before. If digs is <= 0, one digit is kept and the point is suppressed.""" if type(x) != type(''): x = repr(x) sign, intpart, fraction, expo = extract(x) if not intpart: while fract...
0.005489
def transform(self, fn, column=None, dtype=None): """Execute a transformation on a column or columns. Returns the modified DictRDD. Parameters ---------- f : function The function to execute on the columns. column : {str, list or None} The column(...
0.00154
def port_knock_tcp(self, host="localhost", port=22, timeout=15): """Open a TCP socket to check for a listening sevice on a host. :param host: host name or IP address, default to localhost :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds ...
0.00147
def csvSplit(line, delim=',', allowEol=True): """ Take a string as input (e.g. a line in a csv text file), and break it into tokens separated by commas while ignoring commas embedded inside quoted sections. This is exactly what the 'csv' module is meant for, so we *should* be using it, save that it has...
0.001314
async def create(self, token): """Creates a new token with a given policy Parameters: token (Object): Token specification Returns: Object: token ID The create endpoint is used to make a new token. A token has a name, a type, and a set of ACL rules. ...
0.00131
def configure(cls, impl, **kwargs): # type: (Any, **Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be used to set global defaults for some parameters. ...
0.004658
def del_feature(self, pr_name): """ Permanently deletes a node's feature.""" if hasattr(self, pr_name): delattr(self, pr_name) self.features.remove(pr_name)
0.010204
def predictions_and_gradient( self, image=None, label=None, strict=True, return_details=False): """Interface to model.predictions_and_gradient for attacks. Parameters ---------- image : `numpy.ndarray` Single input with shape as expected by the model ...
0.00139
def check_type_of_param_list_elements(param_list): """ Ensures that all elements of param_list are ndarrays or None. Raises a helpful ValueError if otherwise. """ try: assert isinstance(param_list[0], np.ndarray) assert all([(x is None or isinstance(x, np.ndarray)) ...
0.001721
def get_element(self, line, column): """Gets the instance of the element who owns the specified line and column.""" ichar = self.charindex(line, column) icontains = self.contains_index result = None if line < icontains: #We only need to search through the typ...
0.005392
def _sample_action_fluent(self, name: str, dtype: tf.DType, size: Sequence[int], constraints: Dict[str, Constraints], default_value: tf.Tensor, prob: float) -> tf.Tensor: '''Samples the action fluent with given `name`, `dtype`, and `size`. ...
0.00521
def gene_list(list_id=None): """Display or add a gene list.""" all_case_ids = [case.case_id for case in app.db.cases()] if list_id: genelist_obj = app.db.gene_list(list_id) case_ids = [case.case_id for case in app.db.cases() if case not in genelist_obj.cases] if g...
0.000534
def prepare(self): ''' Run the preparation sequence required to start a salt syndic minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Syndic, self).prepare() try: if self.config['verify_env']: ...
0.0016
def Decompress(self, compressed_data): """Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the BZIP2 compressed stream cannot be decompressed. ...
0.005312
def data_parallel(batch_group: List[TensorDict], model: Model, cuda_devices: List) -> Dict[str, torch.Tensor]: """ Performs a forward pass using multiple GPUs. This is a simplification of torch.nn.parallel.data_parallel to support the allennlp model interface. ""...
0.003185
def xviewSlot(*typs, **opts): """ Defines a method as being a slot for the XView system. This will validate the method against the signal properties if it is triggered from the dispatcher, taking into account currency and grouping for the widget. You can specify the optional policy keyword to def...
0.00859
def _add_spanning_relation(self, source, target): """add a spanning relation to this docgraph""" self.add_edge(source, target, layers={self.ns, self.ns+':unit'}, edge_type=EdgeTypes.spanning_relation)
0.008403
def get_spot_price_history(self, start_time=None, end_time=None, instance_type=None, product_description=None, availability_zone=None): """ Retrieve the recent history of spot instances pricing. :type start_time: str :param s...
0.002225
def set_head(self, node): """Link this node to the current leaves.""" for head in self.head: head.next.add(node) self.head[:] = [] self.head.append(node)
0.011429
def calc_qib2_v1(self): """Calculate the first inflow component released from the soil. Required control parameters: |NHRU| |Lnk| |NFk| |DMin| |DMax| Required derived parameter: |WZ| Required state sequence: |BoWa| Calculated flux sequence: |QIB2| ...
0.000368
def findTypeParent(element, tag): """ Finds fist parent of element of the given type @param object element: etree element @param string the tag parent to search for @return object element: the found parent or None when not found """ p = element while True: p = p.getparent() ...
0.002551