text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _RemoveUsers(self, remove_users):
"""Deprovision Linux user accounts that do not appear in account metadata.
Args:
remove_users: list, the username strings of the Linux accounts to remove.
"""
for username in remove_users:
self.utils.RemoveUser(username)
self.user_ssh_keys.pop(use... | 0.007979 |
def get_balance(self, address, api_token):
"""
returns the balance in wei
with some inspiration from PyWallet
"""
broadcast_url = self.base_url + '?module=account&action=balance'
broadcast_url += '&address=%s' % address
broadcast_url += '&tag=latest'
if ap... | 0.003012 |
def write_documentation(self, output_file):
"Issue documentation report on output_file file like object"
if not self.is_opened():
raise helpers.HIDError("Device has to be opened to get documentation")
#format
class CompundVarDict(object):
"""Compound variables dictionary.
... | 0.005376 |
def thermal_conductivity(self, temperature, volume):
"""
Eq(17) in 10.1103/PhysRevB.90.174107
Args:
temperature (float): temperature in K
volume (float): in Ang^3
Returns:
float: thermal conductivity in W/K/m
"""
gamma = self.gruneise... | 0.002307 |
def index_service(self, service_id):
"""
Index a service in search engine.
"""
from hypermap.aggregator.models import Service
service = Service.objects.get(id=service_id)
if not service.is_valid:
LOGGER.debug('Not indexing service with id %s in search engine as it is not valid' % servi... | 0.003215 |
def save(self, path, compressed=True, exist_ok=False):
"""
Save the GADDAG to file.
Args:
path: path to save the GADDAG to.
compressed: compress the saved GADDAG using gzip.
exist_ok: overwrite existing file at `path`.
"""
path = os.path.expan... | 0.003212 |
def get_required_setting(setting, value_re, invalid_msg):
"""
Return a constant from ``django.conf.settings``. The `setting`
argument is the constant name, the `value_re` argument is a regular
expression used to validate the setting value and the `invalid_msg`
argument is used as exception message ... | 0.001269 |
def fetch_url(url):
"""
Fetch the given url, strip formfeeds and decode
it into the defined encoding
"""
with closing(urllib.urlopen(url)) as f:
if f.code is 200:
response = f.read()
return strip_formfeeds(response).decode(ENCODING) | 0.003509 |
def forward(self, pred, target):
"""Compute the loss model.
:param pred: predicted Variable
:param target: Target Variable
:return: Loss
"""
loss = th.FloatTensor([0])
for i in range(1, self.moments):
mk_pred = th.mean(th.pow(pred, i), 0)
... | 0.004525 |
def round_sig_error2(x, ex1, ex2, n):
'''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals.'''
minerr = min(ex1,ex2)
minstex = round_sig(minerr,n)
if minstex.find('.') < 0:
extra_zeros = len(minstex) - n
sigfigs = len(s... | 0.017021 |
def skip(reason):
"""The skip decorator allows for you to always bypass a test.
:param reason: Expects a string
"""
def decorator(test_func):
if not isinstance(test_func, (type, ClassObjType)):
func_data = None
if test_func.__name__ == 'DECORATOR_ONCALL':
... | 0.001205 |
def _iter_config_props(cls):
"""Iterate over all ConfigProperty attributes, yielding (attr_name, config_property) """
props = inspect.getmembers(cls, lambda a: isinstance(a, ConfigProperty))
for attr_name, config_prop in props:
yield attr_name, config_prop | 0.013699 |
def get_all_role_config_groups(resource_root, service_name,
cluster_name="default"):
"""
Get all role config groups in the specified service.
@param resource_root: The root Resource object.
@param service_name: Service name.
@param cluster_name: Cluster name.
@return: A list of ApiRoleConfigGroup object... | 0.014315 |
def get_checksum32(oqparam, hazard=False):
"""
Build an unsigned 32 bit integer from the input files of a calculation.
:param oqparam: an OqParam instance
:param hazard: if True, consider only the hazard files
:returns: the checkume
"""
# NB: using adler32 & 0xffffffff is the documented way... | 0.000751 |
def validate_kwargs(func, kwargs):
"""Validate arguments to be supplied to func."""
func_name = func.__name__
argspec = inspect.getargspec(func)
all_args = argspec.args[:]
defaults = list(argspec.defaults or [])
# ignore implicit 'self' argument
if inspect.ismethod(func) and all_args[:1] ==... | 0.000675 |
def uncomment_lines(lines):
"""Uncomment the given list of lines and return them. The first hash mark
following any amount of whitespace will be removed on each line."""
ret = []
for line in lines:
ws_prefix, rest, ignore = RE_LINE_SPLITTER_UNCOMMENT.match(line).groups()
ret.append(ws_p... | 0.005602 |
def calculate_affinity(user1, user2, round=False): # pragma: no cover
"""
Quick one-off affinity calculations.
Creates an instance of the ``MALAffinity`` class with ``user1``,
then calculates affinity with ``user2``.
:param str user1: First user
:param str user2: Second user
:param round:... | 0.001715 |
def eth_call(self, from_, to=None, gas=None,
gas_price=None, value=None, data=None,
block=BLOCK_TAG_LATEST):
"""https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_call
:param from_: From account address
:type from_: str
:param to: To account address (o... | 0.003012 |
def sendPinnedLocation(
self, location, message=None, thread_id=None, thread_type=None
):
"""
Sends a given location to a thread as a pinned location
:param location: Location to send
:param message: Additional message
:param thread_id: User/Group ID to send to. See ... | 0.003492 |
def get_canonical_absolute_expanded_path(path):
"""Get the canonical form of the absolute path from a possibly relative path
(which may have symlinks, etc.)"""
return os.path.normcase(
os.path.normpath(
os.path.realpath( # remove any symbolic links
os... | 0.011468 |
def delta_cdf(self, d_min, d_max, n=None):
r'''Computes the difference in cumulative distribution function between
two particle size diameters.
.. math::
\Delta Q_n = Q_n(d_{max}) - Q_n(d_{min})
Parameters
----------
... | 0.005597 |
def writeGif(
filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None):
""" writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None)
Write an animated gif from the specified images.
... | 0.000277 |
def imagetransformer_sep_channels_16l_16h_imgnet_lrg_loc_128():
"""separate rgb embeddings."""
hparams = imagetransformer_sep_channels_12l_16h_imagenet_large()
hparams.num_hidden_layers = 16
hparams.local_attention = True
hparams.batch_size = 1
hparams.block_length = 128
return hparams | 0.026667 |
def GetDate(text=None, selected=None, **kwargs):
"""Prompt the user for a date.
This will raise a Zenity Calendar Dialog for the user to pick a date.
It will return a datetime.date object with the date or None if the
user hit cancel.
text - Text to be displayed in the calendar dialog.
... | 0.00382 |
def consult_filters(self, url_info: URLInfo, url_record: URLRecord, is_redirect: bool=False) \
-> Tuple[bool, str, dict]:
'''Consult the URL filter.
Args:
url_record: The URL record.
is_redirect: Whether the request is a redirect and it is
desired tha... | 0.004912 |
def eni_absent(
name,
release_eip=False,
region=None,
key=None,
keyid=None,
profile=None):
'''
Ensure the EC2 ENI is absent.
.. versionadded:: 2016.3.0
name
Name tag associated with the ENI.
release_eip
True/False - release any EIP a... | 0.001169 |
def _add(self, ctx, table_name, record_id, column_values):
"""
:type column_values: list of (column, value_json)
"""
vsctl_table = self._get_table(table_name)
ovsrec_row = ctx.must_get_row(vsctl_table, record_id)
for column, value in column_values:
ctx.add_col... | 0.005249 |
def get_authorization_query_session(self):
"""Gets the ``OsidSession`` associated with the authorization query service.
return: (osid.authorization.AuthorizationQuerySession) - an
``AuthorizationQuerySession``
raise: OperationFailed - unable to complete request
raise: ... | 0.00406 |
def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
... | 0.001961 |
def check_spam(self, ip=None, email=None, name=None, login=None, realname=None,
subject=None, body=None, subject_type='plain', body_type='plain'):
""" http://api.yandex.ru/cleanweb/doc/dg/concepts/check-spam.xml
subject_type = plain|html|bbcode
body_type = plain|html|b... | 0.008791 |
def create_from_tuples(self, tuples, **args):
"""
Creates from a list of (subj,subj_name,obj) tuples
"""
amap = {}
subject_label_map = {}
for a in tuples:
subj = a[0]
subject_label_map[subj] = a[1]
if subj not in amap:
a... | 0.006148 |
def launch_ipython_legacy_shell(args): # pylint: disable=unused-argument
"""Open the SolveBio shell (IPython wrapper) for older IPython versions"""
try:
from IPython.config.loader import Config
except ImportError:
_print("The SolveBio Python shell requires IPython.\n"
"To ins... | 0.000665 |
def point_in_multipolygon(point, multipoly):
"""
valid whether the point is located in a mulitpolygon (donut polygon is not supported)
Keyword arguments:
point -- point geojson object
multipoly -- multipolygon geojson object
if(point inside multipoly) return true else false
"""
c... | 0.003584 |
def AddKeywordsForName(self, name, keywords):
"""Associates keywords with name.
Records that keywords are associated with name.
Args:
name: A name which should be associated with some keywords.
keywords: A collection of keywords to associate with name.
"""
data_store.DB.IndexAddKeyword... | 0.002825 |
def get_tags(self):
"""Returns a list of set of tags."""
return sorted([frozenset(meta_graph.meta_info_def.tags)
for meta_graph in self.meta_graphs]) | 0.005682 |
def reads(paths, filename='data.h5', options=None, **keywords):
""" Reads data from an HDF5 file (high level).
High level function to read one or more pieces of data from an HDF5
file located at the paths specified in `paths` into Python
types. Each path is specified as a POSIX style path where the dat... | 0.000946 |
def expandtree(self, model=None):
"""
Goes through the expand options associated with this context and
returns a trie of data.
:param model: subclass of <orb.Model> || None
:return: <dict>
"""
if model and not self.columns:
schema = model.schema()
... | 0.003356 |
def find_class_in_list(klass, lst):
"""
Returns the first occurrence of an instance of type `klass` in
the given list, or None if no such instance is present.
"""
filtered = list(filter(lambda x: x.__class__ == klass, lst))
if filtered:
return filtered[0]
return None | 0.006579 |
def chunk(iterator, max_size):
"""Chunk a list/set/etc.
:param iter iterator: The iterable object to chunk.
:param int max_size: Max size of each chunk. Remainder chunk may be smaller.
:return: Yield list of items.
:rtype: iter
"""
gen = iter(iterator)
while True:
chunked = lis... | 0.003876 |
def slfo(wnd, res=50, neighbors=2, max_miss=.7, start_delta=1e-4):
"""
Side Lobe Fall Off (dB/oct).
Finds the side lobe peak fall off numerically in dB/octave by using the
``scipy.optimize.fmin`` function.
Hint
----
Originally, Harris rounded the results he found to a multiple of -6, you can
use the A... | 0.01127 |
def nhmmer(self, output_path, unpack, threads, evalue):
'''
nhmmer - Search input path using nhmmer
Parameters
----------
output_path : str
A string containing the path to the input sequences
unpack : obj
UnpackRawReads object, returns string comm... | 0.003018 |
def call_good_cb(self):
"""
If good_cb returns True then keep it
:return:
"""
with LiveExecution.lock:
if self.good_cb and not self.good_cb():
self.good_cb = None | 0.008696 |
def all_simple_bb_paths(self, start_address, end_address):
"""Return a list of path between start and end address.
"""
bb_start = self._find_basic_block(start_address)
bb_end = self._find_basic_block(end_address)
paths = networkx.all_simple_paths(self._graph, source=bb_start.add... | 0.007042 |
def clear(self):
"""
Clears the dict.
"""
self.__values.clear()
self.__access_keys = []
self.__modified_times.clear() | 0.011696 |
def nEx(mt, x, n):
""" nEx : Returns the EPV of a pure endowment (deferred capital).
Pure endowment benefits are conditional on the survival of the policyholder. (v^n * npx) """
return mt.Dx[x + n] / mt.Dx[x] | 0.013575 |
def create(hdf5, name, dtype, shape=(None,), compression=None,
fillvalue=0, attrs=None):
"""
:param hdf5: a h5py.File object
:param name: an hdf5 key string
:param dtype: dtype of the dataset (usually composite)
:param shape: shape of the dataset (can be extendable)
:param compression... | 0.001091 |
def add_stream_logger(level=logging.DEBUG, name=None):
"""
Add a stream logger. This can be used for printing all SDK calls to stdout
while working in an interactive session. Note this is a logger for the
entire module, which will apply to all environments started in the same
session. If you need a ... | 0.001332 |
def read_cache(stream):
"""Read a cache file from the given stream
:return: tuple(version, entries_dict, extension_data, content_sha)
* version is the integer version number
* entries dict is a dictionary which maps IndexEntry instances to a path at a stage
* extension_data is '' or 4 bytes of type ... | 0.002083 |
def __signalReceived(self, *args):
"""Received signal. Cancel previous timer and store args to be forwarded later."""
if self.__disconnecting:
return
with self.__lock:
self.__args = args
if self.__rateLimit == 0:
self.__timer.stop()
... | 0.00454 |
def general_symbolic(target, eqn=None, arg_map=None):
r'''
A general function to interpret a sympy equation and evaluate the linear
components of the source term.
Parameters
----------
target : OpenPNM object
The OpenPNM object where the result will be applied.
eqn : sympy symbolic... | 0.000412 |
def _is_pid_running_on_windows(pid):
"""Check if a process is running on windows systems based on the pid."""
pid = str(pid)
# Hide flashing command prompt
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(r'tasklis... | 0.001447 |
def karma(nick, rest):
"Return or change the karma value for some(one|thing)"
karmee = rest.strip('++').strip('--').strip('~~')
if '++' in rest:
Karma.store.change(karmee, 1)
elif '--' in rest:
Karma.store.change(karmee, -1)
elif '~~' in rest:
change = random.choice([-1, 0, 1])
Karma.store.change(karmee, c... | 0.031665 |
def _author_line(self):
"""
Helper method to concatenate author and institution values, if necessary
:return: string
"""
if self.author and self.institution:
return self.author + ";" + self.institution
elif self.author:
return self.author
e... | 0.008333 |
def get_access_flags_string(value):
"""
Transform an access flag field to the corresponding string
:param value: the value of the access flags
:type value: int
:rtype: string
"""
flags = []
for k, v in ACCESS_FLAGS.items():
if (k & value) == k:
flags.append(v)
... | 0.002924 |
def create_group(self, title = None, parent = None, image = 1,
y = 2999, mon = 12, d = 28, h = 23, min_ = 59,
s = 59):
"""This method creates a new group.
A group title is needed or no group will be created.
If a parent is given, the group will be crea... | 0.014077 |
def get(self, sid):
"""
Constructs a CertificateContext
:param sid: A string that uniquely identifies the Certificate.
:returns: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateContext
:rtype: twilio.rest.preview.deployed_devices.fleet.certificate.CertificateC... | 0.011442 |
def get_file_type(variant_source):
"""Check what kind of file variant source is
Args:
variant_source (str): Path to variant source
Returns:
file_type (str): 'vcf', 'gemini' or 'unknown'
"""
file_type = 'unknown'
valid_vcf_suffixes = ('.vcf', '.vcf.gz... | 0.006002 |
def get(self, req, driver):
"""Get info of a network
Get info of a specific netowrk with id on special cloud
with:
:Param req
:Type object Request
"""
response = driver.get_network(req.params, id)
data = {
'action': "get",
'contr... | 0.004219 |
def create_quiz_submission_start_quiz_taking_session(self, quiz_id, course_id, access_code=None, preview=None):
"""
Create the quiz submission (start a quiz-taking session).
Start taking a Quiz by creating a QuizSubmission which you can use to answer
questions and submit your answe... | 0.006325 |
def log_append(self, oldbinsha, message, newbinsha=None):
"""Append a logentry to the logfile of this ref
:param oldbinsha: binary sha this ref used to point to
:param message: A message describing the change
:param newbinsha: The sha the ref points to now. If None, our current commit s... | 0.005703 |
def _get_token_create_url(config):
'''
Create Vault url for token creation
'''
role_name = config.get('role_name', None)
auth_path = '/v1/auth/token/create'
base_url = config['url']
return '/'.join(x.strip('/') for x in (base_url, auth_path, role_name) if x) | 0.006993 |
def _sample_field(self, sample):
"""Returns string representation of sample-format values.
Raises:
KeyError: if requested sample is not defined.
"""
tag_values = self.sample_tag_values[sample].values()
if tag_values:
return ":".join(tag_values)
el... | 0.00578 |
def process_all(self, texts:Collection[str]) -> List[List[str]]:
"Process a list of `texts`."
if self.n_cpus <= 1: return self._process_all_1(texts)
with ProcessPoolExecutor(self.n_cpus) as e:
return sum(e.map(self._process_all_1, partition_by_cores(texts, self.n_cpus)), []) | 0.016077 |
def get_many(self, type: Type[T], query: Mapping[str, Any], streaming: bool = False) -> Iterable[T]:
"""Gets a query from the data pipeline, which contains a request for multiple objects.
1) Extracts the query the sequence of data sources.
2) Inserts the results into the data sinks (if appropri... | 0.005917 |
def correct_db_restart(self):
"""Ensure DB is consistent after unexpected restarts. """
LOG.info("Checking consistency of DB")
# Any Segments allocated that's not in Network or FW DB, release it
seg_netid_dict = self.service_segs.get_seg_netid_src(fw_const.FW_CONST)
vlan_netid_di... | 0.000418 |
def michalewicz(theta):
"""Michalewicz function"""
x, y = theta
obj = - np.sin(x) * np.sin(x ** 2 / np.pi) ** 20 - \
np.sin(y) * np.sin(2 * y ** 2 / np.pi) ** 20
grad = np.array([
- np.cos(x) * np.sin(x ** 2 / np.pi) ** 20 - (40 / np.pi) * x *
np.sin(x) * np.sin(x ** 2 / np.pi) ... | 0.003711 |
def main(argv=sys.argv, stream=sys.stderr):
"""Entry point for ``tappy`` command."""
args = parse_args(argv)
suite = build_suite(args)
runner = unittest.TextTestRunner(verbosity=args.verbose, stream=stream)
result = runner.run(suite)
return get_status(result) | 0.003521 |
def save(self, inplace=True):
"""
Saves modification to the api server.
"""
data = self._modified_data()
data = data['permissions']
if bool(data):
url = six.text_type(self.href) + self._URL['permissions']
extra = {'resource': self.__class__.__name_... | 0.003846 |
def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs):
'''
Tells remote host agent to start agent identified by desc.
The result value of the fiber is IRecipient.
'''
f = fiber.Fiber()
f.add_callback(agent.initiate_protocol, IRecipient(recp), desc,
allocation... | 0.002257 |
def send(self, smtp=None, **kw):
"""
Sends message.
:param smtp: When set, parameters from this dictionary overwrite
options from config. See `emails.Message.send` for more information.
:param kwargs: Parameters for `emails.Message.send`
:return: Response ... | 0.0059 |
def _format_object_mask(objectmask):
"""Format the new style object mask.
This wraps the user mask with mask[USER_MASK] if it does not already
have one. This makes it slightly easier for users.
:param objectmask: a string-based object mask
"""
objectmask = objectmask.strip()
if (not obje... | 0.002169 |
def Uninstall(self, package_name, keep_data=False, timeout_ms=None):
"""Removes a package from the device.
Args:
package_name: Package name of target package.
keep_data: whether to keep the data and cache directories
timeout_ms: Expected timeout for pushing and installing.... | 0.003484 |
def is_jid(jid):
'''
Returns True if the passed in value is a job id
'''
if not isinstance(jid, six.string_types):
return False
if len(jid) != 20 and (len(jid) <= 21 or jid[20] != '_'):
return False
try:
int(jid[:20])
return True
except ValueError:
ret... | 0.00304 |
def to_table_data(self):
"""
:raises ValueError:
:raises pytablereader.error.ValidationError:
"""
self._validate_source_data()
header_list = []
for json_record in self._buffer:
for key in json_record:
if key not in header_list:
... | 0.00315 |
def filter_arc(w, h, aspect):
"""Aspect ratio convertor. you must specify output size and source aspect ratio (as float)"""
taspect = float(w)/h
if abs(taspect - aspect) < 0.01:
return "scale=%s:%s"%(w,h)
if taspect > aspect: # pillarbox
pt = 0
ph = h
pw = int (h*aspect)
... | 0.022099 |
def run_copy(self,
source_project_dataset_tables,
destination_project_dataset_table,
write_disposition='WRITE_EMPTY',
create_disposition='CREATE_IF_NEEDED',
labels=None):
"""
Executes a BigQuery copy command to copy dat... | 0.003162 |
def detach(self) -> iostream.IOStream:
"""Take control of the underlying stream.
Returns the underlying `.IOStream` object and stops all
further HTTP processing. Intended for implementing protocols
like websockets that tunnel over an HTTP handshake.
This method is only supporte... | 0.003914 |
def decrypt(self, message, **kwargs):
"""Decrypt the contents of a string or file-like object ``message``.
:type message: file or str or :class:`io.BytesIO`
:param message: A string or file-like object to decrypt.
:param bool always_trust: Instruct GnuPG to ignore trust checks.
... | 0.00468 |
def get_instances(self):
"""Mostly used for debugging"""
return ["<%s prefix:%s (uid:%s)>" % (self.__class__.__name__,
i.prefix, self.uid)
for i in self.instances] | 0.008333 |
def path_yield(path):
"""Yield on all path parts."""
for part in (x for x in path.strip(SEP).split(SEP) if x not in (None, '')):
yield part | 0.006452 |
def replace(self, key, value, time=0, compress_level=-1):
"""
Replace a key/value to server ony if it does exist.
:param key: Key's name
:type key: six.string_types
:param value: A value to be stored on server.
:type value: object
:param time: Time in seconds tha... | 0.002597 |
def JG(cpu, target):
"""
Jumps short if greater.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, Operators.AND(cpu.ZF == False, cpu.SF == cpu.OF), target.read(), cpu.PC) | 0.014184 |
def temporary_dir(delete=True, dir=None,
prefix='elasticluster.', suffix='.d'):
"""
Make a temporary directory and make it current for the code in this context.
Delete temporary directory upon exit from the context, unless
``delete=False`` is passed in the arguments.
Arguments *s... | 0.003221 |
def draw_figs(FIGS):
"""
Can only be used if matplotlib backend is set to TKAgg
Does not play well with wxPython
Parameters
_________
FIGS : dictionary of figure names as keys and numbers as values
"""
is_win = True if sys.platform in ['win32', 'win64'] else False
if not is_win:
... | 0.001661 |
def _clean_listofcomponents_tuples(listofcomponents_tuples):
"""force 3 items in the tuple"""
def to3tuple(item):
"""return a 3 item tuple"""
if len(item) == 3:
return item
else:
return (item[0], item[1], None)
return [to3tuple(item) for item in listofcomponen... | 0.00303 |
def _resample_obspy(samples, sr, newsr, window='hanning', lowpass=True):
# type: (np.ndarray, int, int, str, bool) -> np.ndarray
"""
Resample using Fourier method. The same as resample_scipy but with
low-pass filtering for upsampling
"""
from scipy.signal import resample
from math import ce... | 0.002979 |
def _all_get_table_col(self, key, column, fullname):
""" Creates a pytables column instance.
The type of column depends on the type of `column[0]`.
Note that data in `column` must be homogeneous!
"""
val = column[0]
try:
# # We do not want to loose int_
... | 0.003205 |
def readFile(self, pathToFile):
"""
Returns data from a file.
@type pathToFile: str
@param pathToFile: Path to the file.
@rtype: str
@return: The data from file.
"""
fd = open(pathToFile, "rb")
data = fd.read()
fd.close()... | 0.011765 |
def GetVectorAsNumpy(numpy_type, buf, count, offset):
""" GetVecAsNumpy decodes values starting at buf[head] as
`numpy_type`, where `numpy_type` is a numpy dtype. """
if np is not None:
# TODO: could set .flags.writeable = False to make users jump through
# hoops before modifying...
... | 0.002114 |
def encode(self, variables, attributes):
"""
Encode the variables and attributes in this store
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
attributes : dict-like
Dictionary of key/value (... | 0.002649 |
def add_result(self, values):
"""
Add a tuple or increment the value of an existing one
in the rule results dictionary.
"""
idx = [values['host']]
for gid in self.key_gids[1:]:
idx.append(values[gid])
idx = tuple(idx)
try:
... | 0.004587 |
def add_section_break(self):
"""Return `w:sectPr` element for new section added at end of document.
The last `w:sectPr` becomes the second-to-last, with the new `w:sectPr` being an
exact clone of the previous one, except that all header and footer references
are removed (and are therefo... | 0.00788 |
def _call(self, mthd, uri, admin, data, headers, std_headers):
"""
Handles all the common functionality required for API calls. Returns
the resulting response object.
"""
if not uri.startswith("http"):
uri = "/".join((self.auth_endpoint.rstrip("/"), uri))
if a... | 0.002312 |
def get_access_list( self, email, uid ):
'''
Takes and email and matching uid, builds a uref and fetches an access structure that looks like:
{
"count": 1,
"code": 0,
"ts": 1428522205,
"limit": 100,
"offset": 0,
... | 0.017338 |
def _group_batches_shared(xs, caller_batch_fn, prep_data_fn):
"""Shared functionality for grouping by batches for variant calling and joint calling.
"""
singles = []
batch_groups = collections.defaultdict(list)
for args in xs:
data = utils.to_single_data(args)
caller, batch = caller_... | 0.002327 |
def cookie_name_check(cookie_name):
""" Check cookie name for validity. Return True if name is valid
:param cookie_name: name to check
:return: bool
"""
cookie_match = WHTTPCookie.cookie_name_non_compliance_re.match(cookie_name.encode('us-ascii'))
return len(cookie_name) > 0 and cookie_match is None | 0.028754 |
def transform_flask_bare_import(node):
'''Translates a flask.ext.wtf bare import into a non-magical import.
Translates:
import flask.ext.admin as admin
Into:
import flask_admin as admin
'''
new_names = []
for (name, as_name) in node.names:
match = re.match(r'flask\.ext\... | 0.001587 |
def __set_unkown_effect(self, hgvs_string):
"""Sets a flag for unkown effect according to HGVS syntax. The
COSMIC database also uses unconventional questionmarks to denote
missing information.
Args:
hgvs_string (str): hgvs syntax with "p." removed
"""
# Stand... | 0.001967 |
def available_input_formats():
"""
Return all available input formats.
Returns
-------
formats : list
all available input formats
"""
input_formats = []
for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT):
logger.debug("driver found: %s", v)
driver_ = v... | 0.00396 |
def init_neutron_consumer(self, mq):
"""
Init openstack neutron mq
1. Check if enable listening neutron notification
2. Create consumer
:param mq: class ternya.mq.MQ
"""
if not self.enable_component_notification(Openstack.Neutron):
log.debug("disable... | 0.002833 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.