text
stringlengths
78
104k
score
float64
0
0.18
def _chooseBestSegmentPerColumn(cls, connections, matchingCells, allMatchingSegments, potentialOverlaps, cellsPerColumn): """ For all the columns covered by 'matchingCells', choose the column's matching segment with largest number of active...
0.003581
def intersection(line1, line2): """ Return the coordinates of a point of intersection given two lines. Return None if the lines are parallel, but non-colli_near. Return an arbitrary point of intersection if the lines are colli_near. Parameters: line1 and line2: lines given by 4 points (x0,y0,x1...
0.000945
def get_placeholder_data(self, request, obj=None): """ Return the data of the placeholder fields. """ # Return all placeholder fields in the model. if not hasattr(self.model, '_meta_placeholder_fields'): return [] data = [] for name, field in self.mod...
0.004367
def _reset_corpus_iterator(self): """ create an iterator over all documents in the file (i.e. all <text> elements). Once you have iterated over all documents, call this method again if you want to iterate over them again. """ self.__context = etree.iterparse(self...
0.004762
def compute(mechanism, subsystem, purviews, cause_purviews, effect_purviews): """Compute a |Concept| for a mechanism, in this |Subsystem| with the provided purviews. """ concept = subsystem.concept(mechanism, purviews=purviews, ...
0.004386
def _value_loss(self, observ, reward, length): """Compute the loss function for the value baseline. The value loss is the difference between empirical and approximated returns over the collected episodes. Returns the loss tensor and a summary strin. Args: observ: Sequences of observations. ...
0.00789
def notify(self, *args, **kwargs): "See signal" loop = kwargs.pop('loop', self.loop) return self.signal.prepare_notification( subscribers=self.subscribers, instance=self.instance, loop=loop).run(*args, **kwargs)
0.007722
def add(self, response, label=None): """add one response object to the list """ if not isinstance(response, sip_response.sip_response): raise Exception( 'can only add sip_reponse.sip_response objects' ) self.objects.append(response) if lab...
0.004762
def close_hover(self, element, use_js=False): """ Close hover by moving to a set offset "away" from the element being hovered. :param element: element that triggered the hover to open :param use_js: use javascript to close hover :return: None """ try: ...
0.005961
def create_size_estimators(): """Create a dict of name to a function that returns an estimated size for a given target. The estimated size is used to build the largest targets first (subject to dependency constraints). Choose 'random' to choose random sizes for each target, which may be useful for distributed ...
0.010191
def parse_text_to_table(txt): """ takes a blob of text and finds delimiter OR guesses the column positions to parse into a table. input: txt = blob of text, lines separated by \n output: res = table of text """ res = [] # resulting table delim = identify_delim(txt) print('txt to pars...
0.035897
def read_data(file_path): """ Reads a file and returns a json encoded representation of the file. """ if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
0.003268
def minion_pub(self, clear_load): ''' Publish a command initiated from a minion, this method executes minion restrictions so that the minion publication will only work if it is enabled in the config. The configuration on the master allows minions to be matched to salt fu...
0.001919
def main(): """ NAME plotxy_magic.py DESCRIPTION Makes simple X,Y plots INPUT FORMAT Any MagIC formatted file SYNTAX plotxy_magic.py [command line options] OPTIONS -h prints this help message -f FILE to set file name on command rec -c co...
0.027586
def ostree_path(self): """ ostree repository -- content """ if self._ostree_path is None: self._ostree_path = os.path.join(self.tmpdir, "ostree-repo") subprocess.check_call(["ostree", "init", "--mode", "bare-user-only", "--repo", self._ostree_pa...
0.008403
def code_description(self, column=None, value=None, **kwargs): """ The Permit Compliance System (PCS) records milestones, events, and many other parameters in code format. To provide text descriptions that explain the code meanings, the PCS_CODE_DESC provide s complete informatio...
0.003584
def find_peakset(dataset, basecolumn=-1, method='', where=None): """ Find peakset from the dataset Parameters ----------- dataset : list A list of data basecolumn : int An index of column for finding peaks method : str A method name of numpy for finding peaks whe...
0.000835
def persist_upstream_diagram(self, filepath): """Creates upstream steps diagram and persists it to disk as png file. Pydot graph is created and persisted to disk as png file under the filepath directory. Args: filepath (str): filepath to which the png with steps visualization shoul...
0.008881
def get_vlan_brief_output_vlan_vlan_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vlan_brief = ET.Element("get_vlan_brief") config = get_vlan_brief output = ET.SubElement(get_vlan_brief, "output") vlan = ET.SubElement(output, "vl...
0.003929
def to_google_str(self): """ Convert to Google's bounds format: 'latMin,lonMin|latMax,lonMax' """ vb = self.convert_srs(4326) return '%s,%s|%s,%s' % (vb.bottom, vb.left, vb.top, vb.right)
0.014218
def modify_order(self, orderId, quantity=None, limit_price=None): """Modify quantity and/or limit price of an active order for the instrument :Parameters: orderId : int the order id to modify :Optional: quantity : int the required quantit...
0.005758
def get_splits(self, id_num, unit='mi'): """Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or 'km'. """ url = self._build_url('my', 'activities', id_num, 'splits', unit) return self._json(u...
0.006192
def compare(self, range_comparison, range_objs): """ Compares this type against comparison filters """ range_values = [obj.value for obj in range_objs] comparison_func = get_comparison_func(range_comparison) return comparison_func(self.value, *range_values)
0.006557
def format(logger, show_successful=True, show_errors=True, show_traceback=True): """ Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type lo...
0.000815
def decode_chain_list(in_bytes): """Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN :param in_bytes: the input bytes :return the decoded list of strings""" tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN out_strings = [] for i in range(tot_str...
0.007067
def location_name(self, name): """ location.name """ response = self._request( 'location.name', input=name) return _get_node(response, 'LocationList', 'StopLocation')
0.009346
def foex(a, b): """Returns the factor of exceedance """ return (np.sum(a > b, dtype=float) / len(a) - 0.5) * 100
0.008065
def next_session_label(self, session_label): """ Given a session label, returns the label of the next session. Parameters ---------- session_label: pd.Timestamp A session whose next session is desired. Returns ------- pd.Timestamp ...
0.002294
def getmodeldefinition(self, storageobject, required=False): """ find modeldefinition for StorageTableModel or StorageTableQuery """ if isinstance(storageobject, StorageTableModel): definitionlist = [definition for definition in self._modeldefinitions if definition['modelname'] == storageob...
0.005344
def times(self, factor): """Return a new set with each element's multiplicity multiplied with the given scalar factor. >>> ms = Multiset('aab') >>> sorted(ms.times(2)) ['a', 'a', 'a', 'a', 'b', 'b'] You can also use the ``*`` operator for the same effect: >>> sorted(ms...
0.003226
def subproduct(self, ext): """Makes a subproduct filename by calling subproductPath(), then calls subproductUpToDate() to determine if it is up-to-date. Returns tuple of basename,path,uptodate """ fname, fpath = self.subproductPath(ext) return fname, fpath, self.subproduc...
0.005952
def parse_file(self, file_path, currency) -> List[PriceModel]: """ Load and parse a .csv file """ # load file # read csv into memory? contents = self.load_file(file_path) prices = [] # parse price elements for line in contents: price = self.pa...
0.006289
def move_item(self, assessment_id, item_id, preceeding_item_id): """Moves an existing item to follow another item in an assessment. arg: assessment_id (osid.id.Id): the ``Id`` of the ``Assessment`` arg: item_id (osid.id.Id): the ``Id`` of an ``Item`` arg: precee...
0.002639
def read_struct_array(fd, endian, header): """Read a struct array. Returns a dict with fields of the struct array. """ # read field name length (unused, as strings are null terminated) field_name_length = read_elements(fd, endian, ['miINT32']) if field_name_length > 32: raise ParseError(...
0.001412
def swap_across(idx, idy, mat_a, mat_r, perm): """Interchange row and column idy and idx.""" # Temporary permutation matrix for swaping 2 rows or columns. size = mat_a.shape[0] perm_new = numpy.eye(size, dtype=int) # Modify the permutation matrix perm by swaping columns. perm_row = 1.0*perm[:, ...
0.001357
def configure(self, width, height): """See :meth:`set_window_size`.""" self._imgwin_set = True self.set_window_size(width, height)
0.012987
def import_module(modulename): """ Static method for importing module modulename. Can handle relative imports as well. :param modulename: Name of module to import. Can be relative :return: imported module instance. """ module = None try: module = importlib.import_module(modulename) ...
0.00486
def all_experiment_groups(self): """ Similar to experiment_groups, but uses the default manager to return archived experiments as well. """ from db.models.experiment_groups import ExperimentGroup return ExperimentGroup.all.filter(project=self)
0.006849
def extract_ctcp(self, spin, nick, user, host, target, msg): """ it is used to extract ctcp requests into pieces. """ # The ctcp delimiter token. DELIM = '\001' if not msg.startswith(DELIM) or not msg.endswith(DELIM): return ctcp_args =...
0.020362
def get_network_by_device(vm, device, pyvmomi_service, logger): """ Get a Network connected to a particular Device (vNIC) @see https://github.com/vmware/pyvmomi/blob/master/docs/vim/dvs/PortConnection.rst :param vm: :param device: <vim.vm.device.VirtualVmxnet3> instance of adapt...
0.007813
def excluded_length(self): """Surveyed length which does not count toward the included total""" return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])
0.013453
def QPSK_BEP(tx_data,rx_data,Ncorr = 1024,Ntransient = 0): """ Count bit errors between a transmitted and received QPSK signal. Time delay between streams is detected as well as ambiquity resolution due to carrier phase lock offsets of :math:`k*\\frac{\\pi}{4}`, k=0,1,2,3. The ndarray sdata is Tx +/...
0.012992
def do_ams_sto_put(endpoint, body, content_length): '''Do a PUT request to the Azure Storage API and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. body (str): Azure Media Services Content Body. content_length (str): Content_length. Returns: HTTP ...
0.006954
async def get_session_data(self): """Get Tautulli sessions.""" cmd = 'get_activity' url = self.base_url + cmd try: async with async_timeout.timeout(8, loop=self._loop): response = await self._session.get(url) logger("Status from Tautulli: " + str(...
0.002967
def iter_query(query): """Accept a filename, stream, or string. Returns an iterator over lines of the query.""" try: itr = click.open_file(query).readlines() except IOError: itr = [query] return itr
0.004274
def set_dataset_date_from_datetime(self, dataset_date, dataset_end_date=None): # type: (datetime, Optional[datetime]) -> None """Set dataset date from datetime.datetime object Args: dataset_date (datetime.datetime): Dataset date dataset_end_date (Optional[datetime.dateti...
0.004412
def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None): """ Set a metric """ if metric_type == self.HISTOGRAM: self.histogram(metric_name, value, tags=tags, device_name=device_name) elif metric_type == self.INCREMENT: self.incr...
0.010638
def price_change(self): """ This method returns any price change. :return: """ try: if self._data_from_search: return self._data_from_search.find('div', {'class': 'price-changes-sr'}).text else: return self._ad_page_content....
0.007207
def load_mol(self, mol_file): """Loads a MOL file of the ligand (submitted by user) into RDKit environment. Takes: * mol_file * - user submitted MOL file of the ligand Output: * self.mol_mda * - the ligand as MDAnalysis Universe, * self.mol...
0.011803
def import_deleted_fields(self, data): """ Set data fields to deleted """ if self.get_read_only() and self.is_locked(): return if isinstance(data, str): data = [data] for key in data: if hasattr(self, key): delattr(se...
0.003697
def eigs_s(infile="", dir_path='.'): """ Converts eigenparamters format data to s format Parameters ___________________ Input: file : input file name with eigenvalues (tau) and eigenvectors (V) with format: tau_1 V1_dec V1_inc tau_2 V2_dec V2_inc tau_3 V3_dec V3_inc Output ...
0.002494
def get_record(self, path=None, no_pdf=False, test=False, refextract_callback=None): """Convert a record to MARCXML format. :param path: path to a record. :type path: string :param test: flag to determine if it is a test call. :type test: bool :param r...
0.000645
def set_formatter(name, func): """Replace the formatter function used by the trace decorator to handle formatting a specific kind of argument. There are several kinds of arguments that trace discriminates between: * instance argument - the object bound to an instance method. * class argument - the...
0.000408
def create(cls, expr, binds): """ Helper for creating new NumExprFactors. This is just a wrapper around NumericalExpression.__new__ that always forwards `bool` as the dtype, since Filters can only be of boolean dtype. """ return cls(expr=expr, binds=binds, dtype=...
0.006042
def _mine_get(self, load): ''' Gathers the data from the specified minions' mine :param dict load: A payload received from a minion :rtype: dict :return: Mine data from the specified minions ''' load = self.__verify_load(load, ('id', 'tgt', 'fun', 'tok')) ...
0.004515
def main(args, stop=False): """ Arguments parsing, etc.. """ daemon = AMQPDaemon( con_param=getConParams( settings.RABBITMQ_PDFGEN_VIRTUALHOST ), queue=settings.RABBITMQ_PDFGEN_INPUT_QUEUE, out_exch=settings.RABBITMQ_PDFGEN_EXCHANGE, out_key=settings.R...
0.001761
def get_subj_alt_name(peer_cert): """ Given an PyOpenSSL certificate, provides all the subject alternative names. """ # Pass the cert to cryptography, which has much better APIs for this. if hasattr(peer_cert, "to_cryptography"): cert = peer_cert.to_cryptography() else: # This is...
0.000943
def atlasdb_format_query( query, values ): """ Turn a query into a string for printing. Useful for debugging. """ return "".join( ["%s %s" % (frag, "'%s'" % val if type(val) in [str, unicode] else val) for (frag, val) in zip(query.split("?"), values + ("",))] )
0.021352
def _get_image_numpy_dtype(self): """ Get the numpy dtype for the image """ try: ftype = self._info['img_equiv_type'] npy_type = _image_bitpix2npy[ftype] except KeyError: raise KeyError("unsupported fits data type: %d" % ftype) return ...
0.006098
def ConsultarTipoDeduccion(self, sep="||"): "Consulta de tipos de Deducciones" ret = self.client.tipoDeduccionConsultar( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, )['tip...
0.009539
def modify(self, service_name, json, **kwargs): """Modify an AppNexus object""" return self._send(requests.put, service_name, json, **kwargs)
0.012739
def split(self, bitindex): """Split a promise into two promises at the provided index. A common operation in JTAG is reading/writing to a register. During the operation, the TMS pin must be low, but during the writing of the last bit, the TMS pin must be high. Requiring all read...
0.003293
def data_received(self, data): """Receive data from the protocol. Called when asyncio.Protocol detects received data from network. """ _LOGGER.debug("Starting: data_received") _LOGGER.debug('Received %d bytes from PLM: %s', len(data), binascii.hexlify(data)...
0.003831
def get_fulltext_links(doi): """Return a list of links to the full text of an article given its DOI. Each list entry is a dictionary with keys: - URL: the URL to the full text - content-type: e.g. text/xml or text/plain - content-version - intended-application: e.g. text-mining """ metad...
0.002283
def save_post(self, title, text, user_id, tags, draft=False, post_date=None, last_modified_date=None, meta_data=None, post_id=None): """ Persist the blog post data. If ``post_id`` is ``None`` or ``post_id`` is invalid, the post must be inserted into the storag...
0.002469
def check_used(self, pkg): """Check if dependencies used """ used = [] dep_path = self.meta.log_path + "dep/" logs = find_package("", dep_path) for log in logs: deps = Utils().read_file(dep_path + log) for dep in deps.splitlines(): ...
0.005115
def simplify_tree(tree, unpack_lists=True, in_list=False): """Recursively unpack single-item lists and objects where fields and labels only reference a single child :param tree: the tree to simplify (mutating!) :param unpack_lists: whether single-item lists should be replaced by that item :param in_lis...
0.002902
def run_start_backup(cls): """ Connects to a server and attempts to start a hot backup Yields the WAL information in a dictionary for bookkeeping and recording. """ def handler(popen): assert popen.returncode != 0 raise UserException('Could not s...
0.002068
def name(self): # pylint: disable=no-self-use """ Name returns user's name or user's email or user_id :return: best guess of name to use to greet user """ if 'lis_person_sourcedid' in self.session: return self.session['lis_person_sourcedid'] elif 'lis_person_...
0.003663
def _render_module_flags(self, module, flags, output_lines, prefix=''): """Returns a help string for a given module.""" if not isinstance(module, str): module = module.__name__ output_lines.append('\n%s%s:' % (prefix, module)) self._render_flag_list(flags, output_lines, prefix + ' ')
0.006515
def insert_row(self, index, row): """Insert a row before index in the table. Parameters ---------- index : int List index rules apply row : iterable Any iterable of appropriate length. Raises ------ TypeError: If `row...
0.003419
def guest_unpause(self, userid): """Unpause a virtual machine. :param str userid: the id of the virtual machine to be unpaused :returns: None """ action = "unpause guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_unp...
0.006024
def _clear(self, pipe=None): """Helper for clear operations. :param pipe: Redis pipe in case update is performed as a part of transaction. :type pipe: :class:`redis.client.StrictPipeline` or :class:`redis.client.StrictRedis` """ redis = s...
0.005181
def default(): """Retrieves a default Context object, creating it if necessary. The default Context is a global shared instance used every time the default context is retrieved. Attempting to use a Context with no project_id will raise an exception, so on first use set_project_id must be c...
0.010764
def activate(username): """Activate a user. Example: \b ```bash $ polyaxon user activate david ``` """ try: PolyaxonClient().user.activate_user(username) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could no...
0.005703
def create_gw_response(app, wsgi_env): """Create an api gw response from a wsgi app and environ. """ response = {} buf = [] result = [] def start_response(status, headers, exc_info=None): result[:] = [status, headers] return buf.append appr = app(wsgi_env, start_response) ...
0.001119
def script(name, source, saltenv='base', args=None, template=None, exec_driver=None, stdin=None, python_shell=True, output_loglevel='debug', ignore_retcode=False, use_vt=False, keep_env=None): ''...
0.001183
def Mx(mt, x): """ Return the Mx """ n = len(mt.Cx) sum1 = 0 for j in range(x, n): k = mt.Cx[j] sum1 += k return sum1
0.006536
def _create_function(name, doc=""): """ Create a function for aggregator by name""" def _(col): spark_ctx = SparkContext._active_spark_context java_ctx = (getattr(spark_ctx._jvm.com.sparklingpandas.functions, name) (col._java_ctx if isinstance(col,...
0.002347
def _execute_example(self): "Handles the execution of the Example" test_benchmark = Benchmark() try: with Registry(), test_benchmark: if accepts_arg(self.example.testfn): self.example.testfn(self.context) else: s...
0.004213
def vertices(self, values): """ Assign vertex values to the mesh. Parameters -------------- values : (n, 3) float Points in space """ self._data['vertices'] = np.asanyarray(values, order='C', ...
0.005405
def absent(name, if_exists=None, restrict=None, cascade=None, user=None, maintenance_db=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named extension is absent. name ...
0.000442
def make_box_pixel_mask_from_col_row(column, row, default=0, value=1): '''Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list. Parameters ---------- column : iterable, int List of colums values. row : iterable, int List of r...
0.003791
def __fromfile(self, filename, astype=None): """a private method to deduce and load a filename into a matrix object. Uses extension: 'jco' or 'jcb': binary, 'mat','vec' or 'cov': ASCII, 'unc': pest uncertainty file. Parameters ---------- filename : str the na...
0.003183
def update_one(self, filter, update, **kwargs): """ See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_one """ self._arctic_lib.check_quota() return self._collection.update_one(filter, update, **kwargs)
0.010067
def derivative(self,x): ''' Evaluates the derivative of the interpolated function at the given input. Parameters ---------- x : np.array or float Real values to be evaluated in the interpolated function. Returns ------- dydx : np.array or flo...
0.00738
def compute(chart): """ Computes the Almutem table. """ almutems = {} # Hylegic points hylegic = [ chart.getObject(const.SUN), chart.getObject(const.MOON), chart.getAngle(const.ASC), chart.getObject(const.PARS_FORTUNA), chart.getObject(const.SYZYGY) ] ...
0.005119
def add_identities(cls, db, identities, backend): """ Load identities list from backend in Sorting Hat """ logger.info("Adding the identities to SortingHat") total = 0 for identity in identities: try: cls.add_identity(db, identity, backend) ...
0.003745
def check_spec(self, pos_args, kwargs=None): """Check if there are any missing or duplicate arguments. Args: pos_args (list): A list of arguments that will be passed as positional arguments. kwargs (dict): A dictionary of the keyword arguments that will be passed...
0.003958
def compute(self, data, fill_value=None, **kwargs): """Resample the given data using bilinear interpolation""" del kwargs if fill_value is None: fill_value = data.attrs.get('_FillValue') target_shape = self.target_geo_def.shape res = self.resampler.get_sample_from_b...
0.005871
def period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time): """ Calculate the neighborhood probability over the full period of the forecast Args: radius: circular radius from each point in km smoothing: width of Gaussian smoother ...
0.009541
def get_learning_objectives_metadata(self): """Gets the metadata for learning objectives. return: (osid.Metadata) - metadata for the learning objectives *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.learning.ActivityForm.ge...
0.007339
def get_validated_type(object_type: Type[Any], name: str, enforce_not_joker: bool = True) -> Type[Any]: """ Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or ac...
0.004352
def compare_hdf_files(file1, file2): """ Compare two hdf files. :param file1: First file to compare. :param file2: Second file to compare. :returns True if they are the same. """ data1 = FileToDict() data2 = FileToDict() scanner1 = data1.scan scanner2 = data2.scan with h5py.File...
0.002045
def manage_pool(hostname, username, password, name, allow_nat=None, allow_snat=None, description=None, gateway_failsafe_device=None, ignore_persisted_weight=None, ip_tos_to_client=None, ip_tos_to_server=None,...
0.003354
def gettemp(content=None, dir=None, prefix="tmp", suffix="tmp"): """Create temporary file with the given content. Please note: the temporary file must be deleted by the caller. :param string content: the content to write to the temporary file. :param string dir: directory where the file should be crea...
0.001166
def G(self, ID, lat, lon): """ Creates a generic entry for an object. """ # Equatorial coordinates eqM = utils.eqCoords(lon, lat) eqZ = eqM if lat != 0: eqZ = utils.eqCoords(lon, 0) return { 'id': ID, 'lat': lat, ...
0.008734
def set_possible(self): ''' break up a module path to its various parts (prefix, module, class, method) this uses PEP 8 conventions, so foo.Bar would be foo module with class Bar return -- list -- a list of possible interpretations of the module path (eg, foo.bar can be bar...
0.001994
def column_type(self, column_name): """ Report column type as one of 'local', 'series', or 'function'. Parameters ---------- column_name : str Returns ------- col_type : {'local', 'series', 'function'} 'local' means that the column is part of...
0.002014
def random_public_ip(self): """Return a randomly generated, public IPv4 address. :return: ip address """ randomip = random_ip() while self.is_reserved_ip(randomip): randomip = random_ip() return randomip
0.007576