content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_variables_to_train(trainable_scopes, logger):
"""Returns a list of variables to train.
Returns:
A list of variables to train by the optimizer.
"""
if trainable_scopes is None or trainable_scopes == "":
return tf.trainable_variables()
else:
scopes = [scope.strip() for scop... | ae101730521728859ba81ee888522a705f4749c2 | 48,000 |
def password_change_done(request):
"""
View called when the new user password has been accepted
"""
messages.success(
request, _('Your password has been successfully changed.')
)
return redirect('common:current_user_details') | 3e81e12a270baacf82c3e566353563f78d0ebc4f | 48,001 |
from typing import List
def get_most_representative_notices(notice_ids: List[str], mongodb_client: MongoClient, top_k: int = None) -> List[str]:
"""
This function returns top_k the most representative notices, from the list of notices provided.
:param notice_ids:
:param mongodb_client:
:param ... | e29015e7712f8d6296df70d5dbfbfda2e00569b4 | 48,002 |
def remove_ldra_interface(
device, interface=None, vlan_id=None, policy=None, interface_id=None, **kwargs):
"""
Remove DHCP ldra remote-id
Args:
device ('obj'): device to use
interface ('str'): interface to configure
vlan_id ('str'): vlan_id to attach policy
... | 33a3a2e412dc32552416f074412fae40c9e1f6a8 | 48,003 |
def borders(det):
"""
Calculates the borders for image
Parameters
--------------
det: int array
Detected face
Returns
----------------------
l: int list
Coordinates for left bound of border
r: int list
Coordinates for right bound of border
t: int... | d6358c88ee26e64b7b209d2f5f9725a5b3fad9ba | 48,004 |
from rdkit.Dbase.DbConnection import DbConnect
import pickle
def DBToData(dbName, tableName, user='sysdba', password='masterkey', dupCol=-1, what='*', where='',
join='', pickleCol=-1, pickleClass=None, ensembleIds=None):
""" constructs an _MLData.MLDataSet_ from a database
**Arguments**
... | 39e2531c54501c837d52c4e2d4f148b8e5531f2e | 48,005 |
def get_line_row(lines, row):
"""
- lines: (Array string), array of lines
- row: int, >=0, the row index to grab
RETURN: string, if row greater than or equal to lines length, returns ''
"""
if row < len(lines):
return lines[row]
return '' | f03f230b677fabb3c488c496dad7e35f875023fe | 48,006 |
def VerifyLimitsPotential(potential):
"""Verify if the potential seems to verify the borders conditions (to allow bound states). If it doesn't it ask to the user if he is sure that the potential respects these conditions
Parameters:
-----------
potential (str) : a string that indicates the mathemat... | a1545b0360cb5de43c610442d5135a20c7da5893 | 48,007 |
def _get_head_node_ip(stack_name):
"""
Get the IP Address of the head node.
:param stack_name: The name of the cloudformation stack
:param config: Config object
:return private/public ip address
"""
instances = describe_cluster_instances(stack_name, node_type=NodeType.head_node)
if not ... | c699c21e84f0810b2c78fb0435dac07d8a963e79 | 48,008 |
from typing import Tuple
def build_datasets(config: DataConfig) -> Tuple[DataLoader, DataLoader]:
"""
Build training and validation data loaders for training.
Parameters
----------
config: DataConfig
Data configuration such as batch size and validation set.
Returns
-------
tr... | 5012ce15954e87dcd4a0a4323750d88242a0cf76 | 48,009 |
def fmt_begin_msg(app, fromuser, touser):
"""Format a PM begin message"""
msg = "/me began pestering {touser} {toInit} at {time}".format(touser=touser.display_name,
toInit=getInitials(app, touser,
... | 43753f431835f6b235dd17dc1057d5c218f53a59 | 48,010 |
def filter_dict_null(d):
"""
Filters recursively null values from dictionary
"""
if isinstance(d, dict):
return dict(
(k, filter_dict_null(v))
for k, v in list(d.items())
if filter_dict_null(v) is not None
)
elif isinstance(d, list):
if len... | 13b0288f2e032d0e6ca115d02d6540bb8f8739b5 | 48,011 |
import ast
def merge(predicates):
"""
Invoked with a set of predicates that should
be merged into a single AST. The new AST uses
the PushResults node to return the list of matching
predicates, and Both nodes to combine.
"""
# Merge the AST tree's together first using a tree
all_asts = ... | e5425cb0d87e143a3d6d8ac75e5cad1d77a5916b | 48,012 |
def optimize_threshold(model, X, y, TP=0, FP=0, TN=0, FN=0, minimize=True, pos_label=1):
"""
Find the optimal threshold
Returns a tuple containing:
A pandas dataframe used for plotting
The optimal threshold
The cost associated to that threshold
"""
y_pred = model.predict_prob... | 8f586eb8ec7d72f5a33d6a23becc8e8c6c1ec6f2 | 48,013 |
def get_backend_defaults_url(config, backend_type):
"""Return the URL for a backend's pulse defaults."""
hub = config.get('hub', None)
group = config.get('group', None)
project = config.get('project', None)
if hub and group and project:
return '/Network/{}/Groups/{}/Projects/{}/devices/{}/d... | ac84179e03d132c64e55a87856f420968004f209 | 48,014 |
def ugly_numbers(n: int) -> int:
"""
Uses dynamic programming technique to return the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(1)
1
>>> ugly_numbers(20)
36
"""
ugly_nums = [0] * (n)
ugly_nums[0] = 1
i2, i3, i5 = 0, 0, 0
next_2 = ugly_nums[i2] * 2
... | 6691ea90eebe1dc659fea244014f73b9638c3a5d | 48,015 |
def get_publish_dates(df):
"""Get time distribution of publish dates for the given dataframe
Returns
-------
list[int]
Time distribution in a format friendly towards HighCharts
"""
return pd.to_datetime(df["publish_date"]).astype(np.int64) / int(1e6) | d80813eefe2bdc10990f5bfd3138fd42c2bb28fe | 48,016 |
def user_delete(request, pk=None):
"""User Delete View
Description:
view to delete users
"""
try:
user = Client.objects.get(id=pk)
except Exception as e:
messages.error(request, e.args[0])
return HttpResponseRedirect('.')
if request.method == 'GET':
_user ... | de0b17445bc203490f57e910544c9109666c3717 | 48,017 |
from pathlib import Path
import requests
def make_posts(
src, src_pattern, dst, layout, category_layout, comment_layout, comment_detail_layout, **params
):
"""Generate posts from posts directory."""
items = []
for posix_path in Path(src).glob(src_pattern):
src_path = str(posix_path)
... | 3cf368d5fe3e78ca02d00137b2894399e78310ec | 48,018 |
def binary_search(array, item):
"""返回 item 在 array 中的下标,没找到返回 None。"""
low = 0
high = len(array) - 1
while low <= high:
mid = (low + high) // 2
guess = array[mid]
if guess == item:
return mid
elif guess > item:
high = mid - 1
else:
... | 921c4594fd83aa891e0ee53d1d4680c8cc6a620c | 48,019 |
import argparse
def get_parser():
"""Create the argument parser"""
parser = argparse.ArgumentParser(prog="ivpm")
subparser = parser.add_subparsers()
subparser.required = True
subparser.dest = 'command'
update_cmd = subparser.add_parser("update",
help="Fetches packages specifi... | 8aa1eb8bcd275bf749e8d3082147007f62d1933b | 48,020 |
def is_update(flags):
"""Is the opcode in flags UPDATE?
*flags*, an ``int``, the DNS message flags.
Returns a ``bool``.
"""
return from_flags(flags) == Opcode.UPDATE | e4f43a77f3128c43ea127a387fc172433d111fec | 48,021 |
def get_1obj_gt_scenario():
"""
Egovehicle stationary (represented by `o`).
Seqeuence of 4-nanosecond timestamps.
|-|
| |
|-|
|-|
| |
|-|
o (x,y,z) = (0,0,0)
|-|
| |
|-|
|-|
| | (x,y,z)=(-3,2,0)
|-|
"""
centers = []
# timestamp 0
cx = -3
cy = 2
cz = 0
centers += [(cx,cy,cz)]
# timestamp 1
... | 5f528802f8b7f131fdba344e7bcf195e9414bd0b | 48,022 |
import os
import subprocess
def list_folders(root):
"""
List the folders from a root path
:param root:
:return:
"""
commands = ["find", os.path.realpath(root), "-type","d"]
results = subprocess.check_output(commands)
return results.decode().split("\n")[1:] | 04aced7c8ab264e0babe87cc1f3caa6f243de29f | 48,023 |
from typing import Optional
import binascii
def _set_mem(args: [str]) -> Optional[rdcp_command.RDCPCommand]:
"""addr:int hexadecimal_string: str"""
addr = _parse_int_expression(args[0])
value = binascii.unhexlify("".join(args[1:]))
return rdcp_command.SetMem(addr, value, handler=print) | fcba48d5c0c272bd1db99719053f1479128a3760 | 48,024 |
from re import T
def add_board():
"""Lets the user add a board."""
logger.info("My session is: %r" % session)
form = SQLFORM(db.bulletin_boards)
if form.process().accepted:
session.flash = T('Your board was created')
redirect(URL('default', 'bulletin_board', args=[form.vars.id]))
r... | 0d9d6d01a2748c99cba0f9d4ffa485259df86b2f | 48,025 |
def fuel(i: int) -> int:
"""
>>> [fuel(i) for i in [12,14,1969,100756]]
[2, 2, 654, 33583]
"""
return i // 3 - 2 | ea738361f4dc7081c5adeaf628c5424d9919e1bc | 48,026 |
from datetime import datetime
def about(request):
"""Renderea a about"""
assert isinstance(request, HttpRequest)
return render(
request,
'app/about.html',
{
'year':datetime.now().year,
}
) | f03cfb5e50a5150fdf8e0db85fec8f380b854669 | 48,027 |
import psutil
def get_proc_name_from_pid(pid):
"""
using psutil to obtain proc name from pid
:param pid:
:return: proc name
"""
return psutil.Process(pid).name() | 300ce9bcb945fce90a08b8dc2326e899180546fc | 48,028 |
def _create_local(name, shape=None, collections=None):
"""Creates a new local variable.
Args:
name: The name of the new or existing variable.
shape: Shape of the new or existing variable.
collections: A list of collection names to which the Variable will be added.
Returns:
The created variable.
... | 70dffd95cb01212016145120fc8e6e1ef7649f4c | 48,029 |
def ReadStampFile(target_os):
"""Return the contents of the stamp file, or '' if it doesn't exist."""
try:
with open(STAMP_FILE % target_os, 'r') as f:
return f.read().rstrip()
except IOError:
return '' | 6f6fcdafbdbdbb1d46b2464a7569e3cab7a4f789 | 48,030 |
def tts_langs(tld="com"):
"""Languages Naver Text-to-Speech supports.
Args:
tld (string): Top-level domain for the Google Translate host
to fetch languages from. i.e `https://translate.google.<tld>`.
Default is ``com``.
Returns:
dict: A dictionnary of the type `{ '<... | 61421d48b79bf4cc71d7b24119161299cdaea917 | 48,031 |
def matmulBackward1(grad: Tensor, t1: 'Tensor', t2: 'Tensor') -> Tensor:
"""Gradient Function that is used when
a tensor is matrix multiplied to a tensor that
requires gradient.
- Math:
let A.shape == m x n
let B.shape == n x p
Y = A @ B
F(Y) = L
... | c0c5b46e8821b6649d6402db8a528513e34accd3 | 48,032 |
import os
import glob
def get_files(file_pat):
"""Grab files from globbing pattern or stream file"""
if os.path.exists(file_pat):
root, ext = os.path.splitext(file_pat)
if ext.lower() == ".ycsv":
df, d = read_ycsv(file_pat)
fns = df.index.tolist()
else:
... | 14903f7065ea37e3392cdeef50b389653e3ec5e5 | 48,033 |
from typing import List
def make_rooks() -> List[Rook]:
"""Return list of rooks"""
rooks: List[Rook] = []
for k in range(2):
rooks.extend((
Rook(SQUARE_SIZE * k * 7, SQUARE_SIZE * 7, WHITE,
f'{PIECE_PATH}white_rook.png',),
Rook(SQUARE_SIZE * k * 7, SQUARE_S... | 68f22b46c9275e34dc73e85c19b1327729521799 | 48,034 |
from typing import List
from typing import Iterable
def _domains_in_part(part: dc.DesignPart, exclude_fixed: bool) -> List[Domain]:
"""
:param part:
DesignPart (e.g., :any:`Strand`, :any:`Domani`, Tuple[:any:`Strand`, :any:`Strand`])
:param exclude_fixed:
whether to exclude :any:`Domain`'s... | 1219b666ee93db2fcc06d6fd48f604d03980df14 | 48,035 |
def read_temporal_profiles(tracer, kind, filename):
"""\
Read temporal profiles for given `tracer` for
'weekly' or 'annual' profiles.
"""
data = {}
countries = []
snaps = []
filename = filename.format(tracer=tracer)
with open(filename, "r") as profile_file:
for line in prof... | 36718952419eebb0024321f777cafcaa23dddf56 | 48,036 |
import tests
def test_list():
"""
Retrieve a list of tests as json objects.
See the README for details on the formatting.
"""
test_json_objs = []
for test_id, test_name in enumerate(tests):
exec("name = "+test_name+".name", globals())
exec("desc = "+test_name+".desc", globals... | 89ee001a481490a48120b898b682dbd99ef4ad7d | 48,037 |
import os
def resolve_name(arguments, fname):
"""
Return right name and format for an output file.
"""
if arguments.output:
if len(arguments.filename) > 1:
if not os.path.exists(arguments.output):
os.mkdir(arguments.output)
if not os.path.isdir(arguments... | a22cedb13f86829908b81406aceeac15c73df73d | 48,038 |
import os
def is_git_repo(path):
"""
Rudimentary tests for if I have a git repo. Simply look for .git directory
**Positional Arguments:**
path:
- The path that we are assessing
"""
return os.path.exists(os.path.join(path, ".git")) and \
os.path.isdir(os.path.join(path, "... | 00c113010b4aa9a946e50ad3788b4cd110907e79 | 48,039 |
def load_embeddings(file_name: str, embeddings_format: str):
"""Load word embeddings from the given file, either in plain-text format ('text') or in gensim format ('gensim')"""
if embeddings_format == 'text':
return _load_w2v_model_file(filename=file_name)
else:
return _load_w2v_model_gensim... | a9131785ed2ffcbff6efd10c6ae736e318717842 | 48,040 |
def favicon():
"""网站图标"""
# send_static_file是flask里面的寻找static静态文件的方法。通过查看源码得知
return current_app.send_static_file('news/favicon.ico') | ba7c36e003118605d1a786305f931cf1f436a9c3 | 48,041 |
import os
def gcp_application_default_creds_exist():
"""
Return true if the application default credentials file exists.
:return: True if we can find app default creds file otherwise False.
"""
cred_file = os.path.expanduser('~/.config/gcloud/application_default_credentials.json')
return os.pa... | 0ec98a81f74fe4d20bdf2c6e1764338871c303cc | 48,042 |
def compute_tpm(
counts_df: pd.DataFrame, gene_id2length: pd.DataFrame
) -> pd.DataFrame:
"""Compute TPM values
Args:
counts_df: Dataframe containing counts
gene_id2length: Dictionary of gene ID to gene length
Returns:
pd.DataFrame: containing the TPM values
"""
scaling... | d8fc3bcfcc622b6ffb8f36dc382d23d930d2621e | 48,043 |
def sample(env, policies, num_episodes=128, max_steps=1e6, policy_fn=None):
"""Generates a batch of episodes using the given policies"""
batch = Batch()
total_steps = 0
for _ in range(num_episodes):
# Initialize episode and episode batch
obs = env.reset()
current_step = 0
... | d2aa9ccf82907f9d64684d5afa308e5e3b0a32d6 | 48,044 |
import scipy.stats as stats
import scipy.stats as stats
import numpy
def lnprior(pzero_regions, paramSetup):
"""
Function that computes the ln prior probabilities of the model parameters.
"""
priorln = 0.0
mu = 1
# import pdb; pdb.set_trace()
# ensure all parameters are finite
if ... | 22e7b57b8a261a74de22580a8a850f6f3dfbcb26 | 48,045 |
def render_template_to_file(template_path, file_path=None, **values):
"""
Render a 'jinja' template resource to a temporary file.
:param template_path: relative path to the template.
:param file_path: absolute path to the desired output file.
:param values: keyword arguments passed to jinja.
"... | 7af7e2fa2e46bf333ae35985628f81e74cd41f0d | 48,046 |
async def connect(host: str, family: str = None, comm_addr: int = 0, timeout: int = 1, retries: int = 3) -> Inverter:
"""Contact the inverter at the specified host/port and answer appropriate Inverter instance.
The specific inverter family/type will be detected automatically, but it can be passed explicitly.
... | 80ba3ba57cadcb72dc1d9f99e0d4f66f6faa6790 | 48,047 |
import os
def get_extension(filename):
"""
Gets the extension of a file
Parameters
----------
str filename: the filename to extract extension from
"""
try:
return os.path.splitext(filename)[1].replace(".", "")
except (AttributeError, TypeError):
return "" | 6cc4a9eb2755db54801b3314961b32d1104cbe7b | 48,048 |
def fit_generic_continuum(spectrum, median_window=3, model=Chebyshev1D(3),
fitter=LevMarLSQFitter(),
exclude_regions=None, weights=None):
"""
Basic fitting of the continuum of an input spectrum. The input
spectrum is smoothed using a median filter to remov... | b5e279a401a1ff94e6fa7cb0473747dd5cbf0809 | 48,049 |
def sdss_path():
"""Path for absorption/emission lines
"""
return join(_parent_path, 'SDSS') | 894eb310d6d9ad756b365a03ed411bd2569e8a1d | 48,050 |
import os
def prepare_dibco(data_dir=DEFAULT_DATA_DIR,
out_dir=None,
force=False):
""" Downloads and extracts dibco dataset and its annotation data. """
if not os.path.exists(data_dir):
os.makedirs(data_dir)
if out_dir is None:
out_dir = data_dir
if not os.path.exis... | 4b6c78e153801e7ec5908af80a56cc94f74c244d | 48,051 |
def read_log_file(
log_file,
log_entries_to_get=[
"x_pixel_um",
"y_pixel_um",
"z_pixel_um",
"image_paths",
"registration_config",
],
separator=": ",
):
"""
Reads an amap log file, and returns a dict of entries corresponding to
"log_entries_to_get"
... | f339d5cffe1ade818eda1c9ed45a4bb115ce159b | 48,052 |
import os
def lookup_env(names):
"""
Look up for names in environment. Returns the first element
found.
"""
for name in names:
value = os.environ.get(name)
if value:
return value | 0db95875d4dba3eafc659b9bb17e6a01526b599b | 48,053 |
import gzip
import re
def miles_graph():
""" Return the cites example graph in miles_dat.txt
from the Stanford GraphBase.
"""
# open file miles_dat.txt.gz (or miles_dat.txt)
fh = gzip.open('knuth_miles.txt.gz', 'r')
G = nx.Graph()
G.position = {}
G.population = {}
cities = []... | 994005c593573e097f7fb4729b8a4f3d288b002e | 48,054 |
def SetErrorHandler(*args):
"""SetErrorHandler(char const * pszCallbackName=None) -> CPLErr"""
return _gdal.SetErrorHandler(*args) | f76abdc5b689f0ed1f2ea913749b6a6fe116b32f | 48,055 |
from typing import Union
from pathlib import Path
from typing import Dict
def parse_file_path(file_path: Union[str, Path], debug: int = 0) -> Dict:
"""Parse info of timestamp,region,locationId,year from file path.
expected in the string: region/locationId/YYYY/name_YYYYMMDD_HHMMSS
possibilities:
... | 877f4b72dc24777066e48de519ab1ba81fb883b6 | 48,056 |
def get_shift_bits(n, bit_string, shift):
"""Given a bit-string, return an expression to map to the bit-string.
Each index of the given bit-string corresponds to the index of an n-bit
bit vector. This function returns those bits, using the variable for the bit
if the corresponding index in the bit-string is '1... | 6b0b396b3248eeb4cd971256edd70b8052f462e6 | 48,057 |
def get_bag_count(list_of_bags: list, colour: str) -> int:
"""
Recursive function to loop through list.
Gather rules on line.
While there are still rules to be processed, get colour and recursively call function again.
Append to total.
:return: Total amount of bags inside colour.
:rtype: in... | 593bb1d826cd996ca4725fe7e2c18043c8853021 | 48,058 |
def get_wikidata_complexes():
"""Gets all Wikidata items with a Complex Portal ID property"""
get_macromolecular = """
SELECT ?item ?ComplexPortalID
WHERE
{
?item wdt:P7718 ?ComplexPortalID .
}"""
wikidata_complexes = WDItemEngine.execute_sparql_query(
get_macromolecular, as_da... | a71a3fe63ebd67dec7ce0cb38adaf60daa8a9ad0 | 48,059 |
import socket
def _pick_port():
"""
Returns an unused TCP port.
While we can not guarantee it will stay unused, it is very unlikely
that it will become used within a few seconds.
"""
with socket(AF_INET, SOCK_STREAM) as sock:
sock.bind(("", 0))
return sock.getsockname()[1] | 2f9c0e2aa5619db6212e4dc2c78cf0ff12516447 | 48,060 |
def connection_str():
""" SQLAlchemy connection string to test database """
return "postgresql://nebulo_user:password@localhost:4442/nebulo_db" | b5220a9ce7e44acde4154686af00164d2f065a83 | 48,061 |
import os
def get_default_selection():
"""Retrieve the last response file updated."""
try:
if not os.path.exists(defaultresp_path):
return None
with open(defaultresp_path, 'r') as file_ptr:
default_selection = file_ptr.readline()
if default_selection is Non... | 62596694d6b5e072567999f3d9b3d02360bc6566 | 48,062 |
def mfi(high, low, close, volume, length=None, drift=None, offset=None, **kwargs):
"""Indicator: Money Flow Index (MFI)"""
# Validate arguments
length = int(length) if length and length > 0 else 14
high = verify_series(high, length)
low = verify_series(low, length)
close = verify_series(close, l... | ee73c35c4f704360155a1365cdd8eae78d5d0388 | 48,063 |
def load(filename):
"""
"""
with open(filename, "rb") as file_:
data = read(file_)
return data | efc01f2411e910d169d642ed76117cdcff30d6e7 | 48,064 |
import numpy
def caf_L05burst2(CFR, lMmax, t0, burstamp, ltbegin, ltend):
"""
Generate age distribution (CAF) following L05 & add a starburst
"""
# Assume CIMF is a -2 power-law powerlaw
# Follow the evolve MF notation in Gieles 2009, MNRAS
# Fixed model parameters:
lMlim = 2 # minimum m... | 72b0ad5461d728ed371da7d147af85a193cdfd1f | 48,065 |
def Y_tester():
"""
>>> tmp = Y_tester()
>>> tmp(1)
1
>>> tmp(5)
120
>>> tmp(2)
2
"""
"*** YOUR CODE HERE ***"
return Y(lambda f: lambda x: 1 if x == 1 else x * f(x - 1)) | d374a1226da538b7b105de0a8b2ab1e0e2ab5fbc | 48,066 |
def segment_arm(frame: np.ndarray, abs_depth_dev: int = 14) -> np.ndarray:
"""Segments arm region
This method accepts a single-channel depth image of an arm and
hand region and extracts the segmented arm region.
It is assumed that the hand is placed in the center of the image.
:para... | 2647e66570c12237aa242cf22cf27872d395ef2c | 48,067 |
import os
def files_to_list(folder_directory: str) -> list:
"""Read the files in the folder with .txt to a list
Args:
directory (str): the directory to find files
Returns:
list: list with all the files turned into str
"""
dataset = []
director... | 530941e8572a748045c14c4ca9ebdba1c844a42a | 48,068 |
def tiploc_record(records):
"""return CIF file TIPLOC object from 80-character line string"""
this_array = [[line[0:2],line[2:9],line[9:11],line[11:17],line[17:18],line[18:44],line[44:49],line[49:53],line[53:56],line[56:72],line[72:79]] for line in records]
this_frame = pd.DataFrame(data=this_array, columns... | a2b2737b924ad94ec831fd5206bcf259f3602ee0 | 48,069 |
def sort(args) -> list:
"""Performs a sort based on the given args.
Args is of the format (dist, auc, n0, n1) and is one tuple/list.
Throws an error if the array did not sort correctly.
Returns the results."""
dist, auc, n0, n1 = args
results = list()
data, D0, D1 = continuousScale(n0, n1)
comp = Comparator(dat... | a61156e1de8fd37473c5cfc1a596b8d9511d061c | 48,070 |
import os
def needs_rebuild(source, target):
"""Checks if the source file needs to be rebuilt.
Args:
source: The source file to be compared.
target: The target file which we may need to rebuild.
Returns:
True if the source file is newer than the target, or if the target file
does... | 5147d72f2e0a8fad7fc2d63b2fa39025f554defa | 48,071 |
import io
import gzip
import contextlib
import logging
def http_request(url, post=None, headers=None):
"""request data from the HTTP API, returns the response a string. If a
http error occurs it will *not* raise an exception, instead it will
return the content of the error document. This is because we get... | 2e344bdb0561d850a8b2865a280c987d0959f616 | 48,072 |
def org_new(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /org/new API method.
For more info, see: https://documentation.dnanexus.com/developer/api/organizations#api-method-org-new
"""
input_params_cp = Nonce.update_nonce(input_params)
return DXHTTPRequest('/org/new', input_par... | 200489839e21485c8fb862a66e2a3cb0d42865a0 | 48,073 |
import platform
def get_log_path(subfolder=None, filename=None, create=True):
"""
Returns the default log path for the platform. This will be:
- macOS: '~/Library/Logs/SUBFOLDER/FILENAME'
- Linux: '$XDG_CACHE_HOME/SUBFOLDER/FILENAME'
- fallback: '$HOME/.cache/SUBFOLDER/FILENAME'
... | e09157cb91ef378c25dc0fe116c89cc5398b7af3 | 48,074 |
import os
def save_dependence_grid(dirname, kendalls, bounds_tau, grid_type):
"""Save a grid of kendall's into a csv ifile.
The grid is always saved in Kendall's Tau measures.
Parameters
----------
dirname : str
The directory path.
kendalls : list or array
The kendall's tau of... | 79c036d570390518882ea31de94f04422d83e10c | 48,075 |
from typing import Any
def frozen_after_init(cls: C) -> C:
"""Class decorator to freeze any modifications to the object after __init__() is done.
The primary use case is for @dataclasses who cannot use frozen=True due to the need for a custom
__init__(), but who still want to remain as immutable as possi... | 367ee5c692c98aefcc1ea3905e352483d47c43f1 | 48,076 |
async def async_get_trigger_capabilities(
hass: HomeAssistant, config: ConfigType
) -> dict[str, vol.Schema]:
"""List trigger capabilities."""
return {
"extra_fields": vol.Schema(
{vol.Optional(CONF_FOR): cv.positive_time_period_dict}
)
} | bdc59bd309228f5e3df8ad7994ee8ab5c675dd60 | 48,077 |
def check_key_expired(key, node, url):
"""check if key expired if is return url with args so it will push status message
else return url
:param str key: the private link key passed in
:param Node node: the node object wants to access
:param str url: the url redirect to
:retur... | 6d7a64df855dc2dc235dca2fdce14162d71673f3 | 48,078 |
from datetime import datetime
def set_entity_props(entity, args):
""" 设置实体对象属性 """
for column in entity.__table__.columns:
value = args[column.name]
if value is None:
continue
if type(column.type) == db.DateTime:
if value is None:
value = 0
... | 62be944db6541cd3df90b45e9f1008fa535e8f0b | 48,079 |
from typing import Type
from typing import Any
def adsSyncReadByNameEx(
port: int,
address: AmsAddr,
data_name: str,
data_type: Type,
return_ctypes: bool = False,
handle: int = None,
check_length: bool = True,
) -> Any:
"""Read data synchronous from an ADS-device from data name.
:... | 92242e2102c7d8525473b723ed3b18a77d0976e6 | 48,080 |
from covid.impl.util import compute_state
def regularize_occults(events, occults, init_state, stoichiometry):
"""Regularizes an occult matrix such that counting
processes are valid
:param events: a [M, T, X] events tensor
:param occults: a [M, T, X] occults tensor
:param init_state: a [M, S] init... | 087e94d4e41b213094929f265052a01ceb29f314 | 48,081 |
from typing import Tuple
from typing import Dict
from typing import List
def calc_hist_by_group(
df: dd.DataFrame, bins: int, ngroups: int, largest: bool
) -> Tuple[pd.DataFrame, Dict[str, int]]:
"""
Compute a histogram over the values corresponding to the groups in another column
Parameters
----... | 54490fd414bd5d14e8753236fb87cc29430683bf | 48,082 |
def _get_filename(step: base_layer.JTensorOrPartitionSpec) -> str:
"""Returns a filename for the given step."""
step_num = _get_step(step)
return f'decoder_out_{step_num}_shard_{jax.process_index()}' | 7273126af9e62138502a17b7e4cdf87e3579acb0 | 48,083 |
def add_ticket_submit(request):
"""
Ajax submit ticket form.
"""
ticketform = AddTicketForm(request, request.POST)
dc_settings = request.dc.settings
if ticketform.is_valid():
# Send mail to SUPPORT_EMAIL
sendmail(None, 'gui/support/add_ticket_subject.txt', 'gui/support/add_ticke... | abe83eb1783636759278b1468f72e2927c4247c3 | 48,084 |
def order_genes(genes, species, genomes):
"""Returns a list of ordered genes for the specified species, on a given
strand of a given chromosome.
:param genes: list of genes for species (on a given strand of a given
chromosome)
:param species: KEGG organism code
:param genomes: dict of dicts... | a637a14a03d876dc2bf25f01d0ca30a983906f26 | 48,085 |
import re
def perform_search(query):
"""
The perform_serach function takes the query entered by a user and presents the list of documents
that best match the search words entered sorted by their rank results
Args:
query (str): A string containing the query terms entered by the user
... | 2e26177aec3c2d3e0cd38d60e056bb42231ca456 | 48,086 |
def load_image(fname, enforce=None):
"""**[Deprecated]** Imports an image file as an SDL surface.
This function uses either the SDL_image library or the Pillow Python package
for importing images, using SDL2's built-in BMP loader as a fall-back if
neither are available.
.. warning::
Due to ... | 2de4ffea1e73cea5a2a40fd823f770713d0de920 | 48,087 |
import os
def report_this_test_run(suite, make_benchmarks, note, update_time,
test_list, test_file):
""" generate the master page for a single run of the test suite """
# get the current directory
current_dir = os.getcwd()
# switch to the web directory and open the report fi... | 4f04fa83f2eb4b11cea51a9e20dec6b609f2c8f4 | 48,088 |
def xent(pred, label):
""" Calculates Cross Entropy Loss
Args:
pred: Tensor of label predictions
label: Tensor of golden labels (True values)
returns:
Mean Squared Error of predictions and labels
"""
# Note - with tf version <=0.12, this loss has incorrect 2nd deriva... | ca485fda60329afcbc8fcb0555cb9b0ae310b166 | 48,089 |
def scale_image(img: np.ndarray)->np.ndarray:
"""
Return a copy of the array where all non-zero values have been scaled
between 0 and 1
:param img: img to be scaled
"""
mn = np.min(img)
mx = np.max(img)
return ((img-mn)/(-mn+mx))*(img != 0) | d20925baebdbc452eadf7f2dbc12afee31621919 | 48,090 |
def get_dependencies(pom):
"""
Return a list of Dependent package objects found in a MavenPom `pom` object.
"""
dependencies = []
for scope, deps in pom.dependencies.items():
if TRACE:
logger.debug('parse: dependencies.deps: {}'.format(deps))
if scope:
scope =... | 04bff0aa629ca7a38107e9a02cef4b8e8d498b94 | 48,091 |
from typing import Tuple
from typing import Pattern
def format_m_year_execute(input_string:str, match_pattern:Tuple[Pattern, str]) -> str:
"""
Core of loop for format_m_year_strings
"""
return_string = str(input_string) # type:str
search_pattern, month_number = match_pattern # type: Pattern, str
... | 7e1e5d1e897e741d6d63a87fe91b8b37cc9a84bc | 48,092 |
from datetime import datetime
import json
def create_accurat_request(article, request_id, text, src, tgt):
"""This method creates a translation request for MT-Serverland."""
shortname = "accurat_%s_%s" % (request_id,
datetime.datetime.now().isoformat())
# submit a n... | bf939239a06ab94042f625350223fd477153f22b | 48,093 |
from typing import Dict
import yaml
def load_yaml_into_dict(file_path: str) -> Dict:
"""
This loads yaml files into a dictionary to be used in API calls.
"""
with open(file_path, "r") as yaml_file:
loaded = yaml.safe_load(yaml_file)
if isinstance(loaded, dict):
return loade... | 891439af7cdd0e83f360b7398c98890419e8232f | 48,094 |
def get_by(session, model, primary_key_value, primary_key=None):
"""Returns the first instance of `model` whose primary key has the value
`primary_key_value`, or ``None`` if no such instance exists.
If `primary_key` is specified, the column specified by that string is used
as the primary key column. Ot... | 53b30555930e987fff4777f068bd411dfc3ef4a0 | 48,095 |
def group(name: t.Optional[str] = None,
**attrs: t.Any) -> t.Callable[[F], TaskioGroup]:
"""Creates a new :class:`Group` with a function as callback. This
works otherwise the same as :func:`command` just that the `cls`
parameter is set to :class:`Group`.
"""
attrs.setdefault("cls", Taskio... | dcc0c948d59e617123c31f0cc9f77c3292b436db | 48,096 |
def compute_adiabatic_tf(ds, base_var):
"""Compute adiabatic tendencies as in Pierre's TF version
Args:
ds: xarray dataset
base_var: Base variable to be computed
Returns:
adiabatic: xarray dataarray
"""
adiab = (ds[base_var].diff(dim='time', n=1) / dt_sec - ds[phy_dict[base... | 7c21c2faaf35ad80f89b855442fdbb97fa5e6fca | 48,097 |
from typing import Union
def _get_reception_time_from_scene_dir_second(scene_dir_second: str) -> Union[str, None]:
"""If there is time datum inside `scene_dir_second` string, then return it.
Otherwise, return None."""
# second part of scene dir, it can be: `13_53_00`,
# `13_53_00_ETC2`, `14_35_23_CB1... | 89cf95ed1f110c6641de4eae6ac8230d78a7b802 | 48,098 |
import json
import requests
def get_arc_servicedict(url):
"""Returns a dict of service information for an ArcGIS REST service URL
Arguments
url (String): An ArcGIS REST service URL,
e.g. 'http://services.slip.wa.gov.au/arcgis/rest/services/QC/MRWA_Public_Services/MapServer'
"""
... | 80a1775d809c63ea34729c02ddcf98b8488fd825 | 48,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.