Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
363,000
def dump(post, fd, encoding=, handler=None, **kwargs): content = dumps(post, handler, **kwargs) if hasattr(fd, ): fd.write(content.encode(encoding)) else: with codecs.open(fd, , encoding) as f: f.write(content)
Serialize :py:class:`post <frontmatter.Post>` to a string and write to a file-like object. Text will be encoded on the way out (utf-8 by default). :: >>> from io import BytesIO >>> f = BytesIO() >>> frontmatter.dump(post, f) >>> print(f.getvalue()) --- excerpt: ...
363,001
def find(self, instance_ids=None, filters=None): instances = [] reservations = self.retry_on_ec2_error(self.ec2.get_all_instances, instance_ids=instance_ids, filters=filters) for reservation in reservations: instances.extend(reservation.instances) return instances
Flatten list of reservations to a list of instances. :param instance_ids: A list of instance ids to filter by :type instance_ids: list :param filters: A dict of Filter.N values defined in http://goo.gl/jYNej9 :type filters: dict :return: A flattened list of filtered instances. ...
363,002
def iri_to_iriref(self, iri_: ShExDocParser.IriContext) -> ShExJ.IRIREF: return ShExJ.IRIREF(self.iri_to_str(iri_))
iri: IRIREF | prefixedName prefixedName: PNAME_LN | PNAME_NS
363,003
def to_tokens(self, indices): to_reduce = False if not isinstance(indices, list): indices = [indices] to_reduce = True max_idx = len(self.idx_to_token) - 1 tokens = [] for idx in indices: if not isinstance(idx, int) or idx > max_idx...
Converts token indices to tokens according to the vocabulary. Parameters ---------- indices : int or list of ints A source token index or token indices to be converted. Returns ------- str or list of strs A token or a list of tokens according t...
363,004
def upload(self, localpath = , remotepath = , ondup = "overwrite"): .overwritenewcopyoverwrite lpath = localpath.rstrip() lpathbase = os.path.basename(lpath) rpath = remotepath if not lpath: return const.EParameter
Usage: upload [localpath] [remotepath] [ondup] - \ upload a file or directory (recursively) localpath - local path, is the current directory '.' if not specified remotepath - remote path at Baidu Yun (after app root directory at Baidu Yun) ondup - what to do upon duplication ('overwrite' or 'newcopy'), defa...
363,005
def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor=, **kw): size = np.maximum(sizescale*(1 + self.magnitudelimit - self.magnitude), 1) scatter = plt.scatter(self.ra, self.dec, s=size, ...
Plot the ra and dec of the coordinates, at a given epoch, scaled by their magnitude. (This does *not* create a new empty figure.) Parameters ---------- sizescale : (optional) float The marker size for scatter for a star at the magnitudelimit. color : (option...
363,006
def camel_case_from_underscores(string): components = string.split() string = for component in components: string += component[0].upper() + component[1:] return string
generate a CamelCase string from an underscore_string.
363,007
def lineReceived(self, line): if line and line.isdigit(): self._expectedLength = int(line) self._rawBuffer = [] self._rawBufferLength = 0 self.setRawMode() else: self.keepAliveReceived()
Called when a line is received. We expect a length in bytes or an empty line for keep-alive. If we got a length, switch to raw mode to receive that amount of bytes.
363,008
def get_DRAT(delta_x_prime, delta_y_prime, max_ptrm_check): L = numpy.sqrt(delta_x_prime**2 + delta_y_prime**2) DRAT = (old_div(max_ptrm_check, L)) * 100 return DRAT, L
Input: TRM length of best fit line (delta_x_prime), NRM length of best fit line, max_ptrm_check Output: DRAT (maximum difference produced by a ptrm check normed by best fit line), length best fit line
363,009
def original_unescape(self, s): if isinstance(s, basestring): return unicode(HTMLParser.unescape(self, s)) elif isinstance(s, list): return [unicode(HTMLParser.unescape(self, item)) for item in s] else: return s
Since we need to use this sometimes
363,010
def prepend_environ_path(env, name, text, pathsep=os.pathsep): env[name] = prepend_path(env.get(name), text, pathsep=pathsep) return env
Prepend `text` into a $PATH-like environment variable. `env` is a dictionary of environment variables and `name` is the variable name. `pathsep` is the character separating path elements, defaulting to `os.pathsep`. The variable will be created if it is not already in `env`. Returns `env`. Example:...
363,011
def set_value(self, name, value): value = to_text_string(value) code = u"get_ipython().kernel.set_value(, %s, %s)" % (name, value, PY2) if self._reading: self.kernel_client.input(u + code) else: ...
Set value for a variable
363,012
def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.YAML: yaml = ruamel.yaml.YAML(typ = "rt") yaml.representer.add_representer(np.ndarray, numpy_to_yaml) yaml.constructor.add_constructor("!numpy_array", numpy_from_yaml) ...
Create a YAML object for loading a YAML configuration. Args: modules_to_register: Modules containing classes to be registered with the YAML object. Default: None. classes_to_register: Classes to be registered with the YAML object. Default: None. Returns: A newly creating YAML object, co...
363,013
def list(customer, per_page=None, page=None): if isinstance(customer, resources.Customer): customer = customer.id pagination = dict((key, value) for (key, value) in [(, page), (, per_page)] if value) http_client = HttpClient() response, _...
List of cards. You have to handle pagination manually for the moment. :param customer: the customer id or object :type customer: string|Customer :param page: the page number :type page: int|None :param per_page: number of customers per page. It's a good practice to increase this...
363,014
def pre_encrypt_assertion(response): assertion = response.assertion response.assertion = None response.encrypted_assertion = EncryptedAssertion() if assertion is not None: if isinstance(assertion, list): response.encrypted_assertion.add_extension_elements(assertion) else...
Move the assertion to within a encrypted_assertion :param response: The response with one assertion :return: The response but now with the assertion within an encrypted_assertion.
363,015
def run_study_nts(self, study, **kws): goea_results = self.run_study(study, **kws) return MgrNtGOEAs(goea_results).get_goea_nts_all()
Run GOEA on study ids. Return results as a list of namedtuples.
363,016
def retrieve_list_members(self, list_, query_column, field_list, ids_to_retrieve): list_ = list_.get_soap_object(self.client) result = self.call(, list_, query_column, field_list, ids_to_retrieve) return RecordData.from_soap_type(result.recordData)
Responsys.retrieveListMembers call Accepts: InteractObject list_ string query_column possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER' list field_list list ids_to_retrieve Returns a RecordData instance
363,017
def compute(self, cost_matrix): self.C = self.pad_matrix(cost_matrix) self.n = len(self.C) self.original_length = len(cost_matrix) self.original_width = len(cost_matrix[0]) self.row_covered = [False for i in range(self.n)] self.col_covered = [False for i in range...
Compute the indexes for the lowest-cost pairings between rows and columns in the database. Returns a list of (row, column) tuples that can be used to traverse the matrix. :Parameters: cost_matrix : list of lists The cost matrix. If this cost matrix is not square, it ...
363,018
def _yarn_node_metrics(self, rm_address, instance, addl_tags): metrics_json = self._rest_request_to_json(rm_address, instance, YARN_NODES_PATH, addl_tags) if metrics_json and metrics_json[] is not None and metrics_json[][] is not None: for node_json in metrics_json[][]: ...
Get metrics related to YARN nodes
363,019
def check_time_period(self, ds): start = self.std_check(ds, ) end = self.std_check(ds, ) msgs = [] count = 2 if not start: count -= 1 msgs.append("Attr is missing") if not end: count -= 1 msgs.append("Attr is mis...
Check that time period attributes are both set.
363,020
def update(self, url, data): url = self.get_full_url(url) self.log.debug("update url : " + url) post_data = json.dumps(data).encode("UTF-8") request = urllib2.Request(url, post_data) request.add_header(, ) request.add_header(, ) request.get_metho...
update ressources store into LinShare.
363,021
def add_jinja2_ext(pelican): if in pelican.settings: pelican.settings[][].append(AssetsExtension) else: pelican.settings[].append(AssetsExtension)
Add Webassets to Jinja2 extensions in Pelican settings.
363,022
def Decompress(self, compressed_data): try: uncompressed_data = self._bz2_decompressor.decompress(compressed_data) remaining_compressed_data = getattr( self._bz2_decompressor, , b) except (EOFError, IOError) as exception: raise errors.BackEndError(( ).forma...
Decompresses the compressed data. Args: compressed_data (bytes): compressed data. Returns: tuple(bytes, bytes): uncompressed data and remaining compressed data. Raises: BackEndError: if the BZIP2 compressed stream cannot be decompressed.
363,023
def from_passphrase(cls, passphrase=None): if not passphrase: while True: passphrase = create_passphrase(bits_of_entropy=160) hex_private_key = hashlib.sha256(passphrase).hexdigest() if int(hex_private_key, 16) < cls....
Create keypair from a passphrase input (a brain wallet keypair).
363,024
def _beaglebone_id(self): try: with open("/sys/bus/nvmem/devices/0-00500/nvmem", "rb") as eeprom: eeprom_bytes = eeprom.read(16) except FileNotFoundError: return None if eeprom_bytes[:4] != b: return None id_string = eeprom_b...
Try to detect id of a Beaglebone.
363,025
def ctime(message=None): "Counts the time spent in some context" t = time.time() yield if message: print message + ":\t", print round(time.time() - t, 4), "sec"
Counts the time spent in some context
363,026
def _create_tables(self): cursor = self.conn.cursor() create_cmd = .format(self.subdomain_table) db_query_execute(cursor, create_cmd, ()) queue_con = queuedb_open(self.queue_path) queue_con.close()
Set up the subdomain db's tables
363,027
def assignrepr_values2(values, prefix): lines = [] blanks = *len(prefix) for (idx, subvalues) in enumerate(values): if idx == 0: lines.append( % (prefix, repr_values(subvalues))) else: lines.append( % (blanks, repr_values(subvalues))) lines[-1] = lines[-1][:-...
Return a prefixed and properly aligned string representation of the given 2-dimensional value matrix using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values2 >>> import numpy >>> print(assignrepr_values2(numpy.eye(3), 'test(') + ')') test(1.0, 0.0, 0.0, 0.0, 1.0, 0....
363,028
def get_program(self, label: str) -> moderngl.Program: return self._project.get_program(label)
Get a program by its label Args: label (str): The label for the program Returns: py:class:`moderngl.Program` instance
363,029
def pop(self, n=None): if self._popped: assert n is None return [] self._popped = True envs = [] for i, instance in enumerate(self.instances): env = remote.Remote( handle=self._handles[i], vnc_address=.format(i...
Call from main thread. Returns the list of newly-available (handle, env) pairs.
363,030
def onEdge(self, canvas): sides = [] if int(self.position[0]) <= 0: sides.append(1) if (int(self.position[0]) + self.image.width) >= canvas.width: sides.append(3) if int(self.position[1]) <= 0: sides.append(2) if (int(self.position[...
Returns a list of the sides of the sprite which are touching the edge of the canvas. 0 = Bottom 1 = Left 2 = Top 3 = Right
363,031
def filter_object(obj, marks, presumption=DELETE): if isinstance(obj, list): keys = reversed(range(0, len(obj))) else: keys = obj.keys() for k in keys: v = obj[k] m = marks.get(id(v), UNSPECIFIED) if m == DELETE: del obj[k] elif m == KEEP o...
Filter down obj based on marks, presuming keys should be kept/deleted. Args: obj: The object to be filtered. Filtering is done in-place. marks: An object mapping id(obj) --> {DELETE,KEEP} These values apply to the entire subtree, unless inverted. presumption: The default acti...
363,032
def send_patch_document(self, event): msg = self.protocol.create(, [event]) return self._socket.send_message(msg)
Sends a PATCH-DOC message, returning a Future that's completed when it's written out.
363,033
def default_endpoint(ctx, param, value): if ctx.resilient_parsing: return config = ctx.obj[] endpoint = default_endpoint_from_config(config, option=value) if endpoint is None: raise click.UsageError() return endpoint
Return default endpoint if specified.
363,034
def finalize(self, **kwargs): self.set_title(.format(self.name)) manual_legend( self, self._labels, self._colors, loc=, frameon=True ) self.ax.axhline(y=0, c=self.colors[]) self.ax.set_ylabel() self.ax.set_xlabel...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
363,035
def model_average(X, penalization): n_trials = 100 print("ModelAverage with:") print(" estimator: QuicGraphicalLasso (default)") print(" n_trials: {}".format(n_trials)) print(" penalization: {}".format(penalization)) lam = 0.5 if penalization == "random": cv_mod...
Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion matrix. NOTE: This returns precision_ proportions, not cov, prec estimates, so we return the raw proportions for "cov" and the threshold support estimate for prec.
363,036
def _handshake(self): self._ssl = None self._rbio = None self._wbio = None try: self._ssl = libssl.SSL_new(self._session._ssl_ctx) if is_null(self._ssl): self._ssl = None handle_openssl_error(0) mem_bio = lib...
Perform an initial TLS handshake
363,037
def move_emitters(self): moved_emitters = [] for e_pos, e_dir, e_vel, e_range, e_color, e_pal in self.emitters: e_pos = e_pos + e_vel if e_vel > 0: if e_pos >= (self._end + 1): if self.wrap: e_pos = e_pos - (se...
Move each emitter by it's velocity. Emmitters that move off the ends and are not wrapped get sacked.
363,038
def csv(self, client_id): logging.info(.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rejected_datasources( query.sql, query.database, query.schema...
Download the query results as csv.
363,039
def apply_with(self, _, v, ctx): self.v = None if isinstance(v, float): self.v = datetime.date.fromtimestamp(v) elif isinstance(v, datetime.date): self.v = v elif isinstance(v, six.string_types): self.v = from_iso8601(v).date() else: ...
constructor :param v: things used to constrcut date :type v: timestamp in float, datetime.date object, or ISO-8601 in str
363,040
def timeseries_reactive(self): if self._timeseries_reactive is None: if self.grid.network.timeseries.generation_reactive_power \ is not None: try: timeseries = \ self.grid.network.timeseries.generation_reactive_...
Reactive power time series in kvar. Parameters ----------- timeseries_reactive : :pandas:`pandas.Seriese<series>` Series containing reactive power in kvar. Returns ------- :pandas:`pandas.Series<series>` or None Series containing reactive power t...
363,041
def padStr(s, field=None): if field is None: return s else: if len(s) >= field: return s else: return " " * (field - len(s)) + s
Pad the begining of a string with spaces, if necessary.
363,042
def add_child(self, node): assert isinstance(node, Node), "Child node must be a subclass of Node" node.parent = self self.children += [node]
add_child: Adds child node to node Args: node to add as child Returns: None
363,043
def save_user_config(username, conf_dict, path=settings.LOGIN_FILE): users = load_users(path=path) users[username]["full_name"] = _encode_config(conf_dict) save_users(users, path=path)
Save user's configuration to otherwise unused field ``full_name`` in passwd file.
363,044
def affine_rotation_matrix(angle=(-20, 20)): if isinstance(angle, tuple): theta = np.pi / 180 * np.random.uniform(angle[0], angle[1]) else: theta = np.pi / 180 * angle rotation_matrix = np.array([[np.cos(theta), np.sin(theta), 0], \ [-np.sin(theta), np.co...
Create an affine transform matrix for image rotation. NOTE: In OpenCV, x is width and y is height. Parameters ----------- angle : int/float or tuple of two int/float Degree to rotate, usually -180 ~ 180. - int/float, a fixed angle. - tuple of 2 floats/ints, randomly samp...
363,045
def get_fax(self, fax_id, **kwargs): kwargs[] = True if kwargs.get(): return self.get_fax_with_http_info(fax_id, **kwargs) else: (data) = self.get_fax_with_http_info(fax_id, **kwargs) return data
Get a fax record # noqa: E501 Get a specific fax record details like duration, pages etc. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_fax(fax_id, async=True) >>> result ...
363,046
def _connect(self): self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._soc.connect((self._ipaddr, self._port)) self._soc.send(_build_request({: cmd.CMD_MESSAGE_PASSWORD, : self._password}))
Connect to server.
363,047
def start_task_type(self, task_type_str, total_task_count): assert ( task_type_str not in self._task_dict ), "Task type has already been started" self._task_dict[task_type_str] = { "start_time": time.time(), "total_task_count": total_task_count, ...
Call when about to start processing a new type of task, typically just before entering a loop that processes many task of the given type. Args: task_type_str (str): The name of the task, used as a dict key and printed in the progress updates. tot...
363,048
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, , Box)(obj, *args, **kwargs)
Delegate the boxing.
363,049
def iter_filter(self, filters, databases=None, fields=None, filter_behavior="and"): if filter_behavior not in ["and", "or"]: raise ValueError("Filter behavior must be either or ") for dic in self.storage.values(): _pass =...
General purpose filter iterator. This general filter iterator allows the filtering of entries based on one or more custom filters. These filters must contain an entry of the `storage` attribute, a comparison operator, and the test value. For example, to filter out entries with coverage ...
363,050
def incidence(self): self.C = \ spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), ) -\ spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), )
Build incidence matrix into self.C
363,051
def save(self, *args, **kwargs): if not self.pluralName: self.pluralName = self.name + super(self.__class__, self).save(*args, **kwargs)
Just add "s" if no plural name given.
363,052
def host_cache_configured(name, enabled, datastore, swap_size=, dedicated_backing_disk=False, erase_backing_disk=False): t exist (datastore partition will be created and use the entire disk) 3. Raises an error if ``dedicated_backing_disk`` is ``True`` ...
Configures the host cache used for swapping. It will do the following: 1. Checks if backing disk exists 2. Creates the VMFS datastore if doesn't exist (datastore partition will be created and use the entire disk) 3. Raises an error if ``dedicated_backing_disk`` is ``True`` and partitions ...
363,053
def postprocess_image(x, rows, cols, hparams): batch = common_layers.shape_list(x)[0] x = tf.reshape(x, [batch, rows, cols, hparams.hidden_size]) likelihood = getattr(hparams, "likelihood", DistributionType.CAT) if likelihood == DistributionType.DMOL: depth = hparams.num_mixtures * 10 targets = tf.la...
Postprocessing after decoding. Args: x: Tensor of shape [batch, ...], where ... can be any rank such that the number of elements in x is batch * rows * cols * hparams.hidden_size. rows: Integer representing number of rows in a 2-D data point. cols: Integer representing number of columns in a 2-D da...
363,054
def predict(self, recording, result_format=None): evaluate = utils.evaluate_model_single_recording_preloaded results = evaluate(self.preprocessing_queue, self.feature_list, self.model, self.output_semantics, ...
Predict the class of the given recording. Parameters ---------- recording : string Recording of a single handwritten dataset in JSON format. result_format : string, optional If it is 'LaTeX', then only the latex code will be returned Returns ----...
363,055
def context(self, size, placeholder=None, scope=None): return self.leftcontext(size, placeholder,scope) + [self] + self.rightcontext(size, placeholder,scope)
Returns this word in context, {size} words to the left, the current word, and {size} words to the right
363,056
def check_downloaded(self, path, maybe_downloaded): downloaded = [] for pkg in maybe_downloaded: if os.path.isfile(path + pkg): downloaded.append(pkg) return downloaded
Check if files downloaded and return downloaded packages
363,057
def K_pc_1(self): self._check_estimated() if not self._estimation_finished: self._finish_estimation() return self._K
Koopman operator on the modified basis (PC|1)
363,058
def check_instrument(self, dataset): t have to be specified if the same instrument is used for all the measurements. instrument_parameter_variable:long_name = "" ; // RECOMMENDED - Provide a descriptive, long name for this variable. instrument_parameter_variable:comment = "" ; //.. RECOM...
int instrument_parameter_variable(timeSeries); // ... RECOMMENDED - an instrument variable storing information about a parameter of the instrument used in the measurement, the dimensions don't have to be specified if the same instrument is used for all the measurements. instrument_parameter_variable:long_na...
363,059
def ComponentsToPath(components): precondition.AssertIterableType(components, Text) for component in components: if not component: raise ValueError("Empty path component in: {}".format(components)) if "/" in component: raise ValueError("Path component with in: {}".format(components)) if ...
Converts a list of path components to a canonical path representation. Args: components: A sequence of path components. Returns: A canonical MySQL path representation.
363,060
def _quickLevels(self, data): while data.size > 1e6: ax = np.argmax(data.shape) sl = [slice(None)] * data.ndim sl[ax] = slice(None, None, 2) data = data[sl] return self._levelsFromMedianAndStd(data)
Estimate the min/max values of *data* by subsampling.
363,061
def to_region(self): coords = self.convert_coords() log.debug(coords) viz_keywords = [, , , , , , , , , , , , , , , , , ] if isinstance(coords[0], SkyCoord): reg = self.shape_to_sky_region[self...
Converts to region, ``regions.Region`` object
363,062
def ConvertToTemplate(server,template,password=None,alias=None): if alias is None: alias = clc.v1.Account.GetAlias() if password is None: password = clc.v1.Server.GetCredentials([server,],alias)[0][] r = clc.v1.API.Call(,, { : alias, : server, : password, : template }) return(r)
Converts an existing server into a template. http://www.centurylinkcloud.com/api-docs/v1/#server-convert-server-to-template :param server: source server to convert :param template: name of destination template :param password: source server password (optional - will lookup password if None) :param alias: sh...
363,063
def normalize(cls, empty, userdata): if isinstance(userdata, Userdata): return userdata.to_dict() if isinstance(userdata, dict): return cls._dict_to_dict(empty, userdata) if isinstance(userdata, (bytes, bytearray)): return cls._bytes_to_dict(empty, us...
Return normalized user data as a dictionary. empty: an empty dictionary userdata: data in the form of Userdata, dict or None
363,064
def _log_unhandled_exception_and_exit(cls, exc_class=None, exc=None, tb=None, add_newline=False): exc_class = exc_class or sys.exc_info()[0] exc = exc or sys.exc_info()[1] tb = tb or sys.exc_info()[2] if exc_class == SignalHandler.SignalHandledNonLocalExit: return cls._handle_signal_gra...
A sys.excepthook implementation which logs the error and exits with failure.
363,065
def _create_jobs(self, target, jumpkind, current_function_addr, irsb, addr, cfg_node, ins_addr, stmt_idx): if type(target) is pyvex.IRExpr.Const: target_addr = target.con.value elif type(target) in (pyvex.IRConst.U8, pyvex.IRConst.U16, pyvex.IRConst.U32, pyvex.IRConst.U64): ...
Given a node and details of a successor, makes a list of CFGJobs and if it is a call or exit marks it appropriately so in the CFG :param int target: Destination of the resultant job :param str jumpkind: The jumpkind of the edge going to this node :param int current_funct...
363,066
def insert(self, table_name, record, attr_names=None): self.insert_many(table_name, records=[record], attr_names=attr_names)
Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_write_permission| :raises simplesqlite.NullDatabaseConnectionError: ...
363,067
def get_account_funds(self, wallet=None): return self.make_api_request( , , utils.get_kwargs(locals()), model=models.AccountFundsResponse, )
Get available to bet amount. :param Wallet wallet: Name of the wallet in question
363,068
def IndexToColumn (ndx): ndx -= 1 col = chr(ndx % 26 + 65) while (ndx > 25): ndx = ndx // 26 col = chr(ndx % 26 + 64) + col return col
convert index to column. Eg: IndexToColumn(2) = "B", IndexToColumn(28) = "AB"
363,069
def create_table(self): table = self.conn.create_table( name=self.get_table_name(), schema=self.get_schema(), read_units=self.get_read_units(), write_units=self.get_write_units(), ) if table.status != : table.refresh(wait_for_...
Hook point for overriding how the CounterPool creates a new table in DynamooDB
363,070
def save(self, filename=None): if filename is None: filename = self.filename with open(filename, ) as f: f.write(self.data)
Save the smart object to a file. :param filename: File name to export. If None, use the embedded name.
363,071
def get_ccle_cna(gene_list, cell_lines): profile_data = get_profile_data(ccle_study, gene_list, , ) profile_data = dict((key, value) for key, value in profile_data.items() if key in cell_lines) return profile_data
Return a dict of CNAs in given genes and cell lines from CCLE. CNA values correspond to the following alterations -2 = homozygous deletion -1 = hemizygous deletion 0 = neutral / no change 1 = gain 2 = high level amplification Parameters ---------- gene_list : list[str] ...
363,072
def effect_mip(self, mechanism, purview): return self.find_mip(Direction.EFFECT, mechanism, purview)
Return the irreducibility analysis for the effect MIP. Alias for |find_mip()| with ``direction`` set to |EFFECT|.
363,073
def load_job_from_ref(self): if not self.job_id: raise Exception() if not os.path.exists(self.git.work_tree + ): raise Exception() with open(self.git.work_tree + ) as f: self.job = simplejson.loads(f.read(), object_pairs_hook=collections.OrderedDict...
Loads the job.json into self.job
363,074
def sendCommand(self, command): data = { : command } full_url = self.url + urllib.parse.urlencode(data) data = urllib.request.urlopen(full_url) response = re.search(, data.read().decode()) if response == None: response = re.search(, data.read().decode()) return response.group(1).spli...
Sends a command through the web interface of the charger and parses the response
363,075
def _set_vlan_profile(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=vlan_profile.vlan_profile, is_container=, presence=True, yang_name="vlan-profile", rest_name="vlan-profile", parent=self, path_helper=self._path_helper, extmethods=self._extmethods,...
Setter method for vlan_profile, mapped from YANG variable /port_profile/vlan_profile (container) If this variable is read-only (config: false) in the source YANG file, then _set_vlan_profile is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._s...
363,076
def paintEvent(self, event): opt = QtWidgets.QStyleOption() opt.initFrom(self) painter = QtGui.QPainter(self) self.style().drawPrimitive(QtWidgets.QStyle.PE_Widget, opt, painter, self) painter.end()
Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget
363,077
def send_error(self, msgid, error): msg = dumps([3, msgid, error]) self.send(msg)
Send an error.
363,078
def peek(self, count=1, start_from=None): if not start_from: start_from = self.last_received or 1 if int(count) < 1: raise ValueError("count must be 1 or greater.") if int(start_from) < 1: raise ValueError("start_from must be 1 or greater.") ...
Browse messages currently pending in the queue. Peeked messages are not removed from queue, nor are they locked. They cannot be completed, deferred or dead-lettered. This operation will only peek pending messages in the current session. :param count: The maximum number of messages to t...
363,079
def with_division(self, division): if division is None: division = division = slugify(division) self._validate_division(division) self.division = division return self
Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError
363,080
def cut_sequences_relative(records, slices, record_id): with _record_buffer(records) as r: try: record = next(i for i in r() if i.id == record_id) except StopIteration: raise ValueError("Record with id {0} not found.".format(record_id)) new_slices = _update_slic...
Cuts records to slices, indexed by non-gap positions in record_id
363,081
def save(self, file_or_wfs, filename=None, bbox=None, overwrite=None): self._mark_as_changed() override = filename is not None filename = filename or getattr(file_or_wfs, ) if self.basename and not override: basename = self.basename(self._instance) elif file...
Save a Werkzeug FileStorage object
363,082
def append_rows(self, indexes, values): if len(values) != len(indexes): raise ValueError() combined_index = self._index + indexes if len(set(combined_index)) != len(combined_index): raise IndexError() self._index.extend(index...
Appends values to the end of the data. Be very careful with this function as for sort DataFrames it will not enforce sort order. Use this only for speed when needed, be careful. :param indexes: list of indexes to append :param values: list of values to append :return: nothing
363,083
def RingTone(self, Id=1, Set=None): if Set is None: return unicode2path(self._Skype._Property(, Id, )) self._Skype._Property(, Id, , path2unicode(Set))
Returns/sets a ringtone. :Parameters: Id : int Ringtone Id Set : str Path to new ringtone or None if the current path should be queried. :return: Current path if Set=None, None otherwise. :rtype: str or None
363,084
def Publish(self, request, context): LOG.debug("Publish called") try: self.plugin.publish( [Metric(pb=m) for m in request.Metrics], ConfigMap(pb=request.Config) ) return ErrReply() except Exception as err: m...
Dispatches the request to the plugins publish method
363,085
def htmlNodeDumpFile(self, out, cur): if cur is None: cur__o = None else: cur__o = cur._o libxml2mod.htmlNodeDumpFile(out, self._o, cur__o)
Dump an HTML node, recursive behaviour,children are printed too, and formatting returns are added.
363,086
def build_wcscat(image, group_id, source_catalog): open_file = False if isinstance(image, str): hdulist = pf.open(image) open_file = True elif isinstance(image, pf.HDUList): hdulist = image else: log.info("Wrong type of input, {}, for build_wcscat...".format(type(ima...
Return a list of `~tweakwcs.tpwcs.FITSWCS` objects for all chips in an image. Parameters ---------- image : str, ~astropy.io.fits.HDUList` Either filename or HDUList of a single HST observation. group_id : int Integer ID for group this image should be associated with; primarily ...
363,087
def next(self): self.params[] = str(int(self.params[]) + int(self.params[])) return self.marvel.get_characters(self.marvel, (), **self.params)
Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit
363,088
def create(input_block: ModelFactory, rnn_type: str, output_dim: int, rnn_layers: typing.List[int], rnn_dropout: float=0.0, bidirectional: bool=False, linear_layers: typing.List[int]=None, linear_dropout: float=0.0): if linear_layers is None: linear_layers = [] def instantiat...
Vel factory function
363,089
def list( self, accountID, **kwargs ): request = Request( , ) request.set_path_param( , accountID ) request.set_param( , kwargs.get() ) request.set_pa...
Get a list of Orders for an Account Args: accountID: Account Identifier ids: List of Order IDs to retrieve state: The state to filter the requested Orders by instrument: The instrument to filter the ...
363,090
def nextElementSibling(self): ret = libxml2mod.xmlNextElementSibling(self._o) if ret is None:return None __tmp = xmlNode(_obj=ret) return __tmp
Finds the first closest next sibling of the node which is an element node. Note the handling of entities references is different than in the W3C DOM element traversal spec since we don't have back reference from entities content to entities references.
363,091
def setup(package, **kwargs): def read(*paths): p = os.path.join(*paths) if os.path.exists(p): with open(p, ) as f: return f.read() return setuptoolsSetup( name=package.__name__, version=package.__version__, author=pack...
a template for the python setup.py installer routine * take setup information from the packages __init__.py file * this way these informations, like... - __email__ - __version__ - __depencies__ are still available after instal...
363,092
def _validate_config(): t validate azurefsazurefs configuration is not formed as a list, skipping azurefsazurefsOne or more entries in the azurefs configuration list are not formed as a dict. Skipping azurefs: %saccount_namecontainer_nameAn azurefs container configuration is missing either an account_name or a ...
Validate azurefs config, return False if it doesn't validate
363,093
def get_next_seed(key, seed): return hmac.new(key, seed, hashlib.sha256).digest()
This takes a seed and generates the next seed in the sequence. it simply calculates the hmac of the seed with the key. It returns the next seed :param key: the key to use for the HMAC :param seed: the seed to permutate
363,094
def road_address(self): pattern = self.random_element(self.road_address_formats) return self.generator.parse(pattern)
:example ์„ธ์ข…ํŠน๋ณ„์ž์น˜์‹œ ๋„์›€5๋กœ 19 (์–ด์ง„๋™)
363,095
def set_attribute(self, attr, value = True): value = "true" if value else "false" self.conn.issue_command("SetAttribute", self._normalize_attr(attr), value)
Sets a custom attribute for our Webkit instance. Possible attributes are: * ``auto_load_images`` * ``dns_prefetch_enabled`` * ``plugins_enabled`` * ``private_browsing_enabled`` * ``javascript_can_open_windows`` * ``javascript_can_access_clipboard`` * ``offline_storage_database...
363,096
def bismark_mbias_plot (self): description = pconfig = { : , : , : , : , : False, : 100, : 0, : , : [ {: , : , : 100}, {: , : , : 100}, ...
Make the M-Bias plot
363,097
def time_report(self, source=None, **kwargs): if source is None: api_calls = [self[-1]] elif isinstance(source, list): api_calls = source elif source is None: api_calls = self.values() elif isinstance(source, ApiCall): api_calls = ...
This will generate a time table for the source api_calls :param source: obj this can be an int(index), str(key), slice, list of api_calls or an api_call :return: ReprListList
363,098
def range(self, name="range"): with self._name_scope(name): return self.high - self.low
`high - low`.
363,099
def user_exists_p(login, connector): url = + login + _r = connector.get(url) return (_r.status_code == Constants.PULP_GET_OK)
Determine if user exists in specified environment.