content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def transaction(session: Session, nested: bool = False):
"""Auto transaction commit or rollback. This worked with
``session.autocommit=False`` (the default behavior of ``flask-sqlalchemy``)
or ``session.autocommit=True``.
See more: http://flask-sqlalchemy.pocoo.org/2.3/api/#sessions
Tips:
*... | 65b27a8406157547cb6351c5f339fe404e894996 | 69,000 |
def update_talk_tags(talk, talk_json_data):
""" Updates tags associated to this model instance
"""
tags = []
if "snippet" in talk_json_data:
snippet = talk_json_data["snippet"]
if "tags" in snippet:
tags += snippet["tags"]
for tag in tags:
talk.tags.add(tag)
... | 356bb6d1c25f2ea0499cf9f31768a9090d0f8180 | 69,001 |
def multi_callback_factory(callback_factories, **kwargs):
"""
A :func:`callback_factory` which multiplexes the messages
Parameters
----------
callback_factories : iterable of :func:`callback_factory`
The callback to use to issue the message
Return
------
:func:`multi_callback`
... | 65d052c51768897bb83d138bb27e300c1035e1fb | 69,002 |
def calculadora(x = 1, y = 1):
# Docstring
"""
Calculadora
-----------
Cria um dicionário com as principais operações matemáticas, dado dois números.
args
----
x : int ou float
Primeiro número de entrada
y : int ou float
Segundo número de entrada
re... | 6fad4c8c1d388cb5b77c52d68f63a37070379657 | 69,003 |
def tmp_list_config(tmp_config) -> Config:
"""A temporary config for the list plugin with the cli."""
return tmp_config('default_plugins = ["cli", "list"]') | 0afbe64b31f96d5fbeb2131a3785d920fcab594c | 69,004 |
def center2corner(center):
""" convert (cx, cy, w, h) to (x1, y1, x2, y2)
Args:
center: Center or np.array (4 * N)
Return:
center or np.array (4 * N)
"""
if isinstance(center, Center):
x, y, w, h = center
return Corner(x - w * 0.5, y - h * 0.5, x + w * 0.5, y + h * 0.... | 18dcf614a4115e8cab26e31bfecde5b623ef454d | 69,005 |
from typing import Optional
def log_softmax(tensor: MPCTensor, dim: Optional[int] = None) -> MPCTensor:
"""Applies a softmax followed by a logarithm.
While mathematically equivalent to log(softmax(x)), doing these two
operations separately is slower, and numerically unstable. This function
uses an al... | 2061b3ffac043a498661eda035f38eb68a3fd308 | 69,006 |
def unmold_mask_x(mask, bbox, image_shape):
"""Converts a mask generated by the neural network into a format similar
to its original shape.
mask: [height, width] of type float. A small, typically 28x28 mask.
bbox: [y1, x1, y2, x2]. The box to fit the mask in.
Returns a binary mask with the same siz... | 75a344e92f549db147e5879c00caa4c1ab6051a6 | 69,007 |
def broadening(f,dm,model="B",dalpha=0):
"""
Pulse broadeing due to interstellar scattering
The model is taken from Bhat et al., Ap.J. 605, 759 (2004), eqn. 7.
The coefficients, a = -6.46, b = 0.154, and c = 1.07, are only slightly
different from those of Cordes & Lazio (2003), a = -6.59, b = 0.129, and
c =... | f940f56f6fd5786adc839566f14bbf821f7e504b | 69,008 |
def get_queue_cluster_config(cluster_name, cluster_type):
"""
获取队列集群信息
:param cluster_name: 集群名称
:param cluster_type: 集群类型(kafka/pulsar)
:return: 队列集群信息
"""
try:
return QueueClusterConfig.objects.get(cluster_name=cluster_name, cluster_type=cluster_type)
except QueueClusterConfig.... | 474141a542abcf662d4582505ae2ac995d28f9fb | 69,009 |
def piano_roll_to_midi(piece):
"""
piece is a an array of shape (T, 4) for some T.
The (i,j)th entry of the array is the midi pitch of the jth voice at time i. It's an integer in range(128).
outputs a mido object mid that you can convert to a midi file by called its .save() method
"""
piece = np.concatenate... | 740174c67319e0bb0f8dca581cb4d301eed331cf | 69,010 |
def choose_coords():
"""
Choose a random latitude and longitude within certain ranges.
Returns: tuple(float, float)
"""
for i in range(10):
lat, lon = random_coords()
if is_land(lat, lon, ZOOM):
logger.info(
f"Took {i + 1} attempt(s) to find land ({round(l... | c1878dd3c3fc67ccfa363e2ef6d81483fc80befa | 69,011 |
def get_id_or_about(element):
"""Return the ID or the about associated with an element"""
return element.attrib.get(nselem('rdf', 'ID')) or \
element.attrib.get(nselem('rdf', 'about')) | 8f2ac9cdbd22b8f03982baccda781d6a782a8d4a | 69,012 |
import os
def compile(input_path, output_path, digest_blacklist_filter, gzip_files, pairs):
"""
Generate md5 tagged static files that are also compressed with gzip.
:param input_path: The source path of your static files
:type input_path: str
:param output_path: The destination path of your stati... | a3fc059e49881d3b9e698d7d7d58c64a7f32e4f9 | 69,013 |
def custom_jwt_validation(token, leeway=0, exclude=None):
""" perform custom jwt validation
leeway number of seconds of skew that is allowed
exclude is a list of claims to exclude from validation.
jose jwt defaults to:
defaults = {
'verify_signature': True,
... | 353f12bf5e73765f65b247afa1b63f217ad63163 | 69,014 |
def fluidsynth(sequence, sample_rate, sf2_path=None):
"""Synthesizes audio from a music_pb2.NoteSequence using FluidSynth.
This uses the pretty_midi `fluidsynth` method. In order to use this synth,
you must have FluidSynth and pyFluidSynth installed.
Args:
sequence: A music_pb2.NoteSequence to synthesize.... | 8ed386fa76e2ba3387fdfaea4e9c370b2a9c9886 | 69,015 |
def parse(place_id):
"""
Accepts a place_id and returns the data expected by our target forms
"""
place_name = place_id[3:].upper()
place_id = LOOKUP_BY_NAME[place_name]
return {
'name': place_name,
'id': place_id,
} | 6d251a8e26c8cdd8c499d341f76d38fa7de793b0 | 69,016 |
def get_query_list():
"""
Form a query list for all the queries above
"""
query_list = []
for index in range(1, 11):
eval("query_list.append(query_" + str(index) + ")")
# end for
return query_list
pass | ee0d19d8dc04bb8b7b48c0a3dcf35689a5adba23 | 69,017 |
def _call_sampler(sample_n_fn, sample_shape, name=None):
"""Reshapes vector of samples."""
with tf.name_scope(name, "call_sampler", values=[sample_shape]):
sample_shape = tf.convert_to_tensor(
sample_shape, dtype=tf.int32, name="sample_shape")
# Ensure sample_shape is a vector (vs just a scalar).
... | 0ae9e0c2b5e4193335e7bd4567db88a609c194d2 | 69,018 |
def getS3bands(
in_file, coords, band_names, errorfile, s3_instrument, slstr_res
):
"""Extract data from Sentinel-3 bands.
Read the input S3 file and extract data from a list of given bands for the
coordinates (in a provided list) located within the scene.
Args:
in_file (str): Path to a S3... | 96a7ccdedb805be03e5e9ebd8bc0373f3e6bb2f2 | 69,019 |
def Radius(cosx, cosy, cosz, psi0, r, q, qp1by2om2):
"""
>>>Radius(-1., 0., 0., 5454., 0.14, 56., 57./2)
"""
logger.log(9, "start")
code = """
double x, y, z, rc2, rc, rx, rx3, psi, dpsi, dpsidx, dpsidy, dpsidz, dpsidr, dr;
#line 100
//std::cout << sizeof(r) << std::endl;
#line 110
... | 008d667c6224ce9f57964c31f677e3a72b2118dc | 69,020 |
import re
def get_volname_from_vmdk_path(vmdk_path):
"""Returns the volume name from a full vmdk path.
"""
match = re.search(DATASTORE_PATH_REGEXP, vmdk_path)
_, path = match.groups()
vmdk = path.split("/")[-1]
return strip_vmdk_extension(vmdk) | 5c11f9855309f6e07a4a05df5a1e8742f17425c6 | 69,021 |
def convert_constraints_to_rosmsg(constraints, header):
"""Convert COMPAS FAB constraints into ROS Messages."""
if not constraints:
return None
ros_constraints = Constraints()
for c in constraints:
if c.type == c.JOINT:
ros_constraints.joint_constraints.append(
... | c713679eadcf8535524e798a7067ba8dbe2fb010 | 69,022 |
def defined(interp, name):
""" Checks whether a given named constant exists"""
return interp.space.newbool(_lookup_constant(interp, name) is not None) | 83e256f4aa10f503c75f3bdbdfa37e57bac738e9 | 69,023 |
import pathlib
import os
import shutil
def copyFile(srcFilePath, destDir):
"""Copy given local source file to given destination directory (possibly on GCS or local path)
Args:
srcFilePath (str): local source file path
destDir (str): destination file path (local or GCS)
"""
parsedPath ... | 438b1513a568fc8970a8a6c6fbe344e2985b8cf8 | 69,024 |
def line(
df,
x=None,
y="value",
order=None,
legend=None,
title=True,
color=None,
marker=None,
linestyle=None,
fill_between=None,
final_ranges=None,
rm_legend_label=[],
ax=None,
cmap=None,
**kwargs,
):
"""Plot data as lines with or without markers.
Pa... | 3ef4e7e561757dfd4eb4f9702192c11bb10ae94e | 69,025 |
import tests
def exdocobj():
""" Trace support module class """
if putil.exh.get_exh_obj():
putil.exh.del_exh_obj()
def multi_level_write():
"""
Test that multiple calls to the same function with different hierarchy
levels get correctly aggregated
"""
tests.... | ef2c81ae9b0c30bc65e039d43c055b598ad586b4 | 69,026 |
def _load_fit_file(fname):
"""
Returns values as `name: list of values` pairs and dict of `name: unit name`
for the FIT file with the given filename.
Parameters
----------
fname : str
Fully resolved filename of the FIT file to load.
Returns
-------
values : dict
Dic... | bbe9f525568cbf44c9e6590c577647a2c723836e | 69,027 |
def poissonModel(gamma, mesh=None, nx=36, ny=36, width=1):
"""
`gamma` is scaling parameter for left boundary condition
`n_x` and `n_y` are the number of elements for the horizontal/vertical axes of the mesh
"""
# Create mesh and define function space
if mesh is None: mesh = fin.RectangleMesh(fi... | a1679d72733edfcb6f5298c83d79b9aceadaa787 | 69,028 |
def cross_corr(image_1, image_2, hybridizer=0, normal=True):
"""
Normalized Correlation, allowing for hybridization
with cross correlation being the default output if
no hybridization parameter is given
Parameters
----------
image_1: ndarray
First image
image_2: ndarra... | 782791186165bc222722c9cbd7d21a788f258d3d | 69,029 |
def calc_image_entropy_HLS(image):
"""
:param image:
:return:
"""
image_HLS = cv2.cvtColor(image, cv2.COLOR_BGR2HLS)
size = image_HLS.shape
result = []
for i in range(size[len(size) - 1]):
hist = cv2.calcHist([image_HLS], [i], None, [256], [0, 256])
hist = hist[hist > 0]
... | 54a81e768b825bf8250345104881a7322acad6a6 | 69,030 |
def batch_check_user_perm(dataset_list, object_type, request, action_type="query_data"):
"""批量校验用户与对象权限"""
username = request.user.username
object_type = "{}.{}".format(object_type, action_type)
permissions_list = [
{"user_id": username, "action_id": object_type, "object_id": each_dataset} for e... | 2a6c86321eaeec3695fa3a756c31a8361f0ee368 | 69,031 |
from typing import List
from typing import Tuple
def get_ops_and_inputs_by_name_or_regex(
var_names: List[str],
graph: tf_compat.Graph = None,
) -> List[Tuple[tf_compat.Operation, tf_compat.Tensor]]:
"""
Get tuples of operations and the inputs for inputs of operations that match
a regex pattern in... | 912083e1625299ce90d9b3801cc44cf7ebc2e312 | 69,032 |
def random_binomial() -> float:
"""
Creates a random number between -1 and 1 where the numbers close
to 0 are more likely to appear
Returns:
rand_num: random number between -1 and 1
"""
rand_num = np.random.rand() - np.random.rand()
return rand_num | b5491cc6ac931940bd9eb84ff4c3a17bb2c6efba | 69,033 |
def image_upload_view(request):
"""Process images uploaded by users"""
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# Get the current instance object to display in the template
img_obj = form.instan... | aad28e1cca467eed830cb3fe399c6c74ff2dea7b | 69,034 |
import requests
import random
from bs4 import BeautifulSoup
import time
def cms_detct(url, proxy_list):
"""
This method detect the cms of the url
:param url: the pre-process url, a String. example: www.shore-lines.co.uk
:return: A string, One of the following: "Magento", "WordPress", "PrestaShop"
... | 11d267621b449c201cf368d0aac7ff26b67cd7d6 | 69,035 |
def get_iteration_syslist(system_node_list, system_name_list):
"""
Takes a list of system nodes and system names and
returns.
1. List of system names with iter=yes
2. List of system nodes with iter=yes
"""
iteration_sysnamelist = []
iteration_sysnodelist = []
for i in range(0, len(s... | 9745e52151224aa84c5310592d49db3a980045e9 | 69,036 |
def _icrsFromAppGeo(ra, dec, epoch=2000.0, mjd=None):
"""
Convert the apparent geocentric position in (RA, Dec) to
the mean position in the International Celestial Reference
System (ICRS)
This method undoes the effects of precession, annual aberration,
and nutation. It is meant for mapping poi... | b87b0c13864d51fdef8a6dcdeeeae656d26c0d40 | 69,037 |
def check_age(observation):
"""
Validates that observation contains valid age value
Returns:
- assertion value: True if age is valid, False otherwise
- error message: empty if age is valid, False otherwise
"""
age = observation.get("SubjectAge")
if... | 4705cf9c2dca40a67c1944a12e832d503dcf7f92 | 69,038 |
def getseason_pm5(dat, ystart, yend, season):
""" Pick out seasons +/- 5 days """
dpm = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
mondaystr = dat.indexes['time'].strftime('%Y-%m-%d')
nyears = yend - ystart + 1
if (season == 'DJF'):
ndays = dpm[11]+dpm[0]+dpm[1]+10
indices... | 555572cf5e052823cde17417e8a92cd3043bd11a | 69,039 |
import logging
def kurtosis(channelLabel, coefs, logger):
""" """
logger = logging.getLogger(__name__)
coefsNoise = []
for coef in coefs:
numCoef = coef.shape[-1]
std = np.std(coef)
mean = np.mean(coef)
kurt = np.sum((coef - mean)**4) / (numCoef * std**4) - 3
t... | 0818657c79bfa1fa8caf5975d68cba17fad74cf5 | 69,040 |
def open4csv(fname, mode):
""" Open filename `fname` for CSV IO in read or write `mode`
Parameters
----------
fname : str
filename to open
mode : {'r', 'w'}
Mode to open file. Don't specify binary or text modes; we need to
chose these according to python version.
Retur... | 0dd7628458fdb56351c690d6ac7de20e175b7fa5 | 69,041 |
def parse_references_plus_json(data):
""" Function which parses the references_plus json and returns a pandas dataframe of the
results.
Solr Field definition shown below:
<!-- REFS file fields: cited paper-->
<field name="annotation" type="string" indexed="true" stored="true" multiValued="false"/>... | f471a1ecff375e3c0218605e12686dbd9514c54b | 69,042 |
def h1(*text, **kwargs):
"""Return a header 1"""
return tydoc().h1(*text, **kwargs) | 7ee90c0fe832c8ca9e0d0285d7e5cad4b28cf3f5 | 69,043 |
def _has_initializers_setter(value, owning_component=None, context=None):
"""
Assign has_initializers status to Component and any of its owners up the hierarchy.
"""
if value:
# only update owner's attribute if setting to True, because there may be
# other children that have initializers... | 3dbbcf441016a3b7f4c75b946cb5683ad732b45f | 69,044 |
def _initialize_referenced(model_class, attribute):
"""
Adds a property to the target of a reference field that
returns the list of associated objects.
"""
# this should be a descriptor
def _related_objects(self):
return (model_class.objects
.filter(**{attribute.attname: ... | d30c6b929bff136b8175ddf82da645bafa0537b0 | 69,045 |
import hashlib
def sha1(data):
"""
Return the sha1 of "data".
Arguments:
data (bytes): Data.
Returns:
str: Hex encoded.
"""
return _checksum(hashlib.sha1, data) | 88a5373cc20f26e93557160d305ba170357cc059 | 69,046 |
def utc_to_server(dt):
"""Convert the given UTC datetime to the server's TZ."""
server_tz = get_timezone(config.DEFAULT_TIMEZONE)
return dt.astimezone(server_tz) | 867572d80ee9759d56454b92f4e82859ab0fedc6 | 69,047 |
from typing import List
from typing import Tuple
import os
import re
def group_fastqs(fastqs: List[str]) -> List[Tuple[List[str], str]]:
"""Group FASTQs based on common base filename
For example, if you have 2 FASTQs:
- reads_1.fastq
- reads_2.fastq
The common name would be `reads` and the file... | 99c9bb6e23d2611fc2b6956077fd77f3d1aa7b57 | 69,048 |
def nearst_planck(dt: float, dx: float, rho: np.ndarray, phi: np.ndarray, coefs: Params) -> np.ndarray:
""" solve the Nearst-Planck equation one step """
q = np.copy(rho)
for idx in range(1, len(rho)-1):
dif = (rho[idx+1] + rho[idx-1] - 2 * rho[idx]) * dt / dx**2
adv = coefs.beta * 0.25 * (p... | 2c35581112e7d023dfadcf7130265b9ae54b21a2 | 69,049 |
import json
async def beacon_post_region(request):
"""Find datasets using POST endpoint."""
db_pool = request.app['pool']
method, processed_request = await parse_request_object(request)
LOG.info(f"This is the {method} processed request: {processed_request}")
if not processed_request.get("end"):
... | 35d41c84ae2fdccf665667400afd3c4699817dc0 | 69,050 |
import os
import json
def arguments(path="/run/osbuild/api/osbuild"):
"""Retrieve the input arguments that were supplied to API"""
with jsoncomm.Socket.new_client(path) as client:
req = {"method": "get-arguments"}
client.send(req)
msg, fds, _ = client.recv()
assert msg["type"] ... | 464549b307d6bbd3454d9d5f66c9c040c3561ebe | 69,051 |
def getInt(node, prop):
"""Get an int property."""
propertyName = '{node}.{prop}'.format(node=node, prop=prop)
return rv.commands.getIntProperty(propertyName, 0, 1)[0] | 83f452905e8c2d5e216e4677cf44de923727ff39 | 69,052 |
def _promote_vec(v):
"""Promote vectors to their quaternion representation."""
return np.concatenate((np.zeros(v.shape[:-1] + (1,)), v), axis=-1) | 6f5950d3e9da070c88e17305903a2d05558a44c1 | 69,053 |
def get_pg_data(cursor, table):
"""Return data from table in postgresql database."""
col_str = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE "
col_str += "TABLE_NAME = '" + table + "';"
cursor.execute(col_str)
col_names = pd.DataFrame(cursor.fetchall())
sql_str = "SELECT * FROM " + ... | ad47316059659f97617e8a2e78772cfeda27164e | 69,054 |
def expected_value(beta, B):
"""Return the (symbolic) expected value of the phase-type distribution.
Args:
beta (SymPy dx1-matrix): initial distribution vector
B (SymPy dxd-matrix): transition rate matrix
Returns:
SymPy expression:
expected value of PH(:math:`\\bet... | c4bc6d7e302aa62674b92e21a45834e05646ec97 | 69,055 |
from typing import Any
def is_dynamo_value(value: Any) -> bool:
"""Returns True if the value is a Dynamo-formatted value"""
if not isinstance(value, dict) or len(value) != 1:
return False
subkey = next(iter(value.keys()))
return subkey in TYPES_REV | e3d29ace6666c59d36a307755a48d7bb5b21513a | 69,056 |
def move_by_month(month, offset):
"""Get the month with given offset raletive to current month."""
return (((month - 1) + offset) % 12) + 1 | 38229d5a45b4643dfeb64e0e311949b9e26625ef | 69,057 |
def last(element):
"""
A wrapper around element[-1].
params:
element: an element that implements __getitem__
"""
return element[-1] | b299c503a00c45463c4db2e0f0f9afba0cfd2727 | 69,058 |
def is_image_file(filename):
"""Checks if a file is an image.
Arguments:
filename {str} -- File path.
Returns:
bool -- True if the path is PNG or JPG image.
"""
return any(filename.endswith(extension) for extension in [".png", ".jpg", ".jpeg"]) | d2971a57cd4fda456384f1e2f839dc32b3c897a6 | 69,059 |
def c_ctrl_rr(c_ctrl_params):
"""DASSH RoddedRegion object for conceptual control asm"""
flowrate = 1.0
rr = make_rodded_region_fixture('ctrl_rr', c_ctrl_params[0],
c_ctrl_params[1], flowrate)
return activate_rodded_region(rr, 623.15) | f06dcc94646124678cee851cd05e9d67fb4620e2 | 69,060 |
def cu2ho(cu):
"""
Cubochoric vector to homochoric vector.
References
----------
D. Roşca et al., Modelling and Simulation in Materials Science and Engineering 22:075013, 2014
https://doi.org/10.1088/0965-0393/22/7/075013
"""
with np.errstate(invalid='ignore',divide='ignore'):
... | 00511889e5bc0838dd425d8d9b1b6477021e941c | 69,061 |
def delete_singleton_axis( mv, vid=None ):
"""If mv depends on an axis with just one value, create a copy of mv without that axis, and
without the corresponding data dimension. Normally this happens when time has been averaged
out, but there is still a one-valued time axis left (thus one would normally use... | 8d9d180578e5e2aa9db8f2746b1bf1a8697f5210 | 69,062 |
def find_install_execution_to_resume(deployment_id):
"""
Find the last install execution to resume.
:param deployment_id:
:return:
"""
executions = executions_list(deployment_id)
try:
# Get the last install execution
ex = [e for e in executions
if 'install' == e... | 247b764ff0e0f3e09444e8722c70c22216b424ac | 69,063 |
import json
def process_car_control_msg(message):
"""Process the car control msg.
Args:
message (str): The message to process for car control.
Raises:
GenericNonFatalException: If processing message has some problem,
it's not fatal and we ignore it and c... | 67609a1b5714600c2e820e3638d57b705136dfce | 69,064 |
def solve_0dfd9992(x):
"""
Main function to solve the task. Explanation same as in description
I/P : Problem grid (2D Numpy array)
O/P : Solved grid with required values
"""
# Creating a copy of input grid to work on it
sol = x.copy()
# Creating a transpose grid to work on colum... | 3b02fc394bc8f4a93dca4a1404343809a1e2a3e6 | 69,065 |
async def area_list(
db=Depends(get_db),
name:str = None,
):
"""
Get all areas
"""
areas = await search_area(db,name)
return areas | 6a78d95e03176a301df04cf0bb64e18fe4a2afec | 69,066 |
def make_00a8(pc):
"""キャラクターマップ通知"""
return pack_int(pc.map_id) | e0d8fa6974cdd96f2e30e110b16829ce81f491c0 | 69,067 |
def lmAssociation(X, localLandmarks):
""" Return two lists of new and re-observed landmarks.
Landmarks are associated using a nearest-neighbor approach.
localLandmarks is the list of landmarks observed.
X is a StateMatrix object.
"""
newLandmarkds, reobservedLandmark = [], []
count = 0
... | e0dbcc6634d98d2dc4d27cb34380944f8875e9ec | 69,068 |
import re
import os
def delete_conflicts(root=None, config_only=False, force=False):
"""Delete all files with conflicted filenames."""
root = root or find_root()
log.info("%s conflicted files...", 'Deleting' if force else 'Displaying')
pattern = CONFLICT_CONFIG if config_only else CONFLICT_ANY
lo... | a58311e47a19dce16bbc287cc7c1aba8bd56800a | 69,069 |
def get_bucket_credentials(bucket_id):
"""Get S3 credentials for bucket id."""
if bucket_id not in settings.S3_BUCKETS:
raise MarketAccessException(f'Bucket "{bucket_id}" not configured.')
return settings.S3_BUCKETS[bucket_id] | 8b469e9aea1719ccee7c3d7e1379b222cec06c8b | 69,070 |
import bz2
import gzip
import re
import os
import pickle
def save_results(likelihoods,info,compress,obs_filename,output_filename,output_dir):
""" Saves the likelihoods together with information about the chromosome
number, depth of coverage, ancestry, statistics of the genomic windows
and flags th... | 5223cc3b15e95f2e38a453841becf1403c110744 | 69,071 |
def get_comment_history(comment):
"""
This method creates a dictionary of an edit history for
a comment or comment reply
"""
edit_history_list = []
history = comment.edit_history.all()
now = timezone.now()
current_time = now.strftime("%d-%m-%y %H:%M:%S")
for edit in list(history):
... | 74382e2cca7d01d313d5700ae09e827696adc38b | 69,072 |
import sys
def get_build_version():
"""Return the version of MSVC that was used to build Python.
For Python 2.3 and up, the version number is included in
sys.version. For earlier versions, assume the compiler is MSVC 6.
"""
prefix = "MSC v."
i = sys.version.find(prefix)
if i == -1:
... | b785712d3785b4027d269c002521fc8beaf3639a | 69,073 |
def BER(original_img_bin,decoded_img_bin):
"""
Computes Bit-Error-Rate (BER) by comparing 2 binary images.
The ratio of bit errors over total number of bits is returned.
"""
if not original_img_bin.shape == decoded_img_bin.shape:
raise ValueError('Original and decoded images\' sha... | 51b962fdab63d0a087229b4f0f4dfdd0e94412de | 69,074 |
from typing import List
def snake_case(word: str) -> str:
"""Converts given word to snake case.
>>> snake_case("someWord")
"some_word"
"""
underscore = "_"
no_underscore_words = word.split(underscore)
no_underscore_cases: List[str] = []
for w in no_underscore_words:
cases = f... | 138d9f48f3902c48cc09c281233ab937f8d3e29d | 69,075 |
import codecs
def split_dictionary(train_path, valid_path=None, test_path=None):
"""Split source dictionary to train, validation and test sets.
"""
with codecs.open(train_path, "r", "utf-8") as f:
source_dic = f.readlines()
train_dic, valid_dic, test_dic = [], [], []
if valid_path:
with codecs.open(... | 8a21e2695e6ebb29f71b10d199a237494491e0e3 | 69,076 |
def similarity_mapper(pair):
"""
this method receives a pair that the key is User X, and the users who follow user X.
(X, [Y1, .....Yn, -F1, ..., -Fi]) where Fi is a list of direct relation to the user X.
This method calculates all pairs (Yi, Yj) and (Yj, Yi) where i ∈ [1, k], j ∈ [1, k] and i != j, and... | aea4a6363f6537a43928822e575f4ff8cce79904 | 69,077 |
from typing import Optional
from datetime import datetime
def run_information(point_in_time: Optional[datetime]=None):
"""Return information about current run.
There is also the run that covers point_in_time.
"""
_verify_instance()
recorder_runs = get_model('RecorderRuns')
if point_in_time i... | 5c6b9dbee7af36a328d264633a915c636b94124b | 69,078 |
def show_open_dialog(directory=HOME):
"""Show the user a dialog asking for a file to open.
:param directory: The initial directory displayed in the dialog.
:type directory: pathlib.Path or str
:return: The filename of the user-selected file, or None if the dialog was cancelled.
"""
return _plat... | 929d5518f6f59891ed9001c1a428d6f62bbe39ef | 69,079 |
import itertools
def _some2(predicate, iterable):
"""Alternative implementation of :func:`some`."""
result = False
for _ in itertools.dropwhile(complement(predicate), iterable):
result = True
return result | a4441f723fd58c40325bbc9334bf95f441e63b7e | 69,080 |
import math
def asin(x):
"""
x est un nombre
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Retourne un angle en radians dont le sinus vaut x.
"""
return math.asin(x) | b980a538fbf51679bff8d08a84cd9cdb1a486153 | 69,081 |
def latent_heat_of_vaporization(temp):
"""
Calculate the latent heat of vaporization.
Parameters
----------
temp : numeric
Air temperature (K).
Returns
-------
lat_heat_vap : numeric
Latent heat of vaporization (J kg-1).
"""
return c.LATENT_HEAT_OF_VAPORIZATION ... | 1f877a1747875a2ec72557d300b1687985a6d788 | 69,082 |
def check_imdb_dataset(method):
"""A wrapper that wraps a parameter checker around the original IMDBDataset."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shard... | 4c9cadf092ef88ffed25da4049b99073013e1349 | 69,083 |
from typing import Union
from typing import Iterable
from typing import Dict
from typing import Any
def tensors_batch_size(tensors: Union[Tensor, Iterable[Tensor], Dict[Any, Tensor]]):
"""
Default function for getting the batch size from a tensor or collection of tensors.
Returns the batch size (zeroth in... | 76f430f49002968b10536e437c813c0adffde427 | 69,084 |
def get_image_file(uuid, image_file_path):
"""GetImageFile (GET /images/:uuid/file)
Return the image file.
"""
encoded_md5 = get_image_file_md5(uuid, image_file_path)
if NGINX_ENABLED:
res = make_response('')
res.headers['Content-Type'] = 'application/octet-stream'
res.head... | 4275e8f503a7f02c0d5e6d6561a71b81e8c0c35c | 69,085 |
def build_character(
base_info,
background,
characteristics,
fellow_investigators,
hit_points,
inventory,
luck,
magic,
sanity,
skills,
weapons,
):
"""Builds a character object.
Args:
base_info (dict): The base character information.
background (dict):... | 8504ee61d9702eebeb4000d021ab975c0f777033 | 69,086 |
import re
import os
import subprocess
def run_test(command, dirname, example, content, files):
"""Run a single example command in its own directory."""
output = None
inputs = []
match = re.search('-o example(\d+)\.(\w+)', content)
if match:
output = 'example' + match.group(1) + '.' + match.group(2)
... | 4f9e2026e0f59761e9b64806b7b823df0d9b3ce5 | 69,087 |
def average_arc_weight(graph):
"""
average_arc_weight(graph) -> average_arc_weight
"""
weights = []
arcs = graph.get_arcs()
for arc in arcs: weights.append(arc.info)
return average(weights) | c33ac23a5a6db451ab18d63dec471736359c758f | 69,088 |
def removeUser(name):
"""Unregisters a user from this computer. Returns true if the user was removed, false if they weren't registered in the first place.
The user will lose all access to this computer. When the last user is removed from the user list, the computer becomes accessible to all players."""
retu... | 7cc414ed6f7d9e23e4f0993f53366a42c850b5b0 | 69,089 |
import scipy
import six
def istft_noDiv(stft_matrix, hop_length=None, win_length=None, window=None,
center=True, dtype=np.float32):
"""
#Copied from librosa's spectrum.py file, removing division by squared
window, which shouldn't be necessary and can cause problems in recon.
Inverse sh... | 916320e97e71df1f876454c2b43f0ebb1d3bb937 | 69,090 |
import click
import six
def get_client(config):
"""Construct a new wrapped client based on the specified config file."""
# Passing the config file unconditionally here since if the user hasn't
# specified one it'll be None and the config loader will use the default
# locations.
loader = warthog.ap... | 28e6b2039a54b622d5f5dc57398f013a37176306 | 69,091 |
from typing import List
def build_key_row_0(size: KeyboardSize) -> List[Key]:
"""
space bar row
"""
r = [
LeftCtrlKey().set_is_left_hand(),
LeftOsKey().set_is_left_hand(),
LeftAltKey().set_is_left_hand(),
SpaceKey().set_is_left_hand(),
RightAltKey().set_is_right... | 41e828bc6a5abee604dd78f9d34bde5f11b46f6a | 69,092 |
def ensure_bytes(obj, encoding=None):
"""
Convert ``obj`` to a byte string, if it isn't one already.
The conversion method is as follows:
1. If ``obj`` is a byte string, return it unchanged.
2. If ``obj`` is an unicode string, encode it using ``encoding``.
3. Otherwise, cast ``obj`` to unicode... | 4dfff3df2c60d10e6cfce79004a54b597d3d8040 | 69,093 |
import os
def get_level(name):
"""Get level."""
level = 'info' # default level
os_level = os.getenv('LEVEL')
if os_level is not None:
if ',' in os_level:
os_levels = os_level.split(',')
if name in os_levels[1:]:
level = os_levels[0]
else:
level = os_level
return level | b2f11771e90dd3a9f6fdf61636a57a86759a0f18 | 69,094 |
def eval_acc_all(test_fn, all_examples):
"""
Evaluate accuracy n_exampleson `all_examples`.
"""
acc = 0
n_examples = 0
prediction = []
for x1, mask1, x2, mask2, x3, mask3, x4, x5, x6, x7, x8, x9, x10, y in all_examples:
# print(x1.shape)
# print(x2.shape)
# print(... | ec166338d70d5f06cb5999cbf63da8485fd48b9d | 69,095 |
def bound_length(input_paths, tokenizers, shortest, longest):
"""
Return an np.array which flags whether all parallel segments comply with length constraints
and count the number of tokens in each stream (considering valid sequences only).
:param input_paths: paths (list/tuple) to each part of the para... | 1af2e94f276e62c81c14e94309ce6b74b0cf8790 | 69,096 |
def validate_payload(validator: dict, params: dict, required: list = None) -> bool:
""" Validates parameters and body payloads sent to the API """
# Repurposed with permission from https://github.com/yaleman/crowdstrike_api
# __
# ... | fb3d09b0711df2cc77a54f014af614c853b2df8b | 69,097 |
def getClass( typeName ):
"""returns the class of a concrete uno exception, struct or interface
"""
return pyuno.getClass(typeName) | cf7d704bcbcc9d80a192f77ddee9d82528f0826b | 69,098 |
import os
def make_target_exists(target):
"""
Runs a check against the makefile in the current directory to determine
if the target exists so that it can be built.
Parameter descriptions:
target The make target we are checking
"""
try:
cmd = ['make', '-n', target]
... | b82b82bd23e8f9aa98487dbaf8c74cbf9934b9b5 | 69,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.