content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Optional
def get_table(id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetTableResult:
"""
Resource Type definition for AWS::DynamoDB::Table
"""
__args__ = dict()
__args__['id'] = id
if opts is None:
opts = pulumi.Invo... | ef564eeac0443cb99bceddb4959e1abb137570c3 | 50,428 |
def load_perezfornos2012(shuffle=False, subjects=None, figures=None,
random_state=0):
"""Load data from [PerezFornos2012]_
Load the brightness associated with joystick position data described in
[PerezFornos2012]_.
Datapoints were extracted from Figures 3-7 of the paper.
... | 5edd2826e8fa3a0b5a44bf57bfc12104c0899d66 | 50,429 |
def setup_Component_with_parameters():
"""
Sets up a Component with parameters and all options used.
"""
comp = setup_Component_all_keywords()
comp._unfreeze()
# Need to set up attribute parameters
comp.new_par1 = 1.5
comp.new_par2 = 3
comp.new_par3 = None
comp.this_par = "test... | 8e99f241617a8857593da7dc203af5ffe09beb7c | 50,431 |
def dpuSetTaskPriority(task, priority):
"""
Set the priority of one DPU task. Priority range is 0 to 15, 0 has the highest priority.
The priority of the task when it was created defaults to 15.
"""
return pyc_libn2cube.pyc_dpuSetTaskPriority(task, c_int(priority)) | fca91a76d7a36bc09e69153a69ff694b80a39767 | 50,432 |
def find_std(arr):
"""
This function determines the standard deviation of the given array.
Args:
arr = numpy array for which the standard deviation and means are to be determined
Returns:
std = standard deviation of the given array
mean = mean value of the given array
Usage... | 3b6d4962ee3ff31eafb4cd194f2302675c5643de | 50,433 |
import math
def process(frame: np.ndarray, mask: np.ndarray = None, hsv: np.ndarray = None, *,
lower=(20, 100, 100), upper=(35, 255, 255),
min_area_prop=1/64, focal_length=208.5):
"""Find cubes using our vision algorithm.
Args
----
frame: the image to process
mask: optiona... | 7c173299676ad7665b0a9e62ab5aa9be8530552b | 50,434 |
def required_daemons(instance):
"""
Return which daemon types are required by the instance
"""
daemons = [DaemonType.SENSOR]
if isinstance(instance.scheduler, DagsterDaemonScheduler):
daemons.append(DaemonType.SCHEDULER)
if isinstance(instance.run_coordinator, QueuedRunCoordinator):
... | 8c0c016ced926e0bc2db86ca447f4cd7beef7b64 | 50,435 |
import six
def SplitDictOfTensors(t_dict, num_splits):
"""Splits tensors in `t_dict` evenly into `num_splits` along the 1st dimenion.
Args:
t_dict: A dictionary of tensors. Each tensor's 1st dimension is the same
size.
num_splits: A python integer.
Returns:
A list of dictionaries of tensors,... | 53d4ec0b5d1a5222dc6d3e3c5fa115f43aef6260 | 50,436 |
def add_gradient_noise(t, stddev=1e-3, name=None):
"""
Adds gradient noise as described in http://arxiv.org/abs/1511.06807 [2].
The input Tensor `t` should be a gradient.
The output will be `t` + gaussian noise.
0.001 was said to be a good fixed value for memory networks [2].
"""
with tf.name_scope(values... | 7991459fc70ccbffcd19af238265023ab58ca6f6 | 50,437 |
from typing import Any
def find_entering_variable(
tableau: npt.NDArray, pivot_row_index: int, non_basic_variables: set
) -> Any:
"""
Finds the non-basic variable which becomes basic after pivoting
Parameters
----------
tableau : array
A tableau corresponding to a vertex of a Polytope... | 70d4641bef7f92d82c6a7f8b141fd5b463005ccd | 50,439 |
def activity_final(self):
"""Find or create a final node in a Activity
Note that while UML allows multiple final nodes, use of this routine assumes a single is sufficient.
:return: FinalNode for Activity
"""
final = [a for a in self.nodes if isinstance(a, FinalNode)]
if not final:
self.... | 9fe7b2041600c8478f13a3a2f1985e72bc22ed2c | 50,440 |
def contar_caracteres(s):
"""
FUNÇÃO QUE CONTA OS CARACTERES DE UMA STRING
:param s: string a ser contada
"""
num_of_caracteres = {}
for caracter in s:
num_of_caracteres[caracter] = (num_of_caracteres.get(caracter, 0) + 1)
return num_of_caracteres | afad48efc5f2f22f5c8e4622836516d3229266c8 | 50,441 |
def parse_symmetric_morlet_single_scale_parameters( parameter_map ):
"""
Parses parameters for the single scale, symmetric Morlet wavelet generator.
Takes a dictionary of (key, string value)'s and casts the values to the
types expected by get_symmetric_morlet_single_scale_transform().
The following... | 4698ee7d36187d5716ceed968cbe05cbe0985b94 | 50,442 |
from typing import Union
from typing import Iterator
from typing import Optional
from typing import List
def keep_protein_class(data: Union[pd.DataFrame, PandasTextFileReader, Iterator], protein_data: pd.DataFrame,
classes: Optional[Union[dict, List[dict]]] = [{'l2': 'Kinase'}, {'l5': 'Adenosin... | 6d0ecc9e6a7fd05b323fe5bc19565b263594e02b | 50,443 |
import types
def load_embeddings(env_config):
"""Attempt to loads user and movie embeddings from a json or pickle file.
Args:
env_config: `EnvConfig` class from movie_lens_simulator.py
Returns:
embedding_dict containing embeddings for movies and users
"""
path = env_config.embeddings_path
embedd... | 1a10a4995d517d591ce6cbbd1a180acc17f31731 | 50,444 |
def find_one_file(directory, pattern):
"""
Use :func:`find_files()` to find a file and make sure a single file is matched.
:param directory: The pathname of the directory to be searched (a string).
:param pattern: The filename pattern to match (a string).
:returns: The matched pathname (a string).
... | 2d3e6fdbcd650af1685b2f05a0098b9d463900ef | 50,445 |
def image_hosting():
"""
图床
"""
# from app.util import file_list_qiniu
# imgs = file_list_qiniu()
page = request.args.get('page',1, type=int)
imgs = Picture.query.order_by(Picture.id.desc()). \
paginate(page, per_page=20, error_out=False)
return render_template('admin/image_hosti... | fb513bba18a492312ad084b84c86ed9380b43156 | 50,446 |
def get_domain_ip(domain):
"""
Get the IP for the domain. Any IP that responded is good enough.
"""
if domain.canonical.ip is not None:
return domain.canonical.ip
if domain.https.ip is not None:
return domain.https.ip
if domain.httpswww.ip is not None:
return domain.http... | 5f16fe7716561059d00ae33c631ae1df711ecc0e | 50,447 |
def create_frame(i):
"""Helper function to create snapshot objects."""
snap = gsd.hoomd.Snapshot()
snap.configuration.step = i + 1
return snap | 395c830fc3121a6292ac08eea7e963445e0f9a58 | 50,448 |
import torch
def BPR_Loss(positive : torch.Tensor, negative : torch.Tensor) -> torch.Tensor:
"""
Given postive and negative examples, compute Bayesian Personalized ranking loss
"""
distances = positive - negative
loss = - torch.sum(torch.log(torch.sigmoid(distances)), 0, keepdim=True)
return ... | 868df180dc0166b47256d64c60928e9759b80e5f | 50,449 |
def gen_segment(curr_img, curr_predictor,
try_bools = [False, False],
out_trk = None):
"""Apply different methods (see try_bools) iteratively to try to segment
a single shot (non-ALC) image. Because image source is not a mosaic,
extent jittering (zooming in and out) is ... | 84e5ef2e270c9c09faafe1d5e51ce7d0a446dc61 | 50,450 |
import urllib
def query(url):
"""Send the query url and return the DOM
Exception is raised if there is errors"""
u = urllib.FancyURLopener(HTTP_PROXY)
usock = u.open(url)
dom = minidom.parse(usock)
usock.close()
errors = dom.getElementsByTagName('Error')
if errors:
e = buildException(errors)
raise e
r... | e12c7e608aa9beba17b5d6a9bfaba39f73b33547 | 50,451 |
def reshape_img(image):
"""
Reshape an image into the form (height, width, channels).
:param image (np.array): Loaded image
:return: reshaped (np.array): Reshaped image
"""
img = []
for i in range(3):
img_c = np.reshape(image[channel * i:channel * (i + 1)], (image_size, image_size)... | 7c2da20262ed84c8dffc6135a0f6638e0ba89a43 | 50,453 |
def set_levels(lst_all, lst_chiln, lng_level):
"""Top down recursive setting of nesting levels"""
lng_next = lng_level + 1
for id_child in lst_chiln:
dct_child = lst_all[id_child]
dct_child[ATT_LEVEL] = lng_level
lst_next = dct_child[ATT_CHILN]
if lst_next:
set_levels(lst_all, lst_next, lng_next)
return... | b3f6f586d5db9aa5458c639234e55f9baeb1e807 | 50,455 |
from tests.test_plugins.threads_plugin import ThreadPlugin
def ThreadPlugin():
"""
:return: thread plugin class
"""
return ThreadPlugin | 79e59657484db2c894ff9cae58af5c933d7a6df7 | 50,456 |
import math
def get_distance(pos_1, pos_2):
"""Get the distance between two point
Args:
pos_1, pos_2: Coordinate tuples for both points.
"""
x1, y1 = pos_1
x2, y2 = pos_2
dx = x1 - x2
dy = y1 - y2
return math.hypot(dx, dy) | 457827af4625c493537c8501c66ebba73d9ce1a1 | 50,457 |
import re
def jsonContentCategories():
"""
Parses the Google Cloud content categories from a local txt file and returns a nested dictionary (ugly, but effective).
Returns:
Dictionary -- Nested dictionary of content categories.
"""
f = open("google_content_categories.txt", "r")
catArr... | 720ddf12e0b3bd443f2b119c9565d516798555f8 | 50,458 |
def makeFigure():
"""
Makes figure 5.
"""
# Get list of axis objects
ax, f = getSetup((10, 10), (4, 3))
figureMaker(ax, *commonAnalyze(list_of_populations, 2), num_lineages=num_lineages)
subplotLabel(ax)
return f | 3880ab2afb3d93c716774742691833c4eaf88170 | 50,459 |
def gauss2D_FIT(xy, x0, y0, sigma_x, sigma_y):
"""Version of gauss2D used for fitting (1 x_data input (xy)
and flattened output). Returns the value of a gaussian at a 2D set of points for the given
standard deviation with maximum normalized to 1.
The Gaussian axes are assumed to be 90 degrees from each ... | 42dc8fb01de967fa0243372ccae4eeaa22e37571 | 50,460 |
def insert_many(sql, *args):
"""
执行SQL语句
:param sql: insert的SQL语句,可含?
:param args: insert的SQL语句所对应的值
:return: 最后插入行的主键ID
"""
return _insert(sql, True, *args) | 311132a144df8da3e74119331eaadc86cd1cfc30 | 50,461 |
def _sub_matches_cl(subs, state_expr, state):
""" Checks whether any of the substitutions in subs will be applied to
state_expr
Arguments:
subs: substitutions in tuple format
state_expr: target symbolic expressions in which substitutions will
be applied
state: target symboli... | 7ceba9a6c0a83251289dec8f27ccbf1558e47dac | 50,462 |
def find_fxn(tu, fxn, call_graph):
"""
Looks up the dictionary associated with the function.
:param tu: The translation unit in which to look for locals functions
:param fxn: The function name
:param call_graph: a object used to store information about each function
:return: the dictionary for t... | e73783b2eddadcbbc9e9eff39073805fc158c34e | 50,466 |
def _prepare_embeddings(h, m):
"""
Combine FCN outputs with segmentation masks to build a batch of
mask-pooled hidden vectors. Represents the calculation of h_{m}
in the first equation in Henaff et al's paper
:h: batch of embeddings; (N,w,h,d)
:m: batch of NORMALIZED segmentation tensors; ... | 9a8f8f77fa4fdaf340978b6c0320a755b5c4b8a7 | 50,467 |
def estimate_mode_width(distribution):
"""Estimate mode and width-at-half-maximum for a 1D distribution.
Parameters
----------
distribution : array of int or float
The input distribution. ``plt.plot(distribution)`` should look
like a histogram.
Returns
-------
mode : int
... | 6ed4370391fa227d31f4330d9afbabb2795fc9d0 | 50,468 |
def agent_hostname_by_id(agent_id):
"""Given a agent_id provides the agent ip"""
for agent in __get_all_agents():
if agent['id'] == agent_id:
return agent['hostname']
return None | 62fc3510790b8b47a17e98f6394b984628f0073b | 50,469 |
def parse_tile_name(name: str):
""" Parse the tile """
match = reTILE.match(name)
if match is None:
return None
groups = match.groupdict() # type: Dict[str, Any]
groups['tile'] = int(groups['tile'])
return groups | 3bd2219fbefb828bfaea77ac6cd1be3947bb9c63 | 50,470 |
import urllib3
import re
import urllib
import json
import time
def query_object_elasticsearch(query_string, item_type="tor"):
"""Return a dict of Elasticsearch results."""
# make an http request to elasticsearch
#pool = urllib3.HTTPSConnectionPool(settings.ELASTICSEARCH_HOST,
# settings.ELASTIC... | b3b75deaaf4e4f393d4374f6f329009035bfe26d | 50,472 |
from typing import List
def article_to_frequency(article: str) -> List[int]:
"""Convert an article or article description to a list of numbers.
:param article: The article or article description
:return: A list of numbers corresponding to the words
"""
numbers: List[int] = [0] * len(common_words)... | 26f2036a3e3e2bf5dedeef6a068b77f33b559108 | 50,473 |
def Date(default=None, validator=None, repr=False, eq=True, order=True, # NOQA
converter=None, label=None, help=None,): # NOQA
"""
A date attribute. It always serializes to an ISO date string.
Behavior is TBD and for now this is exactly a string.
"""
return String(
default=defau... | ed814cdb67953c05eeb066c008c40f6dffaca49e | 50,475 |
def jsonify_item(category_id, item_id):
"""Return an item information of a category in JSON"""
try:
item = db.session.query(Item).filter_by(
category_id=category_id, id=item_id).one()
return jsonify(Item=item.serialize)
except Exception as e:
abort(404) | 6fd07ff2dfab3bccdbdb29a019f95060d7896370 | 50,477 |
from typing import Union
from typing import Tuple
def parse(source: Union[str, bytes], fnam: str = None, errors: Errors = None,
pyversion: Tuple[int, int] = defaults.PYTHON3_VERSION,
custom_typing_module: str = None) -> MypyFile:
"""Parse a source file, without doing any semantic analysis.
... | 34b7c9d4d868d442c3c92bba98f8cf3bca3c2cf8 | 50,478 |
def encode_multipart_formdata(fields, files):
#http://code.activestate.com/recipes/146306/
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance... | 4f4ab117f922bc38b512794f63abfc2c0355921b | 50,479 |
import re
def ParseMaxRevision(revision_list):
"""Returns the max revision from a list of url@revision string."""
revision_re = re.compile(r'.*@(\d+)')
def RevisionKey(revision):
return revision_re.match(revision).group(1)
max_revision = max(revision_list.split(), key=RevisionKey)
return max_revision.... | e40b1faaf10f0c0b7b0d6118bccd7c0de8d1c030 | 50,480 |
from typing import List
def get_resolv_conf_namservers() -> List[str]:
"""Return list of namserver IPs in /etc/resolv.conf."""
result = []
with open("/etc/resolv.conf") as f:
for line in f:
parts = line.lower().split()
if len(parts) >= 2 and parts[0] == 'nameserver':
... | 859b5811d92778458896dc6fdca4043b6072457a | 50,481 |
import csv
import codecs
def import_gloss_csv(request):
"""
Check which objects exist and which not. Then show the user a list of glosses that will be added if user confirms.
Store the glosses to be added into sessions.
"""
glosses_new = []
glosses_exists = []
# Make sure that the session ... | bb8fb5118832178d56dde8a7c7ad2dfed422f076 | 50,482 |
import numpy
def vis_timeslices(vis: Visibility, timeslice='auto') -> int:
""" Calculate number of time slices in a visibility
:param vis: Visibility
:param timeslice: 'auto' or float (seconds)
:return: Number of slices
"""
assert isinstance(vis, Visibility) or isinstance(vis, BlockVisibility... | d9cf407f5a9e8456c7371cb2d3de05a7404e8e86 | 50,484 |
import torch
def alexnet_metapoison(widths=[16, 32, 32, 64, 64], in_channels=3, num_classes=10, batchnorm=False):
"""AlexNet variant as used in MetaPoison."""
def convblock(width_in, width_out):
if batchnorm:
bn = torch.nn.BatchNorm2d(width_out)
else:
bn = torch.nn.Iden... | 40f84a7d434cd68b9f824ee847ea045e4479f5be | 50,485 |
def checksum(message):
"""
Calculate the GDB server protocol checksum of the message.
The GDB server protocol uses a simple modulo 256 sum.
"""
check = 0
for c in message:
check += ord(c)
return check % 256 | bfba144414f26d3b65dc0c102cb7eaa903de780a | 50,487 |
import torch
def sds_bmm_torch(s_t1, d_t2):
"""
bmm (Batch Matrix Matrix) for sparse x dense -> sparse. This function doesn't support gradient.
And sparse tensors cannot accept gradient due to the limitation of torch implementation.
with s_t1.shape = (b, x, s), d_t2.shape = (b, s, y), the output shape... | a17daf9b000d808ab3a3cf18590373480de2d543 | 50,488 |
def parse_report_filter_values(request, reports):
"""Given a dictionary of GET query parameters, return a dictionary mapping
report names to a dictionary of filter values.
Report filter parameters contain a | in the name. For example, request.GET
might be
{
"crash_report|operating_... | 217a7bfdeb65952637774ebefb6ae0ea7a0d991c | 50,490 |
def generate_jwt(payload):
"""Encode given payload to jwt, return encoded jwt, private key, public key
Args:
payload (dict): the payload to be encoded in the jwt
Returns:
Encoded jwt(json), private key (str) used to encode the payload, public key(str) used to encode the payload
"""
... | 17fec33ea1f8c912740d2833132a26921d052578 | 50,491 |
def advantage_returns(rewards, values, gamma, lam):
"""Compute the advantage and returns from rewards and values."""
# GAE-Lambda advantage calculation.
deltas = rewards[:-1] + gamma * values[1:] - values[:-1]
advantages = discount(deltas, gamma * lam)
# Compute rewards-to-go (targets for the value ... | 1cca149bf6a583fd3932ce4cfaad7ef66d6682f6 | 50,492 |
import itertools
def iter_extend(iterable, length, obj=None):
"""Ensure that iterable is the specified length by extending with obj"""
return itertools.islice(itertools.chain(iterable, itertools.repeat(obj)), length) | 1e6a2bdd36b8bcb3202c4472c9e7621eef9edcf1 | 50,493 |
def _ldap_search(cnx, filter_str, attributes, non_unique='raise'):
"""Helper function to perform the actual LDAP search
@param cnx: The LDAP connection object
@param filter_str: The LDAP filter string
@param attributes: The LDAP attributes to fetch. This *must* include self.ldap_username
@param non... | 4153b6f35f8281a2e41f74200d254f468d8bba0b | 50,494 |
import yaml
def read_yaml(filename:str) -> dict:
"""
Return dic from yaml.
Args:
filename: Output file name.
Returns:
dict: Dictionary object.
"""
with open(filename, 'r') as f:
dic = yaml.load(f, Loader=Loader)
return dic | 9260e1640e1ebfeebb2fb14aeebc3abd87f0d919 | 50,495 |
import hashlib
def download(id):
"""Serve the pickle file"""
passwd = hashlib.sha256(ID.encode()).hexdigest()
if id == passwd:
return send_file("model.pickle", as_attachment=True) | 823b3d53b627b7890dd69e36c6e7daeb4f74f650 | 50,496 |
def get_common_prefix(string_1, string_2):
"""Find the largest common prefix of two strings.
Args:
string_1: A string.
string_2: Another string.
Returns:
The longest common prefix of string_1 and string_2.
"""
# If either string_1 or string_2 is the empty string, the common
... | 1b9d0ba5742c30dff4b06ea02cc4a71a228d82a0 | 50,497 |
def get_user_limit(session: Session, group: Group, modifier: int) -> bool:
"""
Comparing number of free seats and number of users in group and
subgroups with parent groups.
:return: False if space is exhausted.
"""
max_seats = get_num_seats(session, group)
num_users = get_num_users(session,... | 0ce0d460f621355cdbfd61cd9f98f0ec2869103e | 50,498 |
def test_get_annotations_no_data(
pandas_series, coordination_args, monkeypatch
):
"""Test coordination of annotation retrieval when no data retrieved for a given protein."""
def mock_get_anno(*args, **kwargs):
protein_data = []
return protein_data
monkeypatch.setattr(get_genbank_annot... | edb05ace156c0852bd2952615bd195caa12610a2 | 50,499 |
import test
def AddDeviceTest() -> bool:
"""Test of adding Devices to a DeviceGraph."""
t = test('AddDeviceTest')
graph = DeviceGraph()
ltd = LibraryTestDevice('ltd')
sub1 = LibraryTestDevice('sub1')
sub2 = LibraryTestDevice('sub2')
sub11 = LibraryTestDevice('sub11')
sub1.add_submodul... | cea4b956de967f27841a853008773c184bcb9992 | 50,500 |
def get_name(scoring):
"""Get name of score.
"""
if not isinstance(scoring, str):
scoring = get_scorer(scoring)._score_func.__name__.replace('_score', '')
return scoring.replace('neg_', '').replace('maximum_', 'max_') | 13bc2be060213392f44f740dc2f959686176066c | 50,501 |
def community_portal_policies_page_data():
"""
This function pulls and returns all data required for the community
portal stories page and returns a json of this information
"""
return json_loader('./database/raw_data/portal/policiesPageData.json') | d16f5c4e2aea136aef76037f032470cbc7330843 | 50,502 |
def retrieve_redcap_events(url, token, max_time=30):
"""Read the list of events from the REDCap instance using the API"""
data = redcap_api_call(url, token, content='event',
fields={}, max_time=max_time)
# print("events: {}".format(data))
return data | 4815a0f5dc147f0c8c742d2db003bd828a5f7f08 | 50,503 |
import torch
from typing import Optional
def global_to_local_space(
points: torch.Tensor,
cam_pose: torch.Tensor,
device: Optional[torch.device] = None,
_validate_args: bool = True
) -> torch.Tensor:
"""Transform points from global space to local space
Args:
points (torch.tensor): points in shape (b,... | bb3d391e361089889bb03929c9cd36a35ebb2da6 | 50,504 |
def quantization_model_or_class_factory(args, *, model=None, cls=None):
"""Return either converted model for quantization or a quantized version of the class passed"""
if model is not None and cls is not None:
raise AttributeError(
"Pass either model or class to be converted for quantization... | 66c0391def8acd79563cddb14f14b8d20e014a6c | 50,505 |
def get_user(user_id):
"""Get user by ID"""
app.logger.info(
'Starting show user id: {} of request: {}'.format(user_id, g.request_id)
)
response = user_schema.dump(UserService().find_or_404(user_id))
app.logger.info(
'Response of show user id: {} with response: {} of request: {}'.f... | 10f7b2cd6f7281d8e44feccb22af3c5d4d38a1e8 | 50,506 |
import numpy
def check_type_force_float(x, name):
"""
If an int is passed, convert it to a float. If some other type is passed,
raise an exception.
"""
if type(x) is int:
return float(x)
elif type(x) is not float and type(x) is not numpy.float64:
raise TypeError("%r should be a... | 23469a7f5aedd2c0ec30969413a31330a7028dfc | 50,507 |
def platform2str(platform: str) -> str:
""" get full platform name """
if platform == "amd":
return "AMD Tahiti 7970"
elif platform == "nvidia":
return "NVIDIA GTX 970"
else:
raise LookupError | 083e38f45db482c9fe6761c719df4bf0f5719256 | 50,508 |
def pdf_single_grid(request: HttpRequest, calendar_id: int):
"""A PDF grid from start date to end date with a given style and size"""
cal = get_object_or_404(models.Calendar, pk=calendar_id)
try:
style_index = int(request.GET.get('style_index', 0))
size_index = int(request.GET.get('layout_... | a732e1af59a808f1a21b5d59c21c5477c50358df | 50,509 |
def enable_tpoint_group(client, name):
"""Enable trace on a specific tpoint group.
Args:
name: trace group name we want to enable in tpoint_group_mask. (for example "bdev").
"""
params = {'name': name}
return client.call('enable_tpoint_group', params) | 3ff809632e3db683792b4c1f686e52f4fddd993e | 50,511 |
def tags_for_talks(conference=None, status=None):
"""
Return the used tags by talks, filtered by conferences and state of the
talk
"""
talks = models.Talk.objects.all().values('id')
if conference:
talks = talks.filter(conference=conference)
if status:
talks = talks.filter(sta... | 160ebbad248331f5771dcce3454dd14c87b14d30 | 50,512 |
from pydeconz import DeconzSession
from unittest.mock import Mock
from unittest.mock import patch
async def setup_gateway(hass, data):
"""Load the deCONZ switch platform."""
loop = Mock()
session = Mock()
config_entry = config_entries.ConfigEntry(
1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG,... | a43f0caab87c0eb4184fe274a42c8cb885739b3c | 50,513 |
def ldl_fft(G):
"""Compute the LDL decomposition of G.
Args:
G: a Gram matrix
Format: FFT
Corresponds to algorithm 8 (LDL) of Falcon's documentation.
"""
deg = len(G[0][0])
dim = len(G)
L = [[[0 for k in range(deg)] for j in range(dim)] for i in range(dim)]
D = [[[0 for k ... | 9261fa6b7bc37da0a1f03aa1adc501f88e015b93 | 50,514 |
def get_time_step_data(data_in, time_step):
""" Sparses data file for time steps specified by user.
Parameters
----------
data_in : Density
Data to be condensed into time steps
time_step : float
Time steps requested.
Returns
-------
data_out : Density
Data in sp... | 59f2cf665d42f6214c19f6f51c6d50d672821bb9 | 50,515 |
def handle_command(command, event):
"""
Executes bot command if the command is known
"""
# Finds and executes the given command, filling in response
for cmd, callback in command_mapping.items():
if command.lower().startswith(cmd):
# command cleanup
command = command.r... | 34ede12a632595d7d50593014e7019dd06dc6163 | 50,516 |
def select_from_context(context: TreeContext, criterion: CriteriaType, reverse: bool=False):
"""Yields all nodes from context which fulfill the criterion."""
return select_from_context_if(context, create_match_function(criterion), reverse) | d2ee05eb0e1f630d6c6ce96661b21bab1cd62a88 | 50,517 |
def combat_batch_correction(data, batch_col, index_cols):
"""
This function corrects processed data for batch effects. For more information visit: https://pypi.org/project/pycombat/
:param data: pandas dataframe with samples as rows and protein identifiers as columns.
:param batch_col: column with the b... | 2c54f1c64d737b03b357201d91e757d39698031c | 50,518 |
def keyfunc(line):
"""Return the key from a TAB-delimited key-value pair."""
return line.partition("\t")[0] | 39737389cd7a9e8046ff00700004b8864a242914 | 50,519 |
from typing import List
from typing import Optional
import logging
def calculate_average_face_encoding(
face_encodings: List[List[np.ndarray]],
) -> Optional[np.ndarray]:
"""
Calculates the average face encodings with numpy.mean() method.
:param face_encodings: List of image face encodings
"""
... | cf0ac7f92a67e734dd3be07aeed95774f8fa384a | 50,520 |
def make_error_extraction_tests(get_messages):
"""
Create a test case class for testing extraction of fields from exceptions.
@param get_messages: Callable that takes an exception instance, returns
all message dictionaries generated by logging it.
@return: ``TestCase`` subclass.
"""
c... | 87546535a18703a3ee49d55ef3e64589564d0048 | 50,521 |
def lambda_handler(event, context):
""" Lambda Handler (webhook via api gateway) """
update = telebot.types.Update.de_json(event["body"])
bot.process_new_updates([update])
return {
"body": "ok",
"statusCode": 200,
"headers": {"Content-Type": "application/json"},
} | 1d3a2d594d8059bc0cae2a2929257ad09ec6e3e5 | 50,522 |
def html_wrap(html_string):
"""Add an html-head-body wrapper around an html string."""
html_prefix="""<html>
<head>
<title>HTML CSS TESTS</title>
<link rel="stylesheet" type="text/css" href="tests/manual html-css tests/html-css.css">
</head>
<body>"""
html_pos... | 8510549f4de1de25ac98361f757210eafdb02631 | 50,523 |
import collections
import time
import tqdm
def onpolicy_trainer(policy,
train_collector,
test_collector,
max_epoch,
step_per_epoch,
collect_per_step,
repeat_per_collect,
e... | dcc6c2bc5b0aeb2a89045dd6260e2f146fa2bc5e | 50,524 |
def split(ary, n):
"""Given an array, and an integer, split the array into n parts"""
result = []
for i in range(0, len(ary), n):
result.append(ary[i: i + n])
return result | 27ae4f06603de17c993656fae9df07b61f333474 | 50,525 |
def get_blog_name(url: str) -> str:
"""get the name of the blog"""
path = urlparse(url).path
if path.endswith("/"):
return path.split("/")[-2] + ".md"
else:
return path.split("/")[-1] + ".md" | bd281fba9fd0709d0967da8fc0201c16e2962b07 | 50,527 |
def fget_preds(subdict, limit_date=False, lcompdate=None, ucompdate=None):
"""
stack predictions over ensemble runs
get predictions and targets from runs
shape: (90, 20729, 3) (n_ensemble_runs, n_windows, H)
limit_date to crop for comparison with cls, esa etc.
"""
# shorter lookbacks have m... | 6c15d7c56c849da79aa027d9c8a842b837e55c8a | 50,528 |
def entity_is_available(hass: HomeAssistant, entity: str):
"""evaluate whether an entity is ready for targeting"""
state = hass.states.get(entity)
if state is None:
return False
elif state.state == STATE_UNAVAILABLE:
return False
elif state.state != STATE_UNKNOWN:
return True... | eeb517f528d13ba886b1ced4c99ca70f3d3110d7 | 50,530 |
def preview_model(request, content_app, content_class, content_id, preview_mode='default',
load_dynamic_element=False):
""" preview_model """
model_class = apps.get_model(content_app, content_class)
form_class = modelform_factory(
model_class, fields=[field.name for field in model_... | 070a8a4196f23a721dcdfdf597cd7bece46f902c | 50,531 |
def is_valid_word_array(words_to_check):
"""
---------------------------------------------------------------------
DESCRIPTION
Checks if the words in the word (string) array are part of the
dictionary.
---------------------------------------------------------------------
PARAMETERS
words... | 4e2fc556b47b56f9fda859b33593c0c06592bb9b | 50,532 |
from operator import invert
def _polydetrend_get_trend(da, *, dim, degree, preserve_mean, kind):
"""Polydetrend, atomic func on 1 group."""
if len(dim) > 1:
da = da.mean(dim[1:])
dim = dim[0]
pfc = da.polyfit(dim=dim, deg=degree)
trend = xr.polyval(coord=da[dim], coeffs=pfc.polyfit_coeffic... | 7a6c02fae18ddcea42828e7cc9fce3f7f110eb6d | 50,533 |
def image_function(f='sin(x)*cos(y)', xmin=-1, xmax=1, ymin=-1, ymax=1, xsteps=100, ysteps=100, p="x,y", g=None, **kwargs):
"""
Plots a 2-d function over the specified range
f takes two inputs and returns one value. Can also
be a string function such as sin... | 4d93dbf5ecaa71b0e6b4b4f9945209a2f16718b4 | 50,534 |
def manager(manager_maker):
""" return an uninitialized AccountManager instance. """
return manager_maker(addid=False) | 7557829687f7368a20fd52b6cba84a1c236b6ed8 | 50,535 |
def tcp_to_udp_data(d):
"""
Trim TCP packet to send it over UDP.
:param d: (bytes) TCP DNS response
:return: (bytes) UDP ready DNS response
"""
d = d[2:]
return d | efdddfe8aaa9443b2fd2c194401708a12a6b2389 | 50,536 |
import types
from typing import Tuple
def coda_duration(
tr: obspy.Trace,
noise: float,
ptype: str,
cfg: types.ModuleType = config
) -> Tuple[float, float]:
"""Measure duration and associate quality control
Args:
tr: time series
noise: noise level
ptype: plo... | 71e9173ddcd33af5335f47c83a9cb7b86948d71e | 50,537 |
def list_smc_files(path):
"""Lists all SMC files in a directory"""
files = util.list_files(path, ".smc.gz")
files.sort(key=get_smc_sample_iter)
return files | edd4199ab1c88cc57c725708d1edefd48f1e41e6 | 50,539 |
import math
def encMethodSave5(file, picture):
"""Save an picture to a file."""
file.writeBytes(bit32.rshift(picture[0], 8),
bit32.band(picture[1], 0xff))
for i in range(2, len(picture), 4):
file.writeBytes(color.to8Bit(picture[i]), color.to8Bit(picture[i+1]), math.floor(p... | 83df364b62312c4d7def5b8f05fa9cb002230875 | 50,540 |
import json
def get_settings(lang, mode):
"""Get the makefile settings."""
schema_json = make_schema(lang, mode)
error = None
try:
settings = json.loads(request.values.get('settings', '{}'))
except:
log.exception("Error in json parsing the settings variable")
error = escap... | 4fd356040d811270ad569314da5d7e24049e2a42 | 50,541 |
import typing
def vectorFactorization(vec: np.ndarray) -> typing.Tuple[np.ndarray, np.ndarray]:
"""I have probably reinvented a wheel. I have searched the Internet and haven't found this kind of factorization.
Factors a vector vec into the product of an "upper-triangular-like" (mostly upper triangular, but with hol... | dafa2fa9452eb56777d29e555ccdaa0ff813c636 | 50,542 |
def random_funfact():
"""Returns random funfact or None."""
if FunFact.objects.published().count():
return FunFact.objects.random()
return None | 296845df7553d3020be42f991f3cd0f6a887db04 | 50,543 |
def combine_results(results_list):
"""
Given different metrics based on the result lists provided.
Inputs:
results_list: dictionary containing the lists of all the results
Returns:
results_overall: dictionary containing the lists of all the results
now with additional perfo... | 0ce31b6f8ed226d9930173aa4cd4b83289b576b1 | 50,544 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.