text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def do_action_to_ancestors(analysis_request, transition_id):
"""Promotes the transitiion passed in to ancestors, if any
"""
parent_ar = analysis_request.getParentAnalysisRequest()
if parent_ar:
do_action_for(parent_ar, transition_id) | 0.003891 |
def pop_job(self, returning=True):
"""
Pop a job from the pending jobs list.
When returning == True, we prioritize the jobs whose functions are known to be returning (function.returning is
True). As an optimization, we are sorting the pending jobs list according to job.function.returnin... | 0.006141 |
def get_object_from_date_based_view(request, *args, **kwargs): # noqa
"""
Get object from generic date_based.detail view
Parameters
----------
request : instance
An instance of HttpRequest
Returns
-------
instance
An instance of model object or None
"""
import ... | 0.000473 |
def maximum_font_point_size(self, value):
"""
Setter for **self.__maximum_font_point_size** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or ... | 0.007485 |
def publish_mainswitch_state(self, state):
"""publish changed mainswitch state"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.mainswitch_state(self.sequence_number, state))
return self.sequence_number | 0.011364 |
def load_file(self, filename):
"""Load coordinates file.
Results are appended to previously loaded coordinates.
This can be used to load one file per color.
"""
if not os.path.isfile(filename):
return
self.logger.info('Loading coordinates from {0}'.format(f... | 0.000881 |
def rabin_karp_factor(s, t, k):
"""Find a common factor by Rabin-Karp
:param string s: haystack
:param string t: needle
:param int k: factor length
:returns: (i, j) such that s[i:i + k] == t[j:j + k] or None.
In case of tie, lexicographical minimum (i, j) is returned
:complexity: ... | 0.00074 |
def toJSONFilters(actions):
"""Generate a JSON-to-JSON filter from stdin to stdout
The filter:
* reads a JSON-formatted pandoc document from stdin
* transforms it by walking the tree and performing the actions
* returns a new JSON-formatted pandoc document to stdout
The argument `actions` is ... | 0.000888 |
def api_version(self, verbose=False):
'''
Get information about the API
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#api_version_information
'''
return self.__auth_req_get(self.rest_url, verbose=verbose) | 0.007905 |
def remove(self, address):
""" Remove an address from the connection pool, if present, closing
all connections to that address.
"""
with self.lock:
for connection in self.connections.pop(address, ()):
try:
connection.close()
... | 0.00554 |
def from_bank_code(cls, country_code, bank_code):
"""Create a new BIC object from country- and bank-code.
Examples:
>>> bic = BIC.from_bank_code('DE', '20070000')
>>> bic.country_code
'DE'
>>> bic.bank_code
'DEUT'
>>> bic.location_... | 0.004804 |
def ping():
'''
Ping? Pong!
'''
dev = conn()
# Check that the underlying netconf connection still exists.
if dev._conn is None:
return False
# call rpc only if ncclient queue is empty. If not empty that means other
# rpc call is going on.
if hasattr(dev._conn, '_session'):... | 0.001029 |
def get_pushes(self, repository_id, project=None, skip=None, top=None, search_criteria=None):
"""GetPushes.
[Preview API] Retrieves pushes associated with the specified repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
... | 0.005626 |
def blur(dset,fwhm,prefix=None):
'''blurs ``dset`` with given ``fwhm`` runs 3dmerge to blur dataset to given ``fwhm``
default ``prefix`` is to suffix ``dset`` with ``_blur%.1fmm``'''
if prefix==None:
prefix = nl.suffix(dset,'_blur%.1fmm'%fwhm)
return available_method('blur')(dset,fwhm,prefix) | 0.031546 |
def register_callback_deleted(self, func, serialised=True):
"""
Register a callback for resource deletion. This will be called when any resource
is deleted within your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The... | 0.005368 |
def process_model_scores(self, model_names, root_cache,
include_features=False):
"""
Generates a score map for a set of models based on a `root_cache`.
This method performs no substantial IO, but may incur substantial CPU
usage.
:Parameters:
... | 0.002232 |
def bdh(self, tickers, flds, start_date, end_date, elms=None,
ovrds=None, longdata=False):
"""
Get tickers and fields, return pandas DataFrame with columns as
MultiIndex with levels "ticker" and "field" and indexed by "date".
If long data is requested return DataFrame with co... | 0.001635 |
def output_markdown(markdown_cont, output_file):
"""
Writes to an output file if `outfile` is a valid path.
"""
if output_file:
with open(output_file, 'w') as out:
out.write(markdown_cont) | 0.004444 |
def read_long_description(readme_file):
""" Read package long description from README file """
try:
import pypandoc
except (ImportError, OSError) as e:
print('No pypandoc or pandoc: %s' % (e,))
if is_py3:
fh = open(readme_file, encoding='utf-8')
else:
... | 0.002033 |
def load_trace(path, *args, **kwargs):
"""Read a packet trace file, return a :class:`wltrace.common.WlTrace` object.
This function first reads the file's magic
(first ``FILE_TYPE_HANDLER`` bytes), and automatically determine the
file type, and call appropriate handler to process the file.
Args:
... | 0.00303 |
def parse_directives(lexer: Lexer, is_const: bool) -> List[DirectiveNode]:
"""Directives[Const]: Directive[?Const]+"""
directives: List[DirectiveNode] = []
append = directives.append
while peek(lexer, TokenKind.AT):
append(parse_directive(lexer, is_const))
return directives | 0.003311 |
def _reorder_categories_after_dendrogram(adata, groupby, dendrogram,
var_names=None,
var_group_labels=None,
var_group_positions=None):
"""
Function used by plotting functions that need to r... | 0.004241 |
def initFooter(self):
""" Initializes the body/story window """
self.footerWin.bkgd(' ', curses.color_pair(7))
self.footerWin.noutrefresh() | 0.01227 |
def S2_surface(self, sizes, bounds, presets, covers, use_torch=False,
num_samples = 10):
"""Calculates the sensitivity surface of a GrFN for the two variables with
the highest S2 index.
Args:
num_samples: Number of samples for sensitivity analysis.
sizes: Tup... | 0.00282 |
def requestFields(self, field_names, required=False, strict=False):
"""Add the given list of fields to the request
@param field_names: The simple registration data fields to request
@type field_names: [str]
@param required: Whether these values should be presented to
the us... | 0.002165 |
def aer2geodetic(az: float, el: float, srange: float,
lat0: float, lon0: float, h0: float,
ell=None,
deg: bool = True) -> Tuple[float, float, float]:
"""
gives geodetic coordinates of a point with az, el, range
from an observer at lat0, lon0, h0
Parame... | 0.000767 |
def copy_database_structure(self, source, destination, tables=None):
"""Copy multiple tables from one database to another."""
# Change database to source
self.change_db(source)
if tables is None:
tables = self.tables
# Change database to destination
self.cha... | 0.005976 |
def plot_joint_sfs_scaled(*args, **kwargs):
"""Plot a scaled joint site frequency spectrum.
Parameters
----------
s : array_like, int, shape (n_chromosomes_pop1, n_chromosomes_pop2)
Joint site frequency spectrum.
ax : axes, optional
Axes on which to draw. If not provided, a new figu... | 0.00137 |
def get_selinux_context(path):
'''
Get an SELinux context from a given path
CLI Example:
.. code-block:: bash
salt '*' file.get_selinux_context /etc/hosts
'''
out = __salt__['cmd.run'](['ls', '-Z', path], python_shell=False)
try:
ret = re.search(r'\w+:\w+:\w+:\w+', out).g... | 0.002105 |
def initialize(self, configfile=None):
"""Initialize and load the Fortran library (and model, if applicable).
The Fortran library is loaded and ctypes is used to annotate functions
inside the library. The Fortran library's initialization is called.
Normally a path to an ``*.ini`` model... | 0.001922 |
def BeginEdit(self, row, col, grid):
"""
Fetch the value from the table and prepare the edit control
to begin editing. Set the focus to the edit control.
*Must Override*
"""
# Disable if cell is locked, enable if cell is not locked
grid = self.main_window.grid
... | 0.001265 |
def run_simulations(self, parameter_list, data_folder):
"""
This function runs multiple simulations in parallel.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str): folder in which to create output folders.
"""
self... | 0.003515 |
def _render_item(self, depth, key, value = None, **settings):
"""
Format single list item.
"""
strptrn = self.INDENT * depth
lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
lchar = self.fmt... | 0.007911 |
def create_mef(filename=None):
"""
Create a file an MEF fits file called filename. Generate a random
filename if None given
"""
import pyfits, time
if not filename:
### here I know what filename is to start with.
import tempfile
filename=tempfile.mktemp(suffix='.fits')
... | 0.014609 |
def codes_get_long_array(handle, key, size):
# type: (cffi.FFI.CData, str, int) -> T.List[int]
"""
Get long array values from a key.
:param bytes key: the keyword whose value(s) are to be extracted
:rtype: List(int)
"""
values = ffi.new('long[]', size)
size_p = ffi.new('size_t *', size... | 0.002427 |
def _get_parameter_dictionary(self, base_name, dictionary, sorted_keys, parameter):
"""
Recursively loops over the parameter's children, adding
keys (starting with base_name) and values to the supplied dictionary
(provided they do not have a value of None).
"""
# assembl... | 0.006757 |
def nas_auto_qos_set_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nas = ET.SubElement(config, "nas", xmlns="urn:brocade.com:mgmt:brocade-qos")
auto_qos = ET.SubElement(nas, "auto-qos")
set = ET.SubElement(auto_qos, "set")
dscp = E... | 0.006316 |
def CMS(data, format="PEM"):
"""
Factory function to create CMS objects from received messages.
Parses CMS data and returns either SignedData or EnvelopedData
object. format argument can be either "PEM" or "DER".
It determines object type from the contents of received CMS
structure.
""... | 0.002045 |
def get_parameters(parser, token):
"""
{% get_parameters except_field %}
"""
args = token.split_contents()
if len(args) < 2:
raise template.TemplateSyntaxError(
"get_parameters tag takes at least 1 argument"
)
return GetParametersNode(args[1].strip()) | 0.0033 |
def get_connection(cls, pid, connection):
"""Return the specified :class:`~queries.pool.Connection` from the
pool.
:param str pid: The pool ID
:param connection: The connection to return for
:type connection: psycopg2.extensions.connection
:rtype: queries.pool.Connection... | 0.004739 |
def current_earthquake_model_name():
"""Human friendly name for the currently active earthquake fatality model.
:returns: Name of the current EQ fatality model as defined in users
settings.
"""
default_earthquake_function = setting(
'earthquake_function', EARTHQUAKE_FUNCTIONS[0]['key'],... | 0.001919 |
def error_response(error_type="Internal server error",
error_text=None,
status=400,
participant=None):
"""Return a generic server error response."""
traceback.print_exc()
print("Error: {}.".format(error_type))
page = error_page(
error_tex... | 0.001845 |
def _check_value_recursively(key, val, haystack):
"""
Check if there is key _key_ with value _val_ in the given dictionary.
..warning:
This is geared at JSON dictionaries, so some corner cases are ignored,
we assume all iterables are either arrays or dicts
"""
if isinstance(haystack,... | 0.00554 |
def setup_default_layouts(self, index, settings):
"""Setup default layouts when run for the first time."""
self.setUpdatesEnabled(False)
first_spyder_run = bool(self.first_spyder_run) # Store copy
if first_spyder_run:
self.set_window_settings(*settings)
els... | 0.000192 |
def parse_lammps_log(filename="log.lammps"):
"""
Parses log file with focus on thermo data. Both one and multi line
formats are supported. Any incomplete runs (no "Loop time" marker)
will not be parsed.
Notes:
SHAKE stats printed with thermo data are not supported yet.
They are igno... | 0.000444 |
def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the boxscore string.
"""
if self._goals_scored is None and self._goals_allowed is None:
return None
fields_to_include = {
... | 0.000953 |
def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter compile_geometry")
... | 0.001931 |
def get_vault(self):
"""Gets the ``Vault`` at this node.
return: (osid.authorization.Vault) - the vault represented by
this node
*compliance: mandatory -- This method must be implemented.*
"""
if self._lookup_session is None:
mgr = get_provider_manag... | 0.007246 |
def is_single_tree(data_wrapper):
'''Check that data forms a single tree
Only the first point has ID of -1.
Returns:
CheckResult with result and list of IDs
Note:
This assumes no_missing_parents passed.
'''
db = data_wrapper.data_block
bad_ids = db[db[:, COLS.P] == -1][1:,... | 0.002571 |
def create(self, dmeData):
"""
Create a new device management extension package
In case of failure it throws APIException
"""
url = "api/v0002/mgmt/custom/bundle"
r = self._apiClient.post(url, dmeData)
if r.status_code == 201:
return r.json()
... | 0.005571 |
def drawSector(page, center, point, beta, color=None, fill=None,
dashes=None, fullSector=True, morph=None,
width=1, closePath=False, roundCap=False, overlay=True):
""" Draw a circle sector given circle center, one arc end point and the angle of the arc.
Parameters:
cente... | 0.009284 |
def reduce_list_of_bags_of_words(list_of_keyword_sets):
"""
Reduces a number of keyword sets to a bag-of-words.
Input: - list_of_keyword_sets: This is a python list of sets of strings.
Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary.
... | 0.003049 |
def lengths_to_mask(*lengths, **kwargs):
""" Given a list of lengths, create a batch mask.
Example:
>>> lengths_to_mask([1, 2, 3])
tensor([[1, 0, 0],
[1, 1, 0],
[1, 1, 1]], dtype=torch.uint8)
>>> lengths_to_mask([1, 2, 2], [1, 2, 2])
tensor([[[1, ... | 0.005839 |
def _name_value_to_bson(name, value, check_keys, opts,
in_custom_call=False,
in_fallback_call=False):
"""Encode a single name, value pair."""
# First see if the type is already cached. KeyError will only ever
# happen once per subtype.
try:
return ... | 0.000434 |
def init_ns_var(which_ns: str = CORE_NS, ns_var_name: str = NS_VAR_NAME) -> Var:
"""Initialize the dynamic `*ns*` variable in the Namespace `which_ns`."""
core_sym = sym.Symbol(which_ns)
core_ns = Namespace.get_or_create(core_sym)
ns_var = Var.intern(core_sym, sym.Symbol(ns_var_name), core_ns, dynamic=T... | 0.009324 |
def set_content_length(self):
'''Find and set the content length.
.. seealso:: :meth:`compute_checksum`.
'''
if not self.block_file:
self.fields['Content-Length'] = '0'
return
with wpull.util.reset_file_offset(self.block_file):
wpull.util.see... | 0.004773 |
def nunique(self, dropna=True):
"""
Return number of unique elements in the object.
Excludes NA values by default.
Parameters
----------
dropna : bool, default True
Don't include NaN in the count.
Returns
-------
int
See Als... | 0.002415 |
def import_cert(name, cert_format=_DEFAULT_FORMAT, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE,
exportable=True, password='', saltenv='base'):
'''
Import the certificate file into the given certificate store.
:param str name: The path of the certificate file to import.
:param str cer... | 0.003893 |
async def load_uint(reader, width):
"""
Constant-width integer serialization
:param reader:
:param width:
:return:
"""
buffer = _UINT_BUFFER
result = 0
shift = 0
for _ in range(width):
await reader.areadinto(buffer)
result += buffer[0] << shift
shift += 8
... | 0.002967 |
def set_cookie(self, cookie):
"""Set a cookie, without checking whether or not it should be set."""
c = self._cookies
self._cookies_lock.acquire()
try:
if cookie.domain not in c: c[cookie.domain] = {}
c2 = c[cookie.domain]
if cookie.path not in c2: c2[... | 0.008602 |
def flatten(x):
"""
Flatten an arbitrary depth nested list.
"""
# Lifted from: http://stackoverflow.com/a/406822/263969
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(e... | 0.002941 |
def symlink_abiext(self, inext, outext):
"""
Create a simbolic link (outext --> inext). The file names are implicitly
given by the ABINIT file extension.
Example:
outdir.symlink_abiext('1WF', 'DDK')
creates the link out_DDK that points to out_1WF
Return: 0... | 0.005857 |
def _singlenode_searchlight(l, msk, mysl_rad, bcast_var, extra_params):
"""Run searchlight function on block data in parallel.
`extra_params` contains:
- Searchlight function.
- `Shape` mask.
- Minimum active voxels proportion required to run the searchlight
function.
"""
voxel_fn =... | 0.001296 |
def plot_compare(self, other_plotter, legend=True):
"""
plot two band structure for comparison. One is in red the other in blue
(no difference in spins). The two band structures need to be defined
on the same symmetry lines! and the distance between symmetry lines is
the one of t... | 0.000984 |
def translate(self, text, dest='en', src='auto'):
"""Translate text from source language to destination language
:param text: The source text(s) to be translated. Batch translation is supported via sequence input.
:type text: UTF-8 :class:`str`; :class:`unicode`; string sequence (list, tuple, i... | 0.0034 |
def start(self):
"""Start the process, essentially forks and calls target function."""
logger.info("starting process")
process = os.fork()
time.sleep(0.01)
if process != 0:
logger.debug('starting child watcher')
self.loop.reset()
self.child_pi... | 0.007657 |
def decode_cf_timedelta(num_timedeltas, units):
"""Given an array of numeric timedeltas in netCDF format, convert it into a
numpy timedelta64[ns] array.
"""
num_timedeltas = np.asarray(num_timedeltas)
units = _netcdf_to_numpy_timeunit(units)
shape = num_timedeltas.shape
num_timedeltas = num... | 0.001634 |
def get_ordered_idx(id_type, id_list, meta_df):
"""
Gets index values corresponding to ids to subset and orders them.
Input:
- id_type (str): either "id", "idx" or None
- id_list (list): either a list of indexes or id names
Output:
- a sorted list of indexes to subset a dimension... | 0.003044 |
def execute(self, conn, migration_url="", migration_input="", create_by="", migration_request_id="", oldest= False, transaction=False):
"""
Lists all requests if pattern is not provided.
"""
sql = self.sql
binds = {}
if migration_request_id:
sql += " WHERE MR.MIGRATION_REQU... | 0.028681 |
def _set_secpath_standby(self, v, load=False):
"""
Setter method for secpath_standby, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/secpath_standby (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_secpath_standby is conside... | 0.006039 |
def _get_doc_from_filename(filename):
"""Get SBMLDocument from given filename.
Parameters
----------
filename : path to SBML, or SBML string, or filehandle
Returns
-------
libsbml.SBMLDocument
"""
if isinstance(filename, string_types):
if ("win" in platform) and (len(filena... | 0.000644 |
def emulate_mouse(self, key_code, x_val, y_val, data):
"""Emulate the ev codes using the data Windows has given us.
Note that by default in Windows, to recognise a double click,
you just notice two clicks in a row within a reasonablely
short time period.
However, if the applica... | 0.000759 |
def get(typename):
"""get(typename) -> PrimitiveType or ComplexType
Returns the PrimitiveType or ComplexType for typename or None.
"""
dt = getPDT(typename) or getCDT(typename)
if dt is None:
pdt, nelems = ArrayType.parse(typename)
if pdt and nelems:
dt = ArrayType(pdt,... | 0.002915 |
def add(self, resource, replace=False):
"""Add just a single resource."""
uri = resource.uri
if (uri in self and not replace):
raise ResourceListDupeError(
"Attempt to add resource already in resource_list")
self[uri] = resource | 0.006944 |
def buy(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#buy-bitcoin"""
if 'amount' not in params and 'total' not in params:
raise ValueError("Missing required parameter: 'amount' or 'total'")
for required in ['currency', 'payment_method']:
if requir... | 0.005474 |
def cells_dn_meta(workbook, sheet, row, col, final_dict):
"""
Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere.
Check the cell title, and switch it to.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:p... | 0.003716 |
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers in given list and partition them into 2 groups."""
versions_min, ve... | 0.003911 |
def batch_update(self, statements):
"""Perform a batch of DML statements via an ``ExecuteBatchDml`` request.
:type statements:
Sequence[Union[ str, Tuple[str, Dict[str, Any], Dict[str, Union[dict, .types.Type]]]]]
:param statements:
List of DML statements, with optional... | 0.002875 |
def parse_objective_coefficient(entry):
"""Return objective value for reaction entry.
Detect objectives that are specified using the non-standardized
kinetic law parameters which are used by many pre-FBC SBML models. The
objective coefficient is returned for the given reaction, or None if
undefined... | 0.0016 |
def augment_reading_list(self, primary_query, augment_query=None, reverse_negate=False):
"""Apply injected logic for slicing reading lists with additional content."""
primary_query = self.validate_query(primary_query)
augment_query = self.get_validated_augment_query(augment_query=augment_query)
... | 0.0086 |
def find_best_matches(errors, matchers):
"""
Find the best match for each error
We use the Good Enough™ ratio as a watershed level for match scores.
"""
for text_log_error in errors:
matches = find_all_matches(text_log_error, matchers) # TextLogErrorMatch instances, unsaved!
best_... | 0.004298 |
def _post_resource(self, body):
"""
Create new resources and associated attributes.
Example:
acs.post_resource([
{
"resourceIdentifier": "masaya",
"parents": [],
"attributes": [
{
... | 0.001974 |
def _get_mstd(cls, df, column, windows):
""" get moving standard deviation
:param df: data
:param column: column to calculate
:param windows: collection of window of moving standard deviation
:return: None
"""
window = cls.get_only_one_positive_int(window... | 0.003824 |
def maxnorm_regularizer(scale=1.0):
"""Max-norm regularization returns a function that can be used to apply max-norm regularization to weights.
More about max-norm, see `wiki-max norm <https://en.wikipedia.org/wiki/Matrix_norm#Max_norm>`_.
The implementation follows `TensorFlow contrib <https://github.com/... | 0.005397 |
def check_who_am_i(self):
"""
This method checks verifies the device ID.
@return: True if valid, False if not
"""
register = self.MMA8452Q_Register['WHO_AM_I']
self.board.i2c_read_request(self.address, register, 1,
Constants.I2C_READ |... | 0.00659 |
def fetch_list(cls, client, ids):
"""
fetch instruments by ids
"""
results = []
request_url = "https://api.robinhood.com/options/instruments/"
for _ids in chunked_list(ids, 50):
params = {"ids": ",".join(_ids)}
data = client.get(request_url, para... | 0.003442 |
def eval_potential_c(pot,R,z):
"""
NAME:
eval_potential_c
PURPOSE:
Use C to evaluate the interpolated potential
INPUT:
pot - Potential or list of such instances
R - array
z - array
OUTPUT:
potential evaluated R and z
HISTORY:
2013-01-24 - Written ... | 0.020504 |
def get_variable(self, name, initializer):
"""
Create and initialize a variable using a numpy array and set trainable.
:param name: (required str) name of the variable
:param initializer: a numpy array or a tensor
"""
v = tf.get_variable(name, shape=initializer.shape,
ini... | 0.002088 |
def com_google_fonts_check_gasp(ttFont):
"""Is 'gasp' table set to optimize rendering?"""
if "gasp" not in ttFont.keys():
yield FAIL, ("Font is missing the 'gasp' table."
" Try exporting the font with autohinting enabled.")
else:
if not isinstance(ttFont["gasp"].gaspRange, dict):
y... | 0.010553 |
def log_request_data_encode(self, target_system, target_component, id, ofs, count):
'''
Request a chunk of a log
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
id :... | 0.007899 |
def create(self,
alert_config,
occurrence_frequency_count=None,
occurrence_frequency_unit=None,
alert_frequency_count=None,
alert_frequency_unit=None):
"""
Create a new alert
:param alert_config: A list of AlertConfig cl... | 0.004065 |
def runMultiplePassSPonly(df, model, nMultiplePass, nTrain):
"""
run CLA model SP through data record 0:nTrain nMultiplePass passes
"""
predictedField = model.getInferenceArgs()['predictedField']
print "run TM through the train data multiple times"
for nPass in xrange(nMultiplePass):
for j in xrange(nT... | 0.018622 |
def patch(module, external=(), internal=()):
"""
Temporarily monkey-patch dependencies which can be external to, or internal
to the supplied module.
:param module: Module object
:param external: External dependencies to patch (full paths as strings)
:param internal: Internal dependencies to pat... | 0.000522 |
def put_sync(self, **kwargs):
'''
PUT: puts data into the Firebase.
Requires the 'point' parameter as a keyworded argument.
'''
self.amust(("point", "data"), kwargs)
response = requests.put(self.url_correct(kwargs["point"],
kwargs.get("aut... | 0.004255 |
def logical_and(f1, f2): # function factory
'''Logical and from functions.
Parameters
----------
f1, f2 : function
Function that takes array and returns true or false for each item in array.
Returns
-------
Function.
Usage:
filter_func=logical_and(is_data_rec... | 0.004983 |
def get_specific_subnodes(self, node, name, recursive=0):
"""Given a node and a name, return a list of child `ELEMENT_NODEs`, that
have a `tagName` matching the `name`. Search recursively for `recursive`
levels.
"""
children = [x for x in node.childNodes if x.nodeType == x.ELEMEN... | 0.007449 |
def new_schedule(self, program, station, time, duration, new, stereo,
subtitled, hdtv, closeCaptioned, ei, tvRating, dolby,
partNumber, partTotal):
"""Callback run for each new schedule entry"""
if self.__v_schedule:
# [Schedule: EP012964250031, 70387... | 0.014451 |
def list_targets(self):
"""Returns a list of association targets of instance VIFs.
Each association target is represented as FloatingIpTarget object.
FloatingIpTarget is a APIResourceWrapper/APIDictWrapper and
'id' and 'name' attributes must be defined in each object.
FloatingIp... | 0.001351 |
def native(name, ret, interp=None, send_interp=False):
"""Used as a decorator to add the decorated function to the
pfp interpreter so that it can be used from within scripts.
:param str name: The name of the function as it will be exposed in template scripts.
:param pfp.fields.Field ret: The return typ... | 0.004477 |
def posterior(self, x, sigma=1.):
"""Model is X_1,...,X_n ~ N(theta, sigma^2), theta~self, sigma fixed"""
pr0 = 1. / self.scale**2 # prior precision
prd = x.size / sigma**2 # data precision
varp = 1. / (pr0 + prd) # posterior variance
mu = varp * (pr0 * self.loc + prd * x.mean... | 0.005348 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.