content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def _create_repository(repository_path, request=None, bare=True):
""" Receives a path to a (preferably non-existant) directory, and turns it
into a git repository.
"""
os.makedirs(repository_path)
# Dulwich uses a separate method for bare instead of working repositories,
# so ... | 03f5e0d823c492d1e375ddceaabcd7e1afafcb5f | 68,100 |
def fixName(name):
"""PMML tag name substitutions to avoid conflicts with Python syntax."""
out = name.replace("-", "_")
if out == "True":
out = "AlwaysTrue"
elif out == "False":
out = "AlwaysFalse"
elif out == "from":
out = "isfrom"
return out | e5bb85465f8a599f45ff12bf48247beab123472e | 68,101 |
import time
def microseconds():
"""
Get the time in microseconds
"""
return time.time() * 1000000.0 | 82d9258a8b0f68295b9ba2c86a9165309c19ae90 | 68,102 |
def _compute_input_padding(size, bcount, bsize, boffset, bstride):
"""Computes the padding for the operation.
:param size: `[SZH, SZW]` list-like of ints, size of image
:param bcount: `[BCH, BCW]` list of ints
:param bsize:
:param boffset:
:param bstride:
:returns: `pad_h, pad_w` for _pad_inputs function... | bce6ed06406f0d259d029c745e3c9f5ff015959e | 68,103 |
from typing import Union
import string
def _strip_unwanted_chars(price: Union[int, str]) -> str:
"""Returns price text with all unnecessary chars stripped (nonnumeric etc).
Examples:
"100" should return "100"
"100 yen" should return "100"
"10,000" should return "10000"
Args:
price: The raw val... | 18679bbd7e53fcea7cadd3343fc82a3dd875f8af | 68,104 |
import functools
def deprecated(useInstead):
"""Decorator that warns that different function should be used instead."""
def decorate(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
msg = ('Function {} has been deprecated. Use {} instead'
.format(f.__name... | 1f1872c6744db7601e5dd91056e385098ae37e40 | 68,105 |
def select_to_dict(obj: Select) -> dict:
"""
Serialize SQLAlchemy Select to dict
:param obj:
:return:
"""
obj_dict = {}
for column in obj.__table__.columns.keys():
val = getattr(obj, column)
if isinstance(val, Decimal):
val = float(val)
obj_dict[column] =... | f51245709c377d1d1317f4c49fafd43f8ad0569c | 68,106 |
import numpy
def merge_qcdata_res(qcdata, output, res):
"""
Merges QC Data at resolutions other than HH (DD, WW, MM, YY)
:param qcdata: QC Data array
:type qcdata: numpy.recarray
:param output: Output Data array
:type output: numpy.recarray
:param res: temporal resolution
:type re... | 675e77aec46160884af3cd0884f2afe5545fb91f | 68,107 |
def project_array(fine, coarse):
"""Projects a coarse array on a finer array.
The shapes of the two must be evenly divisible.
Mesh must be uniform (i.e., have equal volumes/weights)
Tested on:
* OpenMC fission rates 285 -> 95
* OpenMC fission rates 190 -> 95
* Arbitrary floating point matrix 4x4 -> 2x2
Par... | 84b4476519ff13b629b341d0c3c2048f5975a4fa | 68,108 |
def get_balance(user_id, server_id):
"""
Returns the users balance in the stonks game
:param user_id: the users unique ID
:param server_id: the servers unique ID
:return: the floating value of the users balance
"""
user = collection.find_one({"_id": user_id})
balance = user['cash_balance... | 3c36f40a4a6c11bc3a1e2aa14ea1ad54c7e0b075 | 68,109 |
def single_source_dijkstra_path_length(G, source, weight_function, paths=None, disjunction=sum):
"""Uses (a custom) Dijkstra's algorithm to find shortest weighted paths
Parameters
----------
G : NetworkX graph
source : node
Starting node for path.
weight_function: function
Fun... | 35644cee6a8bb43553cec5f4bdfe12fd9d6a9609 | 68,110 |
def get_log_data():
"""
:return:
"""
log_data_list = list()
conn = connect()
log_data = RBX.table("Logs").run(conn)
for log_item in log_data:
log_data_list.append(log_item)
return log_data_list | 30b8ea4cb0d75c8b874cc7aaaea271309bf50c65 | 68,111 |
import torch
def get_relative_position_matrix(length, max_relative_position, direction, offset=True):
"""
Generate matrix of relative positions between inputs ([..., length]).
:param length:
:param max_relative_position:
:param direction:
:return:
"""
range_vec = torch.arange(length).l... | 32ed90e3a8a29d36e4b57a3bcfd066c15985adaf | 68,112 |
def isDocx(filename):
"""确定上传文件为docx"""
return '.' in filename and filename.rsplit('.', 1)[1] in {"docx",} | 547236d821e0ecb3bb59a2ea00623adbf7d5c6df | 68,113 |
def input_to_output_path(input_path):
"""
args.output_dir/SubjectID-FormID
Args:
input_path:
Returns:
(str): output file path.
"""
# TODO: *Assuming input_path isn't relative or contains subject and form information.
parts = input_path.split('/')
return parts[-3] + "-" +... | 6314b8079e8f2de75ea2af1b78bd4402eeb197b9 | 68,114 |
def extract_features_by_words(text):
"""
Extract the features from words.
:param text: The text to operate on
:return: A list of features objects
"""
features_by_words = []
words = text.split()
word_num = 0
for word in words:
word_features = features_detection(word)
... | 4862a22fa77ab502810c1d17928195eb809eb0df | 68,115 |
import math
def formatRA(ra):
"""Format the ra given in degrees into hours, minutes, seconds."""
if ra is None:
return None
return formatRA_rad((math.pi/180)*ra) | 27fb120f8097ffd0ca9eb4d402dde616ab414976 | 68,116 |
import warnings
def update(data):
"""Update the data in place to remove deprecated properties.
Args:
data (dict): dictionary to be updated
Returns:
True if data was changed, False otherwise
"""
updated = False
if 'include' in data:
msg = ("included configuration files... | 2e604cde4455bb1ab784651798fb3be0cd3733db | 68,117 |
def getHtmlItems(templateName, identifier):
"""
:param templateName:
:param identifier:
:return:
>>> getHtmlItems("sample", "mojeTestId")
{'caption': 'Moje Caption', 'shortDescription': 'Moje shortDescription', 'description': 'Moje dDescription'}
"""
result = {}
divContent = getHtm... | e464daa4978c69440c4a459d41c163dca2a5a072 | 68,118 |
def find(compiler_spec, scope=None, init_config=True):
"""Return specs of available compilers that match the supplied
compiler spec. Return an empty list if nothing found."""
return [c for c in all_compiler_specs(scope, init_config)
if c.satisfies(compiler_spec)] | df2fe11e3674b3ec86bf9aeb25688f4d90bd7892 | 68,119 |
def _get_shape(tensor):
"""Like get_shape().as_list(), but explicitly queries the shape of a tensor
if necessary to ensure that the returned value contains no unknown value."""
shape = tensor.get_shape().as_list()
none_indices = [i for i, d in enumerate(shape) if d is None]
if none_indices:
# Query the s... | 913ee17456866543bc337bcbaaa6680a9bf5399c | 68,120 |
import os
import sys
def exit_if_absent(env_var):
"""Check if an environment variable is absent.
Args:
env_var: Name of environment variable.
Returns:
Returns True if env variable exists, False otherwise.
"""
if not os.environ.get(env_var):
print("%s is required." % (env_va... | a7ae88f9c5be1285ff872d80923e2a1cc3f36b06 | 68,121 |
def add_colorbar(im, aspect=20, pad_fraction=1, **kwargs):
"""Add a vertical color bar to an image plot."""
divider = axes_grid1.make_axes_locatable(im.axes)
width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect)
pad = axes_grid1.axes_size.Fraction(pad_fraction, width)
current_ax = plt.gca()
... | 3bb2420fb7de41e1c5121c874d51fe32722ccf35 | 68,122 |
from typing import List
def calc_high_actual_pd(actual_temps_dict: dict,
final_high_rcp_list: list) -> List[float]:
"""
Return a list of percentage differences of high RCP values to actual temperature values
"""
actual_temps_list = list(actual_temps_dict.values())
high_rcp_... | 6aee2dbf9ab62dab7c5b4671a1c1ce64ad4ad2eb | 68,123 |
def import_prediction_regions(bed_file: str,
chromosomes: list,
chrom_sizes_dictionary: dict,
blacklist: str,
region_length: int = INPUT_LENGTH,
step_size: int = 256):
... | 54b378a8075a5f3a4dc71c133df1d25ffe4d7b77 | 68,124 |
def fc_net(input_tensor):
"""Simple function for constructing a fully connected network."""
x = input_tensor
for hidden_dim in [40, 40]:
x = tf.layers.dense(x, units=hidden_dim)
x = tf.nn.relu(x)
return tf.layers.dense(x, units=1) | 66a3ad3f684a039f0de2ea7b9b2ef34aaf248f8a | 68,125 |
import os
def check_meta_clips(xmldoc):
"""check that a file exists that matches the href in all the clip tags"""
clip_list = xmldoc.getElementsByTagName('clip')
for clip in clip_list:
clip_name = clip.attributes['href'].value
if os.path.exists(clip_name):
print_pass('found a c... | fa329b27bf04b5bf5714eddcb67974ea07f78eef | 68,126 |
def ResponseFAP_Create(*args):
"""
Create() -> ResponseFAP
ResponseFAP_Create(std::string const & publicID) -> ResponseFAP
"""
return _DataModel.ResponseFAP_Create(*args) | 8ce388841db234a25b53c53967dabd064474b96a | 68,127 |
import subprocess
def executeCommand(cmdName, params="", showSpinner=True):
"""Executes the given cmdName command and returns its output"""
myProc = subprocess.Popen(cmdName + " " + params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout, stderr = myProc.communicate()
if len(str(std... | 9c639fb157a0542829bb39aa70aae5f95e3eb635 | 68,128 |
import math
def haversine(lat1, lon1, lat2, lon2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine formula
dl... | 24cf45e8805beb64accc4bd0ae3ddf5b3a2fccbe | 68,129 |
def admin_list(page=None):
"""
管理员列表
"""
if page is None:
page = 1
page_data = Admin.query.join(
Role
).filter(
Role.id == Admin.role_id
).order_by(
Admin.addtime.desc()
).paginate(page=page, per_page=8)
return render_template("admin/admin_list.html", ... | bc0c80067464a972f67fe95532cd9892348b67a9 | 68,130 |
import socket
def _get_my_ip():
"""Returns the actual ip of the local machine.
This code figures out what source address would be used if some traffic
were to be sent out to some well known address on the Internet. In this
case, a Google DNS server is used, but the specific address does not
matte... | 3162475676617118cec0310b7827c49795198ecc | 68,131 |
def image_member_delete(context, memb_ref, session=None):
"""Delete an ImageMember object"""
session = session or get_session()
memb_ref.update(dict(deleted=True))
memb_ref.save(session=session)
return memb_ref | b5d214cf7a1168aaa0108d045803c1b096c52ed7 | 68,132 |
from pathlib import Path
def readZone(zonePath):
"""Read zone folder (e.g. '04_teentopia') and return list of Page"""
zonePath = Path(zonePath)
pages = [
readPage(f) for f in zonePath.iterdir() if not f.name == 'zone.hsp'
]
# "links" in zones.hsp not explicitly defined in hsp file
zo... | c7cf221fb99765ac77e49def14e29f4d594aab40 | 68,133 |
def trigger(hass, config, action):
"""Listen for state changes based on configuration."""
entity_id = config.get(CONF_ENTITY_ID)
below = config.get(CONF_BELOW)
above = config.get(CONF_ABOVE)
value_template = config.get(CONF_VALUE_TEMPLATE)
# pylint: disable=unused-argument
def state_automat... | e2b6a4a65c84a266cacd1bdf0fa9927b27698ecd | 68,134 |
def getMagnitudeFactor(filter_band):
"""
Intermediate computation used by the mfcc function.
Compute the band-dependent magnitude factor for the given filter band
"""
magnitude_factor = 0
if filter_band >= 1 and filter_band <= 14:
magnitude_factor = 0.015
elif filter_band >= 15 and ... | 2b46157dfbea269cee335240536442d2c7d4b836 | 68,135 |
def _default_filter(line):
"""Default bad header filter.
Filters out lines that start with ">From" or "From " (no colon).
"""
line = line.strip()
return (False if line.startswith('>From') or line.startswith('From ') else
True) | 4867ba376914d7d688038c8471f09405b0a17c24 | 68,136 |
def cvGet3D(*args):
"""cvGet3D(CvArr arr, int idx0, int idx1, int idx2) -> CvScalar"""
return _cv.cvGet3D(*args) | 904b484d5129c18e0164481e23e2a532e5abfe1a | 68,137 |
import maya.cmds as cmds
import os
import shutil
def receive_version_file(version_id):
""" receive version file
if not has versions,assembly new file
:rtype: bool
"""
# 按照版本领取文件
print("version id {}".format(version_id))
_version_handle = zfused_api.version.Version(version_id)
... | 33672a2953609805a9a9b2586f6ced27137c3a7e | 68,138 |
def extract_number_missing(data, min_valid, drop_cols=['sample'], group='group'):
"""
Counts how many valid values exist in each column and filters column labels with more valid values than the minimum threshold defined.
:param data: pandas DataFrame with group as rows and protein identifier as column.
... | bd1762374b978a9470cef1fa301bc32b996ad5e7 | 68,139 |
import json
from datetime import datetime
def load_all_configs(_signum, _frame):
"""
Calls individual functions to read various config files required. This
function is called directly (e.g. at startup) and is also registered
with signal handling (e.g. kill -sigusr1 <pid>)
:Parameters:
sign... | b08cf15a1ae8b61a097ad3fb577e28d9ae2b5847 | 68,140 |
from typing import Sequence
def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None:
"""Return all capabilities supported if minimum required are present."""
return [
capability for capability in CAPABILITY_TO_ATTRIB if capability in capabilities
] | d051610f071c31fb03a53a46f20438e5efa8bc56 | 68,141 |
import copy
def parse_input_json_dict(in_json_dict):
"""
Parse an input json dictionary into options, example:
in_json_dict = {
"schema_name": "qc_schema_optimization_input",
"schema_version", 1,
"keywords": {
"coordsys": "tric",
"conv": 1.e-7
}
... | bd0bb8651ddac17b5b1fe218a9e493ba93e838bf | 68,142 |
def get_all_users():
"""Get all user from Acai game
:return user_list: list of all users
:rtype: list
"""
target_url = 'http://acai.berry.ai/api/all_user_ids'
data = urllib2.urlopen(target_url).read()
user_list = data[1:-1].split(',')
for i in range(0, len(user_list)):
user_lis... | 85d3e13dfc9ee12c167da0dd577b2d141a0fbe60 | 68,143 |
import logging
def logger():
"""Configure logging in console and log file.
Returns
-------
rl : logger
Logging in console (ch) and file (fh).
"""
# set root logger (rl)
rl = logging.getLogger('REEEMLogger')
rl.setLevel(logging.INFO)
rl.propagate = False
# set for... | 37b813d1f50f0a9fa4e84a9ca81e96a12ee27067 | 68,144 |
def potential_from_kappa_grid(kappa, grid_spacing):
"""
lensing potential on the convergence grid
the computation is performed as a convolution of the Green's function with the convergence map using FFT
:param kappa: 2d grid of convergence values
:param grid_spacing: pixel size of grid
:return:... | 602d507e13a5af80452b68a4d2b52c5ad122c48a | 68,145 |
def path_exists(path, fs=None, **kwargs):
"""
Check if file exists either remote or local.
Parameters
----------
path : path to file
Returns
-------
exists : bool
"""
fs = fs or fs_from_path(path, **kwargs)
fs.invalidate_cache(path=path)
return fs.exists(path) | e1c95c556b28533eb3144814f1bee52428263abf | 68,146 |
def line_in_triangles_3d(
line_point: np.ndarray, line_direction: np.ndarray, triangles: np.ndarray
):
"""Determine if a line goes through any of a set of triangles.
For example, this could be used to determine if a click was
in a triangle of a mesh.
Parameters
----------
line_point : np.n... | 3a6e747f3bfaa0af820df89ee9a1ce79fdf97624 | 68,147 |
import numpy
def truncate_curve(x, y, length):
"""Truncate a curve to target a given length."""
# Compute cumulative sum of the segments length.
segment_lengths = numpy.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2)
cumul = numpy.cumsum(numpy.insert(segment_lengths, 0, 0.0))
# Find the index of t... | f64cca96b8646dc94a3dbc745241ef0e427a8c2a | 68,148 |
import torch
def dot(input_, other):
"""Wrapper of `torch.dot`.
Parameters
----------
input_ : DTensor
The first operand.
other : DTensor
The second operand.
"""
if input_._data.ndim == 1 and other._data.ndim == 1:
return torch.dot(input_._data, other._data)
re... | e02d6215764f88263912d69720acb6a8a103ed49 | 68,149 |
from django.contrib.syndication.views import feed
def blog_post_feed(request, format, **kwargs):
"""
Blog posts feeds - handle difference between Django 1.3 and 1.4
"""
blog_feed_dict = {"rss": PostsRSS, "atom": PostsAtom}
try:
blog_feed_dict[format]
except KeyError:
raise Http... | e98f85eb703a54946618faf38e6619eb759fb8a7 | 68,150 |
from datetime import datetime
def in_curation_window(comment, max_age=561600, min_age=800):
"""
Based on the max_age (seconds) checks the post is votable or not.
"""
if isinstance(max_age, str):
max_age = int(max_age)
if isinstance(min_age, str):
min_age = int(min_age)
create... | 09c182676e889eec0fc356bbbcd831b01b368ad0 | 68,151 |
def get_tagged_from_server(input_text, caseless=False):
"""
Get pos tagged and ner from the CoreNLP Server
从CoreNLP服务器获取pos标记和ner
疑问:CoreNLP服务器?
参数:input_text:字符串形式的输入文本
:param input_text: input text as a string
返回值:带有pos和ne标签的标记化文本
:return: tokenized text with pos and ne tags
>>> ge... | 15a4eff7735c14f909fb323d241e99bb06b4c4a6 | 68,152 |
def get_date(email):
"""
Takes an email Message object and attempts to parse a date according
to the rules in RFC 2822. If successful, returns a string of the
datetime in UTC and in ISO 8601 format. Otherwise, returns None.
"""
date_str = email.get('Date', '')
try:
email_datetime = e... | d987d62c52c0240b76c46b1939bc77774c64cca3 | 68,153 |
def get_observers():
"""Makes sure _observers cannot be modified."""
return tuple(_observers) | 2da299990eed46a23382944200fb0e939c435031 | 68,154 |
import tempfile
def xlsx_response(filename, table, max_width=118, max_height=90):
"""Return a Microsoft Excel 2007+ file of the given table as an
HttpResponse.
Args:
filename: the name of the downloaded file. The extension will be
'.xlsx'. This parameter is inserted directly to the resp... | fcdcc7bd5a4d1fda0398763712a6c3d8ab79db10 | 68,155 |
def format_pIC50(compound: CompoundAnalysis) -> str:
"""
Format the compound's experimental pIC50 if present, or TBD if not
"""
experimental_data = compound.metadata.experimental_data
if "pIC50" in experimental_data:
return experimental_data["pIC50"]
else:
return "TBD" | 69312c9cdfde4c9765b94f9253e5afb7b871ac26 | 68,156 |
def parse_starlog(path_to_log):
"""Parse star logfile into a dict.
Args:
path_to_log: filepath containing the star run log
Returns:
dict that contains metrics from star log
"""
qc_dict = {}
with open(path_to_log) as f:
for line in f:
if "|" in line:
... | ced4f91846a4c658c1801eeeb75430cdecafb32d | 68,157 |
def make_p_M_uniform(p_M_min=5., p_M_max=8.5, M_step=0.1, n_M=None):
"""
Creates a uniform PDF between the minimum and maximum magnitudes given
by p_M_min and p_M_max.
Parameters
----------
p_M_min : Minimum magnitude.
p_M_max : Maximum magnitude.
M_step : Width of steps in interpolatio... | 2e5ba47e8af5de1b8d62d8a4b338ec130bdafef1 | 68,158 |
def generate_field_radial_bend(
reference_image,
body_mask,
reference_point,
axis_of_rotation=[0, 0, -1],
scale=0.1,
mask_bend_from_reference_point=("z", "inf"),
gaussian_smooth=5,
):
"""
Generates a synthetic field characterised by radial bending.
Typically, this field would be ... | ab4cf885b79df08fc1e3448ad4a1682d110a495c | 68,159 |
def get_distance_metrics():
"""Gets a list of distance-based metrics.
Returns:
list[Metric]: A list of metrics.
"""
return [HausdorffDistance(),
AverageDistance(),
MahalanobisDistance(),
VariationOfInformation(),
GlobalConsistencyError(),
... | d71d263d3d400159b5fe4d92beb010734ab40a5a | 68,160 |
import pandas
def age_group(age: int, bin_count: int = 10, age_cutoff: int = 90) -> str:
"""
Categorical age group given a specific age, codified into a function to enforce consistency.
"""
if pandas.isna(age) or age < 0:
return None
bin_size = age_cutoff // bin_count + 1
if age >= ag... | d37297a296fb90f6c33e406300fae7f2855fb578 | 68,161 |
import sqlite3
def connect_db():
"""Connectts to the specific database."""
return sqlite3.connect(app.config['DATABASE']) | d92187d40f71dc4d4af2866e5877633d7dc34976 | 68,162 |
def get_message():
"""
Get message by message_id
:param message_id
:return:
"""
message_id = request.args.get('message_id')
message = Message.query.get(message_id)
if not message:
return jsonify({
'error': 'No message found'
})
return jsonify({
... | 8ac4ae494c3c3b512c0b19af58db8b0a8a9f131a | 68,163 |
from datetime import datetime
def repo_update(request):
"""
Get the updates for the repo page.
"""
if 'last_request' not in request.GET or 'limit' not in request.GET or 'repo_id' not in request.GET:
return HttpResponseBadRequest('Missing parameters')
this_request = TimeUtils.get_local_tim... | bc99425fcf6beeb85a42d74ad9a09e7992ca185a | 68,164 |
def parse_OWS(string, pos):
"""
Parse optional whitespace from ``string`` at the given position.
Return the new position.
The whitespace itself isn't returned because it isn't significant.
"""
# There's always a match, possibly empty, whose content doesn't matter.
match = _OWS_re.match(st... | 4ab4eb1298406545288af6b807624771b90f92d1 | 68,165 |
def addBinaryB(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_decimal=0
b_decimal=0
for i,num in enumerate(a):
if num == '1':
a_decimal+=pow(2,len(a)-i-1)
for x,num in enumerate(b):
if num == '1':
b_decimal+=pow(2,len(b)-x-1)
result=a_decimal+b_decimal
if result == 0:
return "0"
last="... | 099167e14b4889ce0c08e5934acd2124de91145c | 68,166 |
def get_universe_id_from_script(universe_script):
""" Get the id of a universe given the universe script """
return int(universe_script.split('.')[0].split('_')[1]) | a714d1de25f4972c1cccd6c70453d01e2938af2b | 68,167 |
def getDataFromLine(line):
"""Helper function for processSolution() so it can be called for both solutions.
This function will return the data we are interested in."""
_debug("line: " + line)
# The line contains '/' so we need to split the string
if line.find("/") != -1:
# In certain cases... | 7de8f9bb45ff854785b442487df2bb65d12320ff | 68,168 |
def cut_fiducial(X, ids, isMC, xcorr_flow=False):
""" Basic fiducial (kinematic) selections.
Args:
X: Number of events N x Number of variables D
ids: Variable name array (D)
isMC: is it MC or Data
Returns:
ind: Passing indices (N)
"""
if isMC ==... | 53ac7c70f059f9faae4debce3687a32b094a53a8 | 68,169 |
def emscan(words, vectors, initial, min_similarity=0.5, cluster_ratio=0.5):
"""
A dictionary expansion algorithm that works similarly to DBSCAN. Starting
from an initial cluster, it iteratively adds points (words) to it
- whose similarity with a word already in the cluster is above
min_similarity;... | e8f1e1e86076370c58c80e3458976c65162e79a1 | 68,170 |
import warnings
import os
def update_cfg_using_dotenv() -> list:
"""
In case when there are dotenvs, try to return list of them.
# It is returning a list of hard overwrite.
:return: empty list or overwriting information
"""
# If .env not found, bail
if find_dotenv() == '':
warning... | fa9d8fcaff36c54112962b05b29df9a5579db908 | 68,171 |
import sys
def set_selection(select_id, mod_name=None):
"""
Internal use: Set the feature directly by Id.
Id == -1: ignore this module in switching.
"""
mod_name = mod_name or sys._getframe(1).f_globals['__name__']
__init__()
# Reset the features to the given id
flag = 0
if isinsta... | 45a4f5a16f3769fc0dba47dc6549376f8a934718 | 68,172 |
def Q_p_NH2D(Tex=5*u.K):
"""
It returns the particion function for para-NH2D with an excitation
temperature.
It uses the first 30-energy levels.
"""
if Tex.size == 1:
return np.sum(Q_p_NH2D_i(p_full_index, Tex=Tex))
else:
Q_p_NH2D_all = np.zeros_like(Tex.value)
for i... | 944ecdbc682321982608aaf61155167515f47111 | 68,173 |
from typing import Tuple
def make_networks(
spec: specs.EnvironmentSpec,
hidden_layer_sizes: Tuple[int, ...] = (256, 256)) -> SACNetworks:
"""Creates networks used by the agent."""
num_dimensions = np.prod(spec.actions.shape, dtype=int)
def _actor_fn(obs):
network = hk.Sequential([
hk.nets... | 8e6d37034b0739570ed52bb275747756fab54bbc | 68,174 |
def dict_to_xml(dict):
"""Convert dict to xml.
Args:
dict (dict): Dictionary.
Returns:
str: Return a XML representation of an dict.
"""
return dicttoxml(dict).decode() | 093c035057e26074944363777d16f3a7598561e5 | 68,175 |
def select_following(userid, otherid, limit=None, backid=None, nextid=None):
"""
Returns the users whom the specified user is following.
"""
return select_followed(userid, otherid, limit, backid, nextid, following=True) | 0c734bd3a320cdf297ef107eb7be51ceeb9c4bb7 | 68,176 |
import re
def author_url_to_author_id(url: str) -> int:
"""
Converts an author url into an author id.
:param url: str
:returns int, author id
"""
raw_author_str = url.replace("https://www.goodreads.com/author/", "")
author_rgx = r".*show\/(\d+)\..*"
return int(re.search(author_rgx, ra... | a02b4debbfb11a21fa7d38db94181f95628e9c74 | 68,177 |
def gf_ddf_zassenhaus(f, p, K):
"""Cantor-Zassenhaus: Deterministic Distinct Degree Factorization
Given a monic square-free polynomial `f` in `GF(p)[x]`, computes
partial distinct degree factorization `f_1 ... f_d` of `f` where
`deg(f_i) != deg(f_j)` for `i != j`. The result is returned as a
... | 0316f13dfded75fbccbf792ec9f94458d45797e8 | 68,178 |
import pathlib
import warnings
def parse_table_input_file(in_dfs):
""" Returns a tuple
(instrument name list, creation date list, instr from name list, instr from metadata list)
"""
try:
# Select the Input Files df from the dictionary
df = in_dfs['Input Files']
# Select... | b1da2ff19d1f16a37596e5aa3f2897569dff4172 | 68,179 |
import configparser
def connect(connection_name: str) -> cx_Oracle.Connection:
"""returns an Oracle connection by reading a config file in your F drive"""
config = configparser.ConfigParser()
config.read(f'F:/{connection_name}.ini')
details = config['details']
dsn_tns = cx_Oracle.makedsn(details['hostname'], det... | 49ae3b4021808f06bef2b094501d5b4a6d29e5e6 | 68,180 |
import re
import sys
def get_columns_manual(file=None, cols=[0], colSep=["\t"], header=False, index=None, alias=None):
"""Get specified columns from a file where rows have varying numbers of fields.
Some tables contain a fixed set of fields followed by optional fields. In
these rare cases, traditional pa... | 29ca03bdc6670c9a7d19ee89010b66ae4ed4bfc1 | 68,181 |
def totales_productos():
"""
Ventas Totales por Productos
"""
producto = request.vars.producto
form = SQLFORM.factory(
Field('producto', 'integer', label='Producto', default=producto, widget = SQLFORM.widgets.autocomplete(
request, db.maestro.alias, id_field=db.maestro.id, mode=1... | 2048e4e7b8a2530e9e5a8cfb3272013cff727849 | 68,182 |
from sympy.utilities.lambdify import lambdify
def sympy2casadi(sympy_expr, sympy_var, casadi_var):
"""
Transforms a sympy expression into a casadi function.
Parameters
----------
sympy_expr : sympy expression
sympy_var : list of sympy symbols
casadi_var : list of casady ... | d61051eb81a582438e893ad90fff1e4ba0377f7a | 68,183 |
import functools
def wrap_unauthorized(f):
"""Wrap a function to expect an unauthorized failure."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
try:
f(*args, **kwargs)
except lib_exc.Forbidden:
pass
else:
raise AssertionError("The test was ... | a8cc6a9dd3aad6b39da6450eab3aeb4da78ebcac | 68,184 |
def testForStrayPoints(contour):
"""
There should be no stray points.
Data structure:
(x, y)
"""
contour = wrapContour(contour)
if len(contour) == 1:
pt = contour[0].onCurve
pt = (pt.x, pt.y)
return pt
return None | dc88ab4fa46ecf0d55100ae1d8fc416a3d411df4 | 68,185 |
def tableToDataFrame(table):
"""Converts a vtkTable to a pandas DataFrame"""
if not isinstance(table, vtk.vtkTable):
raise PVGeoError('Input is not a vtkTable')
num = table.GetNumberOfColumns()
names = [table.GetColumnName(i) for i in range(num)]
data = dsa.WrapDataObject(table).RowData
... | be4a749d90f0038d8e1eb3d483cef41a8b6e8620 | 68,186 |
from enum import Enum
from typing import Union
import json
def export_dataset_as_avro(
connect_info: Client, *, url: str, dataset_name: str, fs_type: Enum
) -> Union[JsonDict, bool]:
"""
Takes a connect info object and writes the corresponding avro file to specified url for
specified dataset. By defau... | 30976a4c76ee835c615764322a049ed239846319 | 68,187 |
def signup():
"""
Sign-up user for a ZenType account.
"""
r = request.get_json()
user_email = r.get('email', None)
user_password = r.get('password', None)
userDO = UserAuth.create_new_user(
email=user_email,
password=user_password
)
if userDO is not None:
# if the user was created successfully, give ... | 0a66bab211d7d94d9360f75610e42e799fd6d7b0 | 68,188 |
def _FormAdj_w(a1, a2):
"""
transform eisensteinInteger a1+a2*w -> form 1+3*(x+y*w)
"""
if a1 % 3 == 0:
if a2 % 3 == -1 or a2 % 3 == 2:
return a1 - a2, a1
else:
return a2 - a1, -a1
elif a1 % 3 == 1:
if a2 % 3 == 1:
return a2, a2 -a1
... | f9c5561e46225786fa5250a6be90d77ef2bd7aad | 68,189 |
def handle_pushes(payload: dict) -> dict:
"""Handles push webhook events
:param payload: the payload of the POST request coming from the webhook
:type payload: dict
:returns: an empty widget because no widget is created for pushes
:rtype: dict
"""
if payload['ref'] == 'refs/heads/master':
... | cea03b3eb099716aa4089fc47874e39ffb186400 | 68,190 |
def tstfunc2(*args, **kwargs):
""" a function, that returns a unique result for every call """
rslt = mk_signature(args, kwargs), next(ctr2)
print("Func(%s, %s) => %s" % (args, kwargs, rslt))
return rslt | c24cde839c9f7ab00ad74f7065b68e010d530d5f | 68,191 |
def _cytomine_parameter_name_synonyms(name, prefix="--"):
"""For a given parameter name, returns all the possible usual synonym (and the parameter itself). Optionally, the
function can prepend a string to the found names.
If a parameters has no known synonyms, the function returns only the prefixed $name.
... | 4d8d58571b03182cf31546c370fda81e2caf5800 | 68,192 |
import os
def create_OutletShape_Wrapper(outletPointX, outletPointY, output_shape_file_name):
""" This function expects the service to pass a file path that has the guid
temp folder for the shape_file_name parameter
:param outletPointX
:param outletPointY:
:param shape_file_name:
:return:
... | 0aa6d8cd268f622a673eaeb9a556d917e2dafb56 | 68,193 |
def read_alignment_file(path, trg_lengths, src_lengths):
"""
read flat alignment file
:param path: path to alignment file
:param trg_lengths: array of target lengths (for each sentence)
:param src_lengths: array of source lengths (for each sentence)
:return: array of alignments (unprocessed)
... | d0433b1375e7b7774521316643f48e921587a372 | 68,194 |
def get_deps():
"""Write the result of the bazel query `query` against protobuf to
`out_file`."""
cc_files_output = bazel_query(BAZEL_DEPS_PROTOC_LIB_QUERY)
cc_files = [
name[len(PROTOBUF_CC_PREFIX):] for name in cc_files_output
if name.endswith('.cc') and name.startswith(PROTOBUF_CC_PREFIX)]
p... | 0e83b429c4f59a48f28a6da704cdd25250aee24a | 68,195 |
import cmath
def _angles_for_ZYZ(input_gate):
"""Finds and returns the angles for ZYZ rotation matrix. These are
used to change ZYZ to other combinations.
Parameters
----------
input_gate : :class:`qutip.Qobj`
The gate matrix that's supposed to be decomposed should be a Qobj.
"""
... | 5e3ff37e8528498e0781486e86b7e938b2330ab0 | 68,196 |
from typing import Dict
def __create_lookup_table(root: __Node) -> Dict[str, str]:
"""
Given the root node of huffman tree, uses dfs to assign code words (bit string) to symbols
Parameters
----------
root : __Node
The root node of huffman tree
Returns
-------
Dict[str, str]
... | c73baa919407090cb5def79101870248d84846ea | 68,197 |
import itertools
def phi1k_local_2vN(ind, Ek_grid, fk, hfkp, hfkm, E, Tba, si):
"""
Constructs Phi[1](k) corresponding to local approximation at Ek_grid[ind].
More precisely, generates local approximation kernels L1 and L0, Phi[1](k) = L0(k)Phi[0],
L1(k)Phi[1](k) = L0p(k)Phi[0], L0 = L1^{-1}L0p.
... | 1a023cab70d729041540eea227e5ef5b2ee966fb | 68,198 |
def player_page(map_code):
"""Page for listing other maps made by author of a map."""
maps_listing_page = map_model.find_maps_by_map_author(map_code)
return jsonify({
'maps': maps_listing_page
}) | 7ad0af658a75d1aee4683ffc7675b1b9b548e298 | 68,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.