Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
336,900
def download_file(p_realm, p_url, p_op_file, p_username, p_password): auth_handler = urllib.request.HTTPBasicAuthHandler() auth_handler.add_password(realm=p_realm, uri=p_url, user=p_username, passwd=p_password) op...
Currently not working... # https://docs.python.org/3/library/urllib.request.html#examples # Create an OpenerDirector with support for Basic HTTP Authentication...
336,901
def get_content(qfile, refresh, *args, **kwds): if not refresh and os.path.exists(qfile): with open(qfile, ) as f: content = f.read() else: content = download(*args, **kwds).text.encode() with open(qfile, ) as f: f.write(content) return content
Helper function to read file content as xml. The file is cached in a subfolder of ~/.scopus/. Parameters ---------- qfile : string The name of the file to be created. refresh : bool Whether the file content should be refreshed if it exists. *args, **kwds : Arguments a...
336,902
def is_ready(self): response = self.get() if response.status == 204: return False self._state = self.read(response) ready = self._state.content[] not in [, ] return ready
Indicates whether this job is ready for querying. :return: ``True`` if the job is ready, ``False`` if not. :rtype: ``boolean``
336,903
def JNB(cpu, target): cpu.PC = Operators.ITEBV(cpu.address_bit_size, cpu.CF == False, target.read(), cpu.PC)
Jumps short if not below. :param cpu: current CPU. :param target: destination operand.
336,904
def getter_override(attribute=None, f=DECORATED ): return autoprops_override_decorate(f, attribute=attribute, is_getter=True)
A decorator to indicate an overridden getter for a given attribute. If the attribute name is None, the function name will be used as the attribute name. :param attribute: the attribute name for which the decorated function is an overridden getter :return:
336,905
def copy_course_videos(source_course_id, destination_course_id): if source_course_id == destination_course_id: return course_videos = CourseVideo.objects.select_related(, ).filter( course_id=six.text_type(source_course_id) ) for course_video in course_videos: destination_c...
Adds the destination_course_id to the videos taken from the source_course_id Args: source_course_id: The original course_id destination_course_id: The new course_id where the videos will be copied
336,906
def cook_ref_set(ref, n=4): ref = normalize(ref) counts = count_ngrams(ref, n) return (len(ref), counts, frozenset(counts))
Takes a reference sentences for a single segment and returns an object that encapsulates everything that BLEU needs to know about them. Also provides a set cause bleualign wants it
336,907
def _check_integrity(self, lons, lats): lons = np.array(lons).ravel() lats = np.array(lats).ravel() if len(lons.shape) != 1 or len(lats.shape) != 1: raise ValueError() if lats.size != lons.size: raise ValueError() if (np.abs(lons)).max() > 2.*np...
Ensure lons and lats are: - 1D numpy arrays - equal size - within the appropriate range in radians
336,908
def processing_block_devices(self): tango_db = Database() pb_device_class = "ProcessingBlockDevice" pb_device_server_instance = "processing_block_ds/1" pb_devices = tango_db.get_device_name(pb_device_server_instance, pb_devi...
Get list of processing block devices.
336,909
def has_user(self, username): return self.model.objects.filter( **self._filter_user_by(username) ).exists()
return True if exists user.
336,910
def find_alliteration(self): if len(self.phonological_features_text) == 0: logger.error("No phonological transcription found") raise ValueError else: first_sounds = [] for i, line in enumerate(self.phonological_features_text): firs...
Find alliterations in the complete verse. :return:
336,911
def get_location_from_taobao(ip): global taobao response = requests.get(taobao % ip) if not response.status_code == 200: return l = json.loads(response.content) if not l[] == 0: return l = l[] return ("%s,%s,%s,%s,%s" % (l[], l[], l[], l[], l[])).encode()
{ "code":0, "data":{ "country":"\u65e5\u672c", "country_id":"JP", "area":"", "area_id":"", "region":"", "region_id":"", "city":"", "city_id":"", "county":"", "county_id":"", ...
336,912
def cancel(self, event): with self._lock: self._queue.remove(event) heapq.heapify(self._queue)
Remove an event from the queue. This must be presented the ID as returned by enter(). If the event is not in the queue, this raises ValueError.
336,913
def find_by_user(user: str) -> List[]: return [ApiKey.from_db(key) for key in db.get_keys(qb.from_dict({: user}))]
List API keys for a user.
336,914
async def listDependentTasks(self, *args, **kwargs): return await self._makeApiCall(self.funcinfo["listDependentTasks"], *args, **kwargs)
List Dependent Tasks List tasks that depend on the given `taskId`. As many tasks from different task-groups may dependent on a single tasks, this end-point may return a `continuationToken`. To continue listing tasks you must call `listDependentTasks` again with the `continuatio...
336,915
def _get_link_pages(page, per_page, count, page_url): current_page = _page_arg(page) links = {} end = page * per_page if page > 1: links[] = page_url.replace(current_page, _page_arg(page - 1)) if end < count: links[] = page_url.replace(current_page, _page_arg(page + 1)) ...
Create link header for page metadata. :param page: current page :param per_page: page limit :param count: count of all resources :param page_url: url for resources :return: dictionary with name of the link as key and its url as value
336,916
def linkcode_resolve(domain, info): if domain != : return None modname = info[] fullname = info[] submod = sys.modules.get(modname) if submod is None: return None obj = submod for part in fullname.split(): try: obj = getattr(obj, part) exce...
Determine the URL corresponding to Python object This code is from https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290 and https://github.com/Lasagne/Lasagne/pull/262
336,917
def run(self, verbose=False): if verbose: print((" num_elems = self._get_num_elems(self._all_temperatures) + 1 if num_elems > len(self._all_temperatures): num_elems -= 1 temperatures = [] parameters = [] free_energies = [] ...
Fit parameters to EOS at temperatures Even if fitting failed, simply omit the volume point. In this case, the failed temperature point doesn't exist in the returned arrays.
336,918
def needs(self, reglist): if isinstance(reglist, str): reglist = [reglist] reglist = single_registers(reglist) return len([x for x in self.requires if x in reglist]) > 0
Returns if this instruction need any of the registers in reglist.
336,919
def get_default_bios_settings(self, only_allowed_settings=True): headers_bios, bios_uri, bios_settings = self._check_bios_resource() try: base_config_uri = bios_settings[][][] except KeyError: msg = ("BaseConfigs resource not found. CouldnBaseConfigsdefa...
Get default BIOS settings. :param: only_allowed_settings: True when only allowed BIOS settings are to be returned. If False, All the BIOS settings supported by iLO are returned. :return: a dictionary of default BIOS settings(factory settings). Depending ...
336,920
def assert_less_equal(first, second, msg_fmt="{msg}"): if not first <= second: msg = "{!r} is not less than or equal to {!r}".format(first, second) fail(msg_fmt.format(msg=msg, first=first, second=second))
Fail if first is not less than or equal to second. >>> assert_less_equal('bar', 'foo') >>> assert_less_equal(5, 5) >>> assert_less_equal(6, 5) Traceback (most recent call last): ... AssertionError: 6 is not less than or equal to 5 The following msg_fmt arguments are supported: * ms...
336,921
def filter_t(func): return Transformation(.format(name(func)), partial(filter, func), {ExecutionStrategies.PARALLEL})
Transformation for Sequence.filter :param func: filter function :return: transformation
336,922
def capture_and_print_timeshot(self, start_time, which, other=99, switch="x.x.x.x"): curr_timeout = time.time() - start_time if which in self.time_stats: self.time_stats[which]["total_time"] += curr_timeout self.time_stats[which]["tota...
Determine delta, keep track, and print results.
336,923
def _is_auto_field(self, cursor, table_name, column_name): cursor.execute("SELECT COLUMNPROPERTY(OBJECT_ID(%s), %s, )", (self.connection.ops.quote_name(table_name), column_name)) return cursor.fetchall()[0][0]
Checks whether column is Identity
336,924
def _build_initializer(model, proper_name): def initializer( self, mount: str, trash_container: Labware = None, tip_racks: List[Labware] = None, aspirate_flow_rate: float = None, dispense_flow_rate: float = ...
Build an initializer function for a given pipette. This is a separate function so that the `proper_name` is correctly caught in the closure that it returns.
336,925
def get_client(self, provider): "Get instance of the OAuth client for this provider." if self.client_class is not None: return self.client_class(provider) return get_client(provider)
Get instance of the OAuth client for this provider.
336,926
def request_object(self): obj_to_return = None if self.queue.count > 0: obj_to_return = self.__dequeue() else: self.__init_object() object_to_return = self.__dequeue() self.active_objects += 1 return obj_to_return
Grab an object from the pool. If the pool is empty, a new object will be generated and returned.
336,927
def p_procedure_def(t): global name_dict tid = t[2] value = t[8] lineno = t.lineno(1) if id_unique(tid, , lineno): name_dict[tid] = const_info(tid, value, lineno)
procedure_def : proc_return ID LPAREN proc_firstarg type_specifier_list RPAREN EQUALS constant SEMI
336,928
def empty(self, name, **kwargs): return self._write_op(self._empty_nosync, name, **kwargs)
Create an array. Keyword arguments as per :func:`zarr.creation.empty`.
336,929
def _stop_by_max_time_mins(self): if self.max_time_mins: total_mins_elapsed = (datetime.now() - self._start_datetime).total_seconds() / 60. if total_mins_elapsed >= self.max_time_mins: raise KeyboardInterrupt(.format(total_mins_elapsed))
Stop optimization process once maximum minutes have elapsed.
336,930
def verifyNoUnwantedInteractions(*objs): if objs: theMocks = map(_get_mock_or_raise, objs) else: theMocks = mock_registry.get_registered_mocks() for mock in theMocks: for i in mock.stubbed_invocations: i.verify()
Verifies that expectations set via `expect` are met E.g.:: expect(os.path, times=1).exists(...).thenReturn(True) os.path('/foo') verifyNoUnwantedInteractions(os.path) # ok, called once If you leave out the argument *all* registered objects will be checked. .. note:: **DANGER...
336,931
def register(registerable: Any): listenable = registration_event_listenable_map[type(registerable)] event = RegistrationEvent(registerable, RegistrationEvent.Type.REGISTERED) listenable.notify_listeners(event)
Registers an object, notifying any listeners that may be interested in it. :param registerable: the object to register
336,932
def GetFileSystemTypeIndicators(cls, path_spec, resolver_context=None): if (cls._file_system_remainder_list is None or cls._file_system_store is None): specification_store, remainder_list = cls._GetSpecificationStore( definitions.FORMAT_CATEGORY_FILE_SYSTEM) cls._file_system_remai...
Determines if a file contains a supported file system types. Args: path_spec (PathSpec): path specification. resolver_context (Optional[Context]): resolver context, where None represents the built-in context which is not multi process safe. Returns: list[str]: supported format type...
336,933
def pov(self, color: chess.Color) -> "Score": return self.relative if self.turn == color else -self.relative
Get the score from the point of view of the given *color*.
336,934
def _checkMousePositionForFocus(self): i = 0 cur_pos = pygame.mouse.get_pos() ml, mt = self.position for o in self.options: rect = o.get() if rect: if rect.collidepoint(cur_pos) and self.mouse_pos != cur_pos: self.optio...
Check the mouse position to know if move focus on a option
336,935
def parse_args(self, *args, **kwargs): if _debug: ArgumentParser._debug("parse_args") result_args = _ArgumentParser.parse_args(self, *args, **kwargs) if result_args.buggers: loggers = sorted(logging.Logger.manager.loggerDict.keys()) for logger...
Parse the arguments as usual, then add default processing.
336,936
def load_tcex(self): for arg, value in self.profile.get(, {}).data.items(): if arg not in self._tcex_required_args: continue sys.argv.extend([, ]) sys.argv.extend([, ]) arg = .format(arg) if isinstanc...
Inject required TcEx CLI Args.
336,937
def diffp(self, diffcol: str, name: str="Diff"): try: df = self.df.copy() previous = 0 i = 0 vals = [df[diffcol].iloc[0]] for _, row in df.iterrows(): val = row[diffcol] - previous new = round(val, 1) ...
Add a diff column to the main dataframe: calculate the diff from the previous value :param diffcol: column to diff from :type diffcol: str :param name: diff column name, defaults to "Diff" :type name: str, optional :example: ``ds.diffp("Col 1", "New col")``
336,938
def register(linter): linter.register_checker(EncodingChecker(linter)) linter.register_checker(ByIdManagedMessagesChecker(linter))
required method to auto register this checker
336,939
def namedb_get_account_delta(cur, address, token_type, block_id, vtxindex): sql = args = (address, token_type, block_id, block_id, vtxindex) rows = namedb_query_execute(cur, sql, args) data = [] for r in rows: tmp = {} tmp.update(r) data.append(tmp) if len(data) !...
Get the account state for a token type at the given (block_id,vtxindex), plus the account state for the same token type at the prior operation. The current account must have been debited or credited at (block_id,vtxindex) Returns {'current': ..., 'prior': ...} on success Returns None on error
336,940
def _upload(self, project_id, updating, file_path, language_code=None, overwrite=False, sync_terms=False, tags=None, fuzzy_trigger=None): options = [ self.UPDATING_TERMS, self.UPDATING_TERMS_TRANSLATIONS, self.UPDATING_TRANSLATIONS ] i...
Internal: updates terms / translations File uploads are limited to one every 30 seconds
336,941
def save(self, name): self.finalize() with open(name, ) as f: buf = self._fileobj.read() while buf: f.write(buf) buf = self._fileobj.read()
Copy the contents of the temporary file somewhere else. Finalizes prior to saving. :param name: File path. :type name: unicode | str
336,942
def extract_db_info(self, obj, keys): objl = self.convert(obj) result = super(LinesCatalog, self).extract_db_info(objl, keys) result[] = {} result[] = result[] = str(uuid.uuid1()) result[] = datetime.datetime.utcnow() result[] = QC.GOOD result...
Extract metadata from serialized file
336,943
def p_state(self, state): state[0] = State(state[1][0], state[1][1], state[1][2], state[1][3], state[2])
state : STATE opttexts
336,944
def _load_contents(self, polib, resource): import struct try: return polib.mofile(resource) except (ValueError, AttributeError, struct.error) as e: self.rethrow( "Invalid resource {0}".format(resource), InvalidResourceException)
Parses machine object (MO) format using polib @type resource: str @param resource: resource @rtype: list
336,945
def blocks(self): blocks_df = callMLlibFunc("getMatrixBlocks", self._java_matrix_wrapper._java_model) blocks = blocks_df.rdd.map(lambda row: ((row[0][0], row[0][1]), row[1])) return blocks
The RDD of sub-matrix blocks ((blockRowIndex, blockColIndex), sub-matrix) that form this distributed matrix. >>> mat = BlockMatrix( ... sc.parallelize([((0, 0), Matrices.dense(3, 2, [1, 2, 3, 4, 5, 6])), ... ((1, 0), Matrices.dense(3, 2, [7, 8, 9, 10, 11,...
336,946
def stack_frame_info(stacklevel): import inspect if stacklevel < 1: raise ValueError() frame, filename, line_number, function_name, _, _ = inspect.stack()[stacklevel] module = inspect.getmodule(frame) if module is not None: module_name = module.__name__ else: modu...
Return a named tuple with information about the given stack frame: - filename - line_number - module_name - function_name stacklevel: How far up the stack to look. 1 means the immediate caller, 2 its caller, and so on.
336,947
def _transform_key(self, masterkey): aes = AES.new(self._transf_randomseed, AES.MODE_ECB) for _ in range(self._key_transf_rounds): masterkey = aes.encrypt(masterkey) sha_obj = SHA256.new() sha_obj.update(masterkey) masterkey = sha_obj.dig...
This method creates the key to decrypt the database
336,948
def comp_idat(self, idat): if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() for dat in idat: compressed = compressor.compress(dat) if len(compressed): ...
Generator that produce compressed IDAT chunks from IDAT data
336,949
def bin_hash160(s, hex_format=False): if hex_format and is_hex(s): s = unhexlify(s) return hashlib.new(, bin_sha256(s)).digest()
s is in hex or binary format
336,950
def set(state, host, ctid, save=True, **settings): my-host.net args = [.format(ctid)] if save: args.append() for key, value in six.iteritems(settings): if isinstance(value, list): args.extend(.format(key, v) for v in value) else: args.append(.f...
Set OpenVZ container details. + ctid: CTID of the container to set + save: whether to save the changes + settings: settings/arguments to apply to the container Settings/arguments: these are mapped directly to ``vztctl`` arguments, eg ``hostname='my-host.net'`` becomes ``--hostname my-h...
336,951
def dump(collection: BioCCollection, fp, pretty_print: bool = True): fp.write(dumps(collection, pretty_print))
Serialize ``collection`` as a BioC formatted stream to ``fp``. Args: collection: the BioC collection fp: a ``.write()``-supporting file-like object pretty_print: enables formatted XML
336,952
def supports_caller(func): def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe
Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`.
336,953
def set_detail_level(self, detail_levels): if detail_levels is None: return self.detail_levels = detail_levels if in detail_levels: self.api_detail_level = detail_levels[] if in detail_levels: self.http_detail_level = detail_levels[] ...
Sets the detail levels from the input dictionary in detail_levels.
336,954
def pop_events(self): with self.lock: events = self.events self.events = collections.deque() return events
Pop all events and return a `collections.deque` object. The returned container can be empty. This method is preferred over `pop_event()` as it is much faster as the lock has to be acquired only once and also avoids running into an infinite loop during event processing.
336,955
def get_inputs(node, kwargs): name = node["name"] proc_nodes = kwargs["proc_nodes"] index_lookup = kwargs["index_lookup"] inputs = node["inputs"] attrs = node.get("attrs", {}) input_nodes = [] for ip in inputs: input_node_id = index_lookup[ip[0]] input_nodes.append(proc...
Helper function to get inputs
336,956
def get_balance(): balsq = ses.query(wm.Balance).filter(wm.Balance.user_id == current_user.id) if not balsq: return None bals = [json.loads(jsonify2(b, )) for b in balsq] print "returning bals %s" % bals response = current_app.bitjws.create_response(bals) ses.close() return resp...
Get the latest balance(s) for a single User. Currently no search parameters are supported. All balances returned. --- responses: '200': description: the User's balance(s) schema: items: $ref: '#/definitions/Balance' type: array default: des...
336,957
def energy(self): e = 0 for i in range(len(self.state)): e += self.distance_matrix[self.state[i-1]][self.state[i]] return e
Calculates the length of the route.
336,958
def add_instance(self, name, properties): if name in self.__instances: raise NameError(name) self.__instances[name] = properties
Stores the description of a component instance. The given properties are stored as is. :param name: Instance name :param properties: Instance properties :raise NameError: Already known instance name
336,959
def libvlc_audio_equalizer_set_preamp(p_equalizer, f_preamp): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,), (1,),), None, ctypes.c_int, ctypes.c_void_p, ctypes.c_float) return f(p_equalizer, f_preamp)
Set a new pre-amplification value for an equalizer. The new equalizer settings are subsequently applied to a media player by invoking L{libvlc_media_player_set_equalizer}(). The supplied amplification value will be clamped to the -20.0 to +20.0 range. @param p_equalizer: valid equalizer handle, must not...
336,960
def dump_commands(self, commands): directory = os.path.join(os.path.dirname(self.sql_script), ) fname = os.path.basename(self.sql_script.rsplit()[0]) return dump_commands(commands, directory, fname)
Dump commands wrapper for external access.
336,961
def includes_ofs(self, ofs): return self._b <= ofs < self._b + self._size
:return: True if the given offset can be read in our mapped region
336,962
def add_items(self, items): _items = [self._listitemify(item) for item in items] tuples = [item.as_tuple() for item in _items] xbmcplugin.addDirectoryItems(self.handle, tuples, len(tuples)) self.added_items.extend(_items) return _items
Adds ListItems to the XBMC interface. Each item in the provided list should either be instances of xbmcswift2.ListItem, or regular dictionaries that will be passed to xbmcswift2.ListItem.from_dict. Returns the list of ListItems. :param items: An iterable of items where each item is eith...
336,963
def hash_token(token, salt): digest = hashes.Hash(sha(), backend=default_backend()) digest.update(binascii.unhexlify(token)) digest.update(binascii.unhexlify(salt)) return binascii.hexlify(digest.finalize()).decode()
Calculates the hash of a token and salt. input is unhexlified token and salt must contain an even number of hex digits or a binascii.Error exception will be raised
336,964
def _get_cookie_referrer_host(self): referer = self._original_request.fields.get() if referer: return URLInfo.parse(referer).hostname else: return None
Return the referrer hostname.
336,965
def parse_sacct(sacct_stream): rows = (line.split() for line in sacct_stream) relevant_rows = (row for row in rows if row[0].isdigit()) jobs = [convert_job(row) for row in relevant_rows] return jobs
Parse out information from sacct status output.
336,966
def route_filter_rule_create_or_update(name, access, communities, route_filter, resource_group, **kwargs): AllowDeny12076:51006 if not isinstance(communities, list): log.error( ) return False if not in kwargs: rg_props = __salt__[]( resource_group, ...
.. versionadded:: 2019.2.0 Create or update a rule within a specified route filter. :param name: The name of the rule to create. :param access: The access type of the rule. Valid values are 'Allow' and 'Deny'. :param communities: A list of BGP communities to filter on. :param route_filter: The ...
336,967
def update_sent_packet(self, sent_pkt_size_bytes): self.update_count(self.SENT_PKT_COUNT) self.update_count(self.SENT_PKT_SIZE, incr_by=sent_pkt_size_bytes)
Update sent packet metrics
336,968
def _get_module_via_pkgutil(self, fullname): try: loader = pkgutil.find_loader(fullname) except ImportError: e = sys.exc_info()[1] LOG.debug(, self, fullname, e) return None IOLOG.debug(, ...
Attempt to fetch source code via pkgutil. In an ideal world, this would be the only required implementation of get_module().
336,969
def tenant_get(tenant_id=None, name=None, profile=None, **connection_args): *** kstone = auth(profile, **connection_args) ret = {} if name: for tenant in getattr(kstone, _TENANTS, None).list(): if tenant.name == name: tenant_id = tenant.id ...
Return a specific tenants (keystone tenant-get) CLI Examples: .. code-block:: bash salt '*' keystone.tenant_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get tenant_id=c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.tenant_get name=nova
336,970
def granular_markings_circular_refs(instance): if instance[] != : return if in instance: for marking in instance[]: if in marking and marking[] == instance[]: yield JSONError("`granular_markings` cannot contain any " "references...
Ensure that marking definitions do not contain circular references (ie. they do not reference themselves in the `granular_markings` property).
336,971
def correlation_matrix(df): columns = df.columns.tolist() corr = pd.DataFrame( np.corrcoef(df, rowvar=0), columns=columns, index=columns) return corr
Returns a pandas DataFrame with the pair-wise correlations of the columns. Args: df: pandas DataFrame with columns to run diagnostics on
336,972
def _index_document(self, document, force=False): query = text() self.execute(query, **document)
Adds dataset document to the index.
336,973
def run_pileup(job, tumor_bam, univ_options, somaticsniper_options): work_dir = os.getcwd() input_files = { : tumor_bam[], : tumor_bam[], : somaticsniper_options[], : somaticsniper_options[]} input_files = get_files_from_filestore(job, input_files, work_dir, docker=False...
Runs a samtools pileup on the tumor bam. :param dict tumor_bam: Dict of bam and bai for tumor DNA-Seq :param dict univ_options: Dict of universal options used by almost all tools :param dict somaticsniper_options: Options specific to SomaticSniper :return: fsID for the pileup file :rtype: toil.file...
336,974
def create_deployment(self, ref, force=False, payload=, auto_merge=False, description=, environment=None): json = None if ref: url = self._build_url(, base_url=self._api) data = {: ref, : force, : payload, : auto_merge, : des...
Create a deployment. :param str ref: (required), The ref to deploy. This can be a branch, tag, or sha. :param bool force: Optional parameter to bypass any ahead/behind checks or commit status checks. Default: False :param str payload: Optional JSON payload with extra inf...
336,975
def reconnectRemote(self, remote): if not isinstance(remote, Remote): raise PlenumTypeError(, remote, Remote) logger.info(.format(self, remote)) public, secret = self.selfEncKeys remote.disconnect() remote.connect(self.ctx, public, secret) self.sendPi...
Disconnect remote and connect to it again :param remote: instance of Remote from self.remotes :param remoteName: name of remote :return:
336,976
def _check_for_initial_packet_cb(self, data): self.state = State.CONNECTED self.link_established.call(self.link_uri) self.packet_received.remove_callback(self._check_for_initial_packet_cb)
Called when first packet arrives from Crazyflie. This is used to determine if we are connected to something that is answering.
336,977
def _get_page_meta(self, page): meta = self._pages_meta.get(page) if not meta: src_file = os.path.join(self.pages_dir, page) with open(src_file) as f: _, _ext = os.path.splitext(src_file) markup = _ext.replace(".", "") _met...
Cache the page meta from the frontmatter and assign new keys The cache data will be used to build links or other properties
336,978
def destroy_comment(self, access_token, comment_id): url = data = { : self.client_id, : access_token, : comment_id } r = requests.post(url, data=data) check_error(r) return r.json()[]
doc: http://open.youku.com/docs/doc?id=42
336,979
def _query(self, ResponseGroup="Large", **kwargs): response = self.api.ItemSearch(ResponseGroup=ResponseGroup, **kwargs) root = objectify.fromstring(response) if (hasattr(root.Items.Request, ) and not hasattr(root.Items, )): code = root.Items.Request.Errors.E...
Query. Query Amazon search and check for errors. :return: An lxml root element.
336,980
def map_keys(pvs, keys): rs = [] for pv in pvs: r = dict((v, None) for k, v in keys.items()) for k, v in pv.items(): if k in keys: r[keys[k]] = v r[k] = v rs.append(r) return rs
Add human readable key names to dictionary while leaving any existing key names.
336,981
def _add_g2p_assoc(self, graph, strain_id, sex, assay_id, phenotypes, comment): geno = Genotype(graph) model = Model(graph) eco_id = self.globaltt[] strain_label = self.idlabel_hash.get(strain_id) genotype_id = +.join((re.sub(r, , strain_id), )) genotype...
Create an association between a sex-specific strain id and each of the phenotypes. Here, we create a genotype from the strain, and a sex-specific genotype. Each of those genotypes are created as anonymous nodes. The evidence code is hardcoded to be: ECO:experimental_...
336,982
def dict_conf(filename): f, ext = os.path.splitext(filename) ext = ext.lower() if ext == "conf" or ext == "ini": config = ConfigParser() config.optionxform=str config.read(filename) rv = {} for section in config.sections(): rv[section] = {} for key,value in config.items(...
Return dict object for *.conf file
336,983
def value(self): return { "hasStaticData":self._hasStaticData, "name":self._name, "maxRecordCount":self._maxRecordCount, "layerInfo":self._layerInfo }
returns the object as a dictionary
336,984
def y1(x, context=None): return _apply_function_in_current_context( BigFloat, mpfr.mpfr_y1, (BigFloat._implicit_convert(x),), context, )
Return the value of the second kind Bessel function of order 1 at x.
336,985
def get_initial_state(self, source_length: mx.sym.Symbol, source_seq_len: int) -> AttentionState: dynamic_source = mx.sym.reshape(mx.sym.zeros_like(source_length), shape=(-1, 1, 1)) dynamic_source = mx.sym.broadcast_to(dynamic_source, shape=(0, source_seq_len, self.dynamic_source_num_h...
Returns initial attention state. Dynamic source encoding is initialized with zeros. :param source_length: Source length. Shape: (batch_size,). :param source_seq_len: Maximum length of source sequences.
336,986
def get_core(self): if self.glucose and self.status == False: return pysolvers.glucose41_core(self.glucose)
Get an unsatisfiable core if the formula was previously unsatisfied.
336,987
def __processUsers(self): while self.__usersToProccess.empty() and not self.__end: pass while not self.__end or not self.__usersToProccess.empty(): self.__lockGetUser.acquire() try: new_user = self.__usersToProccess.get(False) exc...
Process users of the queue.
336,988
def count(self, query=None, indices=None, doc_types=None, **query_params): from .query import MatchAllQuery if query is None: query = MatchAllQuery() body = {"query": query.serialize()} path = self._make_path(indices, doc_types, "_count") return self._send_r...
Execute a query against one or more indices and get hits count.
336,989
def order_assimilation(args): (path, drone, data, status) = args newdata = drone.assimilate(path) if newdata: data.append(json.dumps(newdata, cls=MontyEncoder)) status[] += 1 count = status[] total = status[] logger.info(.format(count, total, ...
Internal helper method for BorgQueen to process assimilation
336,990
def render_part(part, field_key=): ctype = part.get_content_type() raw_payload = remove_cte(part) rendered_payload = None _, entry = settings.mailcap_find_match(ctype, key=field_key) if entry is not None: tempfile_name = None stdin = None handler_raw_commandstring =...
renders a non-multipart email part into displayable plaintext by piping its payload through an external script. The handler itself is determined by the mailcap entry for this part's ctype.
336,991
def libvlc_media_player_get_media(p_mi): f = _Cfunctions.get(, None) or \ _Cfunction(, ((1,),), class_result(Media), ctypes.c_void_p, MediaPlayer) return f(p_mi)
Get the media used by the media_player. @param p_mi: the Media Player. @return: the media associated with p_mi, or NULL if no media is associated.
336,992
def search_for_tweets_about(user_id, params): url = "https://api.twitter.com/1.1/search/tweets.json" response = make_twitter_request(url, user_id, params) return process_tweets(response.json()["statuses"])
Search twitter API
336,993
def xminvsks(self, **kwargs): pylab.plot(self._xmins,self._xmin_kstest,) pylab.plot(self._xmin,self._ks,) ax=pylab.gca() ax.set_ylabel("KS statistic") ax.set_xlabel("min(x)") pylab.draw() return ax
Plot xmin versus the ks value for derived alpha. This plot can be used as a diagnostic of whether you have derived the 'best' fit: if there are multiple local minima, your data set may be well suited to a broken powerlaw or a different function.
336,994
def complete_login(self, request, app, token, **kwargs): headers = {: + token.token} userinfo_response = requests.get( self.profile_url, headers=headers, ) userinfo_response.raise_for_status() extra_...
Arguments: request - The get request to the callback URL /accounts/dataporten/login/callback. app - The corresponding SocialApp model instance token - A token object with access token given in token.token Returns: Should return a dict with ...
336,995
def tokenize(self, string): it = colorise.compat.ifilter(None, self._pattern.finditer(string)) try: t = colorise.compat.next(it) except StopIteration: yield string, False return pos, buf, lm, escapeflag = -1, , -1, False if...
Tokenize a string and return an iterator over its tokens.
336,996
def analyze_lopf(self, mode=None, timesteps=None, etrago_max_storage_size=None): if timesteps is None: timesteps = self.network.timeseries.timeindex if not hasattr(timesteps, "__len__"): timesteps = [timesteps] logging.debu...
Analyzes the grid by power flow analysis Analyze the grid for violations of hosting capacity. Means, perform a power flow analysis and obtain voltages at nodes (load, generator, stations/transformers and branch tees) and active/reactive power at lines. The power flow analysis c...
336,997
def user(context, user_id, update_role, add_institute, remove_admin, remove_institute): adapter = context.obj[] user_obj = adapter.user(user_id) if not user_obj: LOG.warning("User %s could not be found", user_id) context.abort() existing_roles = set(user_obj.get(,[])) if upda...
Update a user in the database
336,998
def interp(self): if self.ndim == 0: return elif all(interp == self.interp_byaxis[0] for interp in self.interp_byaxis): return self.interp_byaxis[0] else: return self.interp_byaxis
Interpolation type of this discretization.
336,999
def prompt_toolkit_key_to_vt100_key(key, application_mode=False): application_mode_keys = { Keys.Up: , Keys.Left: , Keys.Right: , Keys.Down: , } if key == Keys.ControlJ: return if key == : return elif application_mode and ke...
Turn a prompt toolkit key. (E.g Keys.ControlB) into a Vt100 key sequence. (E.g. \x1b[A.)