Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
18,100
def filter_zone(self, data): if self.private_zone is not None: if data[][] != self.str2bool(self.private_zone): return False if data[] != .format(self.domain): return False return True
Check if a zone is private
18,101
def get_userstable_data(self): project_users = {} project = self.tab_group.kwargs[] try: roles = api.keystone.role_list(self.request) self._get_users_from_project(project_id=project.id, ...
Get users with roles on the project. Roles can be applied directly on the project or through a group.
18,102
def _warn_silly_options(cls, args): if in args.span_hosts_allow \ and not args.page_requisites: _logger.warning( _( ) ) if in args.span_hosts_allow \ and not args.recursive: _logger.warning(...
Print warnings about any options that may be silly.
18,103
def compare_variants_label_plot(data): keys = OrderedDict() keys[] = {: } keys[] = {: } pconfig = { : , : , : , } return bargraph.plot(data, cats=keys, pconfig=pconfig)
Return HTML for the Compare variants plot
18,104
def _compile_pfgen(self): string = self.pfgen = compile(eval(string), , )
Post power flow computation for PV and SW
18,105
def DBObject(table_name, versioning=VersioningTypes.NONE): def wrapped(cls): field_names = set() all_fields = [] for name in dir(cls): fld = getattr(cls, name) if fld and isinstance(fld, Field): fld.name = name all_fields.append(f...
Classes annotated with DBObject gain persistence methods.
18,106
def get_distbins(start=100, bins=2500, ratio=1.01): b = np.ones(bins, dtype="float64") b[0] = 100 for i in range(1, bins): b[i] = b[i - 1] * ratio bins = np.around(b).astype(dtype="int") binsizes = np.diff(bins) return bins, binsizes
Get exponentially sized
18,107
def _rename_hstore_unique(self, old_table_name, new_table_name, old_field, new_field, keys): old_name = self._unique_constraint_name( old_table_name, old_field, keys) new_name = self._unique_constraint_name( new_table_name, new_field, keys)...
Renames an existing UNIQUE constraint for the specified hstore keys.
18,108
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix): if INITPY in os.listdir(src): root_package = src.split(os.path.sep)[-1] else: root_package = None toplevels = [] for root, subs, files in walk(src, followlinks=followlinks): ...
Look for every file in the directory tree and create the corresponding ReST files. :param app: the sphinx app :type app: :class:`sphinx.application.Sphinx` :param env: the jinja environment :type env: :class:`jinja2.Environment` :param src: the path to the python source files :type src: :cl...
18,109
def generate_nodes(self, topology): nodes = [] devices = topology[] hypervisors = topology[] for device in sorted(devices): hv_id = devices[device][] try: tmp_node = Node(hypervisors[hv_id], self.port_id) except IndexError: ...
Generate a list of nodes for the new topology :param dict topology: processed topology from :py:meth:`process_topology` :return: a list of dicts on nodes :rtype: list
18,110
def list_symbols(self, partial_match=None): symbols = self._symbols.distinct(SYMBOL) if partial_match is None: return symbols return [x for x in symbols if partial_match in x]
Returns all symbols in the library Parameters ---------- partial: None or str if not none, use this string to do a partial match on symbol names Returns ------- list of str
18,111
def apply_layout(self, child, layout): params = self.create_layout_params(child, layout) w = child.widget if w: if layout.get(): dp = self.dp l, t, r, b = layout[] w.setPadding(int(l*dp), int(t*dp), ...
Apply the flexbox specific layout.
18,112
def update( self, alert_condition_nrql_id, policy_id, name=None, threshold_type=None, query=None, since_value=None, terms=None, expected_groups=None, value_function=None, runbook_url=None, ignore_overlap=None, enabled=True): conditions_nrql_dict = self.list(policy...
Updates any of the optional parameters of the alert condition nrql :type alert_condition_nrql_id: int :param alert_condition_nrql_id: Alerts condition NRQL id to update :type policy_id: int :param policy_id: Alert policy id where target alert condition belongs to :type conditi...
18,113
def tradingStatusDF(symbol=None, token=, version=): x = tradingStatus(symbol, token, version) data = [] for key in x: d = x[key] d[] = key data.append(d) df = pd.DataFrame(data) _toDatetime(df) return df
The Trading status message is used to indicate the current trading status of a security. For IEX-listed securities, IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons. For non-IEX-listed securities, IE...
18,114
def _s3_intermediate_upload(file_obj, file_name, fields, session, callback_url): import boto3 from boto3.s3.transfer import TransferConfig from boto3.exceptions import S3UploadFailedError client = boto3.client( "s3", aws_access_key_id=fields["upload_aws_access_key_id"], ...
Uploads a single file-like object to an intermediate S3 bucket which One Codex can pull from after receiving a callback. Parameters ---------- file_obj : `FASTXInterleave`, `FilePassthru`, or a file-like object A wrapper around a pair of fastx files (`FASTXInterleave`) or a single fastx file. I...
18,115
def predict(self, x_test): if self.model: lengths = map(len, x_test) x_test = self.p.transform(x_test) y_pred = self.model.predict(x_test) y_pred = self.p.inverse_transform(y_pred, lengths) return y_pred else: raise OSErro...
Returns the prediction of the model on the given test data. Args: x_test : array-like, shape = (n_samples, sent_length) Test samples. Returns: y_pred : array-like, shape = (n_smaples, sent_length) Prediction labels for x.
18,116
def isSameStatementList(stmListA: List[HdlStatement], stmListB: List[HdlStatement]) -> bool: if stmListA is stmListB: return True if stmListA is None or stmListB is None: return False for a, b in zip(stmListA, stmListB): if not a.isSame(b): r...
:return: True if two lists of HdlStatement instances are same
18,117
def _copy_across(self, rel_path, cb=None): from . import copy_file_or_flo if not self.upstream.has(rel_path): if not self.alternate.has(rel_path): return None source = self.alternate.get_stream(rel_path) sink = self.upstream.put_stream(r...
If the upstream doesn't have the file, get it from the alternate and store it in the upstream
18,118
def distance_to(self, other_catchment): try: if self.country == other_catchment.country: try: return 0.001 * hypot(self.descriptors.centroid_ngr.x - other_catchment.descriptors.centroid_ngr.x, self.descriptors.cent...
Returns the distance between the centroids of two catchments in kilometers. :param other_catchment: Catchment to calculate distance to :type other_catchment: :class:`.Catchment` :return: Distance between the catchments in km. :rtype: float
18,119
def to_dict(self): input_dict = super(Add, self)._save_to_input_dict() input_dict["class"] = str("GPy.kern.Add") return input_dict
Convert the object into a json serializable dictionary. Note: It uses the private method _save_to_input_dict of the parent. :return dict: json serializable dictionary containing the needed information to instantiate the object
18,120
def _metahash(self): if self._cached_metahash: return self._cached_metahash log.debug(, self.address, unicode(self.address)) mhash = util.hash_str(unicode(self.add...
Checksum hash of all the inputs to this rule. Output is invalid until collect_srcs and collect_deps have been run. In theory, if this hash doesn't change, the outputs won't change either, which makes it useful for caching.
18,121
def unescape(msg, extra_format_dict={}): new_msg = extra_format_dict.update(format_dict) while len(msg): char = msg[0] msg = msg[1:] if char == escape_character: escape_key = msg[0] msg = msg[1:] if escape_key == ...
Takes a girc-escaped message and returns a raw IRC message
18,122
async def on_step(self, iteration): self.combinedActions = [] if self.supply_left < 5 and self.townhalls.exists and self.supply_used >= 14 and self.can_afford(UnitTypeId.SUPPLYDEPOT) and self.units(UnitTypeId.SUPPLYDEPOT).not_ready.amount + self.already_pending(UnitTypeId.SUPPLYDEPOT) < 1: ...
- depots when low on remaining supply - townhalls contains commandcenter and orbitalcommand - self.units(TYPE).not_ready.amount selects all units of that type, filters incomplete units, and then counts the amount - self.already_pending(TYPE) counts how many units are queued - but in this bot be...
18,123
def realpred(cls, lemma, pos, sense=None): string_tokens = [lemma] if pos is not None: string_tokens.append(pos) if sense is not None: sense = str(sense) string_tokens.append(sense) predstr = .join([] + string_tokens + []) return cls(P...
Instantiate a Pred from its components.
18,124
def step(self): with self.__lock: self.__value -= 1 if self.__value == 0: self.__event.set() return True elif self.__value < 0: raise ValueError("The counter has gone below 0")...
Decreases the internal counter. Raises an error if the counter goes below 0 :return: True if this step was the final one, else False :raise ValueError: The counter has gone below 0
18,125
def frames(self): if not self._running: raise RuntimeError( %(self._path_to_images)) if self._im_index >= self._num_images: raise RuntimeError() color_filename = os.path.join(self._path_to_images, %(self._im_index, self._color_ext)) color_im =...
Retrieve the next frame from the image directory and convert it to a ColorImage, a DepthImage, and an IrImage. Parameters ---------- skip_registration : bool If True, the registration step is skipped. Returns ------- :obj:`tuple` of :obj:`ColorImage`...
18,126
def html(data, options, center=False, save=False, save_name=None, save_path=, dated=True, notebook=True): def json_dumps(obj): return pd.io.json.dumps(obj) _options = dict(options) _data = data def clean_function_str(key, n=15): if key in _options.keys(): ...
save=True will create a standalone HTML doc under localdir/saved (creating folfer save if necessary) center=True will center the plot in the output cell, otherwise left-aligned by default.
18,127
def close(self): try: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() except socket.error: pass
Closes the tunnel.
18,128
def code_data_whitening(self, decoding, inpt): inpt_copy = array.array("B", inpt) return self.apply_data_whitening(decoding, inpt_copy)
XOR Data Whitening :param decoding: :param inpt: :return:
18,129
def grant_admin_role(self): apiuser = ApiUser(self._get_resource_root(), self.name, roles=[]) return self._put(, ApiUser, data=apiuser)
Grant admin access to a user. If the user already has admin access, this does nothing. If the user currently has a non-admin role, it will be replaced with the admin role. @return: An ApiUser object
18,130
def listdict_to_listlist_and_matrix(sparse): V = range(len(sparse)) graph = [[] for _ in V] weight = [[None for v in V] for u in V] for u in V: for v in sparse[u]: graph[u].append(v) weight[u][v] = sparse[u][v] return graph, weight
Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: linear
18,131
def build_markdown_body(self, text): key_options = { : self.process_date_created, : self.process_date_updated, : self.process_title, : self.process_input } for paragraph in text[]: if in paragraph: self.user =...
Generate the body for the Markdown file. - processes each json block one by one - for each block, process: - the creator of the notebook (user) - the date the notebook was created - the date the notebook was last updated - the input by detecting the edito...
18,132
def adafactor_optimizer_from_hparams(hparams, lr): if hparams.optimizer_adafactor_decay_type == "adam": decay_rate = adafactor_decay_rate_adam( hparams.optimizer_adafactor_beta2) elif hparams.optimizer_adafactor_decay_type == "pow": decay_rate = adafactor_decay_rate_pow( hparams.optimizer...
Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values
18,133
def validate(input_schema=None, output_schema=None, input_example=None, output_example=None, validator_cls=None, format_checker=None, on_empty_404=False, use_defaults=False): @container def _validate(rh_method): @wraps(rh_method) ...
Parameterized decorator for schema validation :type validator_cls: IValidator class :type format_checker: jsonschema.FormatChecker or None :type on_empty_404: bool :param on_empty_404: If this is set, and the result from the decorated method is a falsy value, a 404 will be raised. :type use...
18,134
def list_formats (): print("Archive programs of", App) print("Archive programs are searched in the following directories:") print(util.system_search_path()) print() for format in ArchiveFormats: print(format, "files:") for command in ArchiveCommands: programs = Archi...
Print information about available archive formats to stdout.
18,135
def get_default_config(self): config = super(MySQLCollector, self).get_default_config() config.update({ : , : [], : False, : False, : False, }) ...
Returns the default collector settings
18,136
def pid(self): if not self.base_pathname: return None try: pidfile = os.path.join(self.base_pathname, ) return int(open(pidfile).readline()) except (IOError, OSError): return None
The server's PID (None if not running).
18,137
def push(self, repository, stream=False, raise_on_error=True, **kwargs): response = super(DockerClientWrapper, self).push(repository, stream=stream, **kwargs) if stream: result = self._docker_status_stream(response, raise_on_error) else: result = self._docker_sta...
Pushes an image repository to the registry. :param repository: Name of the repository (can include a tag). :type repository: unicode | str :param stream: Use the stream output format with additional status information. :type stream: bool :param raise_on_error: Raises errors in t...
18,138
def Subgroups(self): return(Groups(alias=self.alias,groups_lst=self.data[],session=self.session))
Returns a Groups object containing all child groups. >>> clc.v2.Group("wa1-4416").Subgroups() <clc.APIv2.group.Groups object at 0x105fa27d0>
18,139
def VerifySignature(self, message, signature, public_key, unhex=True): return Crypto.VerifySignature(message, signature, public_key, unhex=unhex)
Verify the integrity of the message. Args: message (str): the message to verify. signature (bytearray): the signature belonging to the message. public_key (ECPoint): the public key to use for verifying the signature. unhex (bool): whether the message should be un...
18,140
def evolution_strength_of_connection(A, B=None, epsilon=4.0, k=2, proj_type="l2", block_flag=False, symmetrize_measure=True): from pyamg.util.utils import scale_rows, get_block_diag, scale_columns from pyamg.util.linalg import a...
Evolution Strength Measure. Construct strength of connection matrix using an Evolution-based measure Parameters ---------- A : csr_matrix, bsr_matrix Sparse NxN matrix B : string, array If B=None, then the near nullspace vector used is all ones. If B is an (NxK) array, the...
18,141
def panes(self): " List with all panes from this Window. " result = [] for s in self.splits: for item in s: if isinstance(item, Pane): result.append(item) return result
List with all panes from this Window.
18,142
def update_vip(self, vip, body=None): return self.put(self.vip_path % (vip), body=body)
Updates a load balancer vip.
18,143
def parse(self): index_server = None for num, line in enumerate(self.iter_lines()): line = line.rstrip() if not line: continue if line.startswith(): continue if line.startswith() or \ ...
Parses a requirements.txt-like file
18,144
def _textio_iterlines(stream): line = stream.readline() while line != : yield line line = stream.readline()
Iterates over lines in a TextIO stream until an EOF is encountered. This is the iterator version of stream.readlines()
18,145
def nearby_faces(mesh, points): points = np.asanyarray(points, dtype=np.float64) if not util.is_shape(points, (-1, 3)): raise ValueError() rtree = mesh.triangles_tree kdtree = mesh.kdtree distance_vertex = kdtree.query(points)[0].reshape((-1, 1)) distance_vertex += ...
For each point find nearby faces relatively quickly. The closest point on the mesh to the queried point is guaranteed to be on one of the faces listed. Does this by finding the nearest vertex on the mesh to each point, and then returns all the faces that intersect the axis aligned bounding box cen...
18,146
def _create_RSA_private_key(self, bytes): try: private_key = serialization.load_pem_private_key( bytes, password=None, backend=default_backend() ) return private_key except Excep...
Instantiates an RSA key from bytes. Args: bytes (byte string): Bytes of RSA private key. Returns: private_key (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey): RSA private key created from key bytes.
18,147
def __get_tax(self, account_id, **kwargs): params = { : account_id } return self.make_call(self.__get_tax, params, kwargs)
Call documentation: `/account/get_tax <https://www.wepay.com/developer/reference/account-2011-01-15#get_tax>`_, plus extra keyword parameters: :keyword str access_token: will be used instead of instance's ``access_token``, with ``batch_mode=True`` will set `authorization` ...
18,148
def element_data_from_Z(Z): if isinstance(Z, str) and Z.isdecimal(): Z = int(Z) if Z not in _element_Z_map: raise KeyError(.format(Z)) return _element_Z_map[Z]
Obtain elemental data given a Z number An exception is thrown if the Z number is not found
18,149
def _rsa_recover_prime_factors(n, e, d): ktot = d * e - 1 t = ktot while t % 2 == 0: t = t // 2 spotted = False a = 2 while not spotted and a < _MAX_RECOVERY_ATTEMPTS: k = t while k < ktot: cand = pow(a, k,...
Compute factors p and q from the private exponent d. We assume that n has no more than two factors. This function is adapted from code in PyCrypto.
18,150
def find_runner(program): if os.path.isfile(program) and not os.access(program, os.X_OK): try: opened = open(program) except PermissionError: return None first_line = opened.readline().strip() if first_line.startswith(): return shlex....
Return a command that will run program. Args: program: The string name of the program to try to run. Returns: commandline list of strings to run the program (eg. with subprocess.call()) or None
18,151
def setup_versioned_routes(routes, version=None): prefix = + version if version else "" for r in routes: path, method = r route(prefix + path, method, routes[r])
Set up routes with a version prefix.
18,152
def delete_operation(self, name): conn = self.get_conn() resp = (conn .projects() .operations() .delete(name=name) .execute(num_retries=self.num_retries)) return resp
Deletes the long-running operation. .. seealso:: https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects.operations/delete :param name: the name of the operation resource. :type name: str :return: none if successful. :rtype: dict
18,153
def debug_ratelimit(g): assert isinstance(g, github.MainClass.Github), type(g) debug("github ratelimit: {rl}".format(rl=g.rate_limiting))
Log debug of github ratelimit information from last API call Parameters ---------- org: github.MainClass.Github github object
18,154
def sort_by_number_values(x00, y00): if len(x00) < len(y00): return 1 if len(x00) > len(y00): return -1 return 0
Compare x00, y00 base on number of values :param x00: first elem to compare :type x00: list :param y00: second elem to compare :type y00: list :return: x00 > y00 (-1) if len(x00) > len(y00), x00 == y00 (0) if id equals, x00 < y00 (1) else :rtype: int
18,155
def config_get(self, param, default=None): try: return self("config", "--get", param, log_fail=False, log_cmd=False) except exception.CommandFailed: return default
Return the value of a git configuration option. This will return the value of the default parameter (which defaults to None) if the given option does not exist.
18,156
def save(self, filename, binary=True): filename = os.path.abspath(os.path.expanduser(filename)) if in filename: writer = vtk.vtkRectilinearGridWriter() legacy = True elif in filename: writer = vtk.vtkXMLRectilinearGridWriter() l...
Writes a rectilinear grid to disk. Parameters ---------- filename : str Filename of grid to be written. The file extension will select the type of writer to use. ".vtk" will use the legacy writer, while ".vtr" will select the VTK XML writer. binary...
18,157
def remove(): current = True root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE for key in (KEY_C1 % ("", EWS), KEY_C1 % ("NoCon", EWS), KEY_C0 % ("", EWS), KEY_C0 % ("NoCon", EWS)): try: winreg.DeleteKey(root, key) except Wind...
Function executed when running the script with the -remove switch
18,158
def writelines(lines, filename, encoding=, mode=): return write(os.linesep.join(lines), filename, encoding, mode)
Write 'lines' to file ('filename') assuming 'encoding' Return (eventually new) encoding
18,159
def weed(self): _ext = [k for k in self._dict.keys() if k not in self.c_param] for k in _ext: del self._dict[k]
Get rid of key value pairs that are not standard
18,160
def get_data(self, path, **params): xml = self.get_response(path, **params) try: return parse(xml) except Exception as err: print(path) print(params) print(err) raise
Giving a service path and optional specific arguments, returns the XML data from the API parsed as a dict structure.
18,161
def mock_bable(monkeypatch): mocked_bable = MockBaBLE() mocked_bable.set_controllers([ Controller(0, , ), Controller(1, , , settings={: True, : True}), Controller(2, , , settings={: True}) ]) monkeypatch.setattr(bable_interface, , lambda: mocked_bable) return mocked_ba...
Mock the BaBLEInterface class with some controllers inside.
18,162
def arraydifference(X,Y): if len(Y) > 0: Z = isin(X,Y) return X[np.invert(Z)] else: return X
Elements of a numpy array that do not appear in another. Fast routine for determining which elements in numpy array `X` do not appear in numpy array `Y`. **Parameters** **X** : numpy array Numpy array to comapare to numpy array `Y`. Return subset of `...
18,163
def _resolve_group_location(self, group: str) -> str: if os.path.isabs(group): possible_paths = [group] else: possible_paths = [] for repository in self.setting_repositories: possible_paths.append(os.path.join(repository, group)) for ...
Resolves the location of a setting file based on the given identifier. :param group: the identifier for the group's settings file (~its location) :return: the absolute path of the settings location
18,164
def put(self, local_path, remote_path=None): if remote_path is None: remote_path = os.path.basename(local_path) ftp = self.ssh.open_sftp() if os.path.isdir(local_path): self.__put_dir(ftp, local_path, remote_path) else: ftp.put(local...
Copy a file (or directory recursively) to a location on the remote server :param local_path: Local path to copy to; can be file or directory :param remote_path: Remote path to copy to (default: None - Copies file or directory to home directory directory on the remote server)
18,165
def validateSamOptions(options, group=False): if options.per_gene: if options.gene_tag and options.per_contig: raise ValueError("need to use either --per-contig " "OR --gene-tag, please do not provide both") if not options.per_contig and not options.ge...
Check the validity of the option combinations for sam/bam input
18,166
def launch(exec_, args): if not exec_: raise RuntimeError( .format(DEVELOPER_NAME) ) if args.debug: return watched = WatchFile() cmd = [exec_] if args.file is None else [exec_, args.file] cmd.extend([, , watched...
Launches application.
18,167
def search(self): try: filters = json.loads(self.query) except ValueError: return False result = self.model_query if in filters.keys(): result = self.parse_filter(filters[]) if in filters.keys(): result = result.order_by(*...
This is the most important method
18,168
def get_nan_locs(self, **kwargs): if np.issubdtype(self.X.dtype, np.string_) or np.issubdtype(self.X.dtype, np.unicode_): mask = np.where( self.X == ) nan_matrix = np.zeros(self.X.shape) nan_matrix[mask] = np.nan else: nan_matrix = self.X.astype...
Gets the locations of nans in feature data and returns the coordinates in the matrix
18,169
def add_point_region(self, y: float, x: float) -> Graphic: graphic = Graphics.PointGraphic() graphic.position = Geometry.FloatPoint(y, x) self.__display_item.add_graphic(graphic) return Graphic(graphic)
Add a point graphic to the data item. :param x: The x coordinate, in relative units [0.0, 1.0] :param y: The y coordinate, in relative units [0.0, 1.0] :return: The :py:class:`nion.swift.Facade.Graphic` object that was added. .. versionadded:: 1.0 Scriptable: Yes
18,170
def _unpack(struct, bc, offset=0): return struct.unpack_from(bc, offset), offset + struct.size
returns the unpacked data tuple, and the next offset past the unpacked data
18,171
def query(self, model_cls): self._filters_cmd = list() self.query_filters = list() self._order_by_cmd = None self._offset = 0 self._limit = 0 self.query_class = model_cls._name return self
SQLAlchemy query like method
18,172
def _mark_void(self): self.invoice.status = commerce.Invoice.STATUS_VOID self.invoice.save()
Marks the invoice as refunded, and updates the attached cart if necessary.
18,173
def open(self, file_path): from simplesqlite import SimpleSQLite if self.is_opened(): if self.stream.database_path == abspath(file_path): self._logger.logger.debug( "database already opened: {}".format(self.stream.database_path) ...
Open a SQLite database file. :param str file_path: SQLite database file path to open.
18,174
def is_matching_mime_type(self, mime_type): if len(self.include_mime_types) == 0: return True if mime_type is None: return False mime_type = mime_type.lower() return any(mime_type.startswith(mt) for mt in self.include_mime_types)
This implements the MIME-type matching logic for deciding whether to run `make_clean_html`
18,175
def bits(self, count): if count < 0: raise ValueError if count > self._bits: n_bytes = (count - self._bits + 7) // 8 data = self._fileobj.read(n_bytes) if len(data) != n_bytes: raise BitReaderError("not enough data") ...
Reads `count` bits and returns an uint, MSB read first. May raise BitReaderError if not enough data could be read or IOError by the underlying file object.
18,176
def get_gid_list(user, include_default=True): if HAS_GRP is False or HAS_PWD is False: return [] gid_list = list( six.itervalues( get_group_dict(user, include_default=include_default) ) ) return sorted(set(gid_list))
Returns a list of all of the system group IDs of which the user is a member.
18,177
def __get_eval_info(self): if self.__need_reload_eval_info: self.__need_reload_eval_info = False out_num_eval = ctypes.c_int(0) _safe_call(_LIB.LGBM_BoosterGetEvalCounts( self.handle, ctypes.byref(out_num_eval))) ...
Get inner evaluation count and names.
18,178
def MaxPooling( inputs, pool_size, strides=None, padding=, data_format=): if strides is None: strides = pool_size layer = tf.layers.MaxPooling2D(pool_size, strides, padding=padding, data_format=data_format) ret = layer.apply(inputs, scope=tf.get_variable_...
Same as `tf.layers.MaxPooling2D`. Default strides is equal to pool_size.
18,179
def __get_neighbors(self, node_index): return [ index for index in range(len(self.__data_pointer[node_index])) if self.__data_pointer[node_index][index] != 0 ];
! @brief Returns indexes of neighbors of the specified node. @param[in] node_index (uint): @return (list) Neighbors of the specified node.
18,180
def gen_hyper_keys(minion_id, country=, state=, locality=, organization=, expiration_days=): key_dir = os.path.join( __opts__[], ) if not os.path.isdir(key_dir): os.makedirs(key_di...
Generate the keys to be used by libvirt hypervisors, this routine gens the keys and applies them to the pillar for the hypervisor minions
18,181
def list_(properties=, zpool=None, parsable=True): ***size,free*size,free ret = OrderedDict() if not isinstance(properties, list): properties = properties.split() while in properties: properties.remove() properties.insert(0, ) return ret
.. versionadded:: 2015.5.0 Return information about (all) storage pools zpool : string optional name of storage pool properties : string comma-separated list of properties to list parsable : boolean display numbers in parsable (exact) values .. versionadded:: 2018.3....
18,182
def remove(self, dic): for kw in dic: removePair = Pair(kw, dic[kw]) self._remove([removePair])
remove the pair by passing a identical dict Args: dic (dict): key and value
18,183
def get_datastores(service_instance, reference, datastore_names=None, backing_disk_ids=None, get_all_datastores=False): obj_name = get_managed_object_name(reference) if get_all_datastores: log.trace(%s\, obj_name) else: log.trace(%s\ , ...
Returns a list of vim.Datastore objects representing the datastores visible from a VMware object, filtered by their names, or the backing disk cannonical name or scsi_addresses service_instance The Service Instance Object from which to obtain datastores. reference The VMware object fro...
18,184
def index_all(self): self.logger.debug(, self.record_path) with self.db.connection(): for json_path in sorted(self.find_record_files()): self.index_record(json_path)
Index all records under :attr:`record_path`.
18,185
def _identify_heterogeneity_blocks_seg(in_file, seg_file, params, work_dir, somatic_info): def _segment_by_cns(target_chrom, freqs, coords): with open(seg_file) as in_handle: reader = csv.reader(in_handle, dialect="excel-tab") next(reader) for cur_chrom, start, end...
Identify heterogeneity blocks corresponding to segmentation from CNV input file.
18,186
def _library_check(self): try: output = yield from gns3server.utils.asyncio.subprocess_check_output("ldd", self._path) except (FileNotFoundError, subprocess.SubprocessError) as e: log.warn("Could not determine the shared library dependencies for {}: {}".format(self._pat...
Checks for missing shared library dependencies in the IOU image.
18,187
def get_content_version(cls, abspath: str) -> str: data = cls.get_content(abspath) hasher = hashlib.md5() if isinstance(data, bytes): hasher.update(data) else: for chunk in data: hasher.update(chunk) return hasher.hexdigest()
Returns a version string for the resource at the given path. This class method may be overridden by subclasses. The default implementation is a hash of the file's contents. .. versionadded:: 3.1
18,188
def manifest(txt, dname): _, files = _expand_source(txt, dname, HTML) return files
Extracts file manifest for a body of text with the given directory.
18,189
def plot_one_month(x, y, xlabel=None, ylabel=None, title=None, ylim=None): plt.close("all") fig = plt.figure(figsize=(20, 10)) ax = fig.add_subplot(111) ax.plot(x, y) days = DayLocator(range(365)) daysFmt = DateFormatter("%Y-%m-%d") ax.xaxis.set_major_locator(days) a...
时间跨度为一月。 major tick = every days
18,190
def user_save(self): if not self.cur_user: return username = self.user_username_le.text() first = self.user_first_le.text() last = self.user_last_le.text() email = self.user_email_le.text() self.cur_user.username = username self.cur_user.firs...
Save the current user :returns: None :rtype: None :raises: None
18,191
def comments(context, obj): content_type = ContentType.objects.get_for_model(obj.__class__) comment_list = LogEntry.objects.filter( content_type=content_type, object_id=obj.pk, action_flag=COMMENT ) return { : obj, : comment_list, : context[], }
Render comments for obj.
18,192
def rev_after(self, rev: int) -> int: self.seek(rev) if self._future: return self._future[-1][0]
Return the earliest future rev on which the value will change.
18,193
def _distarray_no_missing(self, xc, xd): from scipy.spatial.distance import pdist, squareform def pre_normalize(x): idx = 0 for i in sorted(self.attr.keys()): if self.attr[i][0] == : continue ...
Distance array calculation for data with no missing values. The 'pdist() function outputs a condense distance array, and squareform() converts this vector-form distance vector to a square-form, redundant distance matrix. *This could be a target for saving memory in the future, by not needing to expand t...
18,194
def render_pyquery(self, **kwargs): from pyquery import PyQuery as pq return pq(self.render(**kwargs), parser=)
Render the graph, and return a pyquery wrapped tree
18,195
def _trim_tree(state): for n in list(state.tree.leaf_node_gen): if n.type_str == TYPE_NODE_TAG: n.parent.child_list.remove(n) return _trim_tree(state)
Trim empty leaf nodes from the tree. - To simplify the tree conversion, empty nodes are added before it is known if they will contain items that connect back to the authenticated subject. If there are no connections, the nodes remain empty, which causes them to be removed here. - Removing a leaf n...
18,196
def init(opts): proxy_dict = opts.get(, {}) opts[] = proxy_dict.get(, False) netmiko_connection_args = proxy_dict.copy() netmiko_connection_args.pop(, None) netmiko_device[] = netmiko_connection_args.pop(, opts.get(, True)) tr...
Open the connection to the network device managed through netmiko.
18,197
def _make_reversed_wildcards(self, old_length=-1): if len(self._reversed_wildcards) > 0: start = old_length else: start = -1 for wildcards, func in self._wildcard_functions.items(): for irun in range(start, len(self)): ...
Creates a full mapping from all wildcard translations to the corresponding wildcards
18,198
def _handle_exception(self, row, exception): self._log(.format(self._source_reader.row_number)) self._log(row) self._log(str(exception)) self._log(traceback.format_exc())
Logs an exception occurred during transformation of a row. :param list|dict|() row: The source row. :param Exception exception: The exception.
18,199
def make_cutter(self): return cadquery.Workplane() \ .circle(self.access_diameter / 2) \ .extrude(self.access_height)
Create solid to subtract from material to make way for the fastener's head (just the head)