Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
365,600
def get_supercell_matrix(self, supercell, struct): if self._primitive_cell: raise ValueError("get_supercell_matrix cannot be used with the " "primitive cell option") struct, supercell, fu, s1_supercell = self._preprocess(struct, ...
Returns the matrix for transforming struct to supercell. This can be used for very distorted 'supercells' where the primitive cell is impossible to find
365,601
def GetSOAPEnvUri(self, version): attrname = % join(split(version, ), ) value = getattr(self, attrname, None) if value is not None: return value raise ValueError( % version )
Return the appropriate SOAP envelope uri for a given human-friendly SOAP version string (e.g. '1.1').
365,602
def name(value, known_modules=[]): if value is None: return if not isinstance(value, type): value = type(value) tname = value.__name__ if hasattr(builtins, tname): return tname modname = value.__module__ if modname == : return tname if known_modules an...
Return a name that can be imported, to serialize/deserialize an object
365,603
def _generate_components(self, X): rs = check_random_state(self.random_state) if (self._use_mlp_input): self._compute_biases(rs) self._compute_weights(X, rs) if (self._use_rbf_input): self._compute_centers(X, sp.issparse(X), rs) self._co...
Generate components of hidden layer given X
365,604
def dispatch(self, command, app): if self.is_glimcommand(command): command.run(app) else: command.run()
Function runs the active command. Args ---- command (glim.command.Command): the command object. app (glim.app.App): the glim app object. Note: Exception handling should be done in Command class itself. If not, an unhandled exception may result ...
365,605
def _dump_spec(spec): with open("spec.yaml", "w") as f: yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False)
Dump bel specification dictionary using YAML Formats this with an extra indentation for lists to make it easier to use cold folding on the YAML version of the spec dictionary.
365,606
def _z2deriv(self,R,z,phi=0.,t=0.): l,n = bovy_coords.Rz_to_lambdanu (R,z,ac=self._ac,Delta=self._Delta) jac = bovy_coords.Rz_to_lambdanu_jac(R,z, Delta=self._Delta) hess = bovy_coords.Rz_to_lambdanu_hess(R,z, Delta=self._Delta) dldz = jac[0,1] ...
NAME: _z2deriv PURPOSE: evaluate the second vertical derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t- time OUTPUT: the second vertical derivative ...
365,607
def mrca_matrix(self): M = dict() leaves_below = dict() for node in self.traverse_postorder(): leaves_below[node] = list() if node.is_leaf(): leaves_below[node].append(node); M[node] = dict() else: for i in range(len(no...
Return a dictionary storing all pairwise MRCAs. ``M[u][v]`` = MRCA of nodes ``u`` and ``v``. Excludes ``M[u][u]`` because MRCA of node and itself is itself Returns: ``dict``: ``M[u][v]`` = MRCA of nodes ``u`` and ``v``
365,608
def p_concat_list(p): if p[1].__class__ == node.expr_list: p[0] = node.concat_list([p[1], p[3]]) else: p[0] = p[1] p[0].append(p[3])
concat_list : expr_list SEMI expr_list | concat_list SEMI expr_list
365,609
def param_projection(self, x_param, y_param, metric): return param_projection(self.estimator.cv_results_, x_param, y_param, metric)
Projects the grid search results onto 2 dimensions. The wrapped GridSearch object is assumed to be fit already. The display value is taken as the max over the non-displayed dimensions. Parameters ---------- x_param : string The name of the parameter to be visualized...
365,610
def is_driver(self): if hasattr(self, ): if set( (, , , , ) ).intersection( [ imp.dll.lower() for imp in self.DIRECTORY_ENTRY_IMPORT ] ):...
Check whether the file is a Windows driver. This will return true only if there are reliable indicators of the image being a driver.
365,611
def thousands(x): import locale try: locale.setlocale(locale.LC_ALL, "en_US.utf8") except Exception: locale.setlocale(locale.LC_ALL, "en_US.UTF-8") finally: s = % x groups = [] while s and s[-1].isdigit(): groups.append(s[-3:]) s = s[...
>>> thousands(12345) '12,345'
365,612
def minimal_raw_seqs(self): seqs = [[], []] for letter in self.oneletter: if one2two.has_key(letter): seqs[0].append(one2two[letter][0]) seqs[1].append(one2two[letter][1]) else: seqs[0].append(letter) seqs[1...
m.minimal_raw_seqs() -- Return minimal list of seqs that represent consensus
365,613
def slice_slice(old_slice, applied_slice, size): step = (old_slice.step or 1) * (applied_slice.step or 1) items = _expand_slice(old_slice, size)[applied_slice] if len(items) > 0: start = items[0] stop = items[-1] + int(np.sign(step)) if stop < 0: stop...
Given a slice and the size of the dimension to which it will be applied, index it with another slice to return a new slice equivalent to applying the slices sequentially
365,614
def loaded(self, request, *args, **kwargs): serializer = self.get_serializer(list(Pack.objects.all()), many=True) return Response(serializer.data)
Return a list of loaded Packs.
365,615
def _encrypt_asymmetric(self, encryption_algorithm, encryption_key, plain_text, padding_method, hashing_algorithm=None): if encryption_algorithm == enums.Cryptogra...
Encrypt data using asymmetric encryption. Args: encryption_algorithm (CryptographicAlgorithm): An enumeration specifying the asymmetric encryption algorithm to use for encryption. Required. encryption_key (bytes): The bytes of the public key to use for ...
365,616
def get_graphql_schema_from_orientdb_schema_data(schema_data, class_to_field_type_overrides=None, hidden_classes=None): if class_to_field_type_overrides is None: class_to_field_type_overrides = dict() if hidden_classes is None: hidden_classes...
Construct a GraphQL schema from an OrientDB schema. Args: schema_data: list of dicts describing the classes in the OrientDB schema. The following format is the way the data is structured in OrientDB 2. See the README.md file for an example of how to query this data...
365,617
def _data_block(stream): while len(stream) > 0: line = stream.popleft() if line.startswith(): yield DataHeader(line[1:].strip()) else: data_item = line.strip() if data_item: yield DataItem(line) else: conti...
Process data block of ``CTfile``. :param stream: Queue containing lines of text. :type stream: :py:class:`collections.deque` :return: Tuples of data. :rtype: :class:`~ctfile.tokenizer.DataHeader` or :class:`~ctfile.tokenizer.DataItem`
365,618
def CompressStream(in_stream, length=None, compresslevel=2, chunksize=16777216): in_read = 0 in_exhausted = False out_stream = StreamingBuffer() with gzip.GzipFile(mode=, fileobj=out_stream, compresslevel=compresslevel) as compress_s...
Compresses an input stream into a file-like buffer. This reads from the input stream until either we've stored at least length compressed bytes, or the input stream has been exhausted. This supports streams of unknown size. Args: in_stream: The input stream to read from. length: The t...
365,619
def get_endpoint_map(self): log.debug("getting end points...") cmd, url = DEVICE_URLS["get_endpoint_map"] return self._exec(cmd, url)
returns API version and endpoint map
365,620
def joint_plot(x, y, marginalBins=50, gridsize=50, plotlimits=None, logscale_cmap=False, logscale_marginals=False, alpha_hexbin=0.75, alpha_marginals=0.75, cmap="inferno_r", marginalCol=None, figsize=(8, 8), fontsize=8, *args, **kwargs): with _plt.rc_context({: fontsize,}): hexbin_marginal_sep...
Plots some x and y data using hexbins along with a colorbar and marginal distributions (X and Y histograms). Parameters ---------- x : ndarray The x data y : ndarray The y data marginalBins : int, optional The number of bins to use in calculating the marginal his...
365,621
def get_training_data(batch_size): return gluon.data.DataLoader( CIFAR10(train=True, transform=transformer), batch_size=batch_size, shuffle=True, last_batch=)
helper function to get dataloader
365,622
def GetRootFileEntry(self): path_spec = tsk_partition_path_spec.TSKPartitionPathSpec( location=self.LOCATION_ROOT, parent=self._path_spec.parent) return self.GetFileEntryByPathSpec(path_spec)
Retrieves the root file entry. Returns: TSKPartitionFileEntry: a file entry or None of not available.
365,623
async def get_response_metadata(response: str) -> str: logger = logging.getLogger(__name__) logger.debug("get_response_metadata: >>> response: %r", response) if not hasattr(get_response_metadata, "cb"): logger.debug("get_response_metadata: Creating callback") get_resp...
Parse transaction response to fetch metadata. The important use case for this method is validation of Node's response freshens. Distributed Ledgers can reply with outdated information for consequence read request after write. To reduce pool load libindy sends read requests to one random node in the pool...
365,624
def p_tag_ref(self, p): p[0] = AstTagRef(self.path, p.lineno(1), p.lexpos(1), p[1])
tag_ref : ID
365,625
def migrate(uri: str, archive_uri: str, case_id: str, dry: bool, force: bool): scout_client = MongoClient(uri) scout_database = scout_client[uri.rsplit(, 1)[-1]] scout_adapter = MongoAdapter(database=scout_database) scout_case = scout_adapter.case(case_id) if not force and scout_case.get(): ...
Update all information that was manually annotated from a old instance.
365,626
def handle_bind_iq_set(self, stanza): if not self.stream: logger.error("Got bind stanza before stream feature has been set") return False if self.stream.initiator: return False peer = self.stream.peer if peer.resource: rai...
Handler <iq type="set"/> for resource binding.
365,627
def get_layer_heights(heights, depth, *args, **kwargs): bottom = kwargs.pop(, None) interpolate = kwargs.pop(, True) with_agl = kwargs.pop(, False) for datavar in args: if len(heights) != len(datavar): raise ValueError() if with_agl: sfc_height = np.min(h...
Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer using the heights only. Parameters ---------- heights : array-like Atmospheric heights depth : `pint.Quantity` ...
365,628
def list_messages(self): messages = sorted(self._messages_definitions.values(), key=lambda m: m.msgid) for message in messages: if not message.may_be_emitted(): continue print(message.format_help(checkerref=False)) print("")
Output full messages list documentation in ReST format.
365,629
def fastqIterator(fn, verbose=False, allowNameMissmatch=False): it = fastqIteratorSimple(fn, verbose=verbose, allowNameMissmatch=allowNameMissmatch) for s in it: yield s
A generator function which yields FastqSequence objects read from a file or stream. This is a general function which wraps fastqIteratorSimple. In future releases, we may allow dynamic switching of which base iterator is used. :param fn: A file-like stream or a string; if this is a ...
365,630
def curve_points(self, beginframe, endframe, framestep, birthframe, startframe, stopframe, deathframe, filternone=True, noiseframe=None): if endframe < beginframe and framestep > 0: assert False, "infinite loop: beginframe = {0}, endframe = {1}, framestep = {2}".format(...
returns a list of frames from startframe to stopframe, in steps of framestepj warning: the list of points may include "None" elements :param beginframe: first frame to include in list of points :param endframe: last frame to include in list of points :param framestep: framestep ...
365,631
def zip(self, destination: typing.Union[str, Path] = None, encode: bool = True) -> str: if encode: self._encode() if destination is None: destination_path = self.miz_path.parent.joinpath(f) else: destination_path = elib.path.ensure_file(destination, ...
Write mission, dictionary etc. to a MIZ file Args: destination: target MIZ file (if none, defaults to source MIZ + "_EMIZ" Returns: destination file
365,632
def _loadFromHStream(self, dtype: HStream, bitAddr: int) -> int: ch = TransTmpl(dtype.elmType, 0, parent=self, origin=self.origin) self.children.append(ch) return bitAddr + dtype.elmType.bit_length()
Parse HUnion type to this transaction template instance :return: address of it's end
365,633
def add_to_manifest(self, manifest): manifest.add_service(self.service.name) manifest.add_env_var(self.__module__ + , self.service.settings.data[]) manifest.add_env_var(self.__module__ + , self.get_predix_zone_id()) manifest.wr...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
365,634
def create_checklist_item(self, card_id, checklist_id, checklistitem_json, **kwargs): return self.client.create_checklist_item(card_id, checklist_id, checklistitem_json, **kwargs)
Create a ChecklistItem object from JSON object
365,635
def iteritems(self, **options): iter = self.query(**options) while True: obj = iter.next() yield (obj.id, obj)
Return a query interator with (id, object) pairs.
365,636
def getServiceDependenciesUIDs(self): deps = self.getServiceDependencies() deps_uids = [service.UID() for service in deps] return deps_uids
This methods returns a list with the service dependencies UIDs :return: a list of uids
365,637
def git_remote(self): if self._git_remotes is None or len(self._git_remotes) < 1: return None if in self._git_remotes: return self._git_remotes[] k = sorted(self._git_remotes.keys())[0] return self._git_remotes[k]
If the distribution is installed via git, return the first URL of the 'origin' remote if one is configured for the repo, or else the first URL of the lexicographically-first remote, or else None. :return: origin or first remote URL :rtype: :py:obj:`str` or :py:data:`None`
365,638
def _search(self, mdb, query, filename, season_num, episode_num, auto=False): choices = [] for datasource, movie in mdb.search(query, season=season_num, episode=episode_num): if auto: return datasource, movie fmt = u choices.append(option((dat...
Search the movie using all available datasources and let the user select a result. Return the choosen datasource and produced movie dict. If auto is enabled, directly returns the first movie found.
365,639
def config(conf, confdefs): conf = conf.copy() for name, info in confdefs: conf.setdefault(name, info.get()) return conf
Initialize a config dict using the given confdef tuples.
365,640
def hierarchical_match(d, k, default=None): if d is None: return default if type(k) != list and type(k) != tuple: k = [k] for n, _ in enumerate(k): key = tuple(k[0:len(k)-n]) if len(key) == 1: key = key[0] try: d[key] except: ...
Match a key against a dict, simplifying element at a time :param df: DataFrame :type df: pandas.DataFrame :param level: Level of DataFrame index to extract IDs from :type level: int or str :return: hiearchically matched value or default
365,641
def add_clause(self, clause, soft=False): cl = list(map(lambda l: self._map_extlit(l), clause)) if not soft: self.oracle.add_clause(cl) else: self.soft.append(cl) sel = cl[0] if len(cl) > 1 or...
The method for adding a new hard of soft clause to the problem formula. Although the input formula is to be specified as an argument of the constructor of :class:`LBX`, adding clauses may be helpful when *enumerating* MCSes of the formula. This way, the clauses are added ...
365,642
def Delete(self): self.public_ip.source_restrictions = [o for o in self.public_ip.source_restrictions if o!=self] return(self.public_ip.Update())
Delete this source restriction and commit change to cloud. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].source_restrictions[0].Delete().WaitUntilComplete() 0
365,643
def annual_event_counts_card(kind=, current_year=None): if kind == : card_title = else: card_title = .format(Event.get_kind_name_plural(kind)) return { : card_title, : kind, : annual_event_counts(kind=kind), : current_year }
Displays years and the number of events per year. kind is an Event kind (like 'cinema', 'gig', etc.) or 'all' (default). current_year is an optional date object representing the year we're already showing information about.
365,644
def add_random_tile(self): x_pos, y_pos = np.where(self._state == 0) assert len(x_pos) != 0 empty_index = np.random.choice(len(x_pos)) value = np.random.choice([1, 2], p=[0.9, 0.1]) self._state[x_pos[empty_index], y_pos[empty_index]] = value
Adds a random tile to the grid. Assumes that it has empty fields.
365,645
def add_pool_member(self, name, port, pool_name): if not self.check_pool(pool_name): raise CommandExecutionError( .format(pool_name) ) members_seq = self.bigIP.LocalLB.Pool.typefactory.create( ) members_seq.items = [] ...
Add a node to a pool
365,646
def connect(self, cback, subscribers=None, instance=None): if subscribers is None: subscribers = self.subscribers if self._fconnect is not None: def _connect(cback): self._connect(subscribers, cback) notify = partial(self._notify_one...
Add a function or a method as an handler of this signal. Any handler added can be a coroutine. :param cback: the callback (or *handler*) to be added to the set :returns: ``None`` or the value returned by the corresponding wrapper
365,647
def getWmWindowType(self, win, str=False): types = self._getProperty(, win) or [] if not str: return types return [self._getAtomName(t) for t in types]
Get the list of window types of the given window (property _NET_WM_WINDOW_TYPE). :param win: the window object :param str: True to get a list of string types instead of int :return: list of (int|str)
365,648
def map(self, func, *columns): if not columns: return map(func, self.rows) else: values = (self.values(column) for column in columns) result = [map(func, v) for v in values] if len(columns) == 1: return result[0] else: ...
Map a function to rows, or to given columns
365,649
def reduce_dimensionality(self, data): if type(data) is Instance: return Instance( javabridge.call( self.jobject, "reduceDimensionality", "(Lweka/core/Instance;)Lweka/core/Instance;", data.jobject)) else: return Ins...
Reduces the dimensionality of the provided Instance or Instances object. :param data: the data to process :type data: Instances :return: the reduced dataset :rtype: Instances
365,650
def read_end_of_message(self): read = self._file.read last = read(1) current = read(1) while last != b and current != b and not \ (last == b and current == b): last = current current = read(1)
Read the b"\\r\\n" at the end of the message.
365,651
def find_obfuscatables(tokens, obfunc, ignore_length=False): global keyword_args keyword_args = analyze.enumerate_keyword_args(tokens) global imported_modules imported_modules = analyze.enumerate_imports(tokens) skip_line = False skip_next = False obfuscatables = [] for index, ...
Iterates over *tokens*, which must be an equivalent output to what tokenize.generate_tokens() produces, calling *obfunc* on each with the following parameters: - **tokens:** The current list of tokens. - **index:** The current position in the list. *obfunc* is expected to return t...
365,652
def size_container_folding(value): if len(value) < MAX_LEN: if isinstance(value, list): return ast.List([to_ast(elt) for elt in value], ast.Load()) elif isinstance(value, tuple): return ast.Tuple([to_ast(elt) for elt in value], ast.Load()) elif isinstance(value, ...
Convert value to ast expression if size is not too big. Converter for sized container.
365,653
def last_restapi_key_transformer(key, attr_desc, value): key, value = full_restapi_key_transformer(key, attr_desc, value) return (key[-1], value)
A key transformer that returns the last RestAPI key. :param str key: The attribute name :param dict attr_desc: The attribute metadata :param object value: The value :returns: The last RestAPI key.
365,654
def arange(start, stop=None, step=1.0, repeat=1, infer_range=None, ctx=None, dtype=mx_real_t): if infer_range is not None: warnings.warn(, DeprecationWarning) if ctx is None: ctx = current_context() return _internal._arange(start=start, stop=stop, step=step, repeat...
Returns evenly spaced values within a given interval. Values are generated within the half-open interval [`start`, `stop`). In other words, the interval includes `start` but excludes `stop`. The function is similar to the built-in Python function `range` and to `numpy.arange`, but returns an `NDArray`....
365,655
def readConfigFromJSON(self, fileName): self.__logger.debug("readConfigFromJSON: reading from " + fileName) with open(fileName) as data_file: data = load(data_file) self.readConfig(data)
Read configuration from JSON. :param fileName: path to the configuration file. :type fileName: str.
365,656
def _init_options(self, kwargs): self.options = self.task_config.options if self.options is None: self.options = {} if kwargs: self.options.update(kwargs) for option, value in list(self.options.items()): try: if value...
Initializes self.options
365,657
def do_output(self, *args): if args: action, params = args[0], args[1:] log.debug("Pass %s directly to output with %s", action, params) function = getattr(self.output, "do_" + action, None) if function: function(*params)
Pass a command directly to the current output processor
365,658
def preprocess_images(raw_color_im, raw_depth_im, camera_intr, T_camera_world, workspace_box, workspace_im, image_proc_config): inpaint_rescale_factor = image_proc_config[] ...
Preprocess a set of color and depth images.
365,659
def _create_socket(self, socket_family): sock = socket.socket(socket_family, socket.SOCK_STREAM, 0) sock.settimeout(self._parameters[] or None) if self.use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( ...
Create Socket. :param int socket_family: :rtype: socket.socket
365,660
def iter_format_block( self, text=None, width=60, chars=False, fill=False, newlines=False, append=None, prepend=None, strip_first=False, strip_last=False, lstrip=False): if fill: chars = False iterlines = self.iter_block( ...
Iterate over lines in a formatted block of text. This iterator allows you to prepend to each line. For basic blocks see iter_block(). Arguments: text : String to format. width : Maximum width for each line. The prepend string ...
365,661
def stmt_lambdef_handle(self, original, loc, tokens): if len(tokens) == 2: params, stmts = tokens elif len(tokens) == 3: params, stmts, last = tokens if "tests" in tokens: stmts = stmts.asList() + ["return " + last] else: ...
Process multi-line lambdef statements.
365,662
def compute(self, inputs, outputs): if len(self.queue) > 0: data = self.queue.pop() else: raise Exception("RawValues: No data: queue is empty ") outputs["resetOut"][0] = data["reset"] outputs["dataOut"][:] = data["dataOut"]
Get the next record from the queue and outputs it.
365,663
def sim_levenshtein(src, tar, mode=, cost=(1, 1, 1, 1)): return Levenshtein().sim(src, tar, mode, cost)
Return the Levenshtein similarity of two strings. This is a wrapper of :py:meth:`Levenshtein.sim`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison mode : str Specifies a mode for computing the Levenshtein distance: ...
365,664
def extract_zip(zip_file_path): dfs = {} with zipfile.ZipFile(zip_file_path, mode=) as z_file: names = z_file.namelist() for name in names: content = z_file.read(name) _, tmp_file_path = tempfile.mkstemp() try: with open(tmp_file_path, ) a...
Returns: dict: Dict[str, DataFrame]
365,665
def get_comment(self, project, work_item_id, comment_id, include_deleted=None, expand=None): route_values = {} if project is not None: route_values[] = self._serialize.url(, project, ) if work_item_id is not None: route_values[] = self._serialize.url(, work_item_...
GetComment. [Preview API] Returns a work item comment. :param str project: Project ID or project name :param int work_item_id: Id of a work item to get the comment. :param int comment_id: Id of the comment to return. :param bool include_deleted: Specify if the deleted comment sho...
365,666
def _fold_line(self, line): if len(line) <= self._cols: self._output_file.write(line) self._output_file.write(self._line_sep) else: pos = self._cols self._output_file.write(line[0:self._cols]) self._output_file.write(self._line_sep) ...
Write string line as one or more folded lines.
365,667
def hotp(key, counter, digits=6): msg = struct.pack(, counter) hs = hmac.new(key, msg, hashlib.sha1).digest() offset = six.indexbytes(hs, 19) & 0x0f val = struct.unpack(, hs[offset:offset + 4])[0] & 0x7fffffff return .format(val=val % 10 ** digits, digits=digits)
These test vectors come from RFC-4226 (https://tools.ietf.org/html/rfc4226#page-32). >>> key = b'12345678901234567890' >>> for c in range(10): ... hotp(key, c) '755224' '287082' '359152' '969429' '338314' '254676' '287922' '162583' '399871' '520489'
365,668
def parse_dict_header(value): result = {} for item in parse_http_list(value): if not in item: result[item] = None continue name, value = item.split(, 1) if value[:1] == value[-1:] == : value = unquote_header_value(value[1:-1]) result[name...
Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict: >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] If there is no value for a key it wi...
365,669
def as_dict(self): if not self._is_valid: self.validate() from .converters import to_dict return to_dict(self)
Returns the model as a dict
365,670
def _zforce(self,R,z,phi=0.,t=0.): if self._new: if nu.fabs(z) < 10.**-6.: return 0. kalphamax1= R ks1= kalphamax1*0.5*(self._glx+1.) weights1= kalphamax1*self._glw sqrtp= nu.sqrt(z**2.+(ks1+R)**2.) sqr...
NAME: zforce PURPOSE: evaluate vertical force K_z (R,z) INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - time OUTPUT: K_z (R,z) HISTORY: 2012-12-27 - Written - Bovy ...
365,671
def reprioritize(self, stream_id, depends_on=None, weight=16, exclusive=False): self._priority.reprioritize(stream_id, depends_on, weight, exclusive)
Update the priority status of an existing stream. :param stream_id: The stream ID of the stream being updated. :param depends_on: (optional) The ID of the stream that the stream now depends on. If ``None``, will be moved to depend on stream 0. :param weight: (optional) The new weigh...
365,672
def pyside_load_ui(uifile, base_instance=None): form_class, base_class = load_ui_type(uifile) if not base_instance: typeName = form_class.__name__ finalType = type(typeName, (form_class, base_class), {}) base_instance = finalType() ...
Provide PyQt4.uic.loadUi functionality to PySide Args: uifile (str): Absolute path to .ui file base_instance (QWidget): The widget into which UI widgets are loaded Note: pysideuic is required for this to work with PySide. This seems to work correctly in Maya as well as outsid...
365,673
def _convert_to_dict(self, setting): the_dict = {} set = dir(setting) for key in set: if key in self.ignore: continue value = getattr(setting, key) the_dict[key] = value return the_dict
Converts a settings file into a dictionary, ignoring python defaults @param setting: A loaded setting module
365,674
def SearchFileNameTable(self, fileName): goodlogging.Log.Info("DB", "Looking up filename string in database".format(fileName), verbosity=self.logVerbosity) queryString = "SELECT ShowID FROM FileName WHERE FileName=?" queryTuple = (fileName, ) result = self._ActionDatabase(queryString, queryTuple...
Search FileName table. Find the show id for a given file name. Parameters ---------- fileName : string File name to look up in table. Returns ---------- int or None If a match is found in the database table the show id for this entry is returned, otherwise this...
365,675
def get_all_roles(path_prefix=None, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return None _roles = conn.list_roles(path_prefix=path_prefix) roles = _roles.list_roles_response.list_ro...
Get and return all IAM role details, starting at the optional path. .. versionadded:: 2016.3.0 CLI Example: salt-call boto_iam.get_all_roles
365,676
def watchdog_handler(self): _LOGGING.debug(, self.name) self.watchdog.stop() self.reset_thrd.set()
Take care of threads if wachdog expires.
365,677
def dropbox_factory(request): try: return request.registry.settings[].get_dropbox(request.matchdict[]) except KeyError: raise HTTPNotFound()
expects the id of an existing dropbox and returns its instance
365,678
def version_option(version=None, *param_decls, **attrs): if version is None: module = sys._getframe(1).f_globals.get() def decorator(f): prog_name = attrs.pop(, None) message = attrs.pop(, ) def callback(ctx, param, value): if not value or ctx.resilient_parsing:...
Adds a ``--version`` option which immediately ends the program printing out the version number. This is implemented as an eager option that prints the version and exits the program in the callback. :param version: the version number to show. If not provided Click attempts an auto disc...
365,679
def record_command(self, cmd, prg=): self._log(self.logFileCommand , force_to_string(cmd), prg)
record the command passed - this is usually the name of the program being run or task being run
365,680
def train(self, x_data, y_data): x_train, _, y_train, _ = train_test_split( x_data, y_data, test_size=0.67, random_state=None ) self.model.fit(x_train, y_train)
Trains model on inputs :param x_data: x matrix :param y_data: y array
365,681
def log_det_jacobian(self, inputs): del inputs num_events = tf.reduce_prod(tf.shape(inputs)[1:-1]) log_det_jacobian = num_events * tf.reduce_sum(self.log_scale) return log_det_jacobian
Returns log det | dx / dy | = num_events * sum log | scale |.
365,682
def ping(host, timeout=False, return_boolean=False): *** if timeout: if __grains__[] == : cmd = .format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = .format(timeout, salt.utils.network.sanitize_host(host)) else: cmd = .format(salt.utils.network...
Performs an ICMP ping to a host .. versionchanged:: 2015.8.0 Added support for SunOS CLI Example: .. code-block:: bash salt '*' network.ping archlinux.org .. versionadded:: 2015.5.0 Return a True or False instead of ping output. .. code-block:: bash salt '*' netwo...
365,683
def set_exception(self, exception, override=False): with self._lock: if not self.done() or override: self._exception = exception self._status =
Set an exception for the TransferFuture Implies the TransferFuture failed. :param exception: The exception that cause the transfer to fail. :param override: If True, override any existing state.
365,684
def download_uniprot_file(uniprot_id, filetype, outdir=, force_rerun=False): my_file = .format(uniprot_id, filetype) url = .format(my_file) outfile = op.join(outdir, my_file) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): urlretrieve(url, outfile) return outfile
Download a UniProt file for a UniProt ID/ACC Args: uniprot_id: Valid UniProt ID filetype: txt, fasta, xml, rdf, or gff outdir: Directory to download the file Returns: str: Absolute path to file
365,685
def _create_glance_db(self, root_db_pass, glance_db_pass): print red(env.host_string + ) sudo( "mysql -uroot -p{0} -e \"CREATE DATABASE glance;\"".format(root_db_pass), shell=False) sudo("mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO @ IDENTIFIED BY ;\"".f...
Create the glance database
365,686
def server_deployment_mode(command, parser, cluster, cl_args): client_confs = cdefs.read_server_mode_cluster_definition(cluster, cl_args) if not client_confs[cluster]: return dict() if not cl_args.get(, None): Log.debug("Using cluster definition from file %s" \ % cliconfig.get_cluster_c...
check the server deployment mode for the given cluster if it is valid return the valid set of args :param cluster: :param cl_args: :return:
365,687
def _pdb_frame(self): if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
Return current Pdb frame if there is any
365,688
def get_distance_matrix(self): assert self.lons.ndim == 1 distances = geodetic.geodetic_distance( self.lons.reshape(self.lons.shape + (1, )), self.lats.reshape(self.lats.shape + (1, )), self.lons, self.lats) return numpy.matrix(distances, ...
Compute and return distances between each pairs of points in the mesh. This method requires that the coordinate arrays are one-dimensional. NB: the depth of the points is ignored .. warning:: Because of its quadratic space and time complexity this method is safe to use ...
365,689
def plot(self, data=None, **kwargs): from .plot.plot import plot as plotter if data is None: d = copy.copy(self.data) transform = copy.copy(self.xform_data) if any([k in kwargs for k in [, , , , , ]]): ...
Plot the data Parameters ---------- data : numpy array, pandas dataframe or list of arrays/dfs The data to plot. If no data is passed, the xform_data from the DataGeometry object will be returned. kwargs : keyword arguments Any keyword arguments sup...
365,690
def retrieve_console_log(self, filename=None, dir=None): if hasattr(self, "consoleLog") and self.consoleLog is not None: logger.debug("Retrieving PE console log: " + self.consoleLog) if not filename: filename = _file_name(, self.id, ) return s...
Retrieves the application console log (standard out and error) files for this PE and saves them as a plain text file. An existing file with the same name will be overwritten. Args: filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.stdouterr` where `id` is t...
365,691
def kill_tweens(self, obj = None): if obj is not None: try: del self.current_tweens[obj] except: pass else: self.current_tweens = collections.defaultdict(set)
Stop tweening an object, without completing the motion or firing the on_complete
365,692
def create_gce_image(zone, project, instance_name, name, description): disk_name = instance_name try: down_gce(instance_name=instance_name, project=project, zone=zone) except HttpError as e: if e.resp.s...
Shuts down the instance and creates and image from the disk. Assumes that the disk name is the same as the instance_name (this is the default behavior for boot disks on GCE).
365,693
def _nodes(self): return list(set([node for node, timeslice in super(DynamicBayesianNetwork, self).nodes()]))
Returns the list of nodes present in the network Examples -------- >>> from pgmpy.models import DynamicBayesianNetwork as DBN >>> dbn = DBN() >>> dbn.add_nodes_from(['A', 'B', 'C']) >>> sorted(dbn._nodes()) ['B', 'A', 'C']
365,694
def get_port_profile_status_input_port_profile_status(self, **kwargs): config = ET.Element("config") get_port_profile_status = ET.Element("get_port_profile_status") config = get_port_profile_status input = ET.SubElement(get_port_profile_status, "input") port_profile_stat...
Auto Generated Code
365,695
def initialiseDevice(self): logger.debug("Initialising device") self.getInterruptStatus() self.setAccelerometerSensitivity(self._accelerationFactor * 32768.0) self.setGyroSensitivity(self._gyroFactor * 32768.0) self.setSampleRate(self.fs) for loop in self.ZeroReg...
performs initialisation of the device :param batchSize: the no of samples that each provideData call should yield :return:
365,696
def compute_header_hmac_hash(context): return hmac.new( hashlib.sha512( b * 8 + hashlib.sha512( context._.header.value.dynamic_header.master_seed.data + context.transformed_key + b ).digest() ).digest(), ...
Compute HMAC-SHA256 hash of header. Used to prevent header tampering.
365,697
def parse_description(): from os.path import dirname, join, exists readme_fpath = join(dirname(__file__), ) if exists(readme_fpath): textlines = [] with open(readme_fpath, ) as f: textlines = f.readlines() text = .join(textlines).strip() return text ...
Parse the description in the README file pandoc --from=markdown --to=rst --output=README.rst README.md CommandLine: python -c "import setup; print(setup.parse_description())"
365,698
def ekbseg(handle, tabnam, cnames, decls): handle = ctypes.c_int(handle) tabnam = stypes.stringToCharP(tabnam) ncols = ctypes.c_int(len(cnames)) cnmlen = ctypes.c_int(len(max(cnames, key=len)) + 1) cnames = stypes.listToCharArrayPtr(cnames) declen = ctypes.c_int(len(max(decls, key=len)) +...
Start a new segment in an E-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekbseg_c.html :param handle: File handle. :type handle: int :param tabnam: Table name. :type tabnam: str :param cnames: Names of columns. :type cnames: list of str. :param decls: Declarations of...
365,699
def _to_ctfile(self): output = io.StringIO() for key in self: if key == : for line in self[key].values(): output.write(line) output.write() elif key == : ctab_str = self[key]._to_ctfile() ...
Convert :class:`~ctfile.ctfile.CTfile` into `CTfile` formatted string. :return: ``CTfile`` formatted string. :rtype: :py:class:`str`.