content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bbox_to_radec_grid(wcs, bbox, tol=1e-7):
"""
Create an ra/dec grid aligned with pixels from a bounding box.
Parameters
----------
wcs : `lsst.afw.geom.SkyWcs`
WCS object
bbox : `lsst.geom.Box2I`
Bounding box
tol : `float`
Tolerance for WCS grid approximation
... | 5f11541dd1c1bbdaffa4fff8048785f511f41757 | 3,628,000 |
def step2(x):
"""Convolution of three step functions."""
y = np.zeros_like(x)
y[x > 0] = 1/2 * x[x > 0]**2
return y | dadfd366ecd1900ed7993b49084b79c0ca10f275 | 3,628,001 |
from typing import Union
from datetime import datetime
from typing import List
from pathlib import Path
def evtx2json(input_path: str, shift: Union[str, datetime], multiprocess: bool = False, chunk_size: int = 500) -> List[dict]:
"""Convert Windows Eventlog to List[dict].
Args:
input_path (str): Inpu... | 677f8927567bbaaa49e47073a08526781e64d6da | 3,628,002 |
import math
def multid_dilution_wrapper(inducers,constructs,fname,avoidedges=[],maxinducer=500,\
wellvol=50,shuffle=False,wellorder="across",mypath=".",start=None):
"""this function contains some helpful pre-sets for doing multiple
inducer sweeps in a 384 well plate.
inducers:
this is ... | d18063c3396d093d0792dbb70b6d968234f2fcca | 3,628,003 |
def matyas(x: np.ndarray):
"""
The Matyas function has no local minima except the global one.
The function is usually evaluated on the square xi ∈ [-10, 10], for all i = 1, 2.
Global minimum at (0, 0)
:param x: 2-dimensional
:return: float
"""
assert x.shape[-1] == 2
x1 = x.T[0]
... | 1e33694a26d0829e49c81691dd45d662d71961f2 | 3,628,004 |
def flatten(array: list):
"""Converts a list of lists into a single list of x elements"""
return [x for row in array for x in row] | 178f8ddb6e4b4887e8c1eb79f32fe51c0cf5fd89 | 3,628,005 |
def slice_sample(x_start, logpdf_target, D, num_samples=1, burn=1, lag=1,
w=1.0, rng=None):
"""Slice samples from the univariate disitrbution logpdf_target.
Parameters
----------
x_start : float
Initial point.
logpdf_target : function(x)
Evaluates the log pdf of target distr... | 8937ddc6bd3e6368c75bb9eb9f65766a2376baf1 | 3,628,006 |
from typing import Dict
import os
def format_object_name(meta: Dict, object_name: str) -> str:
"""
Parameters
----------
metas: Dict
Single Granule metadata JSON response from CMR
object_name: str
Name of object (ex. hdf file, xml file)
Returns
----------
str
Ob... | 6df876ab50467ef3111a8f1fe68f0d4d257d4a6c | 3,628,007 |
def ShortName(url):
"""Returns a shortened version of a URL."""
parsed = urlparse.urlparse(url)
path = parsed.path
hostname = parsed.hostname if parsed.hostname else '?.?.?'
if path != '' and path != '/':
last_path = parsed.path.split('/')[-1]
if len(last_path) < 10:
if len(path) < 10:
r... | 80669ecbe46bdb0adf3f9c9a9ceb35a9a628fc27 | 3,628,008 |
def select_attachment(pattern, cursor):
"""Prompt the user for the attachment that matches the pattern.
Args:
This function takes the same arguments as the find_attachments
function.
Returns:
A (parentItemID, path) pair, None if no matches were found.
"""
attachments = find... | 84ec1b4cb869321eb2d21147cc7576e9d31ce5b3 | 3,628,009 |
def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | a456ce7790232ecf8ea4f6f68109a2023f4f257b | 3,628,010 |
from typing import Union
import pathlib
def log_git(repo_path: Union[pathlib.Path, str], repo_name: str = None):
"""
Use python logging module to log git information
Args:
repo_path (Union[pathlib.Path, str]): path to repo or file inside repository (repository is recursively searched)
"""
... | ca11f8247ca875ff45c477baa3a7ae89dcfdc92c | 3,628,011 |
def datetime_to_absolute_validity(d, tzname='Unknown'):
"""Convert ``d`` to its integer representation"""
n = d.strftime("%y %m %d %H %M %S %z").split(" ")
# compute offset
offset = FixedOffset.from_timezone(n[-1], tzname).offset
# one unit is 15 minutes
s = "%02d" % int(floor(offset.seconds / (... | 2dcf6001bfb84bc87c16f4e6cfda390a56466eb3 | 3,628,012 |
def backward_committor(basis, weights, in_domain, guess, lag, test_basis=None):
"""Estimate the backward committor using DGA.
Parameters
----------
basis : list of (n_frames[i], n_basis) ndarray of float
Basis for estimating the committor. Must be zero outside of the
domain.
weights... | ffec1798c41903e26c84ecb85c15c9a7b075db25 | 3,628,013 |
def get_language_from_request(request, current_page=None):
"""
Return the most obvious language according the request
"""
language = get_language_in_settings(request.REQUEST.get('language', None))
if language is None:
language = getattr(request, 'LANGUAGE_CODE', None)
if language is None... | ae224ba3c4900821b664ba12cd2c5d95b87031b7 | 3,628,014 |
from typing import Tuple
import struct
def process_refund_contract_transaction(contract_transaction_bytes: bytes, delivery_time: int,
funding_value: int, funding_output_script: P2MultiSig_Output, server_keys: ServerKeys,
account_metadata: AccountMetadata, channel_row: ChannelRow) -> Tuple[bytes, bytes... | 95554ca7ba14a0e945e1d4deb45548b5508b5dc5 | 3,628,015 |
def _get_link_url(start_component_revision_dict, end_component_revision_dict):
"""Return link text given a start and end revision. This is used in cases
when revision url is not available."""
url = start_component_revision_dict['url']
if not url:
return None
vcs_viewer = source_mapper.get_vcs_viewer_for_... | 8b7c18c2aa3d58f5b77d56ace86fed2a521f326c | 3,628,016 |
import subprocess
def blastall_available():
"""Returns True if blastall can be run, False otherwise."""
cmd = str(BLASTALL_DEFAULT)
# Can't use check=True, as blastall without arguments returns 1!
try:
result = subprocess.run(
cmd,
shell=False,
check=False,
... | dbea3ce6a425ad7e1d14fb0e0e26df24a995832e | 3,628,017 |
import math
def get_inv_unit(block_index,diff):
"""
given a block index and a 0-indexed layer in that block, returns a unit index.
"""
bottleneck_block_mapping = {1:0,
2:3,
3:7,
4:13}
return bottleneck... | ed6936a81dd8f32f76a27efcf89b8e76d384b008 | 3,628,018 |
from typing import Union
import os
def find_image_any_format(filename: str, folder: str) -> Union[str, None]:
"""Takes a filename and returns an image of any of the supported formats."""
for _format in IMAGES:
image = f"{filename}.{_format}"
image_path = IMAGE_SET.path(filename=image, folder=f... | d65311deaaf8c08730927a66ac0a3016a9dc424a | 3,628,019 |
def dummy_token(db, dummy_app_link):
"""Return a token for the dummy app/user."""
token_string = TOKEN_PREFIX_OAUTH + generate_token()
token = OAuthToken(access_token=token_string, app_user_link=dummy_app_link, scopes=['read:legacy_api', 'read:user'])
token._plaintext_token = token_string
db.session... | 4ef1c7ab09db2a33cf6cfff9c0281603c7e8cb19 | 3,628,020 |
import sys
import os
def get_update_packages():
"""
Return a list of dict about package updates
"""
pkgs = []
apt_pkg.init()
# force apt to build its caches in memory for now to make sure
# that there is no race when the pkgcache file gets re-generated
apt_pkg.config.set("Dir::Cache::... | 24966d55db8e8d9c455fed394595eeba52a766f0 | 3,628,021 |
import sys
def learn_conditional_density(model, xs, ys, ws=None, regularizer=None, val_frac=0.05, step=ss.Adam(a=1.e-4), minibatch=100, patience=20, monitor_every=1, logger=sys.stdout, rng=np.random):
"""
Train model to learn the conditional density p(y|x).
"""
xs = np.asarray(xs, np.float32)
ys ... | eeb6d66eec4e10a26ca1505d9d0a493d8662531f | 3,628,022 |
import subprocess
def _run_with_output(command, cwd="caffe/"):
""" Runs a comand, and displays the output as it is running.
Args:
command: The command to run.
cwd: Directory to run command in.
Returns:
The command output. """
popen = subprocess.Popen(command, stdout=subprocess.PIPE, cwd=cwd)
lin... | 4b0e5b73e6df9226841602048b8ca33ce4026a55 | 3,628,023 |
def powspec_highom(fs, mu, s, kp, km, vr, vt, tr):
"""Return the high-frequency behavior of the power spectrum"""
o = 2*pi*fs
Td = np.log((mu + s - vr) / (mu + s - vt)) + tr
Ppp = (kp*exp(-(kp+km)*tr)+km)/(kp+km)
return r0(locals()) * (1.-Ppp*Ppp*np.exp(-2*kp*(Td-tr)))/(1+Ppp*Ppp*np.exp(-2*kp*(Td-tr... | 6e02a6a930ca326286a8214e132c2ab203ca35f5 | 3,628,024 |
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
result_list = []
for i in range(limit):
id_max_price, max_price = find_max_price(data)
result_list.append(data.pop(id_max_price))
return result_list | e380183071686778244656fbfaeac80630527fd5 | 3,628,025 |
def makeBlock(data):
"""Applies the block tags to text
"""
global appliedstyle
return "%s%s%s" % (appliedstyle['block'][0], data, appliedstyle['block'][1]) | 018f0ec12742241ab3e62b3125e47fc33c2bcadc | 3,628,026 |
def by_key(dct, keys, fill_val=None):
""" dictionary on a set of keys, filling missing entries
"""
return dict(zip(keys, values_by_key(dct, keys, fill_val=fill_val))) | cd069ab90a5a8db26f6191a81f52d352a231efbd | 3,628,027 |
import random
def get_vivo_uri():
"""
Find an unused VIVO URI with the specified VIVO_URI_PREFIX
"""
test_uri = VIVO_URI_PREFIX + 'n' + str(random.randint(1, 9999999999))
query = """
SELECT COUNT(?z) WHERE {
<""" + test_uri + """> ?y ?z
}"""
response = vivo_sparql_query(query)
while int... | d68f3676de24907fb9399e5ac995c0c3963483dd | 3,628,028 |
def imbothat(img, el):
"""
Function to mimic MATLAB's imbothat function
Returns bottom-hat of image
Bottom-hat defined to be the difference between input and
the closing of the image
"""
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, el)
return closing - img | 8c0b51b443169a6feec10b92fecac99d271cdb9a | 3,628,029 |
import numpy
def _downsampling_base(
primary_id_strings, storm_times_unix_sec, target_values, target_name,
class_fraction_dict, test_mode=False):
"""Base for `downsample_for_training` and `downsample_for_non_training`.
The procedure is described below.
[1] Find all storm objects in the h... | 0e5b834e0ca011ad83c3929ad05757c777cfc77a | 3,628,030 |
def liste_erreur(estimation, sol):
"""
Renvoie une liste d'erreurs pour une estimation et un pas donnés.
Paramètres
----------
estimation : estimation calculée pour la résolution de l'équation différentielle
sol : solution exacte
"""
(x,y) = estimation ... | 61a800f1316a153d50e39ce80239ddd4b841f74e | 3,628,031 |
def get_pods_amount(v1: CoreV1Api, namespace) -> int:
"""
Get an amount of pods.
:param v1: CoreV1Api
:param namespace: namespace
:return: int
"""
pods = v1.list_namespaced_pod(namespace)
return 0 if not pods.items else len(pods.items) | f676bc9ec4c2fc48c4ff3c332e4201b6ca591f87 | 3,628,032 |
def create_pod(kube_host, kube_port, namespace, pod_name, image_name,
container_port_list, cmd_list, arg_list):
"""Creates a Kubernetes Pod.
Note that it is generally NOT considered a good practice to directly create
Pods. Typically, the recommendation is to create 'Controllers' to create and
ma... | 1c578c4eec5df0ec37ba687f053d932c37be7186 | 3,628,033 |
import os
import shutil
import zipfile
import glob
def detection(post_id):
""" zipファイル展開 """
file = File.objects.get(pk=post_id)
p_id = post_id % 10
OUT_DIR = os.path.join(
BASE_DIR,
'media',
'images',
str(p_id))
if os.path.exists(OUT_DIR):
shutil.rmtree(OUT... | 01eed17ac8fa3dad87184ba4e2dc90ba7ae339ca | 3,628,034 |
import json
def convert_jupyter_to_databricks(
input_filename: str = "nofile", output_filename: str = "nofile"
):
"""Main function to convert jupyter files to databricks python files.
Args:
input_filename (str, optional): input filename .ipynb. Defaults to "nofile".
output_filename (str, ... | 6a5fc3010a84a4fdbeb817bd57824e99867cb6dc | 3,628,035 |
import warnings
def insul_diamond(pixels, bins,
window=10, ignore_diags=2, balanced=True, norm_by_median=True):
"""
Calculates the insulation score of a Hi-C interaction matrix.
Parameters
----------
pixels : pandas.DataFrame
A table of Hi-C interactions. Must follow the Cooler co... | a2ce240a669789b1beacc443c122b805ac34cb57 | 3,628,036 |
import random
import numpy
def add_frame(dataset):
""" process a dataset consisting of a list of imgs"""
if args.place != 'random':
offset = eval(args.place)
assert type(offset) == tuple and len(offset) == 2
Xs = dataset[0]
newX = []
for (idx, k) in enumerate(Xs):
if args.... | 948e0e09a12f3835b10ba1d5dd4a5720b7477f0f | 3,628,037 |
def floor(x: ndarray) -> ndarray:
"""Returns the floor of the input, element-wise.."""
return _which_np(x).floor(x) | 58eae0a1b0802514041dc445ac246dc0345c3640 | 3,628,038 |
def brightness_classification(ms_image):
"""
Description of brightness_classification
Classifies pixels of image using a simplified version of the method described in:
- http://www.sciencedirect.com/science/article/pii/S0169204617301950
Geometrical rules are not applied.
Args:
... | 2201b0bbd9cff115709fa73c4dda412cc6fdbb75 | 3,628,039 |
def build_lights(cfg):
"""Build lights."""
return LIGHTS.build(cfg) | 7d6bbca9676f78d849b95f81df49e39e36bdb04a | 3,628,040 |
def get_obo(force: bool = False) -> Obo:
"""Get miRBase as OBO."""
version = bioversions.get_version(PREFIX)
return Obo(
ontology=PREFIX,
name="miRBase",
iter_terms=get_terms,
iter_terms_kwargs=dict(version=version, force=force),
typedefs=[from_species, has_mature],
... | 9202600c1e24a2582fadb62269e21a0f30aea1c0 | 3,628,041 |
import token
import requests
def create_invitation(secrets) -> dict:
"""
Create an invitation for an existing share.
"""
subscription_id = secrets["SUBSCRIPTIONID"]
resource_group_name = "rg_crosstenant"
account_name = "kmdatashare"
share_name = "publishershare1"
invitation_name = "inv... | 6be8cb7aa5d5eef2cababb8e9e918fe0de5f16d0 | 3,628,042 |
def allocate_lock():
"""Dummy implementation of _thread.allocate_lock()."""
return LockType() | 2163feff679d8ea7535e2db13b38e44bf6778e0b | 3,628,043 |
import copy
def cropped_thumbnail(instance, field_name, width=None, height=None, scale=None, **kwargs):
"""Cropper"""
thumbnail_options = copy(kwargs)
ratiofield = instance._meta.get_field(field_name)
image = getattr(instance, ratiofield.image_field)
if ratiofield.image_fk_field:
image = g... | 2f33e33e4591bd16291f5411912596ffff578d3e | 3,628,044 |
import math
def find_roots_quadratic(a: float, b: float, c: float) -> set:
"""Return a set containing the solutions to the equation ax^2 + bx + c = 0.
Each solution is a float.
You may ASSUME that:
- a != 0
- (b * b) - (4 * a * c) >= 0
>>> find_roots_quadratic(1, -15, 56) == {8.0, 7.0}
... | 664f3ec213200ac2ed3a1cc4f8001da4331938bc | 3,628,045 |
def reconcile(
column_to_reconcile,
type_id=None,
top_res=1,
property_mapping=None,
reconciliation_endpoint="https://wikidata.reconci.link/en/api",
):
"""
Reconcile a DataFrame column
This is the main function of this package, it takes in a Pandas Series,
that is, a column of a Data... | f43b14df7016714207612e755231ca17515d46a8 | 3,628,046 |
def dilute_mask(mask, dilute_distance=0):
"""Expand mask regions with given distance
mask: image with dim (H, W, C)
"""
if dilute_distance == 0: # no dilution
return mask
background = np.zeros_like(mask)
# left, right, up, down dilute
l_dilute = background.copy()
r_dilute = back... | 94599454e65c1a55c324d99547bd325c268138fb | 3,628,047 |
def with_expected_arguments(args, env={}):
"""Python script that checks its argv and environment."""
arg_string = ', '.join(['"{}"'.format(arg) for arg in args])
return _SCRIPT_WITH_EXPECTED_ARGUMENTS_TEMPLATE.format(arg_string, env) | 8ae6545da4dbc175501e80af277f84e6f9b32498 | 3,628,048 |
import numpy
def createisosurfacemesh(grid, step=None, offset=None, isolevel=None):
"""
This function creates an isosurface from voxel data using the
marching cubes algorithm.
Returns a mesh.
**Parameters:**
`grid` : 3D numpy array containing the voxel data
`step` : voxel sizes ... | 0dbb1bb4a4d468ec3fc4c30366137f0218904067 | 3,628,049 |
import os
import re
def get_property(prop, project):
"""Get certain property from project folder."""
with open(os.path.join(project, '__init__.py')) as f:
result = re.search(r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format(prop),
f.read())
return result.group(1) | 8a0c09d9ce5ee448d648400f66a6b56669871cff | 3,628,050 |
def get_project_cls_by_name(project_name: str) -> tp.Type[bb.Project]:
"""Look up a BenchBuild project by it's name."""
for project_map_key in bb.project.ProjectRegistry.projects:
if not _is_vara_project(project_map_key):
# currently we only support vara provided projects
continu... | 23b346628841cd6de4159cf7ca67db40929b76f8 | 3,628,051 |
def get_next_non_summer_quarter(request):
"""
Return the Term object for the non-summer quarter after the quarter
refered in the current user sesssion.
"""
return get_next_non_summer_term(get_current_quarter(request)) | a3339645813d3835ba33c552ad8ef04fc33fe1fb | 3,628,052 |
def trick_for_mountaincar(state, done, reward, state_):
"""
-1 for each time step, until the goal position of 0.5 is reached.
As with MountainCarContinuous v0, there is no penalty for climbing the left hill,
which upon reached acts as a wall.
state[0] means position: -1.2 ~ 0.6
state[1] veloc... | 7ef703f6df9c1d10a250c18cb85def2702a3378d | 3,628,053 |
def create_optimizer(
learning_rate, num_train_steps,
warmup_steps=0, warmup_proportion=0, lr_decay_power=1.0,
layerwise_lr_decay_power=-1, n_transformer_layers=None):
"""Creates an optimizer and training op."""
global_step = tf.train.get_or_create_global_step()
increment_global_step_op = t... | 03218eb5861388bb5042e8006224a6dddd8b83a2 | 3,628,054 |
def build_cpo_transition_matrix(val):
""" Builds a TransitionMatrix model expression from a Python value.
If active, this method uses the value cache to return the same CpoExpr for the same value.
Args:
val: Value to convert. Iterator or iterators of integers, or existing TransitionMatrix expressi... | eff10fd7cc1a6d7cffb15b1b6589e9a7d9624ec8 | 3,628,055 |
from datetime import datetime
def quarter_to_month(str_date):
"""
Transform string representing year and quarter in date.
Parameters
----------
str_date : string
String representing year (YYYY) and quarter (qq) as YYYYQq.
Returns
-------
date : datetime.date
Transform... | f3cb5fa80df0638c26525fb8f50413a72e125572 | 3,628,056 |
def edge_failure_sampling(failure_scenarios,edge_column):
"""Criteria for selecting failure samples
Parameters
---------
failure_scenarios - Pandas DataFrame of failure scenarios
edge_column - String name of column to select failed edge ID's
Returns
-------
edge_failure_samples - List ... | 91c251241dcde7d457b69b2033a1751b3ae963fd | 3,628,057 |
def basicClusteringProperties(network, clustering):
"""
compute diversity and related properties for the given clustering
adds results to node attributes
"""
if clustering == 'Cluster':
properties = ['InterclusterFraction', 'ClusterDiversity', 'ClusterBridging', 'ClusterCentrality']
else... | bcfed0fb0b6aaf8e7e5d3fb21f212ad165b6ad54 | 3,628,058 |
def deserializer(chain) -> Contract:
"""Set crowdsale end strategy."""
# Create finalizer contract
args = []
contract, hash = chain.provider.deploy_contract('TestBytesDeserializer', deploy_args=args)
return contract | 2db7302256cb7b2d500852ae9012ebf5bf07c04f | 3,628,059 |
def get_payload(fetch_me):
"""Get object from s3, reads underlying http stream, returns bytes.
Args:
fetch_me (dict): Mandatory. Must contain key:
- methodArgs
- Bucket: string. s3 bucket name.
- Key: string. s3 key name.
Returns:
bytes: payload ... | 0a62d0125ea9501591901ce94edc99379d64da1e | 3,628,060 |
from typing import List
def repl_remove_attributes_from_sgr(matchobj, remove: List[str]) -> str:
"""Addapted remove_sequence_from_text function to be used with regex"""
return remove_attributes_from_sgr(matchobj.group(0), remove) | b235361f59565f1095d488d06c4b07a2005a61d4 | 3,628,061 |
def _update_data(entity_id, public_key, sso_url, expires_at):
"""
Update/Create the SAMLProviderData for the given entity ID.
Return value:
False if nothing has changed and existing data's "fetched at" timestamp is just updated.
True if a new record was created. (Either this is a new provide... | 73d05b2531a35b202ea9d365051c53052f836df6 | 3,628,062 |
import time
import random
def my_solver(filename: str) -> str:
"""Dummy solver function.
It does nothing apart from waiting on average 2.5sec
:type filename: object
:Return: the same filename a the input
"""
print("Running my solver")
time.sleep(random.random() * 2)
return filename | 8aac2ebe64e8c3d1596441942e4c9a348c977f8f | 3,628,063 |
def distance_reward_predator(dx, dy, dz):
"""
Returns: Reward = $\exp(-c \cdot d^2)$
"""
distance = np.linalg.norm([dx, dy, dz])
rw = np.exp(-config.reward.coef_distance_reward_predator * distance * distance)
return rw, distance | eb99bfa00746b545ee13f4b3b52203c567744d38 | 3,628,064 |
import os
def load_combo_catalog():
"""Load a union of the user and global catalogs for convenience"""
user_dir = user_data_dir()
global_dir = global_data_dir()
cat_dirs = []
if os.path.isdir(user_dir):
cat_dirs.append(user_dir + '/*.yaml')
cat_dirs.append(user_dir + '/*.yml')
... | 8d0a86a9600b53ca55ccd7f4ac7a048d3e602ecf | 3,628,065 |
def flags_t_v_chan(data, chan, targets, freq_range=None, pol=[0, 1], **plot_kwargs):
"""Waterfall plot of flagged data in channels vs time.
Parameters
----------
data : :class:`np.ndarray`
complex, shape(num_times, num_chans, num_pol)
chan : :class:`np.ndarray`
real, shape(num_chans... | ac8146cd765620918384347cb4933de3439324e7 | 3,628,066 |
import numpy
import copy
def canonical_pruning(X, y, sample_weight, initial_mx_formula,
loss_function,
iterations=100,
n_candidates=100,
n_kept_best=0,
learning_rate=0.1,
regularization=... | 02b7b95638cb25250f36ad6a5ff799238c1230af | 3,628,067 |
import re
def count_arg_nums(method_signature):
"""
Based on the method signature(jni format) to count the arguments number.
:param method_signature: method signature(jni format)
:return: arguments number
"""
arg_signature = re.findall(re.compile(r'\((.*?)\)'), method_signature)[0]
pattern... | 6703653e26ced05baf1a639d93d6435ea8b6ff8e | 3,628,068 |
import netaddr # try to cast to IP Address
def ip_to_net_ent_title_ios(ip_addr):
""" Converts an IP address into an OSI Network Entity Title
suitable for use in IS-IS on IOS.
>>> ip_to_net_ent_title_ios(IPAddress("192.168.19.1"))
'49.1921.6801.9001.00'
"""
try:
ip_words = ip_addr.wor... | 294e1ce7296f7573455de114bd2bf17cbf81b89c | 3,628,069 |
def voiceProgression(key, chordProgression):
"""Voices a chord progression in a specified key using DP.
Follows eighteenth-century voice leading procedures, as guided by the cost
function defined in the `chordCost` and `progressionCost` functions.
Returns a list of four-pitch chords, corresponding to s... | cb989f59a9b51d09903985c8be55b8f034bbff23 | 3,628,070 |
def metade(valor:float, formatado:bool = False):
"""
Retorna a metade do valor que você botou
:param valor: o valor que você quer a metade
:param formatado: Se você quer que o valor estaja formatado para R$
:return: A metade do valor
"""
valor /= 2
if(formatado == True):
valorfo... | df6c3fb48ac68620e5d585361e277503902fe476 | 3,628,071 |
def may_data():
"""
Values of a few transport coefficients calculated with
the closed analytic Fermi-Dirac expressions for the
free electron mass at 300 K. The values assume acoustic
phonon scattering.
Parameters
----------
None
Returns
-------
data : ndarray
| Dime... | 14bfb558c2a75a417979c7b112d000f7bd5084d2 | 3,628,072 |
def and_nominal_group(sentence):
"""
add 'and' between nominal groups separated with nothing
Input=sentence Output=sentence
"""
# init
i = 0
list_nominal_group = our_list = []
while i < len(sentence):
# We start by finding the first nominal g... | f204797743326c6146fb2e363bd3f783a6da7a32 | 3,628,073 |
import base64
import zlib
def decompressData(contentData):
"""
Handles the actual decompression of Base64 data.
Args:
contentData: String of Base64 content
Returns:
contentData: Decompressed content of ASCII printable
"""
decoded = base64.b64decode(contentData)
# IO.Comp... | 98ca474f64f7eed2e87fda1602f21a5cbfe517c7 | 3,628,074 |
def compute_edge_measures(ntwk):
"""
These return edge-based measures
"""
iflogger.info("Computing edge measures:")
measures = {}
# iflogger.info('...Computing google matrix...' #Makes really large networks (500k+ edges))
# measures['google_matrix'] = nx.google_matrix(ntwk)
# iflogger.in... | cc426521836ece0dbaa219fade1bc94a7948b5a7 | 3,628,075 |
def gen_new_axis(x_axis, expr, precision):
"""evaluate lagrange interpolation"""
new_x = np.arange(min(x_axis), max(x_axis), precision)
f = lambdify('x', expr, "numpy")
new_y = f(new_x)
return new_x, new_y | 576f52d2b94098472e8f2ed91cffe3587011949c | 3,628,076 |
from typing import Tuple
def calc_fresnel_coefficients(n1, n2, cos_theta1, cos_theta2 = None) -> Tuple:
"""
Args:
n1: Refractive index in first medium.
n2: Refractive index in second medium
cos_theta1: Cosine of angle of incidence.
Returns:
"""
assert np.all(cos_theta1>=... | df37ddb4dece7ee0f89b1974dfe8093deba50b0c | 3,628,077 |
def _fetch_detailed_dataset(args=None):
"""
Fetch detailed info by crawling the detailed artwork pages, using
the links from the basic dataset.
Parallelized with vislab.utils.distributed.map_through_rq.
"""
basic_df = get_basic_df(args)
print("Fetching detailed Wikipaintings dataset by scr... | 9a2c20f1f39046cfff4402066105b0256803bffd | 3,628,078 |
def crop_image(image):
"""
Crop an image that has a padding of 0 value so that there is no empty
margin. Return the cropped image, and the x, y offsets of the new image
coordinates relative to the uncropped image. If there is no non-zero value
in the image, returns False.
Parameters
-------... | 005e4b5ea79bccfffe04a2ccef3c33df2f29f249 | 3,628,079 |
def create_node_from_server(server):
""" Translate AWS EC2 Instance representation into a Node object.
"""
return Node(
id=server.id,
ip=server.private_ip_address,
extIp=server.public_ip_address,
az=server.placement['AvailabilityZone'],
name="",
state=server_s... | 2406e611c60ed5be9240cc09dec7d85bd7f673a2 | 3,628,080 |
def if_nametoindex(name):
"""
Converts interface name to ifindex
@name - inteface name
@return - ifindex in case of success, else raises exception
"""
ret = libc.if_nametoindex(name)
if not ret:
raise RuntimeError("Invalid Name")
return ret | 04c57a397b2b9f62a90ab6b6e4478a8cfc9e238c | 3,628,081 |
import os
import subprocess
def run_export(export_s3_uri, export_id):
"""Run spark export
Args:
export_s3_uri (str): location of job definition
export_id (str): ID of export job to process
"""
status_uri = "s3://{}/export-statuses/{}".format(
os.getenv("DATA_BUCKET"), export_... | f5e264d71f45f59f35d6345e7654bd976c2f4380 | 3,628,082 |
def gauss_seidel_split(A):
""" split A matrix in additive lower and upper triangular matrices
Args:
A (ndarray): input matrix
Returns:
L (ndarray): lower triangular matrix
U (ndarray): upper triangular matrix (zero diagonal)
"""
L = np.tril(A)
U = np.triu(A)
np.... | 411f38c48540c8072994e3300da6e49c5d57f7e9 | 3,628,083 |
def _define_annuli(angle_list, ann, n_annuli, fwhm, radius_int, annulus_width,
delta_rot, n_segments, verbose, strict=False):
""" Function that defines the annuli geometry using the input parameters.
Returns the parallactic angle threshold, the inner radius and the annulus
center for each... | 8681ec5e94f5779439c6715a56508cf30fe01cad | 3,628,084 |
import torch
import tqdm
import sys
def train(cfg: dict):
""" Train a model for multiple epochs with a given configuration. """
global_seed = cfg.get('global_seed')
if global_seed is not None:
torch.manual_seed(global_seed)
torch.backends.cudnn.deterministic = True
torch.backends.c... | 9be7753917fcf5626bee344917fe0b02967d974e | 3,628,085 |
from HTMLParser import HTMLParser
def get_links_from_html(html_body):
"""
Extract all <a></a> links from html body
:returns: list of dicts with links data
:param html_body:
"""
links = []
class MyHTMLParser(HTMLParser):
def handle_starttag(self, tag, attrs):
self.... | 99a5dd8445e97588d58fda50052ccdbfcea09036 | 3,628,086 |
def adj_to_networkx(graphs):
"""Convert adj matrices to networkx graphs."""
return [nx.from_numpy_array(g) for g in graphs] | 69f05f305f5e34385a02092443b907ecfc375d09 | 3,628,087 |
async def add_datasource(request: Request, call_next):
"""
Attach the data source to the request.state.
"""
# Retrieve the datas ource from query param.
source = data_source(request.query_params.get("source", default="jhu"))
# Abort with 404 if source cannot be found.
if not source:
... | a4624752b3c7a3ede7f7fc564e97a3394350fb9d | 3,628,088 |
from typing import Optional
from typing import List
from typing import Union
from typing import OrderedDict
def summary(
data,
var_names: Optional[List[str]] = None,
fmt: str = "wide",
kind: str = "all",
round_to=None,
include_circ=None,
stat_funcs=None,
extend=True,
credible_inter... | 9d69b4f305a05dcc85f7b02d1e4cef5a80f6a099 | 3,628,089 |
def matrix_multiply(MM):
"""Multiplies a list of matrices: M[0] * M[1] * M[2]..."""
P = MM[0]
for M in MM[1:]:
P = dot(P, M)
return P | d63a9ecad8c951383e9fac4bb35e976972fdd658 | 3,628,090 |
import requests
import html
def urban_lookup(word):
""" returns definitions for a given word from urban dictionary """
resp = requests.get(UD_URL % word)
if resp.ok: # check for 200
doc = html.fromstring(resp.read())
return [d.text for d in doc.xpath('//div[@class="definition"]')]
... | bfba0040c5fbd36570a035abe96d7e2862bb6799 | 3,628,091 |
from typing import List
from typing import Dict
from typing import Optional
from typing import Any
def encode_sequences(
sequences: List[str],
vocab: Dict[str, int],
target_size: Optional[int] = None,
eos: int = -1,
sos: Optional[int] = None,
pad: Optional[int] = None,
**kwargs: Any,
) -> ... | dc0edd5bac8356df6a491efb8a331516573306b5 | 3,628,092 |
def form_columns(form):
"""
:param form: Taken from requests.form
:return: columns: list of slugified column names
labels: dict mapping string labels of special column types
(observed_date, latitude, longitude, location)
to names of columns
"""
labels = {}
... | a3a2fdaa17310c04bb28675f88976cd7283f65a9 | 3,628,093 |
def resolve_bbox_order(bbox, crs, size):
"""
Utility that puts the OGC WMS/WCS BBox in the order specified by the CRS.
"""
crs = pyproj.CRS(crs)
r = 1
if crs.axis_info[0].direction != "north":
r = -1
lat_start, lon_start = bbox[:2][::r]
lat_stop, lon_stop = bbox[2::][::r]
siz... | 13c29fe44b241f262c1c07b144f9592b1649714e | 3,628,094 |
import collections
def _r(val):
"""
Convert val to valid R code
"""
if isinstance(val, str):
# no quoting quote
if val.startswith("quote("):
return val
return '"{0}"'.format(val)
if val is True:
return "TRUE"
if val is False:
return "FALSE"... | 6a6fbcbfd0a32105aa2b2d796525421e9d156d25 | 3,628,095 |
def bin2int(buf):
"""the reverse of int2bin, convert a binary buffer to an integer"""
x = 0
for b in bytearray(buf):
x <<= 8
x |= b
return x | 0c0edd88d7d4157f60641bc05f810184ef56f133 | 3,628,096 |
from vardefunc.noise import decsiz
from vsutil import get_y
from typing import Union
from typing import Tuple
def main() -> Union[vs.VideoNode, Tuple[vs.VideoNode, ...]]:
"""Vapoursynth filtering"""
src = JP_BD.clip_cut
panorama = flt.panner_x(src, JP_BD.workdir.to_str() + r"/assets/ED/FGCBD_NCED1_panora... | b8a2d52e66f42ab23f5e31ea8cf8907d1da6c453 | 3,628,097 |
import base64
import six
def UrlSafeB64Decode(message):
"""wrapper of base64.urlsafe_b64decode.
Helper method to avoid calling six multiple times for preparing b64 strings.
Args:
message: string or binary to decode
Returns:
decoded data in string format.
"""
data = base64.urlsafe_b64decode(six.e... | f675c56f0bbd35661adfbea85135a9434fd7b107 | 3,628,098 |
def crypto_box_open_afternm(ciphertext, nonce, k):
"""
Decrypts and returns the encrypted message ``ciphertext``, using the shared
key ``k`` and the nonce ``nonce``.
:param ciphertext: bytes
:param nonce: bytes
:param k: bytes
:rtype: bytes
"""
if len(nonce) != crypto_box_NONCEBYTES... | 05cdce773ac9537e18661713f491bedafcd2d836 | 3,628,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.