content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def train_valid_or_test():
"""
主程序
:return:
"""
# 建立参数、数据、模型、模型最佳值
pas = Params()
p = pas.p
model, model_name, size = pas.build_model_one_by_one(flag=p['prme'])
best = GlobalBest(at_nums=p['at_nums'])
_, starts_ends_tes = pas.compute_start_end(flag='test')
_, starts_ends_auc ... | 60,000 |
def get_phi(row):
"""Helper function for rotating data.
row: 2D-entry in matrix with shape (?, 2)
"""
return np.arctan2(row[0], row[1]) | 60,001 |
def _get_export_path(path, working_path):
"""Creates an export path and filename (with extension).
Arguments:
path (str): The input file path.
working_path (str): Working path
Returns:
(str): Export file path.
"""
filename, extension = _basename(path)
export_path = os.p... | 60,002 |
def clone(id, path):
"""
- Download all files in a dataset or from a Job output
Eg: alice/projects/mnist/1/files, alice/projects/mnist/1/output or alice/dataset/mnist-data/1/
Using /output will download the files that are saved at the end of the job.
Note: This will download the files that are sa... | 60,003 |
def verifyProxy(ip, type):
"""
验证代理的有效性
"""
request_header = {
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36"
}
url = "http://www.baidu.com"
# 填写代理地址
proxy = {type: ip}
# 创建proxyHandler
proxy_ha... | 60,004 |
def execute_orca(inp_tp, work_dir, exec_cmd, subs=None, subs_delims=("<",">"),
sim_name="orcarun",
inp_ext=_DEF.FILE_EXTS[_E_SW.ORCA][_E_FT.INPUTFILE],
out_ext=_DEF.FILE_EXTS[_E_SW.ORCA][_E_FT.OUTPUT],
wait_to_complete=True,
bohrs=False):
"""Executes |orca... | 60,005 |
def str_aula(value): # Only one argument.
"""Converts a string into all lowercase"""
if(value == True):
return "Sim"
else:
return "Nao" | 60,006 |
def unions_buffered(contig, buffer, lower_bound='start', upper_bound='stop'):
"""
Calculate interval unions among loci of a contig and extend them
with a non-overlapping buffer.
The new cluster intervals will contain only fields of the upper
and lower bounds of clusters which may be named with the
... | 60,007 |
def backtrack(maps, k):
"""
1. string map을 입력받아 백트래킹시 현재 상태의 저장이 필요
@param maps: list
@param k: int
@return: None
"""
if k == 5:
max_value = 0
for i in range(n):
for j in range(n):
if max_value < maps[i][j]:
max_value = maps[i][... | 60,008 |
def coll_exc_xsec(eng, species=None):
""" e-e collisional excitation cross section in cm\ :sup:`2`\ .
See 0906.1197.
Parameters
----------
eng : float or ndarray
Abscissa of *kinetic* energies.
species : {'HI', 'HeI', 'HeII'}
Species of interest.
Returns
-------
f... | 60,009 |
def test_get_smallest_intervals_between_pitch_classes(key: tuple[str, str], value: int) -> None:
"""Test `get_smallest_intervals_between_pitch_classes` function."""
mapping = get_smallest_intervals_between_pitch_classes()
assert mapping[key] == value | 60,010 |
def mirror_tree(root: TreeNode):
"""
Offer 27 二叉树的镜像
:param root:
:return:
"""
if not root:
return []
nodes = [root]
while nodes:
node = nodes.pop(0)
node.left, node.right = node.right, node.left
if node.left:
nodes.append(node.left)
i... | 60,011 |
def get_scheduled_query_output(arn: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetScheduledQueryResult]:
"""
The AWS::Timestream::ScheduledQuery resource creates a Timestream Scheduled Query.
"""
... | 60,012 |
def reverse_digit(x):
"""
Reverses the digits of an integer.
Parameters
----------
x : int
Digit to be reversed.
Returns
-------
rev_x : int
`x` with it's digits reversed.
"""
# Initialisations
if x < 0:
neg = True
else:
neg ... | 60,013 |
def yyyymmdd(d, separator=''):
"""
:param d: datetime instance
separator: string
:return: string: yyyymmdd
"""
month = d.month
if month < 10:
month = '0' + str(month)
else:
month = str(month)
day = d.day
if day < 10:
day = '0' + str(day)
else:
... | 60,014 |
def _download(url, path):
"""
Download a file from the Google drive and save it at the given ``path``.
"""
logger.info('Downloading %s', url)
google.download(url, path) | 60,015 |
def recurrent_layers(
value,
layer_sizes,
bidirectional=True,
dropout=0.0,
rnn_type="lstm",
return_sequences=False):
"""
Make one or more RNN layers
"""
if rnn_type == "lstm":
rnn_class = LSTM
elif rnn_type == "gru":
rnn_class = GRU
... | 60,016 |
def load(environment="common"):
"""Load configuration parameters for an environment, or the common
configuration shared by all environments.
"""
basedir = os.path.abspath(
os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
)
settingsdir = os.path.join(basedir, "backend", "main",... | 60,017 |
def describe_domain(FleetArn=None, DomainName=None):
"""
Provides information about the domain.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_domain(
FleetArn='string',
DomainName='string'
)
:type FleetArn: string
:par... | 60,018 |
def _applicable_weight_based_methods(weight, qs):
"""Return weight based shipping methods that are applicable for the total weight."""
qs = qs.weight_based()
min_weight_matched = Q(minimum_order_weight__lte=weight) | Q(
minimum_order_weight__isnull=True
)
max_weight_matched = Q(maximum_order... | 60,019 |
def write_to_file(output_file_handle_dict, inferred_text, line_count, limits, cues):
"""Write the inferred text to SRT file
Follows a specific format for SRT files
Args:
output_file_handle_dict : Mapping of subtitle format (eg, 'srt') to open file_handle
inferred_text : text to be written
... | 60,020 |
def path(a, b):
""" A path of nodes from a to b
>>> from blaze.expr.table import TableSymbol
>>> t = TableSymbol('t', '{name: string, amount: int, id: int}')
>>> expr = t['amount'].sum()
>>> list(path(expr, t))
[sum(t['amount']), t['amount'], t]
"""
while not a.isidentical(b):
y... | 60,021 |
def index_phenomenon(es, index_l, type_l, phenomenon = None, threshold=0):
"""
Indexes a phenomenon of a file.
Returns the id that the phenomenon will have in the database.
"""
if phenomenon is None:
return
pid = None
pid = abs(hash(str(phenomenon)))
phenomenon["id"] = pid
... | 60,022 |
def _run_hive_query(cursor, query, has_results=False):
"""
Executes a given hive query on a specified database
:param cursor: cursor to run queries on
:param query: the specified hive query to run
:return: results
"""
_print_debug('Executing query: {}'.format(query))
cursor.execute(query... | 60,023 |
def main():
""" heconsole main entrypoint """
ret = 0
if '--help' in sys.argv or '-h' in sys.argv or len(sys.argv) == 1:
print(__doc__)
else:
program = sys.argv[1]
args = sys.argv[2:]
try:
if args:
ret = subprocess.call([program] + args)
... | 60,024 |
def _imwread(imgName):
""" Reads a *.imw file. imgName should come with no extension. """
w, h = _readDim(imgName + '.dim')
return _readImage(imgName + '.imw', w, h, '>H', 2) | 60,025 |
def train(**kwargs):
"""
Train network
https://docs.deep-hybrid-datacloud.eu/projects/deepaas/en/latest/user/v2-api.html#deepaas.model.v2.base.BaseModel.train
:param kwargs:
:return:
"""
message = { "status": "ok",
"training": [],
}
import os
# use ... | 60,026 |
def sync_ensemble(workers: WorkerSet) -> None:
"""Syncs dynamics ensemble weights from driver (main) to workers.
Args:
workers (WorkerSet): Set of workers, including driver (main).
"""
def get_ensemble_weights(worker):
policy_map = worker.policy_map
policies = policy_map.keys()... | 60,027 |
def last_days_quotations(request):
"""Return last days quotations of a currency.
Keyword arguments:
request -- parameters [ days, currency ]
"""
args = request.GET
days = int(args.get('days', None))
currency = args.get('currency', None)
quotations = Quotation()
quotations_list = qu... | 60,028 |
def cksum(buf):
"""Return computed CRC-32c checksum."""
return done(add(0xffffffff, buf)) | 60,029 |
def yuv420_to_rgb(image_y: Tensor, image_uv: Tensor) -> Tensor:
"""Convert an YUV420 image to RGB. Image data is assumed to be in the
range of [0.0, 1.0] for luma and [-0.5, 0.5] for chroma. Input need to be
padded to be evenly divisible by 2 horizontal and vertical. This function
assumed chroma siting ... | 60,030 |
def read_sensor_types_file(csv_file: str) -> []:
"""
Read in a csv file
:param csv_file: path to file
:type: csv_file: str
:return: sensor_types
:rtype: dict
"""
sensor_types = {}
with open(csv_file, mode='r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for ... | 60,031 |
def task_say_hello(self, room, caller):
"""
Send the "hello" message to a Spark space.
Args:
room: A :py:obj:`dict` that identifies the Spark space (room) where
the output should be sent. Note the identified room can be either
a group room (> 2 people) or a 1-on-1 room.
... | 60,032 |
def ping(value=0):
"""Return given value + 1, must be an integer."""
return {'value': value + 1} | 60,033 |
def Lf(lo, hi):
"""Log-uniform distributed floatint point number."""
return math.exp(random.uniform(math.log(lo), math.log(hi))) | 60,034 |
def the_task_ends_with_status(step, status):
""" Wait for task execution and check task status """
print "TEST DATA - Region: {}; Image: {}; Flavor: {}".format(world.region_name, world.image_sdc_aware_id,
world.flavor_id)
check_task_status(wor... | 60,035 |
def main():
"""Main function that runs histogram equalization metric battery on an image."""
import argparse
import hist._cmd_line_util as cui
parser = argparse.ArgumentParser(
description='Calculate a series of metrics on the histogram equalization on an image')
cui.add_input_image(parser)... | 60,036 |
def test_default_args():
"""
Verify that default arguments are properly passed to the isolated function call.
"""
def isolated_function(arg1='default1', arg2='default2', arg3='default3'):
return arg1, arg2, arg3
# Sanity check
assert isolated_function.__defaults__ == ('default1', 'defau... | 60,037 |
def partition_data(array, partition_size=500, seed=None):
"""Partition the into multiple groups with given size
It will partition the data with same schema if seed is consistent for
each partitioning
Args:
array (array)
partition_size(int): size of each partition group, default=500
... | 60,038 |
def add_character(story, name='"Merquivest Monogarymbalid"', role="stranger"):
"""
Adds a new character to the story with the given name and role. Returns the
id Predicate for the added character.
"""
character = next_id_prs(story, "chr", 1)[0]
story.add(character)
story.add( intrinsic_pr(story, character... | 60,039 |
def cli():
"""Command-line interface (looks at sys.argv to decide what to do)."""
import getopt
class BadUsage(Exception): pass
_adjust_cli_sys_path()
try:
opts, args = getopt.getopt(sys.argv[1:], 'bk:n:p:w')
writing = False
start_server = False
open_browser = False... | 60,040 |
def resize_image_and_boxes(image, boxes, new_size):
""" Resizes image and boxes.
:param image: Image to resize.
:param boxes: Boxes to resize.
:param new_size: New size of the image.
:return: Resized image and boxes.
"""
resized_image = image.resize(new_size)
scale = np.zeros(2)
sca... | 60,041 |
def InstallerNotifyServer():
"""An emergency function Invoked when the client installation failed."""
# We make a temporary emergency config file to contain the new client id. Note
# that the notification callback does not really mean anything to us, since
# the client is not installed and we dont have basic in... | 60,042 |
def _standard_frame_length(header):
"""Calculates the length of a standard ciphertext frame, given a complete header.
:param header: Complete message header object
:type header: aws_encryption_sdk.structures.MessageHeader
:rtype: int
"""
frame_length = 4 # Sequence Number
frame_length += h... | 60,043 |
def train_opts(parser):
"""
These options are passed to the training of the model.
Be careful with these as they will be used during unmixing.
"""
group = parser.add_argument_group('General')
group.add('--src_dir', '-src_dir', type=str, required=True,
help="System path to the Samson director... | 60,044 |
def f(x):
"""
Quadratic function.
It's easy to see the minimum value of the function
is 5 when is x=0.
"""
return x**2 + 5 | 60,045 |
def encrypt(pubkey_path, file_path, output_path, mode="r"):
"""Encrypt file with PublicKey
@param pubkey_path: the publickey path
@param file_path: the file need to be encrypted
@param mode: the file open mode
@param output_path: the output file path
"""
key = RSA.importKey(open(pubkey_path).read())
wi... | 60,046 |
def execute_query(sql_query_file: str,
query_params: dict,
target_table: str,
client):
"""Helper function to exectue a query
Arguments:
- sql_query_file: Full path to the .sql file that contains the query.
Any query parameters should be wit... | 60,047 |
def coerce_retention_period(value):
"""
Coerce a retention period to a Python value.
:param value: A string containing the text 'always', a number or
an expression that can be evaluated to a number.
:returns: A number or the string 'always'.
:raises: :exc:`~exceptions.ValueError` ... | 60,048 |
def daily_log_return(close, fillna=False):
"""Daily Log Return (DLR)
https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe
Args:
close(pandas.Series): dataset 'Close' column.
fillna(bool): if True, fill nan values.
Returns:
pandas.Series: New fea... | 60,049 |
def find_links_fast(communities_grouped, max_parent_combinations, offsets,
min_forward_containment=0, min_backward_containment=0,
reverse_mappings=None):
"""find_links_fast
Under development.
"""
n_largest_combos = 0
edge_list = []
for i, communities in enumerate(communiti... | 60,050 |
def read(path):
"""Return dict-like object of config parameters from file path."""
return ConfigObj(path, unrepr=True) | 60,051 |
def builds_file(file: str, do_clean: bool = False) -> Dict[str, PyssectGraph]:
"""Takes a python file and returns the corresponding PyssectGraph"""
with open(file, 'r') as f:
return ASTtoCFG().build(ast.parse(f.read()), do_clean) | 60,052 |
def dropLabels(events, minPct=.05):
"""
# apply weights, drop labels with insufficient examples
"""
while True:
df0 = events['bin'].value_counts(normalize=True)
if df0.min() > minPct or df0.shape[0] < 3:
break
print('dropped label: ', df0.argmin(), df0.min())
... | 60,053 |
def get_partitions(raw_data_id):
"""
获取rt_id对应的kafka topic的partition数量
@:param rt_id: result_table表的id
:return: kafka上rt_id对应的topic的分区数量
"""
rawdata = model_manager.get_raw_data_by_id(raw_data_id)
if rawdata:
kafka_bs = _get_rawdata_kafka_bootstrap_server(rawdata)
if kafka_bs... | 60,054 |
def plot_confusion_matrix(
Y_pred,
Y_true,
config,
target_names=None,
species_dict=None,
title="Confusion matrix",
cmap=None,
normalize=False,
scores=False,
score_size=12,
save=None,
):
"""Plot a confusion matrix of the predicted labels and the true labels for
the tes... | 60,055 |
def csv_states(filename, bot_filtered=True):
"""
Writes the states to file.
"""
db = twitterproj.connect()
template = "{},{},{}"
with io.open(filename, 'w', encoding='utf-8') as f:
f.write("# state name, state abbrev, fips\n")
lines = []
for state in twitterproj.hashtag_... | 60,056 |
def test_rotate(angle):
"""We can rotate a vector."""
r, theta = vec2(1, 1).rotated(angle).to_polar()
assert theta % tau == approx((angle + tau / 8) % tau)
assert r == approx(2 ** 0.5) | 60,057 |
def test_deploy_package(qipkg_action, tmpdir, record_messages):
""" Test Deploy Package """
try:
import qi
d_proj = qipkg_action.add_test_project("d_pkg")
pml_path = os.path.join(d_proj.path, "d_pkg.pml")
d_package = qipkg_action("make-package", pml_path)
url = get_ssh_ur... | 60,058 |
def latest(history_secs=600, max_data_points=200):
"""
Retrieve latest data, with sampling to indicated
number of data points
NOTE: all speedtests are always returned
"""
return {
'ip_local': ip.local(),
'speedtest': DATA['speedtest'],
** {
k: _sample_buffer(... | 60,059 |
def expand_modules(
files_or_modules: List[str],
ignore_list: List[str],
ignore_list_re: List[Pattern],
ignore_list_paths_re: List[Pattern[str]],
) -> Tuple[List[ModuleDescriptionDict], List[ErrorDescriptionDict]]:
"""Take a list of files/modules/packages and return the list of tuple
(file, modu... | 60,060 |
def RegisterDolphinFixture(server):
"""Registers API of DolphinBFTFixture."""
dolphin = dolphin_bft_fixture.DolphinBFTFixture()
dolphin.Init(**DOLPHIN_RAIDEN_CONF)
server.register_instance(dolphin) | 60,061 |
def calc_chi2_stats(df_popl, df_cust, attributes, alpha=0.05, exclude_na=True, use_perc=True):
"""
Calculates the chi-sq stays for the attribute to compare the
similarities between population and customer
ref: https://machinelearningmastery.com/chi-squared-test-for-machine-learning/
:params df_popl:... | 60,062 |
def hammingDistance(str1, str2):
""" Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`.
Args
---
`str1 : string` The first string
`str2 : string` The second string
Returns
---
`differences : int` The differences between `str1` and `str2`
... | 60,063 |
def prepare_data(df, n_cell_x, n_cell_y):
"""
Feature engineering and computation of the grid.
"""
# Creating the grid
size_x = 10. / n_cell_x
size_y = 10. / n_cell_y
eps = 0.00001
xs = np.where(df.x.values < eps, 0, df.x.values - eps)
ys = np.where(df.y.values < eps, 0, df.y.values ... | 60,064 |
def powerstat_ucsc(sg, wanted_servers):
"""
Get the power status of the UCS Central servers.
"""
try:
handle = UCSCUtil.ucsc_login(sg)
except KubamError as e:
return jsonify({"error": str(e)}), Const.HTTP_UNAUTHORIZED
try:
powerstat = UCSCServer.list_servers(handle)
... | 60,065 |
def _interpret_parameters(params):
"""Replace params with 'value' and 'width' with a Const object
having that specific value and width
Example:
'param1': {'value': 10, 'width': 8}
is replaced with:
'param1': Const(10, shape=(8))
:param params: dict of {'name': val} where val is... | 60,066 |
def _from_pretrained(cls, *args, **kw):
"""Load a transformers model in TF2, with fallback to PyTorch weights."""
try:
return cls.from_pretrained(*args, **kw)
except OSError as e:
logging.warning("Caught OSError loading model: %s", e)
logging.warning(
"Re-trying to convert from PyTorch checkpo... | 60,067 |
def get_frame_durations(file):
"""
Return an array of each frame duration in the given file. Durations are
in milliseconds.
"""
pos = file.tell()
frame_durations = []
last_frame_timestamp = None
def collect_timestamps(frame, timestamp):
timestamp = round(timestamp*1000)
... | 60,068 |
def pedirOpcion():
"""Pide y devuelve un entero en el rango de opciones validas"""
correcto = False
num = 0
while not correcto:
try:
num = int(input("Elige una opcion -> "))
if num < 0 or num > 3:
raise ValueError
correcto = True
excep... | 60,069 |
def option_comment(path_to_dot_setting, option_name, comment):
"""Returns 200: Successful,
201: Option name was not found in .setting.xml file, file could be corrupted"""
file_r = open(path_to_dot_setting, 'r')
file_temp = open(path_to_dot_setting + '.temp', 'w')
file_r_contents = file_r.readlin... | 60,070 |
def extract_preprocessing_json(root: str):
"""
:param root:
:return:
"""
vols_xymin, vols_ccords = dict(), dict()
for path in tqdm(sorted(glob(root))):
volume_name = "_".join(path[:-5].split("/")[-2:])
with open(path, 'rb') as file:
json_file = json.load(file)["shap... | 60,071 |
def slugurl(context, slug):
"""Returns the URL for the page that has the given slug."""
page = Page.objects.filter(slug=slug).first()
if page:
return pageurl(context, page)
else:
return None | 60,072 |
def _order_dict(d):
"""Convert dict to sorted OrderedDict"""
if isinstance(d, dict):
d = [(k, v) for k, v in d.items()]
d = sorted(d, key=lambda x: x[0])
return OrderedDict(d)
elif isinstance(d, OrderedDict):
return d
else:
raise Exception('Must be dict or Ordered... | 60,073 |
def _sampling_probabilities(indices):
"""
Compute marginal sampling probabilities for each training point so
that the classes will be balanced.
"""
N, k = indices.shape
probs = np.zeros(N)
for i in range(k):
not_missing = indices[:,i] != -1
probs[not_missing] += 1./(np.s... | 60,074 |
def AddToPruningCollections(weight,
mask,
threshold,
gradient=None,
old_weight=None,
old_old_weight=None):
"""Add mask, threshold, and weight vars to their respective collections... | 60,075 |
def plot_proj_error(traj_top, traj_left, X, Y, Z, cam_top, cam_left, time, savedir='data_treat/Reproj_error.png', plot=True):
"""Plot the reprojected trajectory for each camera to check for the trajectory errors
:param traj_top,traj_left: screen trajectory for the top and left cameras
:param X,Y,Z:... | 60,076 |
def findmodulefiles(output=None):
"""Produce a file containing a list of (modulename, filename-or-None)
tuples mapping module names to source files"""
# Immedeately grab the names
import sys
module_names = sys.modules.keys()[:]
import os
if not output:
if os.name == 'mac':
import macfs
output, ok = m... | 60,077 |
def temp_monthly():
"""Returns temperature obs from the database"""
session = Session(bind=engine)
year_ago = dt.date(my_date.year, my_date.month, my_date.day) - dt.timedelta(days=365)
# In the function (logic should be the same from the starter_climate_analysis.ipynb notebook):
# Calculate the date 1 y... | 60,078 |
def test_delete(app):
"""Test record indexing."""
with app.app_context():
recid = uuid.uuid4()
record = Record.create({'title': 'Test'}, id_=recid)
db.session.commit()
client_mock = MagicMock()
RecordIndexer(search_client=client_mock).delete(record)
client_mock.... | 60,079 |
def get_comment_app():
"""
Get the comment app (i.e. "commentary") as defined in the settings
"""
# Make sure the app's in INSTALLED_APPS
comments_app = _get_setting('APP', DEFAULT_COMMENTS_APP)
if not apps.is_installed(comments_app):
raise ImproperlyConfigured(
'The COMMENTS... | 60,080 |
def say(s):
"""prints to screen or webpage"""
if context=='browser':
_appendToBody(s)
else:
print(s) | 60,081 |
def get_report_types():
"""Get the types of reports that are available
:rtype: list
"""
return [{"type": key, "name": val["name"]} for key, val in REPORTS.items()] | 60,082 |
def read_fasta(fasta_file):
"""
read a fasta file and retrieve its sequences
"""
sequences = AlignIO.read(fasta_file, "fasta")
return sequences | 60,083 |
def display_get_rule_name():
"""display function to prompt for the name of the rule to add"""
return input("Name of the rule to add: ") | 60,084 |
def target(observation: Union[int, float], *, label: str = "") -> None:
"""Calling this function with an ``int`` or ``float`` observation gives it feedback
with which to guide our search for inputs that will cause an error, in
addition to all the usual heuristics. Observations must always be finite.
H... | 60,085 |
def _get_stack_status(stack_name, region):
"""
Returns the stack status which will be one of:
'CREATE_IN_PROGRESS'
'CREATE_FAILED'
'CREATE_COMPLETE'
'ROLLBACK_IN_PROGRESS'
'ROLLBACK_FAILED'
'ROLLBACK_COMPLETE'
'DELETE_IN_PROGRESS'
'DELETE_FAILED'
... | 60,086 |
def in_virtualenv() -> bool:
"""Return True when pype is executed inside a virtual env."""
return (
hasattr(sys, 'real_prefix')
or (
hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
) | 60,087 |
def parse_varint(stream):
"""
Parses SQLite's "varint" (short for variable-length integer) as mentioned here: https://www.sqlite.org/fileformat2.html#varint
"""
usable_bytes = read_usable_bytes(stream)
value = 0
for index, usable_byte in enumerate(usable_bytes):
# For all bytes except ... | 60,088 |
def _fix_matplotlib_crash():
"""Set Matplotlib backend to avoid a crash.
The default Matplotlib backend crashes Python on OSX when run on a thread
that's not the main thread, so here we set a safer backend as a fix.
Users can always disable this behavior by setting the config
runner.fixMatplotlib =... | 60,089 |
def _latest_input() -> Path:
"""Since the exports are complete exports, can just use the most recent export"""
return last(sorted(get_files(config.export_path), key=lambda p: p.stat().st_mtime)) | 60,090 |
def jacobian(func: Callable, delta: float):
"""Finite differences approximation to the Jacobian."""
def jacfn(z):
num_dims = len(z)
Jac = np.zeros((num_dims, num_dims))
for j in range(num_dims):
pert = np.zeros(num_dims)
pert[j] = 0.5 * delta
zh = func... | 60,091 |
def add_servermgr_to_path():
"""
locate our servermgr directory and add it to python path for both
this process and our subprocesses.
"""
for dir in ("..", "../..", "../../.."):
if os.path.exists(os.path.join(dir, "servermgr")):
pp = os.environ.get("PYTHONPATH", None)
... | 60,092 |
def get_full_width(text, get_full_width_char, get_full_width_number, get_full_width_symbol):
"""
Get full width characters.
:param text: original text.
:param get_full_width_char: set True to get full width English letter.
:param get_full_width_number: set True to get full width number.
:param ... | 60,093 |
def obtain_transitive_fingerprint_v_short(
strategy, turns, repetitions, processes=1
):
"""
Obtain the transitive fingerprint against short run time
for a given strategy and save the figure to the assets dir
"""
short_run_time = [s() for s in axl.short_run_time_strategies]
fp = axl.Transitiv... | 60,094 |
def polar_to_cartesian_2d(rho, phi):
"""Convert polar points to cartesian points.
Convert polar coordinate points in 2D to cartesian coordinate points in 2D.
This function uses the notation convention of ISO 80000-2:2009 and its
related successors.
Parameters
----------
rho : array_like
... | 60,095 |
def ast_rotate_left_while_assoc_prec(ast):
"""Performs a left rotation of the AST around its root if associativity and precedence are not enforced yet.
Args:
ast: The AST dict.
Returns:
The new root of the rotated AST.
"""
if ("op" in ast) and (ast["op"] in all_op_data):
if... | 60,096 |
def plot_confusion_matrix(cm, classes, filename, title='Confusion matrix', cmap=plt.cm.Blues):
"""
绘制混淆矩阵,如果本地有图形界面或
Args:
cm: 混淆矩阵,numpy.ndarray
classes: 类名
filename: 保存文件路径
title: 标题
cmap: 使用的色系
"""
import itertools
plt.imshow(cm, interpolation='neares... | 60,097 |
def convert_direction_from_string(s: str):
"""Convert direction (SkyCoord) from string
TODO: Make more general!
:param s: String
:return:
"""
ra, dec, frame = s.split(',')
d = SkyCoord(ra, dec, unit='deg', frame=frame.strip())
return d | 60,098 |
def memoryUsage(data, detail=1):
"""Got memory usage of dataset
Parameters
----------
data: dataFrame
"""
if detail:
display(data.memory_usage())
memory = data.memory_usage().sum() / (1024 * 1024)
print("Memory usage : {0:.2f}MB".format(memory))
return memory | 60,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.