text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def add_to(self, parent, additions):
"Modify parent to include all elements in additions"
for x in additions:
if x not in parent:
parent.append(x)
self.changed() | 0.00905 |
def split_tracks(lat,lon,*args):
'''assumes eastward motion'''
tracks = []
lt,ln = [lat[0]],[lon[0]]
zz = [[z[0]] for z in args]
for i in range(1,len(lon)):
lt.append(lat[i])
for z,a in zip(zz,args):
z.append(a[i])
d1 = abs(lon[... | 0.018699 |
def get_validation_errors(data, schema=None):
"""Validation errors for a given record.
Args:
data (dict): record to validate.
schema (Union[dict, str]): schema to validate against. If it is a
string, it is intepreted as the name of the schema to load (e.g.
``authors`` or... | 0.000969 |
def _call(self, x, out=None):
"""Return ``self(x[, out])``."""
# TODO: pass reasonable options on to the interpolator
def nearest(arg, out=None):
"""Interpolating function with vectorization."""
if is_valid_input_meshgrid(arg, self.grid.ndim):
input_type =... | 0.003082 |
def time_correlation_direct_by_mtx_vec_prod(P, mu, obs1, obs2=None, time=1, start_values=None, return_P_k_obs=False):
r"""Compute time-correlation of obs1, or time-cross-correlation with obs2.
The time-correlation at time=k is computed by the matrix-vector expression:
cor(k) = obs1' diag(pi) P^k obs2
... | 0.002202 |
def draw(args):
"""
%prog draw --input newicktrees [options]
Draw phylogenetic trees into single or combined plots.
Input trees should be one of the following:
1. single Newick format tree file
2. a dir containing *ONLY* the tree files to be drawn
Newick format:
http://evolution.gene... | 0.005484 |
def _getEventsOnDay(self, request, day):
"""Return all the events in this site for a given day."""
home = request.site.root_page
return getAllEventsByDay(request, day, day, home=home)[0] | 0.009524 |
def distances_within(coords_a, coords_b, cutoff,
periodic=False, method="simple"):
"""Calculate distances between the array of coordinates *coord_a*
and *coord_b* within a certain cutoff.
This function is a wrapper around different routines and data structures
for distance sear... | 0.003463 |
def color(cls, value):
"""task value/score color"""
index = bisect(cls.breakpoints, value)
return colors.fg(cls.colors_[index]) | 0.013245 |
def simplex_select_entering_arc(self, t, pivot):
'''
API:
simplex_select_entering_arc(self, t, pivot)
Description:
Decides and returns entering arc using pivot rule.
Input:
t: current spanning tree solution
pivot: May be one of the followin... | 0.003241 |
def create(domain_name, years, **kwargs):
'''
Try to register the specified domain name
domain_name
The domain name to be registered
years
Number of years to register
Returns the following information:
- Whether or not the domain was renewed successfully
- Whether or not ... | 0.005516 |
def run_hooks(self, name, event=None, context=None):
"""
Runs plugin hooks for each registered plugin.
"""
hooks = {
"pre:setup": lambda p: p.pre_setup(self),
"post:setup": lambda p: p.post_setup(self),
"pre:invoke": lambda p: p.pre_invoke(event, conte... | 0.003264 |
def draw_imf_samples(**kwargs):
''' Draw samples for power-law model
Parameters
----------
**kwargs: string
Keyword arguments as model parameters and number of samples
Returns
-------
array
The first mass
array
The second mas... | 0.001036 |
def incr(self, name, amount=1):
"""
Increase the value at key ``name`` by ``amount``. If no key exists, the value
will be initialized as ``amount`` .
Like **Redis.INCR**
:param string name: the key name
:param int amount: increments
:return: the integer value at... | 0.007205 |
def ssh_invite(ctx, code_length, user, **kwargs):
"""
Add a public-key to a ~/.ssh/authorized_keys file
"""
for name, value in kwargs.items():
setattr(ctx.obj, name, value)
from . import cmd_ssh
ctx.obj.code_length = code_length
ctx.obj.ssh_user = user
return go(cmd_ssh.invite, c... | 0.003058 |
def add_path(self, w, h):
"""Reference to `a:custGeom` descendant or |None| if not present."""
custGeom = self.spPr.custGeom
if custGeom is None:
raise ValueError('shape must be freeform')
pathLst = custGeom.get_or_add_pathLst()
return pathLst.add_path(w=w, h=h) | 0.006369 |
def _embed(x, order=3, delay=1):
"""Time-delay embedding.
Parameters
----------
x : 1d-array, shape (n_times)
Time series
order : int
Embedding dimension (order)
delay : int
Delay.
Returns
-------
embedded : ndarray, shape (n_times - (order - 1) * delay, ord... | 0.001923 |
def text_filter_changed(self, text):
"""
Called to handle changes to the text filter.
:param text: The text for the filter.
"""
text = text.strip() if text else None
if text is not None:
self.__text_filter = ListModel.TextFilter("text_for_filter", te... | 0.004914 |
def __ds(self):
"""
Get the I{default} service if defined in the I{options}.
@return: A L{PortSelector} for the I{default} service.
@rtype: L{PortSelector}.
"""
ds = self.__client.options.service
if ds is not None:
return self.__find(ds) | 0.006515 |
def update_if_absent(self, **kwargs):
"""Update the settings when the target fields are None.
Args:
kwargs: The keyword arguments to set corresponding fields.
"""
for arg in kwargs:
if hasattr(self, arg):
if getattr(self, arg) is None:
... | 0.003724 |
def pitch_tuning(frequencies, resolution=0.01, bins_per_octave=12):
'''Given a collection of pitches, estimate its tuning offset
(in fractions of a bin) relative to A440=440.0Hz.
Parameters
----------
frequencies : array-like, float
A collection of frequencies detected in the signal.
... | 0.000477 |
def open(self):
"""Open the subtitle file into an Aeidon project."""
try:
self.project.open_main(self.filename)
except UnicodeDecodeError:
with open(self.filename, 'rb') as openfile:
encoding = get_encoding(openfile.read())
try:
... | 0.005563 |
def _process_group(input_group, required_group, groupname, append_subgroups=None):
"""
Process one group from the input yaml. Ensure it has the required entries. If there is a
subgroup that should be processed and then appended to the rest of the subgroups in that group,
handle it accordingly.
:p... | 0.004769 |
def service_info(self, name):
"""Pull descriptive info of a service by name.
Information returned includes the service's user friendly
name and whether it was preregistered or added dynamically.
Returns:
dict: A dictionary of service information with the following keys
... | 0.003185 |
def DeriveDataRegex(fieldName, db, deriveInput, overwrite, fieldVal, histObj={},
blankIfNoMatch=False):
"""
Return a new field value based on match (of another field) against regex
queried from MongoDB
:param string fieldName: Field name to query against
:param MongoClient db: M... | 0.001157 |
def get_reference_fields(self, exclude_models=None):
"""
Get all Django model fields which reference the Item model.
"""
if exclude_models is None:
exclude_models = []
result = []
for django_model in django.apps.apps.get_models():
if any([issubclas... | 0.005487 |
def upload(name):
'''Handle upload on POST if authorized.'''
storage = fs.by_name(name)
return jsonify(success=True, **handle_upload(storage)) | 0.006494 |
def move(self, path_list, dest, **kwargs):
"""
移动文件或文件夹
:param path_list: 在百度盘上要移动的源文件path
:type path_list: list
:param dest: 要移动到的目录
:type dest: str
"""
def __path(path):
if path.endswith('/'):
return path.split('/')[-2]
... | 0.004587 |
def json_2_nic(json_obj):
"""
transform JSON obj coming from Ariane to ariane_clip3 object
:param json_obj: the JSON obj coming from Ariane
:return: ariane_clip3 NIC object
"""
LOGGER.debug("NIC.json_2_nic")
return NIC(nic_id=json_obj['nicID'],
... | 0.003035 |
def obtain_token(self):
"""
Try to obtain token from all end-points that were ever used to serve the
token. If the request returns 404 NOT FOUND, retry with older version of
the URL.
"""
token_end_points = ('token/obtain',
'obtain-token',
... | 0.005908 |
def rate_limits(self):
"""Returns a list of rate limit details."""
if not self._rate_limits:
self._rate_limits = utilities.get_rate_limits(self.response)
return self._rate_limits | 0.009302 |
def plateid6(self, filetype, **kwargs):
"""Print plate ID, accounting for 5-6 digit plate IDs.
Parameters
----------
filetype : str
File type parameter.
plateid : int or str
Plate ID number. Will be converted to int internally.
Returns
-... | 0.003384 |
def jp_compose(s, base=None):
""" append/encode a string to json-pointer
"""
if s == None:
return base
ss = [s] if isinstance(s, six.string_types) else s
ss = [s.replace('~', '~0').replace('/', '~1') for s in ss]
if base:
ss.insert(0, base)
return '/'.join(ss) | 0.006557 |
def is_lop(ch,block_op_pairs_dict=get_block_op_pairs('{}[]()')):
'''
# is_lop('{',block_op_pairs_dict)
# is_lop('[',block_op_pairs_dict)
# is_lop('}',block_op_pairs_dict)
# is_lop(']',block_op_pairs_dict)
# is_lop('a',block_op_pairs_dict)
'''
for i in range(1,block_op_pairs_dict.__len__(... | 0.006757 |
def set_modulations(self,
dimension,
phonon_modes,
delta_q=None,
derivative_order=None,
nac_q_direction=None):
"""Generate atomic displacements of phonon modes.
The design of this fea... | 0.004082 |
def version_msg():
"""Return the Cookiecutter version, location and Python powering it."""
python_version = sys.version[:3]
location = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
message = u'Cookiecutter %(version)s from {} (Python {})'
return message.format(location, python_version) | 0.003125 |
def to_unit_cell(self, in_place=False):
"""
Move frac coords to within the unit cell cell.
"""
frac_coords = np.mod(self.frac_coords, 1)
if in_place:
self.frac_coords = frac_coords
else:
return PeriodicSite(self.species, frac_coords, self.lattice,
... | 0.005277 |
def add_resource_factory(self, factory_callback: factory_callback_type,
types: Union[type, Sequence[Type]], name: str = 'default',
context_attr: str = None) -> None:
"""
Add a resource factory to this context.
This will cause a ``resourc... | 0.005877 |
def _load(self):
"""
Execute the logic behind the merging.
"""
if "PYFUNCEBLE_AUTO_CONFIGURATION" not in PyFunceble.environ:
# The auto configuration environment variable is not set.
while True:
# We infinitly loop until we get a reponse which is... | 0.00273 |
def _download_rtd_zip(rtd_version=None, **kwargs):
"""
Download and extract HTML ZIP from RTD to installed doc data path.
Download is skipped if content already exists.
Parameters
----------
rtd_version : str or `None`
RTD version to download; e.g., "latest", "stable", or "v2.6.0".
... | 0.000468 |
def switch(self, time=None):
"""Obtain switch parameter, ie number of times the stage shifts."""
stag_to_int = {'NREM1': 1, 'NREM2': 2, 'NREM3': 3, 'REM': 5, 'Wake': 0}
hypno = [stag_to_int[x['stage']] for x in self.get_epochs(time=time) \
if x['stage'] in stag_to_int.keys()]
... | 0.010554 |
def load_file(self, filename):
"""Load file into treeview"""
self.counter.clear()
# python2 issues
try:
etree = ET.parse(filename)
except ET.ParseError:
parser = ET.XMLParser(encoding='UTF-8')
etree = ET.parse(filename, parser)
eroot =... | 0.003886 |
def cmd_slow_requests(self):
"""List all requests that took a certain amount of time to be
processed.
.. warning::
By now hardcoded to 1 second (1000 milliseconds), improve the
command line interface to allow to send parameters to each command
or globally.
... | 0.003883 |
def tf_initialize(self, x_init, b):
"""
Initialization step preparing the arguments for the first iteration of the loop body:
$x_0, 0, p_0, r_0, r_0^2$.
Args:
x_init: Initial solution guess $x_0$, zero vector if None.
b: The right-hand side $b$ of the system of... | 0.005149 |
def fmt_sia(sia, ces=True):
"""Format a |SystemIrreducibilityAnalysis|."""
if ces:
body = (
'{ces}'
'{partitioned_ces}'.format(
ces=fmt_ces(
sia.ces,
'Cause-effect structure'),
partitioned_ces=fmt_ces(
... | 0.001236 |
def from_file(cls, address_book, filename, supported_private_objects,
localize_dates):
"""
Use this if you want to create a new contact from an existing .vcf
file.
"""
return cls(address_book, filename, supported_private_objects, None,
localize_dates) | 0.012539 |
def lock_input_target_config_target_running_running(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
lock = ET.Element("lock")
config = lock
input = ET.SubElement(lock, "input")
target = ET.SubElement(input, "target")
config_target... | 0.003559 |
def genderize(name, api_token=None):
"""Fetch gender from genderize.io"""
GENDERIZE_API_URL = "https://api.genderize.io/"
TOTAL_RETRIES = 10
MAX_RETRIES = 5
SLEEP_TIME = 0.25
STATUS_FORCELIST = [502]
params = {
'name': name
}
if api_token:
params['apikey'] = api_to... | 0.0027 |
def update_certificate(self, certificate_id, **kwargs):
"""Update a certificate.
:param str certificate_id: The certificate id (Required)
:param str certificate_data: X509.v3 trusted certificate in PEM format.
:param str signature: This parameter has been DEPRECATED in the API and does ... | 0.002935 |
def list_assigned_licenses(entity, entity_display_name, license_keys=None,
service_instance=None):
'''
Lists the licenses assigned to an entity
entity
Dictionary representation of an entity.
See ``_get_entity`` docstrings for format.
entity_display_name
... | 0.002172 |
def raw_read(self):
"""https://github.com/frictionlessdata/datapackage-py#resource
"""
contents = b''
with self.raw_iter() as filelike:
for chunk in filelike:
contents += chunk
return contents | 0.007692 |
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... | 0.007049 |
def convert_ints_to_bytes(in_ints, num):
"""Convert an integer array into a byte arrays. The number of bytes forming an integer
is defined by num
:param in_ints: the input integers
:param num: the number of bytes per int
:return the integer array"""
out_bytes= b""
for val in in_ints:
... | 0.009852 |
def scaffold():
"""Start a new site."""
click.echo("A whole new site? Awesome.")
title = click.prompt("What's the title?")
url = click.prompt("Great. What's url? http://")
# Make sure that title doesn't exist.
click.echo("Got it. Creating %s..." % url) | 0.00361 |
def plot (data, headers=None, pconfig=None):
""" Return HTML for a MultiQC table.
:param data: 2D dict, first keys as sample names, then x:y data pairs
:param headers: list of optional dicts with column config in key:value pairs.
:return: HTML ready to be inserted into the page
"""
if headers is... | 0.008986 |
def recordtype_row_strategy(column_names):
""" Recordtype row strategy, rows returned as recordtypes
Column names that are not valid Python identifiers will be replaced
with col<number>_
"""
try:
from namedlist import namedlist as recordtype # optional dependency
except ImportError:
... | 0.001837 |
def process_save(X, y, tokenizer, proc_data_path, max_len=400, train=False, ngrams=None, limit_top_tokens=None):
"""Process text and save as Dataset
"""
if train and limit_top_tokens is not None:
tokenizer.apply_encoding_options(limit_top_tokens=limit_top_tokens)
X_encoded = tokenizer.encode_te... | 0.00292 |
def session(self):
"""A context manager for this client's session.
This function closes the current session when this client goes out of
scope.
"""
self._session = requests.session()
yield
self._session.close()
self._session = None | 0.006757 |
def get_addresses_from_input_file(input_file_name):
"""Read addresses from input file into list of tuples.
This only supports address and zipcode headers
"""
mode = 'r'
if sys.version_info[0] < 3:
mode = 'rb'
with io.open(input_file_name, mode) as input_file:
reader = csv.read... | 0.003036 |
def permute(num):
"Permutation for randomizing data order."
if permute_data:
return np.random.permutation(num)
else:
logging.warning("Warning not permuting data")
return np.arange(num) | 0.004545 |
def daemonize(umask=0, work_dir="/", max_fd=1024, redirect="/dev/null"):
"""
When this function is called, the process is daemonized (by forking + killing its parent).
It becomes a background task.
It is useful to release the console.
"""
if not redirect:
redirect = "/dev/null"
if h... | 0.002706 |
def class_error(self, input_data, targets, average=True,
cache=None, prediction=False):
""" Return the classification error rate
"""
if cache is not None:
activations = cache
else:
activations = \
self.feed_forward(input_data, pr... | 0.007246 |
def cumsum(self, axis=0, *args, **kwargs):
"""
Cumulative sum of non-NA/null values.
When performing the cumulative summation, any non-NA/null values will
be skipped. The resulting SparseArray will preserve the locations of
NaN values, but the fill value will be `np.nan` regardl... | 0.001938 |
def _parse_directory(self):
"""
Parse the storage directory in the config.
Returns:
str
"""
if self._parser.has_option('storage', 'directory'):
directory = self._parser.get('storage', 'directory')
# Don't allow CUSTOM_APPS_DIR as a storage dir... | 0.00335 |
def process_and_show(self):
"""
Run :meth:`process` and :meth:`show_source` after each other.
"""
for name, klass in sorted(self.classes.items()):
logger.debug('Processing class: %s', name)
if not isinstance(klass, DvClass):
klass = DvClass(klass, ... | 0.005141 |
def __SendMediaBody(self, start, additional_headers=None):
"""Send the entire media stream in a single request."""
self.EnsureInitialized()
if self.total_size is None:
raise exceptions.TransferInvalidError(
'Total size must be known for SendMediaBody')
body_st... | 0.001787 |
def set_end(self,t):
"""
Override the GPS end time (and set the duration) of this ScienceSegment.
@param t: new GPS end time.
"""
self.__dur -= self.__end - t
self.__end = t | 0.010152 |
def valueFromString(self, value, context=None):
"""
Converts the inputted string text to a value that matches the type from
this column type.
:param value | <str>
"""
if value == 'now':
return datetime.datetime.now().time()
elif dateutil_parser:
... | 0.003241 |
def show_ntp_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_ntp = ET.Element("show_ntp")
config = show_ntp
input = ET.SubElement(show_ntp, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.... | 0.004525 |
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs):
"""Compute kernel matrix"""
if method.lower() in ['gaussian', 'gauss', 'rbf']:
K = np.exp(-dist(x1, x2) / (2 * sigma**2))
return K | 0.004808 |
def getIDsFromFiles(files):
"""given a path or list of files, return ABF IDs."""
if type(files) is str:
files=glob.glob(files+"/*.*")
IDs=[]
for fname in files:
if fname[-4:].lower()=='.abf':
ext=fname.split('.')[-1]
IDs.append(os.path.basename(fname).replace('.'+... | 0.017094 |
def merge_ticket(self, ticket_id, into_id):
""" Merge ticket into another (undocumented API feature).
:param ticket_id: ID of ticket to be merged
:param into: ID of destination ticket
:returns: ``True``
Operation was successful
``False``
... | 0.004115 |
def Consultar(self, nro_doc):
"Llama a la API pública de AFIP para obtener los datos de una persona"
n = 0
while n <= 4:
n += 1 # reintentar 3 veces
try:
if not self.client:
if DEBUG:
war... | 0.002853 |
def main(branch):
"""Checkout, update and branch from the specified branch."""
try:
# Ensure that we're in a git repository. This command is silent unless
# you're not actually in a git repository, in which case, you receive a
# "Not a git repository" error message.
output = subp... | 0.000636 |
def isConjNorthNode(self):
""" Returns if object is conjunct north node. """
node = self.chart.getObject(const.NORTH_NODE)
return aspects.hasAspect(self.obj, node, aspList=[0]) | 0.01 |
def _make_request(self, url, parameters, result_key):
"""Make http/https request to Google API.
Method prepares url parameters, drops None values, and gets default
values. Finally makes request using protocol assigned to client and
returns data.
:param url: url part - specifies... | 0.001404 |
def outputMode(self, outputMode):
"""Specifies how data of a streaming DataFrame/Dataset is written to a streaming sink.
Options include:
* `append`:Only the new rows in the streaming DataFrame/Dataset will be written to
the sink
* `complete`:All the rows in the streaming Da... | 0.008806 |
def read_messages(fobj, magic_table):
"""Read messages from a file-like object until stream is exhausted."""
messages = []
while True:
magic = read_magic(fobj)
if not magic:
break
func = magic_table.get(magic)
if func is not None:
messages.append(fun... | 0.003831 |
def seconds_remaining(self, ttl):
"""Return number of seconds left before Imgur API needs to be queried for this instance.
:param int ttl: Number of seconds before this is considered out of date.
:return: Seconds left before this is expired. 0 indicated update needed (no negatives).
:r... | 0.012346 |
def first(self):
"""Return the first record or raise an exception if the result doesn't contain any data
:return:
- Dictionary containing the first item in the response content
:raise:
- NoResults: If no results were found
"""
if not self._stream:
... | 0.005495 |
def save(self):
"""
Saves a new rating - authenticated users can update the
value if they've previously rated.
"""
user = self.request.user
self.undoing = False
rating_value = self.cleaned_data["value"]
manager = self.rating_manager
if user.is_aut... | 0.002979 |
def pack(self):
'''pack a FD FDM buffer from current values'''
for i in range(len(self.values)):
if math.isnan(self.values[i]):
self.values[i] = 0
return struct.pack(self.pack_string, *self.values) | 0.008032 |
def install_virtualenv_p3(root, python_version):
""" Install virtual environment for Python 3.3+; removing the old one if it exists """
import venv
builder = venv.EnvBuilder(system_site_packages=False, clear=True, symlinks=False, upgrade=False)
builder.create(root)
ret_code = subprocess.call([VE_SCR... | 0.007813 |
def list_consumer_group(self, project, logstore):
""" List consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:return: ListConsumerGroupResponse
"""
resource = "/logstores... | 0.005556 |
def setViewModel(self, model):
"""Sets the model for the enclosed TableView in this widget.
Args:
model (DataFrameModel): The model to be displayed by
the Table View.
"""
if isinstance(model, DataFrameModel):
self.enableEditing(False)
... | 0.004926 |
def get_document(self, id):
"""
Retrieves a particular document from this project.
"""
obj_list = self.document_list
matches = [i for i in obj_list if str(i.id) == str(id)]
if not matches:
raise DoesNotExistError("The resource you've requested does not \
exist... | 0.005025 |
def on_connect(self, connection):
"Called when the socket connects"
self._sock = connection._sock
self._buffer = SocketBuffer(self._sock, self.socket_read_size)
self.encoder = connection.encoder | 0.00885 |
def update_video(self, access_token, video_id, title=None,
tags=None, category=None, copyright_type=None,
public_type=None, watch_password=None,
description=None, thumbnail_seq=None):
"""doc: http://open.youku.com/docs/doc?id=50
"""
... | 0.00523 |
def isin(self, values):
"""
Compute boolean array of whether each index value is found in the
passed set of values.
Parameters
----------
values : set or sequence of values
Returns
-------
is_contained : ndarray (boolean dtype)
"""
... | 0.003546 |
def get_extended_summaryf(self, *args, **kwargs):
"""Extract the extended summary from a function docstring
This function can be used as a decorator to extract the extended
summary of a function docstring (similar to :meth:`get_sectionsf`).
Parameters
----------
``*args... | 0.002415 |
def of(self, *indented_blocks) -> "CodeBlock":
"""
By default, marks the block as expecting an indented "body" blocks of which are then supplied
as arguments to this method.
Unless the block specifies a "closed_by", if no body blocks are supplied or they are all Nones,
this will... | 0.006809 |
def trigger_methods(instance, args):
""""
Triggers specific class methods using a simple reflection
mechanism based on the given input dictionary params.
Arguments:
instance (object): target instance to dynamically trigger methods.
args (iterable): input arguments to trigger objects to
... | 0.000779 |
def get_block_symbol_data(editor, block):
"""
Gets the list of ParenthesisInfo for specific text block.
:param editor: Code editor instance
:param block: block to parse
"""
def list_symbols(editor, block, character):
"""
Retuns a list of symbols found in the block text
... | 0.000628 |
def call(self, method, *args):
""" Calls the service method defined with the arguments provided """
try:
response = getattr(self.client.service, method)(*args)
except (URLError, SSLError) as e:
log.exception('Failed to connect to responsys service')
raise Conn... | 0.002092 |
async def publish(self, subject, payload,
ack_handler=None,
ack_wait=DEFAULT_ACK_WAIT,
):
"""
Publishes a payload onto a subject. By default, it will block
until the message which has been published has been acked back.
A... | 0.002657 |
def norm(table):
"""
fit to normal distribution
"""
print('# norm dist is broken', file=sys.stderr)
exit()
from matplotlib.pyplot import hist as hist
t = []
for i in table:
t.append(np.ndarray.tolist(hist(i, bins = len(i), normed = True)[0]))
return t | 0.016949 |
def new_cipher(self, key, iv, digest=None):
"""
@param key: the secret key, a byte string
@param iv: the initialization vector, a byte string. Used as the
initial nonce in counter mode
@param digest: also known as tag or icv. A byte string containing the
... | 0.001994 |
def get_external_tools_in_course(self, course_id, params={}):
"""
Return external tools for the passed canvas course id.
https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index
"""
url = COURSES_API.format(course_id) + "/external_tools"
ex... | 0.004228 |
def add_cell_params(self, params, pos=None):
"""
Add cell of Python parameters
:param params: parameters to add
:return:
"""
self.params = params
cell_str = '# Parameters:\n'
for k, v in params.items():
cell_str += "{} = {}\n".format(k, repr(v... | 0.005495 |
def post_process(self, paths, dry_run=False, **options):
"""
Overridden to work around https://code.djangoproject.com/ticket/19111
"""
with post_process_error_counter(self):
with patched_name_fn(self, 'hashed_name', 'hashed name'):
with patched_name_fn(self, '... | 0.005472 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.