code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def dump(post, fd, encoding='utf-8', handler=None, **kwargs): """ 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.d...
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: ...
def find(self, instance_ids=None, filters=None): """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: dic...
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. ...
def iri_to_iriref(self, iri_: ShExDocParser.IriContext) -> ShExJ.IRIREF: """ iri: IRIREF | prefixedName prefixedName: PNAME_LN | PNAME_NS """ return ShExJ.IRIREF(self.iri_to_str(iri_))
iri: IRIREF | prefixedName prefixedName: PNAME_LN | PNAME_NS
def to_tokens(self, indices): """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 ...
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...
def upload(self, localpath = '', remotepath = '', ondup = "overwrite"): ''' 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...
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...
def plot(self, sizescale=10, color=None, alpha=0.5, label=None, edgecolor='none', **kw): ''' 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 : (opti...
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...
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_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.
def lineReceived(self, line): """ 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. """ if line and line.isdigit(): self._expectedLength = int(l...
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.
def get_DRAT(delta_x_prime, delta_y_prime, max_ptrm_check): """ 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 """ L = num...
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
def original_unescape(self, s): """Since we need to use this sometimes""" 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 ...
Since we need to use this sometimes
def prepend_environ_path(env, name, text, pathsep=os.pathsep): """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 c...
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:...
def set_value(self, name, value): """Set value for a variable""" value = to_text_string(value) code = u"get_ipython().kernel.set_value('%s', %s, %s)" % (name, value, PY2) if self._reading: self.kernel_client.i...
Set value for a variable
def yaml(modules_to_register: Iterable[Any] = None, classes_to_register: Iterable[Any] = None) -> ruamel.yaml.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_r...
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...
def list(customer, per_page=None, page=None): """ 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: n...
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...
def pre_encrypt_assertion(response): """ 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. """ assertion = response.assertion response.assertion = None ...
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.
def run_study_nts(self, study, **kws): """Run GOEA on study ids. Return results as a list of namedtuples.""" 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.
def retrieve_list_members(self, list_, query_column, field_list, ids_to_retrieve): """ Responsys.retrieveListMembers call Accepts: InteractObject list_ string query_column possible values: 'RIID'|'EMAIL_ADDRESS'|'CUSTOMER_ID'|'MOBILE_NUMBER' list fiel...
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
def compute(self, cost_matrix): """ 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...
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 ...
def _yarn_node_metrics(self, rm_address, instance, addl_tags): """ Get metrics related to YARN nodes """ metrics_json = self._rest_request_to_json(rm_address, instance, YARN_NODES_PATH, addl_tags) if metrics_json and metrics_json['nodes'] is not None and metrics_json['nodes']['n...
Get metrics related to YARN nodes
def check_time_period(self, ds): """ Check that time period attributes are both set. """ start = self.std_check(ds, 'time_coverage_start') end = self.std_check(ds, 'time_coverage_end') msgs = [] count = 2 if not start: count -= 1 m...
Check that time period attributes are both set.
def update(self, url, data): """ update ressources store into LinShare.""" url = self.get_full_url(url) self.log.debug("update url : " + url) # Building request post_data = json.dumps(data).encode("UTF-8") request = urllib2.Request(url, post_data) request.add_head...
update ressources store into LinShare.
def add_jinja2_ext(pelican): """Add Webassets to Jinja2 extensions in Pelican settings.""" if 'JINJA_ENVIRONMENT' in pelican.settings: # pelican 3.7+ pelican.settings['JINJA_ENVIRONMENT']['extensions'].append(AssetsExtension) else: pelican.settings['JINJA_EXTENSIONS'].append(AssetsExtension...
Add Webassets to Jinja2 extensions in Pelican settings.
def Decompress(self, compressed_data): """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. ...
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.
def from_passphrase(cls, passphrase=None): """ Create keypair from a passphrase input (a brain wallet keypair).""" if not passphrase: # run a rejection sampling algorithm to ensure the private key is # less than the curve order while True: passphrase =...
Create keypair from a passphrase input (a brain wallet keypair).
def _beaglebone_id(self): """Try to detect id of a Beaglebone.""" 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'\xaaU3\xee': ...
Try to detect id of a Beaglebone.
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
def _create_tables(self): """ Set up the subdomain db's tables """ cursor = self.conn.cursor() create_cmd = """CREATE TABLE IF NOT EXISTS {} ( fully_qualified_subdomain TEXT NOT NULL, domain TEXT NOT NULL, sequence INTEGER NOT NULL, owner TEXT NOT...
Set up the subdomain db's tables
def assignrepr_values2(values, prefix): """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(') + ')'...
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....
def get_program(self, label: str) -> moderngl.Program: """ Get a program by its label Args: label (str): The label for the program Returns: py:class:`moderngl.Program` instance """ 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
def pop(self, n=None): """Call from main thread. Returns the list of newly-available (handle, env) pairs.""" if self._popped: assert n is None return [] self._popped = True envs = [] for i, instance in enumerate(self.instances): env = remote.R...
Call from main thread. Returns the list of newly-available (handle, env) pairs.
def onEdge(self, canvas): """ 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 """ sides = [] if int(self.position[0]) <= 0: ...
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
def filter_object(obj, marks, presumption=DELETE): '''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 subtr...
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...
def send_patch_document(self, event): """ Sends a PATCH-DOC message, returning a Future that's completed when it's written out. """ msg = self.protocol.create('PATCH-DOC', [event]) return self._socket.send_message(msg)
Sends a PATCH-DOC message, returning a Future that's completed when it's written out.
def default_endpoint(ctx, param, value): """Return default endpoint if specified.""" if ctx.resilient_parsing: return config = ctx.obj['config'] endpoint = default_endpoint_from_config(config, option=value) if endpoint is None: raise click.UsageError('No default endpoint found.') ...
Return default endpoint if specified.
def finalize(self, **kwargs): """ Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments. """ # Add the title to the plot self.set_title...
Finalize executes any subclass-specific axes finalization steps. The user calls poof and poof calls finalize. Parameters ---------- kwargs: generic keyword arguments.
def model_average(X, penalization): """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. ...
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.
def _handshake(self): """ Perform an initial TLS handshake """ 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 ...
Perform an initial TLS handshake
def move_emitters(self): """ Move each emitter by it's velocity. Emmitters that move off the ends and are not wrapped get sacked. """ 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...
Move each emitter by it's velocity. Emmitters that move off the ends and are not wrapped get sacked.
def csv(self, client_id): """Download the query results as csv.""" logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rejected...
Download the query results as csv.
def apply_with(self, _, v, ctx): """ constructor :param v: things used to constrcut date :type v: timestamp in float, datetime.date object, or ISO-8601 in str """ self.v = None if isinstance(v, float): self.v = datetime.date.fromtimestamp(v) elif isin...
constructor :param v: things used to constrcut date :type v: timestamp in float, datetime.date object, or ISO-8601 in str
def timeseries_reactive(self): """ 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 ...
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...
def padStr(s, field=None): """ Pad the begining of a string with spaces, if necessary. """ 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.
def add_child(self, node): """ add_child: Adds child node to node Args: node to add as child Returns: None """ 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
def save_user_config(username, conf_dict, path=settings.LOGIN_FILE): """ Save user's configuration to otherwise unused field ``full_name`` in passwd 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.
def affine_rotation_matrix(angle=(-20, 20)): """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....
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...
def get_fax(self, fax_id, **kwargs): # noqa: E501 """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 >>...
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 ...
def _connect(self): """Connect to server.""" self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._soc.connect((self._ipaddr, self._port)) self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD, 'sha': self._password}))
Connect to server.
def start_task_type(self, task_type_str, 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 ke...
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...
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
Delegate the boxing.
def iter_filter(self, filters, databases=None, fields=None, filter_behavior="and"): """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 `stora...
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 ...
def incidence(self): """Build incidence matrix into self.C""" self.C = \ spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\ spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd')
Build incidence matrix into self.C
def save(self, *args, **kwargs): ''' Just add "s" if no plural name given. ''' if not self.pluralName: self.pluralName = self.name + 's' super(self.__class__, self).save(*args, **kwargs)
Just add "s" if no plural name given.
def host_cache_configured(name, enabled, datastore, swap_size='100%', dedicated_backing_disk=False, erase_backing_disk=False): ''' Configures the host cache used for swapping. It will do the following: 1. Checks if backing disk exists 2. Creates...
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 ...
def postprocess_image(x, rows, cols, hparams): """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...
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...
def predict(self, recording, result_format=None): """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 ...
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 ----...
def context(self, size, placeholder=None, scope=None): """Returns this word in context, {size} words to the left, the current word, and {size} words to the right""" 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
def check_downloaded(self, path, maybe_downloaded): """Check if files downloaded and return downloaded packages """ 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
def K_pc_1(self): 'Koopman operator on the modified basis (PC|1)' self._check_estimated() if not self._estimation_finished: self._finish_estimation() return self._K
Koopman operator on the modified basis (PC|1)
def check_instrument(self, dataset): ''' 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 measur...
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...
def ComponentsToPath(components): """Converts a list of path components to a canonical path representation. Args: components: A sequence of path components. Returns: A canonical MySQL path representation. """ precondition.AssertIterableType(components, Text) for component in components: if not...
Converts a list of path components to a canonical path representation. Args: components: A sequence of path components. Returns: A canonical MySQL path representation.
def _quickLevels(self, data): """ Estimate the min/max values of *data* by subsampling. """ 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._...
Estimate the min/max values of *data* by subsampling.
def to_region(self): """ Converts to region, ``regions.Region`` object """ coords = self.convert_coords() log.debug(coords) viz_keywords = ['color', 'dash', 'dashlist', 'width', 'font', 'symsize', 'symbol', 'symsize', 'fontsize', 'fontstyle', 'use...
Converts to region, ``regions.Region`` object
def ConvertToTemplate(server,template,password=None,alias=None): """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...
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...
def normalize(cls, empty, userdata): """Return normalized user data as a dictionary. empty: an empty dictionary userdata: data in the form of Userdata, dict or None """ if isinstance(userdata, Userdata): return userdata.to_dict() if isinstance(userdata, dict)...
Return normalized user data as a dictionary. empty: an empty dictionary userdata: data in the form of Userdata, dict or None
def _log_unhandled_exception_and_exit(cls, exc_class=None, exc=None, tb=None, add_newline=False): """A sys.excepthook implementation which logs the error and exits with failure.""" exc_class = exc_class or sys.exc_info()[0] exc = exc or sys.exc_info()[1] tb = tb or sys.exc_info()[2] # This exceptio...
A sys.excepthook implementation which logs the error and exits with failure.
def _create_jobs(self, target, jumpkind, current_function_addr, irsb, addr, cfg_node, ins_addr, stmt_idx): """ 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...
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...
def insert(self, table_name, record, attr_names=None): """ 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_writ...
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: ...
def get_account_funds(self, wallet=None): """Get available to bet amount. :param Wallet wallet: Name of the wallet in question """ return self.make_api_request( 'Account', 'getAccountFunds', utils.get_kwargs(locals()), model=models.Account...
Get available to bet amount. :param Wallet wallet: Name of the wallet in question
def IndexToColumn (ndx): """convert index to column. Eg: IndexToColumn(2) = "B", IndexToColumn(28) = "AB" """ 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"
def create_table(self): ''' Hook point for overriding how the CounterPool creates a new table in DynamooDB ''' table = self.conn.create_table( name=self.get_table_name(), schema=self.get_schema(), read_units=self.get_read_units(), w...
Hook point for overriding how the CounterPool creates a new table in DynamooDB
def save(self, filename=None): """ Save the smart object to a file. :param filename: File name to export. If None, use the embedded name. """ if filename is None: filename = self.filename with open(filename, 'wb') 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.
def get_ccle_cna(gene_list, cell_lines): """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 ...
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] ...
def effect_mip(self, mechanism, purview): """Return the irreducibility analysis for the effect MIP. Alias for |find_mip()| with ``direction`` set to |EFFECT|. """ 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|.
def load_job_from_ref(self): """ Loads the job.json into self.job """ if not self.job_id: raise Exception('Job not loaded yet. Use load(id) first.') if not os.path.exists(self.git.work_tree + '/aetros/job.json'): raise Exception('Could not load aetros/job...
Loads the job.json into self.job
def sendCommand(self, command): """Sends a command through the web interface of the charger and parses the response""" data = { 'rapi' : command } full_url = self.url + urllib.parse.urlencode(data) data = urllib.request.urlopen(full_url) response = re.search('\<p>&gt;\$(.+)\<script', data.read().dec...
Sends a command through the web interface of the charger and parses the response
def _set_vlan_profile(self, v, load=False): """ 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 popula...
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...
def paintEvent(self, event): """ Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget """ opt = QtWidgets.QStyleOption() opt.initFrom(self) painter = QtGui.QPainter(self) self.st...
Reimplementation of paintEvent to allow for style sheets See: http://qt-project.org/wiki/How_to_Change_the_Background_Color_of_QWidget
def send_error(self, msgid, error): """Send an error.""" msg = dumps([3, msgid, error]) self.send(msg)
Send an error.
def peek(self, count=1, start_from=None): """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. ...
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...
def with_division(self, division): """Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError """ if division is None: division = '' division = sl...
Add a division segment Args: division (str): Official name of an electoral division. Returns: IdBuilder Raises: ValueError
def cut_sequences_relative(records, slices, record_id): """ Cuts records to slices, indexed by non-gap positions in 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("Rec...
Cuts records to slices, indexed by non-gap positions in record_id
def save(self, file_or_wfs, filename=None, bbox=None, overwrite=None): '''Save a Werkzeug FileStorage object''' self._mark_as_changed() override = filename is not None filename = filename or getattr(file_or_wfs, 'filename') if self.basename and not override: basename...
Save a Werkzeug FileStorage object
def append_rows(self, indexes, values): """ 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:...
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
def RingTone(self, Id=1, Set=None): """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 ...
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
def Publish(self, request, context): """Dispatches the request to the plugins publish method""" LOG.debug("Publish called") try: self.plugin.publish( [Metric(pb=m) for m in request.Metrics], ConfigMap(pb=request.Config) ) return...
Dispatches the request to the plugins publish method
def htmlNodeDumpFile(self, out, cur): """Dump an HTML node, recursive behaviour,children are printed too, and formatting returns are added. """ 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.
def build_wcscat(image, group_id, source_catalog): """ 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 gr...
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 ...
def next(self): """ Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit """ self.params['offset'] = str(int(self.params['offset']) + int(self.params['limit'])) return self.marvel.get_characters(self.marvel, (), **self.params)
Returns new CharacterDataWrapper TODO: Don't raise offset past count - limit
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): """ Vel factory function """ if linear_layers is None: linear_lay...
Vel factory function
def list( self, accountID, **kwargs ): """ 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 re...
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 ...
def nextElementSibling(self): """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 entiti...
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.
def setup(package, **kwargs): """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__ ...
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...
def _validate_config(): ''' Validate azurefs config, return False if it doesn't validate ''' if not isinstance(__opts__['azurefs'], list): log.error('azurefs configuration is not formed as a list, skipping azurefs') return False for container in __opts__['azurefs']: if not is...
Validate azurefs config, return False if it doesn't validate
def get_next_seed(key, seed): """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 """ return...
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
def road_address(self): """ :example ์„ธ์ข…ํŠน๋ณ„์ž์น˜์‹œ ๋„์›€5๋กœ 19 (์–ด์ง„๋™) """ pattern = self.random_element(self.road_address_formats) return self.generator.parse(pattern)
:example ์„ธ์ข…ํŠน๋ณ„์ž์น˜์‹œ ๋„์›€5๋กœ 19 (์–ด์ง„๋™)
def set_attribute(self, attr, value = True): """ 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_...
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...
def bismark_mbias_plot (self): """ Make the M-Bias plot """ description = '<p>This plot shows the average percentage methylation and coverage across reads. See the \n\ <a href="https://rawgit.com/FelixKrueger/Bismark/master/Docs/Bismark_User_Guide.html#m-bias-plot" target="_blank">bismark user ...
Make the M-Bias plot
def time_report(self, source=None, **kwargs): """ 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 """ if source is None: api_...
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
def range(self, name="range"): """`high - low`.""" with self._name_scope(name): return self.high - self.low
`high - low`.
def user_exists_p(login, connector): """ Determine if user exists in specified environment. """ url = '/users/' + login + '/' _r = connector.get(url) return (_r.status_code == Constants.PULP_GET_OK)
Determine if user exists in specified environment.