content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pathlib
def stat(path: str):
"""Gets stat of path `path`
e.g
j.sals.fs.stat("/home/rafy/test_dir/test") -> os.stat_result(st_mode=33204, st_ino=795348, st_dev=2049, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1586445434, st_mtime=1586445434, st_ctime=1586445434)
Args:
... | 49bb135af5895247a5114083e0d6abf99ecffc2b | 70,777 |
def create_array(start: int64, end: int64, step: int64) -> ArrayI64:
"""
Function that creates an array that contains elements from start (inclusive) to end (non-inclusve) increasing the given steps
Note: if It is not possible to go from start to end, an empty array will be returned.
For example: create... | c34da8efa683f3cbb5809b99fde97e29c8c3307f | 70,778 |
def fidelity(state, target_state):
""" Compute the fidelity between two states. """
return jnp.abs(state.T.conj() @ target_state) ** 2 | 147a54d19dd043071348359ab88fdc438b0dd51f | 70,779 |
def common_path_prefix(p1, p2):
"""
Return the common leading path between two posix paths and the number of
common path segments.
"""
return common_segments(p1, p2, common_func=common_prefix) | 7269cb78021cb9c13d99ad1eeecf72fde19dfd38 | 70,780 |
def run_scatter_2d(c=1500, dc=150, freq=25, dx=(5, 5), dt=0.0001,
nx=(50, 50),
num_shots=2, num_sources_per_shot=2,
num_receivers_per_shot=2,
propagator=None, prop_kwargs=None, device=None,
dtype=None):
"""Runs run_scatte... | 681ce4c70e954ce9b8a12a16a1a74c5c5b9de4d5 | 70,781 |
def weighted_avg(values, weights):
"""
Compute weighted average of a masked array. Used in computing mean amplitude vs uv from flagged data.
:param values: Input masked array.
:param weights: Input weights.
:return: average, standard_error, standard_deviation
"""
average = np.ma.average(val... | da5c52a6726af40af7b90dc5ed50d1679c49efa0 | 70,783 |
def _compute_range_weights(guide, grid_shape):
"""Computes range weights for the given guide image and grid shape.
Args:
guide: The guide image with shape (h, w).
grid_shape: The grid shape, an array-like containing [gh, gw, gd, gc].
Returns:
An (image_extent, grid_extent) array with the spatial wei... | e5ed284c1f929440a0f96128c5c24e834128e1c1 | 70,784 |
def isActive(level: int):
""" Simple function to check if a logging level is active.
:return: True if active and false otherwise.
note:: Author(s): Mitch """
return activeLevels[level] | 529b46c3d2bbafcb8d156b73ea40545ff7a700b8 | 70,785 |
def orthoFeats(dfX,
varThres=.95):
"""Given a dataframe dfX of features, compute orthofeatures dfP
"""
dfZ = dfX.sub(dfX.mean(), axis=1).div(dfX.std(), axis=1) # standardize
dot = pd.DataFrame(np.dot(dfZ.T, dfZ),
index=dfX.columns, columns=dfX.columns)
eVal, ... | a2d51ade9a44bede86b075ed85ec7fcc5b50d516 | 70,786 |
def commit(repo, msg):
"""
commit all staged files to the current branch
"""
if staged_changes(repo):
return ["No stagged changes to commit..."]
# there are stagged changes that need to be committed
git = ["git", "commit", "-a", "-m", msg]
retval, status = run_command(git, repo)
... | dadee748c5673eeca360d56bbc646d236ea8826d | 70,787 |
def unique_equalityset(C, D, b, af, bf, abs_tol=1e-7, verbose=0):
"""Return equality set E with the following property:
P_E = {x | af x = bf} intersection P
where P is the polytope C x + D y < b
The inequalities have to be satisfied with equality everywhere on
the face defined by af and bf.
"... | 8ea408b6264664ad8381c5cb6063b67eafe0d945 | 70,788 |
def create_pascal_label_colormap():
"""Creates a label colormap used in PASCAL VOC segmentation benchmark.
Returns:
A Colormap for visualizing segmentation results.
"""
colormap = np.zeros((256, 3), dtype=int)
ind = np.arange(256, dtype=int)
for shift in reversed(range(8)):
for channel i... | 584d42ec89c178c573d94a1e3b7e14df7d1b39da | 70,791 |
import cProfile
import time
import pstats
def profile(fn):
"""
Profile the decorated function, storing the profile output in /tmp
Inspired by
https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python
"""
def profiled_fn(*args, **kwargs):
filepath = "/tmp/%s.profile" % fn.__... | aaf1711fefee698ff5456e120dcc06cbb8c22a8f | 70,792 |
from fractions import Fraction
def fractions():
"""Generates instances of fractions.Fraction."""
return tuples(integers(), integers(min_value=1)).map(
lambda t: Fraction(*t)
) | 5afcfa2042a341f0c7a1945033016954127c759d | 70,793 |
def instance_metadata_get(context, instance_uuid):
"""Get all metadata for an instance."""
return IMPL.instance_metadata_get(context, instance_uuid) | 03b1ff55df1d0a947e4b3e40441508f969814cc7 | 70,795 |
from typing import Optional
def _tw_resource(resources: list[Resource]) -> Optional[TWResource]:
"""
Return the TWResource instance, if any, contained in resources,
else return None.
"""
tw_resources = [
resource for resource in resources if isinstance(resource, TWResource)
]
retur... | e199e7e26b96358e39fe13893633fbb3ec6bf61a | 70,796 |
from typing import Dict
def collect_format_types(package_names: str) -> Dict[str, FileTypeFormat]:
"""Finds subclasses of the example_filetype_format.FileTypeFormat from a
list of package names.
Args:
package_names: A list of Python package names as strings.
Returns:
A mapping of cla... | f910af206d2587ce027b21df114d0b512154fae5 | 70,797 |
import hmac
def get_signed_params(params):
"""Sign a url by appending `&_signature=xxxxx` to given params (string or dict).
:param params: String or dict of parameters."""
if not isinstance(params, string_types):
params = urlencode(params)
signature = hmac.new(params)
signature.update(get_secret())
return p... | 90408c6882c36a59d8840e3f699789d594ca05a4 | 70,798 |
def go():
"""used to render classification results"""
# save user input in query
query = request.args.get('query', '')
# use model to predict classification for query
classification_labels = model.predict([query])[0]
classification_results = dict(zip(df.columns[4:], classification_labels))
... | 29921ea0cf7bd928305f8b3096696be11c75234d | 70,799 |
def eval_numerical_gradient_array(f, x, df, h=1e-5):
"""
Evaluate a numeric gradient for a function that accepts a numpy
array and returns a numpy array.
"""
grad = np.zeros_like(x)
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
old... | 62beb1aff8e207c1c9d8e54eb1f4ef2b9427f165 | 70,800 |
from typing import List
def store_files(files: List[int]) -> List[int]:
"""
Sorts elements according to their weighted usage.
@params:
files: 2D array with length and access for file.
The best way to store the files is according to the relation between
the times they'... | ded129d9d3e75050715f21fba047f9b63c678fc5 | 70,801 |
def get_polygonal_mask_data(im, mask_file, check=False, save=True,
msg='click vertices'):
"""
Shows user masks overlayed on given image and asks through a dialog box
if they are acceptable. Returns True for 'yes' and False for 'no'.
"""
maskdat... | 6a356e94df6fd16bac24a800c0ee1ffa381394e4 | 70,802 |
def repository_webhooks_url(namespace, repository):
""" Returns the list of webhooks in a repository. """
return _BASE_URL_V2 % ('repositories/%s/%s/hooks' % (namespace, repository)) | c10e6c048bba5c8d7b7f827773a3d43510e513bd | 70,803 |
def _patched_mocksignature(func, mock=None, skipfirst=False):
"""
Fixes arguments order and support of staticmethods in mock.mocksignature.
"""
static = False
if isinstance(func, staticmethod):
static = True
func = func.__func__
if mock is None:
mock = mock_module.Mock()... | 324a62a082ffa9bca5738541d05cc3f38a55928f | 70,805 |
def graph_fs(X, y, **kwargs):
"""
This function implement the graph structural feature selection algorithm GOSCAR
Objective Function
min_{w} 1/2 ||X*w - y||_F^2 + lambda1 ||w||_1 + lambda2 \sum_{(i,j) \in E} max{|w_i|, |w|_j}
Input:
X: {numpy array}, shape (n_samples, n_features)
... | 80411b500bff2f3cf23be53a5f7e7deaa1101d93 | 70,806 |
def get_fuzzy_ratio_matcher_with_overrides(override_list, override_return):
"""
Returns a `fuzzy_ratio` matcher function with a given `override_list` and `override_return`.Useful for functional programming where we want to pre-specify
those values.
:param override_list:
:param override_return:
:... | 86a905a9628470a2c270c0b4bf897d7218224451 | 70,807 |
import asyncio
def _ensure_coroutine_function(func):
"""Return a coroutine function.
func: either a coroutine function or a regular function
Note a coroutine function is not a coroutine!
"""
if asyncio.iscoroutinefunction(func):
return func
else:
async def coroutine_function(... | e8271691abe4d4b7b965efe561f137adf77f6b4f | 70,808 |
import psutil
import math
def mem_per_core(prefix="G"):
"""Calculate available memory per core"""
conversion = 1e6
if prefix == "G" or prefix == "g":
conversion = 1e6
elif prefix == "M" or prefix == "m":
conversion = 1e3
else:
pass
cores = psutil.cpu_count()
mem = p... | 5b2ba03dc2184efe1c21d35dec98f0f5b6773388 | 70,809 |
import time
def log_once(key):
"""Returns True if this is the "first" call for a given key.
Various logging settings can adjust the definition of "first".
Example:
>>> if log_once("some_key"):
... logger.info("Some verbose logging statement")
"""
global _last_logged
if ... | 871eeecd28b19d0d37891596c00af8c509e7e595 | 70,811 |
def interpolate_value(x, y, t):
"""Find the value of x: y(x) = t."""
if t > max(y) or t < min(y):
raise RuntimeError("t outside of [%f, %f]" % (min(y), max(y)))
for j in range(1, len(x)):
x0 = x[j - 1]
y0 = y[j - 1]
x1 = x[j]
y1 = y[j]
if (y0 - t) * (y1 - ... | cebddb77534a5a09b825fa08c1083c2dc65db5d8 | 70,813 |
def pwd(session, *_):
"""Prints the current directory"""
print(session.env.pwd)
return 0 | 0f63b0483453f30b9fbaf5f561cb8eb90f38e107 | 70,815 |
from Vision.VPE import VisualProgramingEnvironment
def createVision(root=None, interactive=True):
"""
"""
ed = VisualProgramingEnvironment(master=root, name='Vision',
withShell= not interactive)
ed.treeNetpane.configurepane('libtree', size=1)
ed.showLibraries()
... | 93cc9989e0107484d9202b91d87f224625ae3a85 | 70,816 |
def calc_tree_mamount(path,head_name,currency,info,cur_depth):
"""
Return a tuple:
(res_str, multi_amount)
(Recursive)
"""
if not isinstance(info,dict):
# This is a terminal leaf which contains amount of money.
return None,{currency:info}
shallow_keys = list(info.keys())
... | 865e90638846383e1514fbe46e43b6b793753922 | 70,817 |
from typing import Tuple
def decode_python_encoding(source: bytes, pyversion: Tuple[int, int]) -> str:
"""Read the Python file with while obeying PEP-263 encoding detection.
Returns:
A tuple: the source as a string, and the hash calculated from the binary representation.
"""
# check for BOM UTF... | 31f5bdc54baf08418f9347c88fe3b9ccb88eb183 | 70,818 |
import array
def three_point_circle(p1, p2, p3):
"""
Computes the center and radius of a circle from
3 points on its circumference.
:param p1: Point 1
:param p2: Point 2
:param p3: Point 3
:return: center, radius
"""
# Midpoints
a1 = (p1 + p2) / 2.0
a2 = (p2 + p3) / 2.0
... | d7290ae89bc2f706b0577573d7910bb634bd2047 | 70,819 |
def percent_replies(user):
"""
description:
en: Percent of comments that are replies.
de: Prozent der Kommentare, die Antworten gibt.
type: float
valid: probability
"""
return sum(1 if c.get('parent_id', '') else 0 for c in user['comments'])/len(user['comments']) | 2e9f78fa41742cbc9a6d6a692b9acf41200d4146 | 70,821 |
def list_roles(*args):
"""DEPRECATED: Use list"""
return list(*args) | 397cafd85ab863edf08d12ba647bcb670c371eed | 70,822 |
def rescale_js(value: float, deadzone: float, exponential: float = 1.5) -> float:
"""Rescale a joystick input, applying a deadzone and exponential.
Args:
value: the joystick value, in the interval [-1, 1].
deadzone: the deadzone to apply.
exponential: the strength of the exponential to ... | c803eaf94f8bf67d8d376555d095b545f499a653 | 70,823 |
import itertools
def collapse_metrics(metrics):
"""Collapses a list of MetricData objects into a single MetricData object.
Validates that the points are consistent, i.e. have the same set of fields,
and the same start_time, if present.
Assumes that all metrics have the same metric name.
Args:
metrics... | 4274dd84835dc997ef01d888452cca7a60d8320a | 70,824 |
import random
def create_random_peers(HostList, flowsPerHost=1):
"""
Create random iperf peers to generate traffic.
"""
peers = []
for host in HostList:
for i in xrange(flowsPerHost):
peer = random.choice(HostList)
while (peer == host or (host, peer) in peers):
peer = random.choice(HostList)
peer... | 7acfef054e50753c3e74fec563a6b94efa375e75 | 70,825 |
def get_prop_solar(locator, building_names, prop_rc_model, prop_envelope):
"""
Gets the sensible solar gains from calc_Isol_daysim and stores in a dataframe containing building 'Name' and
I_sol (incident solar gains).
:param locator: an InputLocator for locating the input files
:param building_name... | 69ee468e6ed341d2b6c5f99bb991b64c9b7d9900 | 70,826 |
def faster_rcnn_model_builder(type=FasterRCNNType.BASIC, dilation=[1, 1, 1]):
"""
The faster r-cnn model builder.
:param type: FasterRCNNType. The type of model.
:param dilation: Integer. See https://pytorch.org/docs/master/generated/torch.nn.Conv2d.html for further information.
:return: The complete model.
"""
... | ee5bf02cf50fa4775c2431ee1e681ddc6ee44d63 | 70,827 |
def load_buff(buff_id: int) -> 'BeneficialBuff':
"""
Loads a buff from the DB table spells_buffs, whose contents are the following:
entry, name, duration, stat, amount, stat2, amount2,stat3, amount3, comment
1, Heart of a Lion, 5,strength, 10, ... | 81f487787fb346c62e5e3f24a917c41fafee7499 | 70,828 |
def _get_owner(owner_pk: int) -> Owner:
"""returns the owner or raises exception"""
try:
owner = Owner.objects.get(pk=owner_pk)
except Owner.DoesNotExist:
raise Owner.DoesNotExist(
"Requested owner with pk {} does not exist".format(owner_pk)
)
return owner | 583dd08b5ef27c472d7522f48a7a1e1a8c4e7a32 | 70,829 |
def feature_list_and_dict(features):
"""
Assign numerical indices to a global list of features
:param features: iterable of feature names
:return: sorted list of features, dict mapping features to their indices
"""
feature_list = sorted(features)
feature_dict = {feat:i for i, feat in enumera... | 11006cdc4871c339cf3936a1734f012f21d92459 | 70,830 |
def smooth_coeval_gauss(cube, fwhm, nu_axis):
"""
This smooths the slices parallel to the given axis of the cube by Gaussian filter.
Parameters:
cube (numpy array) : The data cube that is to be smoothed.
fwhm (float) : The fwhm of the Gaussian filter.
... | fd1270891e7cde93a0e2e87e1778990970f030cc | 70,831 |
from functools import reduce
def setop2d_variadic_functor(op):
"""Return a variadic version of the function returned by setop2d_functor.
"""
def setop2d_variadic(*args):
return reduce(
setop2d_functor(op),
args
)
return setop2d_variadic | 94ad9d4367245df012961a3b951c82895f0f3fcb | 70,832 |
def getNameRefTag(elem):
"""
Check that the object name exists, if not then create it.
Return a tuple of (name, reference, tag)
"""
tag = etree.QName(elem).localname
name = makeNewName(tag if sname not in elem.attrib else elem.attrib[sname], elem)
ref = elem.get(sreference, name)
return ... | e2f828ff62d70f0c215545ff336201adebdd875e | 70,833 |
def load_weights(network, filename):
"""
Loads a model’s weights
filename is the path of the file that the model should be loaded from
Returns: the loaded model
"""
network.load_weights(filename)
return None | 583003f0232fdfdf06eb172db97d22440877cb53 | 70,834 |
def _get_ad_accounts() -> [adaccount.AdAccount]:
"""Retrieves the ad accounts of the user whose access token was provided and
returns them as a list.
Returns:
A list of ad accounts
"""
system_user = user.User(fbid='me')
ad_accounts = system_user.get_ad_accounts(fields=['account_id',
... | 40df9409192d585d8f58e039447c7829894b5177 | 70,835 |
def preprocessing_fn(inputs):
"""Preprocesses Covertype Dataset.
Scales numerical features and generates vocabularies
and mappings for categorical features.
Args:
inputs: A map from feature keys to raw not-yet-transformed features
Returns:
A map from transformed fe... | e732d011dca42e1f6a1b4c4d602788f6eb4c9d16 | 70,836 |
def idfs(corpus):
""" Compute IDF
Args:
corpus (RDD): input corpus
Returns:
RDD: a RDD of (token, IDF value)
"""
N = corpus.count()
uniqueTokens = corpus.flatMap(lambda (x,y): set(list(y)))
tokenCountPairTuple = uniqueTokens.map(lambda a: (a,1.0))
tokenSumPairTuple = toke... | e0de861dc09d05a0091250e670abd0dffca51460 | 70,837 |
def build_idf_vocab(corpus):
"""Build the inverse document frequency(idf) dictionary
:param corpus: a list of string represent the articles to generate idf dict
:returns: a dict that maps a word to its idf value
:rtype: dict(string, float)
"""
vectorizer = CountVectorizer(vocabulary=None)
... | 5deacd0bdf09f662bd257d31325ecf0f21a911b0 | 70,838 |
def compute_St(data):
"""
Given a dataset, computes the variance matrix of its features.
"""
n_datapoints, n_features = data.shape
# Computing the 'mean image'. A pixel at position (x,y) in this image is the
# mean of all the pixels at position (x,y) of the images in the dataset.
# This cor... | 99f55de9c19f7304136e5737d9acba0e6de4d2fd | 70,839 |
def gridpoints_forecast_url(wfo: str, x: int, y: int) -> str:
"""gridpoint forecast."""
return API_URL + API_GRIDPOINTS_FORECAST.format(wfo, x, y) | da3e47fd141f792ff1423383e8548bd9322e3a7e | 70,840 |
import math
def is_nan(value):
""" Function which identifies the "nan" on empty cells """
try:
return math.isnan(float(value))
except ValueError:
return False | 635136f9d468f072deba93e9c05320de1634f675 | 70,841 |
def grab_selenium(xpath, browser_name=None):
"""
抓取单个信息,
:param xpath: xpath地址,
:param browser_name: 对应浏览器driver,
:return: 单个抓取值,
"""
current_driver = driver_handle(browser_name)
xpath, frame_flag = frame_xpath(current_driver, xpath)
data_info = current_driver.find_element_by_xpath(x... | 9137b96afe899727759cd84b1a60024b4506da6d | 70,842 |
def data():
"""
http://..../[app]/default/data/tables
http://..../[app]/default/data/create/[table]
http://..../[app]/default/data/read/[table]/[id]
http://..../[app]/default/data/update/[table]/[id]
http://..../[app]/default/data/delete/[table]/[id[
http://..../[app]/default/data/select/[ta... | 95b1c34f78b5a3f9d12d039879a259dc6d4e225d | 70,843 |
from pathlib import Path
import toml
def create(config: Path) -> YoonKimCNN:
""" Construct the model from a config file
Args:
config: path the a toml config file
"""
config = toml.load(config)
return YoonKimCNN(Hyperparameters(**config['model'])) | be10c698fabf7dd5f4357a3431bf5351da3f7eff | 70,844 |
def guessLanguageName(text):
"""
Returns the language name. i.e. 'english'
"""
lang = guessLanguage(text)
return _getName(lang) | e1e8d300c338afde8224b6126938e7af6825d5e5 | 70,845 |
def view_report(request, pk):
"""
查看报告
:param request:
:param pk: str or int:报告名称索引
:return:
"""
reports = TestReports.objects.get(id=pk).reports
return render_to_response('view_report.html', {"reports": mark_safe(reports)}) | 24e39142ed90ce8c7361cd5ed23866985813ac47 | 70,846 |
def resnetb_deformable_block(layer_ind, inputs, features, radius, fdim, config, training):
"""
Block performing a resnet bottleneck convolution (1conv > KPconv > 1conv + shortcut)
"""
with tf.variable_scope('conv1'):
w = weight_variable([int(features.shape[1]), fdim // 2])
x = conv_ops.... | 82c9074693e9365161e2151ac226c298e5995b76 | 70,847 |
from typing import Tuple
from pathlib import Path
from typing import Concatenate
def uResNet34(input_size: Tuple = None, weights: Path = None, n_carotage: int = None) -> Model:
"""Definition of the model structure with a ResNet-34 decoder"""
if K.image_data_format() == 'channels_last':
seismic_shape =... | 99ed760944e1ee11c4e7b36ea0bdc67151141851 | 70,848 |
def get_end_time(self):
"""
Returns times when particles exit the system (end of trajectory).
The end time (ns) is given as the time elapsed since the begining
of the simulation and is returned for all trajectories as an ndarray.
Parameters
----------
self : trajectories object
Tra... | 37e770cc45d7c872e0b803d795ff93f58456deff | 70,849 |
def metamodel_to_swagger_type_converter(input_type):
"""
Converts API Metamodel type to their equivalent Swagger type.
A tuple is returned. first value of tuple is main type.
second value of tuple has 'format' information, if available.
"""
input_type = input_type.lower()
if input_type == 'd... | a1f01124546acc3035d3db3329b0194ac65c2f17 | 70,850 |
def provider(function: CallableT) -> CallableT:
"""Decorator for :class:`Module` methods, registering a provider of a type.
>>> class MyModule(Module):
... @provider
... def provide_name(self) -> str:
... return 'Bob'
@provider-decoration implies @inject so you can omit it and things... | ef7f271f9cad6413e6051f28a61d33d1847cfe11 | 70,851 |
def get_address(address_id, token):
"""
Retieve user address
:param address_id:
:param token:
:return:
"""
url = get_url('addresses', address_id)
headers = header_token(token)
return get_call(url, headers=headers) | e651c502438f208aee65346c54cadc8e8c980c12 | 70,852 |
def decrypt_same_row(two_chars, key_table):
"""Description: given that the two characters are in the same row, decrypt
the two characters by taking the letter in key_table to the index to the
left of that letter. If the letter is already at the leftmost character,
wrap around the table and take the righ... | da1fd19cccef48afac40e8381fc7e35aa8dd4fcd | 70,854 |
def is_instance(arg, types, allow_none=False):
"""
>>> is_instance(1, int)
True
>>> is_instance(3.5, float)
True
>>> is_instance('hello', str)
True
>>> is_instance([1, 2, 3], list)
True
>>> is_instance(1, (int, float))
True
>>> is_instance(3.5, (int, float))
True
... | 52149919b010909614c7dc83e189fa3b8a950393 | 70,855 |
def cmp_grade(grade1, grade2):
"""Return 0 for equal grades, 1 if grade1 > grade2, or -1 if grade1 < grade2."""
if grade1 == grade2:
return 0
elif grade1.letter and not grade2.letter:
return 1
elif grade2.letter and not grade1.letter:
return -1
else:
idx1 = grade_orde... | af2a68c657f42cd558cb392f48bccd04b88d1c4a | 70,856 |
def should_hide_from_search(obj) -> bool:
"""Returns true if metadata search hints should not be included."""
return hasattr(obj, _NO_SEARCH_HINTS) | 0940de47e26f96005d099fa97b9eae13def30a8f | 70,857 |
def gere_action(action, espace):
"""fonction qui affiche les options du menu
----------------------------
Entrées : action de type string
objet Espace initialisé
Sorties : l'action est effectuée
"""
if action == "I":
espace.iteration()
iter_affiche(espace)
elif action ==... | 1f436e912b595414d033fad732e888ddba1de11b | 70,858 |
def node_transforms(node):
"""
Returns all transforms nodes of a given node
:param node: str
:return: list(str)
"""
return maya.cmds.listRelatives(node, type='transform') | cea7241ab4d75601c4e2943a1372553e1b38e7ee | 70,860 |
def migrate_value(value):
"""Convert `value` to a new-style value, if necessary and possible.
An "old-style" value is a value that uses any `value` field other than
the `tensor` field. A "new-style" value is a value that uses the
`tensor` field. TensorBoard continues to support old-style values on
... | 38f5cb6a8a787be79f61cac238fa0943b2954c29 | 70,861 |
from typing import Union
from typing import Tuple
def _get_X_y_standard_specification(
series: pd.Series, lags: Union[int, list]
) -> Tuple[pd.DataFrame, pd.Series]:
"""
Returns the matrix with features X and y for the
standard specifcation without constant as described on
page 252.
:param se... | f2922ae0188ad7ebec970257ca710d942ef8f574 | 70,862 |
def get_ground_fare(transport_type):
"""
_ground_fare $1
:entity_type (transport_type)
"""
processed_transport_type, _ = process_entity_string(
transport_type, "transport_type")
sql = "SELECT ground_fare FROM ground_service WHERE transport_type = '%s'" % (
processed_transport_typ... | 751b06586b3ffce29af60dc14406fbae7738f1f9 | 70,863 |
def derivative_2nd(f,x,h):
"""function to calaculate 2nd derivative"""
h = float(h)
func=f(x)
return (f(x+h)-(2*func)+(f(x-h)))/(h*h) | 6c420bf2cf8cff27fb3e1f022d67d62bf38c9631 | 70,864 |
def get_fire_mode(weapon):
"""Returns current fire mode for a weapon."""
return weapon['firemodes'][weapon['firemode']] | 691fc5e9b3ce40e51ab96930086f8d57e5fa6284 | 70,867 |
def cal_mx(train_data,i,feats_dict,template):
"""
Calculate the matrix which is needed in the calculation of forward and
backward probabilities.
Parameters
----------
train_data:List
"train_data" is the same as that used in function "feats_extract()"
in module "feature... | 8279217f78e2118c7e5237a0c73d0e506593dac4 | 70,868 |
def group_create(request, template_name='groups/group_form.html'):
"""
Returns a group form page.
Templates: ``groups/group_form.html``
Context:
form
GroupForm object
"""
if request.method == 'POST':
form = GroupForm(request.POST, request.FILES)
if form.is_va... | 4363c849e34c43fe51f3e43d9a983625382dd7f4 | 70,870 |
def get_object_name(remote, object_id):
"""Return the string name of the scene object with the given ID"""
cmd = mmapi.StoredCommands()
cmd_key = cmd.AppendSceneCommand_GetObjectName(object_id)
remote.runCommand(cmd)
obj_name_vec = mmapi.vectorub()
cmd.GetSceneCommandResult_GetObjectName(cmd_key... | c7822b315291eeb3cc437820734449e4b2916c14 | 70,871 |
def data_to_str(data, contents_ignore_fields, grab_only_fields):
"""
desc: recursively converts all data to a single concatenated string
only works for strings, lists and dicts
"""
c = ""
if type(data) == list:
for d in data:
c += " " + data_to_str(d, contents_ignore_fields, grab_only_fi... | e66bcea4b40f48166bb256b06f8595604e5d8f62 | 70,872 |
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from typing import Dict
from typing import Any
def search(
query_string: str,
index_name: str,
categories: List[str],
language_codes: List[str],
offset: Optional[int] = None,
... | 8aa6ef96b01eb3b2900f4c21833e501d3fb4cd5d | 70,873 |
def is_logged_in():
"""Checks if someone, anyone, is logged in."""
if not USERNAME_COOKIE in session:
return False
user = db.get_db().users.find_one({'_id' : session[USERNAME_COOKIE]})
if not user:
unset()
return False
if not ACCESS_TOKEN_COOKIE in session \
or not ACC... | aad04242f69da31f08b601c0896cb555d344ac7d | 70,874 |
import requests
def get_song_url_list(id: int) -> list:
"""Gets list of urls of songs by an artist
Args:
id: Artist's Genius id
Returns:
list of song urls
"""
# build and send search request to genius api
page = 1
base_url = 'https://api.genius.com'
headers = {'Autho... | 740ed37e9f6903ea52b3c1523f392cc38fbc4442 | 70,877 |
def homogeneous_format(frm, return_length=False):
"""
Determine a struct format from a CPHD format string, requiring that any multiple
parts are all identical.
Parameters
----------
frm : str
return_length : bool
Return the number of elements?
Returns
-------
str
""... | 35c0d51d820414dfe6abc65cc8aaf70771b3c0ab | 70,878 |
def build_wider_omata_encoder_decoder(input_shape, latent_dim, initializer,
info=False, act="elu", dense_act=None):
"""
This encoder-decoder pair currently works for 55 by 42 grids
Args:
input_shape (tuple): Shape tuple of input grids
latent_dim (int): ... | bb97b3172388a115dc1e919deb24c8e86cc6f334 | 70,879 |
from typing import Optional
def extract_clean_data(
adata: AnnData,
obs_mask: str = "clean_cell",
var_mask: str = "clean_gene",
*,
name: Optional[str] = ".clean",
top_level: bool = True,
) -> Optional[AnnData]:
"""
Extract a "clean" subset of the ``adata`` to compute metacells for.
... | 1eac6c6d80503b8e7768d160c6467a842d98e25f | 70,880 |
def part1(input_lines):
"""
You receive a signal directly from the CPU. Because of your recent assistance with jump
instructions, it would like you to compute the result of a series of unusual register
instructions.
Each instruction consists of several parts: the register to modify, whether to incr... | 227b9b5fcb5ffad4a1b0aeca5116239ea20ec682 | 70,881 |
def depth_first_ordering(adjacency, root):
"""Compute depth-first ordering of connected vertices.
Parameters
----------
adjacency : dict
An adjacency dictionary. Each key represents a vertex
and maps to a list of neighboring vertex keys.
root : str
The vertex from which to s... | fcff465cfaa2e3a500e8d177e6b9e78cc66bc21d | 70,882 |
from typing import Union
def on_leave(data: dict, activity: Activity) -> (int, Union[str, None]):
"""
leave a room
:param data: activity streams format, needs actor.id (user id), actor.summary (user name), target.id (room id)
:param activity: the parsed activity, supplied by @pre_process decorator, N... | f493af19407c93755939ab8a7ec0c0a69ba465f3 | 70,883 |
def encode_dxt1(image):
"""Encode a PIL Image into DXT1 (stored in bytearray)."""
pixels = image.load()
# you can access the colours in the image by indexing:
# pixels[x, y]
# => (red, green, blue)
# for example, pixels[0, 0] returns (r, g, b) for the top-left pixel
# for more info, see the ... | 5bc6eae61b57de9e81743e5c72725f7c6f62b34f | 70,884 |
import types
def make_function_type(cffi_func):
"""
Return a Numba type for the given CFFI function pointer.
"""
cffi_type = ffi.typeof(cffi_func)
sig = map_type(cffi_type)
return types.ExternalFunctionPointer(sig, get_pointer=get_pointer) | 69419789c07955ae75c72b246fd96d80e87099cd | 70,885 |
def build_error_response(error=None, code=400, scope=None, description=None, uri=None):
"""
RFC 6750 has a slightly odd way to complain about invalid tokens! This is used in the token authenticator
class to build responses for invalid or missing tokens.
:param error:
One of 'invalid request', '... | 6640914b20e5b50012d54c4fccfb9148837b1de5 | 70,886 |
def get_posts(subreddit_):
"""Gets amount of posts within last hour, upvotes, and number of comments.
Inputs
-----
str: Desired subreddit name.
Returns
------
dict: {'submission(id)': ['score','len(comments)']}
"""
subreddit = reddit.subreddit(subreddit_)
posts = dict()
for ... | 533ec837e575e0af0f0e878c74d8709a2f1f9b34 | 70,887 |
from typing import Optional
from typing import Dict
async def _generate_condition_with_substitutions(generator: ChangeGeneratorModel):
"""
Generates a condition with substitutions if they are needed.
:param generator:
:return:
"""
condition: Optional[Dict] = generator.condition
if isinsta... | b5026063e48014d807deb08bb319ad4733f617df | 70,888 |
import json
def import_users_dump(filepath):
"""
Parse users data stored in the JSON file and load it in user MySQL table
:param filepath: path to JSON file
:returns: an integer representing the number of rows added to the database
if an error occurred or the file wasn't found it returns None
... | 9b0eec48888848d5ba33880b74f2e38c61a19871 | 70,889 |
def read_channel(remote_conn):
"""Handle the PY2/PY3 differences to write data out to the device."""
return remote_conn.read_very_eager().decode('utf-8', 'ignore') | e9fe97ed23657d2f3bb4b55f108a1c2d29d7b2e6 | 70,890 |
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from em... | cc192ade4884028a7f0a14f811c59fda56a278ac | 70,891 |
def rotation_between(v1, v2):
"""Returns a rotation matrix that rotates v2 around the z-axis to match v1."""
angle1 = np.arctan2(v1[1], v1[0])
angle2 = np.arctan2(v2[1], v2[0])
angle = angle1 - angle2
rot = quaternion.as_rotation_matrix(quaternion.from_rotation_vector(np.array([0.0, 0.0, angle])))
... | 6c0a2af1c0cfcefb09f75bd7bc06df6d8f116770 | 70,892 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.