text
stringlengths
78
104k
score
float64
0
0.18
def gcj02tobd09(lng, lat): """ 火星坐标系(GCJ-02)转百度坐标系(BD-09) 谷歌、高德——>百度 :param lng:火星坐标经度 :param lat:火星坐标纬度 :return: """ z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_pi) theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_pi) bd_lng = z * math.cos(theta) ...
0.002519
def defaultBuilder(value, nt): """Reasonably sensible default handling of put builder """ if callable(value): def logbuilder(V): try: value(V) except: _log.exception("Error in Builder") raise # will be logged again retu...
0.003916
def resolve(self, s): """ Resolve strings to objects using standard import and attribute syntax. """ name = s.split('.') used = name.pop(0) try: found = self.importer(used) for frag in name: used += '.' + frag ...
0.002759
def hash(self): """Generate a hash value.""" h = hash_pandas_object(self, index=True) return hashlib.md5(h.values.tobytes()).hexdigest()
0.0125
def _raw_weights(self): """Create a numpy array containing the raw sensor weights. """ if self._debug: return np.array([[],[],[],[]]) if not self._running: raise ValueError('Weight sensor is not running!') if len(self._weight_buffers) == 0: ti...
0.009506
def _update_limits_from_api(self): """ Call the service's API action to retrieve limit/quota information, and update AwsLimit objects in ``self.limits`` with this information. """ try: self.connect() resp = self.conn.get_send_quota() except Endpoin...
0.00428
def setSortedBy( self, sortedBy ): """ Sets the sorting information for this widget to the inputed sorting options. This can be either a list of terms, or a comma deliminated string. :param sortedBy | <str> || [(<str> column, <str> direction), ..] ""...
0.016162
def run(): """Command for reflection database objects""" parser = OptionParser( version=__version__, description=__doc__, ) parser.add_option( '-u', '--url', dest='url', help='Database URL (connection string)', ) parser.add_option( '-r', '--render', dest='render...
0.001076
def append(self, fdata, offset, query='/content/uploads'): """ append binary data to an upload `fdata` - binary data to send to pulp `offset` - the amount of previously-uploaded data """ query = '%s/%s/%s/' % (query, self.uid, offset) _r = self.connector.put(query...
0.006861
def detect_build(snps): """ Detect build of SNPs. Use the coordinates of common SNPs to identify the build / assembly of a genotype file that is being loaded. Notes ----- rs3094315 : plus strand in 36, 37, and 38 rs11928389 : plus strand in 36, minus strand in 37 and 38 rs2500347 : plu...
0.004321
def set_argsx(self, arguments, *args): """ Setup the command line arguments, the first item must be an (absolute) filename to run. Variadic function, must be NULL terminated. """ return lib.zproc_set_argsx(self._as_parameter_, arguments, *args)
0.01087
def wasb_write(self, log, remote_log_location, append=True): """ Writes the log to the remote_log_location. Fails silently if no hook was created. :param log: the log to write to the remote_log_location :type log: str :param remote_log_location: the log's location in remo...
0.001919
def on(cls, hook): """Hook decorator.""" def decorator(function_): cls._hooks[hook].append(function_) return function_ return decorator
0.010929
def level_to_number(value): """ Coerce a logging level name to a number. :param value: A logging level (integer or string). :returns: The number of the log level (an integer). This function translates log level names into their numeric values. The :mod:`logging` module does this for us on Pyth...
0.001447
def get_exit_code(self): """Executes the external command and get its exitcode, stdout and stderr :return: exit code of command """ args = shlex.split(self.cmd) proc = Popen(args, stdout=PIPE, stderr=PIPE) out, err = proc.communicate() out, err = out.dec...
0.009302
def blake_encode_ngrams(ngrams, # type: Iterable[str] keys, # type: Sequence[bytes] ks, # type: Sequence[int] l, # type: int encoding # type: str ): # type: (...) -> bitarray.b...
0.001686
def get_mor_by_moid(si, obj_type, obj_moid): ''' Get reference to an object of specified object type and id si ServiceInstance for the vSphere or ESXi server (see get_service_instance) obj_type Type of the object (vim.StoragePod, vim.Datastore, etc) obj_moid ID of the obje...
0.005272
def set_state(self, state): """ Overriding the SimStatePlugin.set_state() method :param state: A SimState object :return: None """ # Sanity check if REGION_MAPPING not in state.options: # add REGION_MAPPING into state.options l.warning('O...
0.003239
def add_query(self, query, join_with=AND): """Join a new query to existing queries on the stack. Args: query (tuple or list or DomainCondition): The condition for the query. If a ``DomainCondition`` object is not provided, the input should conform to the inte...
0.00274
def build_absolute_uri(request, url): """ Allow to override printing url, not necessarily on the same server instance. """ if app_settings.get('CAPTURE_ROOT_URL'): return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url) return request.build_absolute_uri(url)
0.003425
def _gotitem(self, key, ndim, subset=None): """ Sub-classes to define. Return a sliced object. Parameters ---------- key : string / list of selections ndim : 1,2 requested ndim of result subset : object, default None subset to act on ...
0.001765
def save(self): """Save the index data back to the wily cache.""" data = [i.asdict() for i in self._revisions.values()] logger.debug("Saving data") cache.store_archiver_index(self.config, self.archiver, data)
0.008333
def _construct_nested_stack(self): """Constructs a AWS::CloudFormation::Stack resource """ nested_stack = NestedStack(self.logical_id, depends_on=self.depends_on, attributes=self.get_passthrough_resource_attributes()) nested_stack.Parameters = self.Para...
0.005739
def pad_chunk_columns(chunk): """Given a set of items to be inserted, make sure they all have the same columns by padding columns with None if they are missing.""" columns = set() for record in chunk: columns.update(record.keys()) for record in chunk: for column in columns: ...
0.002695
def central_likelihood(self, axis): """Returns new histogram with all values replaced by their central likelihoods along axis.""" result = self.cumulative_density(axis) result.histogram = 1 - 2 * np.abs(result.histogram - 0.5) return result
0.011029
def prox_dca(x, f, g, niter, gamma, callback=None): r"""Proximal DCA of Sun, Sampaio and Candido. This algorithm solves a problem of the form :: min_x f(x) - g(x) where ``f`` and ``g`` are two proper, convex and lower semicontinuous functions. Parameters ---------- x : `LinearSpa...
0.000453
def get_list(self, mutagen_file): """Get a list of all values for the field using this style. """ return [self.deserialize(item) for item in self.fetch(mutagen_file)]
0.010526
def where(self, field, value = None, operator = '='): """ Establece condiciones para la consulta unidas por AND """ if field is None: return self conjunction = None if value is None and isinstance(field, dict): for field, value in field.items(): ...
0.012766
def parse(url, engine=None, conn_max_age=0, ssl_require=False): """Parses a database URL.""" if url == 'sqlite://:memory:': # this is a special case, because if we pass this URL into # urlparse, urlparse will choke trying to interpret "memory" # as a port number return { ...
0.001096
def fillHSV(self, hsv, start=0, end=-1): """Fill the entire strip with HSV color tuple""" self.fill(conversions.hsv2rgb(hsv), start, end)
0.013072
def regex_last_key(regex): """Sort key function factory that puts items that match a regular expression last. >>> from nose.config import Config >>> from nose.pyversion import sort_list >>> c = Config() >>> regex = c.testMatch >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.p...
0.001767
def async_run(self, keyword, *args, **kwargs): ''' Executes the provided Robot Framework keyword in a separate thread and immediately returns a handle to be used with async_get ''' handle = self._last_thread_handle thread = self._threaded(keyword, *args, **kwargs) thread.start() ...
0.007246
def imean(nums): r"""Return identric (exponential) mean. The identric mean of two numbers x and y is: x if x = y otherwise :math:`\frac{1}{e} \sqrt[x-y]{\frac{x^x}{y^y}}` Cf. https://en.wikipedia.org/wiki/Identric_mean Parameters ---------- nums : list A series of numbers ...
0.001004
def pre_dissect(self, s): """ We need to parse the padding and type as soon as possible, else we won't be able to parse the message list... """ if len(s) < 1: raise Exception("Invalid InnerPlaintext (too short).") tmp_len = len(s) - 1 if s[-1] != b"\x...
0.003115
def _find_and_replace(text, start_string, end_string, replace_fn): """Remove everything found between instances of start_string and end_string. Replace each such instance with replace_fn(removed_text) e.g. _find_and_replace(u"the [[fat]] cat [[sat]]", u"[[", u"]]", lambda x: x) = u"the fat cat sat" Args:...
0.009514
def dump(values): """ Dump a ValueTree instance, returning its dict representation. :param values: :type values: ValueTree :return: :rtype: dict """ root = {} def _dump(_values, container): for name,value in _values._values.items(): if isinstance(value, ValueTree...
0.003576
def _parse_values(values, extra=None): """ Utility function to flatten out args. For internal use only. :param values: list, tuple, or str :param extra: list or None :return: list """ coerced = list(values) if coerced == values: values = coerced else: coerced =...
0.001984
def _obj_display(obj, display=''): """Returns string representation of an object, either the default or based on the display template passed in. """ result = '' if not display: result = str(obj) else: template = Template(display) context = Context({'obj':obj}) res...
0.00542
def convert_field(self, name, field): """ Convert a single field from a Peewee model field to a validator field. :param name: Name of the field as defined on this validator. :param name: Peewee field instance. :return: Validator field. """ if PEEWEE3: ...
0.002201
def handel_default(self) -> None: """ 处理设置到body上的数据默认 headers """ raw_body = self._body body = cast(Optional[bytes], None) default_type = 2 charset = self._charset or self._default_charset if raw_body is None: pass elif isinstance(raw_b...
0.001511
def validate(args): """ %prog validate input.vcf genome.fasta Fasta validation of vcf file. """ import pyfasta p = OptionParser(validate.__doc__) p.add_option("--prefix", help="Add prefix to seqid") opts, args = p.parse_args(args) vcffile, fastafile = args pf = opts.prefix ...
0.000907
def getFailedItems(self): """ Return an iterable of two-tuples of listeners which raised an exception from C{processItem} and the item which was passed as the argument to that method. """ for failed in self.store.query(BatchProcessingError, BatchProcessingError.processor ...
0.007937
def tanh_discrete_unbottleneck(x, hidden_size): """Simple un-discretization from tanh.""" x = tf.layers.dense(x, hidden_size, name="tanh_discrete_unbottleneck") return x
0.022857
def dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=0, utf8_encoding='standard'): """data [,options] -> marshalled data Convert an argument tuple or a Fault instance to an XML-RPC request (or response, if the methodresponse option is used). In addition to the da...
0.001353
def parse(self, text, element, context='eqn'): """ context : <string> 'eqn', 'defn' If context is set to equation, lone identifiers will be parsed as calls to elements If context is set to definition, lone identifiers will be cleaned and returned. """ ...
0.009697
def calculate_bidirectional_lstm_output_shapes(operator): ''' See bidirectional LSTM's conversion function for its output shapes. ''' check_input_and_output_numbers(operator, input_count_range=[1, 5], output_count_range=[1, 5]) check_input_and_output_types(operator, good_input_types=[FloatTensorType...
0.004126
def dynamic_template_data(self, value): """Data for a transactional template :param value: Data for a transactional template :type value: DynamicTemplateData, a JSON-serializeable structure """ if not isinstance(value, DynamicTemplateData): value = DynamicTemplateDat...
0.002466
def blend(self, proportion=0.2, stratify=False, seed=100, indices=None): """Blend a single model. You should rarely be using this method. Use `ModelsPipeline.blend` instead. Parameters ---------- proportion : float, default 0.2 Test size holdout. stratify : b...
0.004047
def _apply_rate(self, max_rate, aggressive=False): """ Try to adjust the rate (characters/second) of the fragments of the list, so that it does not exceed the given ``max_rate``. This is done by testing whether some slack can be borrowed from the fragment before ...
0.003682
def log_x_cb(self, w, val): """Toggle linear/log scale for X-axis.""" self.tab_plot.logx = val self.plot_two_columns()
0.014085
def delkey(ctx, pubkeys): """ Delete a private key from the wallet """ if not pubkeys: pubkeys = click.prompt("Public Keys").split(" ") if click.confirm( "Are you sure you want to delete keys from your wallet?\n" "This step is IRREVERSIBLE! If you don't have a backup, " "...
0.002174
def getBucketValues(self): """ See the function description in base.py """ if self._bucketValues is None: numBuckets = len(self.encoder.getBucketValues()) self._bucketValues = [] for bucketIndex in range(numBuckets): self._bucketValues.append(self.getBucketInfo([bucketIndex])[0].value...
0.011364
def _cookie_attrs(self, cookies): """Return a list of cookie-attributes to be returned to server. like ['foo="bar"; $Path="/"', ...] The $Version attribute is also added when appropriate (currently only once per request). """ # add cookies in order of most specific (ie...
0.001722
def _parse(self, string): """Parse a string and return its features. :param string: A one-symbol string in NFD Notes ----- Strategy is rather simple: we determine the base part of a string and then search left and right of this part for the additional features as ...
0.001757
def print_config(self, _): ''' Print configuration. ''' for section in self.config.sections(): print '[%s]' % section items = dict(self.config.items(section)) for k in items: print "%(a)s=%(b)s" % {'a': k, 'b': items[k]} print ''
0.006472
def morphological_chan_vese(image, iterations, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=lambda x: None): """Morphological Active Contours without Edges (MorphACWE) Active contours without edges implemented with morph...
0.000247
def reset_env(exclude=[]): """Remove environment variables, used in Jupyter notebooks""" if os.getenv(env.INITED): wandb_keys = [key for key in os.environ.keys() if key.startswith( 'WANDB_') and key not in exclude] for key in wandb_keys: del os.environ[key] return...
0.002809
def onca(word, max_length=4, zero_pad=True): """Return the Oxford Name Compression Algorithm (ONCA) code for a word. This is a wrapper for :py:meth:`ONCA.encode`. Parameters ---------- word : str The word to transform max_length : int The maximum length (default 5) of the code ...
0.001404
def load(path=None, **kwargs): ''' Loads the configuration from the file provided onto the device. path (required) Path where the configuration/template file is present. If the file has a ``.conf`` extension, the content is treated as text format. If the file has a ``.xml`` extensio...
0.001211
def find_by_task(self, task, params={}, **options): """Returns the compact records for all attachments on the task. Parameters ---------- task : {Id} Globally unique identifier for the task. [params] : {Object} Parameters for the request """ path = "/tasks/%s/at...
0.007389
def send(self): """ Send a verification email to the user. """ context = { "verification_url": app_settings.EMAIL_VERIFICATION_URL.format( key=self.key ) } email_utils.send_email( context=context, from_email...
0.002933
def _can_retry(self, batch, error): """ We can retry a send if the error is transient and the number of attempts taken is fewer than the maximum allowed """ return (batch.attempts < self.config['retries'] and getattr(error, 'retriable', False))
0.006667
def fetch(elastic, backend, limit=None, search_after_value=None, scroll=True): """ Fetch the items from raw or enriched index """ logging.debug("Creating a elastic items generator.") elastic_scroll_id = None search_after = search_after_value while True: if scroll: rjson = get_...
0.000917
def make_estimator_input_fn(self, mode, hparams, data_dir=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Retur...
0.011544
def minute_change(device): '''When we reach a minute change, animate it.''' hours = datetime.now().strftime('%H') minutes = datetime.now().strftime('%M') def helper(current_y): with canvas(device) as draw: text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT)) ...
0.005882
def sync2(queryset, model_objs, unique_fields, update_fields=None, returning=False, ignore_duplicate_updates=True): """ Performs a sync operation on a queryset, making the contents of the queryset match the contents of model_objs. Note: The definition of a sync requires that we return untouched rows fr...
0.007498
def tostring(self, cnf): """Convert Cnf object ot Dimacs cnf string cnf: Cnf object In the converted Cnf there will be only numbers for variable names. The conversion guarantees that the variables will be numbered alphabetically. """ self.varname...
0.007913
def data(self): """ Read all of the documents from disk into an in-memory list. """ def read(path): with open(path, 'r', encoding='UTF-8') as f: return f.read() return [ read(f) for f in self.files ]
0.006944
def try_float(s, default=None, minimum=None): """ Try parsing a string into a float. If None is passed, default is returned. On failure, InvalidFloat is raised. """ if not s: return default try: val = float(s) except (TypeError, ValueError): raise InvalidNumbe...
0.002273
def switch_charset(characters, target=''): ''' Transforms an iterable of kana characters to its opposite script. For example, it can turn [u'あ', u'い'] into [u'ア', u'イ'], or {u'ホ': u'ボ} into {u'ほ': u'ぼ'}. There are no safety checks--keep in mind that the correct source and target values must be ...
0.001842
def _non_framed_body_length(header, plaintext_length): """Calculates the length of a non-framed message body, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int plaintext_length: Length of plaintext in bytes :r...
0.003442
def _pseudodepths_wenner(configs, spacing=1, grid=None): """Given distances between electrodes, compute Wenner pseudo depths for the provided configuration The pseudodepth is computed after Roy & Apparao, 1971, as 0.11 times the distance between the two outermost electrodes. It's not really clear w...
0.001282
def map(self, mapper: Callable[[Any], Any]) -> 'Observable': r"""Map a function over an observable. Haskell: fmap f m = Cont $ \c -> runCont m (c . f) """ source = self return Observable(lambda on_next: source.subscribe(compose(on_next, mapper)))
0.010453
def searchZone(self, zone, q=None, has_geo=False, callback=None, errback=None): """ Search a zone for a given search query (e.g., for geological data, etc) :param zone: NOT a string like loadZone - an already loaded ns1.zones.Zone, like one returned from loadZone :return: """ ...
0.007194
def p_ExtendedAttributeIdent(p): """ExtendedAttributeIdent : IDENTIFIER "=" IDENTIFIER""" p[0] = model.ExtendedAttribute( name=p[1], value=model.ExtendedAttributeValue(name=p[3]))
0.015707
def writeText (self, filename=None): """Writes a text representation of this sequence to the given filename (defaults to self.txtpath). """ if filename is None: filename = self.txtpath with open(filename, 'wt') as output: self.printText(output)
0.01444
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_high_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 3) self.set_attributes(priority, address, rtr) self.closed = self...
0.004376
def extract_date_time(self, the_time_stamp): """Extract the parts of a date given a timestamp as per below example. :param the_time_stamp: The 'event_timestamp' attribute from grid.xml. :type the_time_stamp: str # now separate out its parts # >>> e = "2012-08-07T01:55:12WIB" ...
0.001166
def parse_meta(file_content, cable): """\ Extracts the reference id, date/time of creation, the classification, and the origin of the cable and assigns the value to the provided `cable`. """ end_idx = file_content.rindex("</table>") start_idx = file_content.rindex("<table class='cable'>", 0, end...
0.003427
def reorder_matrix(m1, cost='line', verbose=False, H=1e4, Texp=10, T0=1e-3, Hbrk=10): ''' This function rearranges the nodes in matrix M1 such that the matrix elements are squeezed along the main diagonal. The function uses a version of simulated annealing. Parameters ---------- M1 : NxN n...
0.001145
def write_word_data(self, addr, cmd, val): """Write a word (2 bytes) of data to the specified cmd register of the device. Note that this will write the data in the endianness of the processor running Python (typically little endian)! """ assert self._device is not None, 'Bus mus...
0.00641
def next_frame_basic_stochastic(): """Basic 2-frame conv model with stochastic tower.""" hparams = basic_deterministic_params.next_frame_basic_deterministic() hparams.stochastic_model = True hparams.add_hparam("latent_channels", 1) hparams.add_hparam("latent_std_min", -5.0) hparams.add_hparam("num_iteration...
0.01934
def set_time(self, time): """ 时间状态 """ rest_time = int(self.song_total_time) - self.time - 1 minute = int(rest_time) / 60 sec = int(rest_time) % 60 return str(minute).zfill(2) + ':' + str(sec).zfill(2)
0.007752
def render(self, is_unicode=False, **kwargs): """Render the graph, and return the svg string""" self.setup(**kwargs) svg = self.svg.render( is_unicode=is_unicode, pretty_print=self.pretty_print ) self.teardown() return svg
0.007092
def lookup_search_result(self, result, **kw): """Perform :meth:`lookup` on return value of :meth:`search`.""" return self.lookup(s['id_str'] for s in result['statuses'], **kw)
0.010471
def check_in(choices, **params): """Checks parameters are in a list of allowed parameters Parameters ---------- choices : array-like, accepted values params : object Named arguments, parameters to be checked Raises ------ ValueError : unacceptable choice of parameters """...
0.001919
def extend_transformations(self, transformations, return_alternatives=False): """ Extends a sequence of transformations to the TransformedStructure. Args: transformations: Sequence of Transformations return_alternatives: Whether to return a...
0.004304
def parse_macro_params(token): """ Common parsing logic for both use_macro and macro_block """ try: bits = token.split_contents() tag_name, macro_name, values = bits[0], bits[1], bits[2:] except IndexError: raise template.TemplateSyntaxError( "{0} tag requires at ...
0.000642
def get_object_from_classbased_instance( instance, queryset, request, *args, **kwargs): """ Get object from an instance of classbased generic view Parameters ---------- instance : instance An instance of classbased generic view queryset : instance A queryset instance ...
0.000582
def save_params(model_name: str): """Save current global listener params to a file""" with open(model_name + '.params', 'w') as f: json.dump(pr.__dict__, f)
0.005814
def invite(self, email, roles=None): """ Send invitation to email with a list of roles :param email: :param roles: None or "ALL" or list of role_names :return: """ if roles is None: role_ids = [self.roles['Guest'].roleId] elif roles == "ALL": ...
0.002849
def from_diff(diff, options=None, cwd=None): """Create a Radius object from a diff rather than a reposistory. """ return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
0.010204
def save(self, commit=True, **kwargs): """ Saves the considered instances. """ if self.post: for form in self.forms: form.instance.post = self.post super().save(commit)
0.009091
def auth_traps_enabled(name, status=True): ''' Manage the sending of authentication traps. :param bool status: The enabled status. Example of usage: .. code-block:: yaml snmp-auth-traps: win_snmp.auth_traps_enabled: - status: True ''' ret = {'name': na...
0.002664
def transform_flask_from_import(node): '''Translates a flask.ext from-style import into a non-magical import. Translates: from flask.ext import wtf, bcrypt as fcrypt Into: import flask_wtf as wtf, flask_bcrypt as fcrypt ''' new_names = [] # node.names is a list of 2-tuples. Eac...
0.00122
def _notify_thing_lid_change(self, from_lid, to_lid): """Used by Thing instances to indicate that a rename operation has happened""" try: with self.__private_things: self.__private_things[to_lid] = self.__private_things.pop(from_lid) except KeyError: logge...
0.007267
def get_neighbors_of_site_with_index(struct, n, approach="min_dist", delta=0.1, \ cutoff=10.0): """ Returns the neighbors of a given site using a specific neighbor-finding method. Args: struct (Structure): input structure. n (int): index of site in S...
0.002111
def update(self): """Update processes stats using the input method.""" # Init new stats stats = self.get_init_value() if self.input_method == 'local': # Update stats using the standard system lib # Note: Update is done in the processcount plugin # Jus...
0.002653
def get_value(self, field, quick): # type: (Field, bool) -> Any """ Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quic...
0.002212
def remove(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to close %...
0.005479