content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_input_json(params_dict : dict, filename : str="input.json"):
"""
Writes job parameters/hyperparameters in `params_dict` to CSV using the specified
`filename`.
"""
json_path = params_dict["job_dir"] + filename
with open(json_path, "w") as json_file:
json.dump(params_dict, json... | 52,400 |
def masked( arr, v, mask ):
""" Performs the 1D convolution on arr, omitting pixels under the mask """
arr = arr.astype(float)
smoothed = conv( arr*mask, v )
norm = conv( mask.astype(np.float), v )
return smoothed/norm | 52,401 |
def call_data_to_hdf5(call_data, output_file):
"""Write several summary statistics calculated by `VariantCallData`
to a HDF5 file.
Parameters
----------
call_data : VariantCallData
output_file : str
Output file name
"""
with h5py.File(output_file, 'w') as h5:
for scaffo... | 52,402 |
def runVIC(dbname, options):
"""Driver function for performing a VIC forecast simulation"""
startyear, startmonth, startday = map(
int, options['forecast']['startdate'].split('-'))
endyear, endmonth, endday = map(
int, options['forecast']['enddate'].split('-'))
# if date(endyear, endmont... | 52,403 |
def crop_validation_images(dataset_path, side_length, stride, scales, validation_cam_folder_name):
"""
if the scales are not modified, this function can run only once.
crop the validation images to reduce the validation time
the output is in `validation_cam_folder_name/crop_images`
images are s... | 52,404 |
def _raise_error(request, error, message='Unknown error', status_code=400):
"""
Raise an error response.
Use this when you need to return an error to the client from inside of
nested function calls.
Parameters
----------
error : str
Identifying error key
message : str, optional... | 52,405 |
def audit_systems(
url: str,
headers: Dict[str, str],
include_keys: Optional[List] = None,
) -> None:
"""
Audits the system resources from the server for compliance.
This should be flexible enough to accept further audits in
the future and return them as well as being called from other
... | 52,406 |
def fetch_ssr(url):
"""Retrive ssr links form url, return a list."""
# TODO: sometimes we need to try to get via a proxy.
# base64_ssr = requests.get(url).text
headers = {
'User-Agent': 'Mozilla/5.0',
}
req = request.Request(url, headers=headers)
base64_ssr = request.url... | 52,407 |
def check_smv_with_counterexample(FnameSMV, DynamicReorder=True, DisableReachableStates=True):
"""
Calls :ref:`installation_nusmv` with the query defined in the *smv* file *FnameSMV*.
The remaining arguments are :ref:`installation_nusmv` options, see the manual at http://nusmv.fbk.eu for details.
See :r... | 52,408 |
def api_get_videos_duration(list_videos, api_service):
"""Get the duration of 50 videos at once.
:param list_videos: A list of video IDs, maximum size 50.
:param api_service: API Google Token generated with Google.py call.
:return: a dictionary associating video id and duration of said video.
"""
... | 52,409 |
def build_pieces(headers, batch_size, start, end, max_piece_size=100000, metadata_columns=None):
"""
Build pieces function takes as input a list of headers and
returns a list of pieces split in size maximum max_piece_size.
Input: (filename, count, count_before)
Output: (filename:str, piece_start:int... | 52,410 |
def collect_values(wdlfile: str, separate_required: bool,
category_key: str, fallback_category: str,
description_key: str, fallback_description: str,
fallback_description_to_object: bool,
strict: bool) -> Dict:
"""
:param wdlfile: The w... | 52,411 |
def _GetConfigMapsChanges(args):
"""Return config map env var and volume changes for given args."""
volume_kwargs = {}
env_kwargs = {}
updates = _StripKeys(
getattr(args, 'update_config_maps', None) or args.set_config_maps or {})
volume_kwargs['updates'] = {
k: v for k, v in updates.items() if _I... | 52,412 |
def get_std_out_file(app_name: str):
"""Get temporary stdout file for the app
Args:
app_name: Name of the Application
"""
default_dir = get_default_dir(app_name)
file_name = os.path.join(default_dir, "std_out.txt")
return file_name | 52,413 |
def dice_loss(pred, target):
"""Cacluate dice loss
Parameters
----------
pred:
predictions from the model
target:
ground truth label
"""
smooth = 1.0
pred = torch.sigmoid(pred)
p_flat = pred.view(-1)
t_flat = target.view(-1)
intersection = (... | 52,414 |
def write_json(in_file):
"""Write the update.json file."""
with in_file:
sites = pickle.load(in_file)
# Prep data for reporting.
sites_descending = sorted(sites, key=lambda s: s.latest_courses, reverse=True)
all_courses, _, _ = courses_and_orgs(sites)
json_update(sites_descending, all_c... | 52,415 |
def stock_em_dxsyl(market: str = "上海主板") -> pd.DataFrame:
"""
东方财富网-数据中心-新股数据-打新收益率
http://data.eastmoney.com/xg/xg/dxsyl.html
:param market: choice of {"上海主板", "创业板", "深圳主板"}
:type market: str
:return: 指定市场的打新收益率数据
:rtype: pandas.DataFrame
"""
market_map = {"上海主板": "2", "创业板": "3", ... | 52,416 |
def get_ssm_parameter_list_output(name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetSsmParameterListResult]:
"""
Use this data source to access information about an existing resource.
"""
... | 52,417 |
def get_warningness() -> int:
"""Gets the warning level of the entire program"""
return _warningness | 52,418 |
def node_degree_xy(G,nodes=None):
"""Return iterator of degree-degree pairs for edges in G.
Parameters
----------
G : NetworkX graph
nodes: list or iterable (optional)
Use only edges that start or end in nodes in this container.
The default is all nodes.
Notes
-----
F... | 52,419 |
def distanceMetrics(vol1, vol2, voxelsize_mm):
"""
avgd[mm] - Average symmetric surface distance
rmsd[mm] - RMS symmetric surface distance
maxd[mm] - Maximum symmetric surface distance
"""
# crop data to reduce computation time
pads1 = getDataPadding(vol1)
pads2 = getDataPadding(vol2)
... | 52,420 |
def point_in_quadrilateral_2d(
point: np.ndarray, quadrilateral: np.ndarray
) -> bool:
"""Determines whether a point is inside a 2D quadrilateral.
Parameters
----------
point : np.ndarray
(2,) array containing coordinates of a point.
quadrilateral : np.ndarray
(4, 2) array conta... | 52,421 |
def pSEDIa( sedtype ):
""" returns the likelihood of observing
host galaxy with the given rest-frame
B-K color, assuming the SN is a Ia.
The SED type is from the GOODZ SED template
set (Dahlen et al 2010).
1=E, 2=Sbc, 3=Scd, 4=Irr, 5,6=Starburst
plus 4 interpolations between each.
... | 52,422 |
def markov(bot, msg):
"""Return the best quote ever."""
if final_model:
# This tries to generate a sentence that doesn't "overlap", or
# share too much similarity with seeded text.
# Read more here: https://github.com/jsvine/markovify#basic-usage
sentence = final_model.make_sente... | 52,423 |
def _test_two_line(fnn_flag):
"""
测试两根直线 分割
:param fnn_flag: 神经网络分类标记
:return: NULL
"""
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
# 训练样本个数
train_sample_count = 1000
# 训练样本,输入,每个向量元素的最大值
train_sx_max = list()
train_sx_max.append(1)
train_sx_max.append(1)
# 两根直线 分割的样本... | 52,424 |
def main():
"""
Main testing script. Run through all the tests above that start with "test_" and execute them.
Designed to be run via the command line with $python test_Query.py
:return:
:rtype:
"""
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import test_Query # curiously enough, this works!... | 52,425 |
def two_body_mc_stress_stress_jit(
bond_array_1,
c1,
etypes1,
bond_array_2,
c2,
etypes2,
d1,
d2,
d3,
d4,
sig,
ls,
r_cut,
cutoff_func,
):
"""2-body multi-element kernel between two partial stress components
accelerated with Numba.
Args:
bon... | 52,426 |
def user_quota(ctx):
"""update the quota limit for the given address"""
ctx.hdlr.user_quotalimit(
ctx.args.address.lower(), ctx.args.storage, ctx.args.messages
) | 52,427 |
def pytest_configure(config):
"""
pytest hook used to add plugin install dir as place for pytest to find tests
"""
if config.getoption("repo_health"):
# Add path to pytest-repo-health dir so pytest knows where to look for checks
file_dir = os.path.dirname(os.path.dirname(os.path.realpa... | 52,428 |
def new_world_news(cat):
"""[categories]\n\n
lore \n
general\n
updates\n
"""
return nww.news(cat) | 52,429 |
def aggregation_svg(es, query: Query):
""" Execute aggregation query and render as an SVG. """
is_internal = "/logs" in request.headers.get('Referer', '')
width = query.args.pop('width', '100%' if is_internal else '1800')
width_scale = None
if width != '100%':
width_scale = tinygraph.Scale(... | 52,430 |
def transposem(inp):
"""Transpose multiple matrices."""
perm = list(range(len(inp.shape)))
perm[-2], perm[-1] = perm[-1], perm[-2]
return tf.transpose(inp, perm) | 52,431 |
def interpolate(x, y, x0):
"""
Interpolates array Y (y=f(x)) at point x0, returning y0
x must be in increasing order
"""
x_a = 0
i_a = -1
x_b = 0
i_b = -1
i = 0
for point in x:
if (point <= x0):
x_a = point
i_a = i
if (point > x0):
... | 52,432 |
def list_api_tokens(
component_manager: ComponentManager = Depends(get_component_manager),
token: str = Depends(get_api_token),
) -> Any:
"""Returns list of created API tokens associated with the authenticated user."""
authorized_access = component_manager.verify_access(token)
# Check if the caller ... | 52,433 |
def get_val_via_socket(key):
"""Retrieve value of key from redis over Unix socket file."""
set_redis_socket_pool()
global SOCKET_POOL
# retrieve value
r = StrictRedis(connection_pool=SOCKET_POOL)
res = r.get(key)
return res.decode() if hasattr(res, "decode") else res | 52,434 |
def euclidean_distance(goal_pose):
"""Euclidean distance between current pose and the goal."""
return sqrt(pow((goal_pose.pose.position.x - pose.pose.pose.position.x), 2) +
pow((goal_pose.pose.position.y - pose.pose.pose.position.y), 2)) | 52,435 |
def setup_images(path=None, series=None, offset=None, size=None,
proc_mode=None, allow_import=True):
"""Sets up an image and all associated images and metadata.
Paths for related files such as registered images will generally be
constructed from ``path``. If :attr:`config.prefix` is set, i... | 52,436 |
def get_rel_join_parts(database, from_table, rel) -> QueryParts:
"""
:param Database database: The database being reviewed.
:param Table from_table:
:param Relationship rel: The relationship to get the parts from.
:return: New join parts for a join based on a relationship.
"""
to_table = dat... | 52,437 |
def cook_estimator(base_estimator, std_estimator=None, space=None, random_state=None,
base_estimator_params=None):
"""Cook a default estimator.
For the special base_estimator called "DUMMY" the return value is None.
This corresponds to sampling points at random, hence there is no need
for an e... | 52,438 |
def _convert_and_box_cache(
arg: DatetimeScalarOrArrayConvertible,
cache_array: "Series",
name: Optional[str] = None,
) -> "Index":
"""
Convert array of dates with a cache and wrap the result in an Index.
Parameters
----------
arg : integer, float, string, datetime, list, tuple, 1-d arr... | 52,439 |
def generate_file_path(package_path, file_name):
"""
Dynamically generate full path to file, including filename and extension.
:param package_path: (array) ordered list of packages in path to test file
:param file_name: (string) name of the file w/ test, including the extension
:return: (string) fu... | 52,440 |
def write_partition(
df: DataFrame, output_table: str, output_path: str,
partition_spec: Mapping[str, str], mode: str = 'overwrite'
) -> None:
"""Write dataframe to disk as parquet and add to hive metastore"""
for k, v in partition_spec.items():
df = df.withColumn(k, F.lit(v))
expect_schema... | 52,441 |
def pdread_2col(filename: str, noheader: bool = False) -> Tuple[ndarray, ndarray]:
"""Read in a 2 column file with pandas.
Parameters
----------
filename: str
Name of file to read.
noheader: bool
Flag indicating if there is no column names given in file.
Default = False.
... | 52,442 |
async def infer_type_map_array(engine, fn, ary):
"""Infer the return type of map_array."""
fn_t = await fn['type']
ary_t = await ary['type']
if not isinstance(ary_t, Array):
raise MyiaTypeError('Expected array')
xref = engine.vref({'type': ary_t.elements})
return Array(await fn_t(xref)) | 52,443 |
def _fullname(attr):
"""Fully qualified name of an attribute."""
fullname = ""
if hasattr(attr, "__module__"):
fullname += attr.__module__
if hasattr(attr, "__name__"):
if fullname:
fullname += "."
fullname += attr.__name__
if not fullname:
fullname = str(... | 52,444 |
def readme2tex():
""" Modifie un README.md mensuel en appelant une fonction. """
cwd = os.getcwd()
for month in range(1, 13):
month_name = MONTHS[month - 1]
month_lower = month_name.lower()
month_norm = remove_accents(month_lower)
solutions_md = Path(month_norm) / "INPUT.... | 52,445 |
def example_positionfixes():
"""Positionfixes for tests."""
p1 = Point(8.5067847, 47.4)
p2 = Point(8.5067847, 47.5)
p3 = Point(8.5067847, 47.6)
t1 = pd.Timestamp("1971-01-01 00:00:00", tz="utc")
t2 = pd.Timestamp("1971-01-01 05:00:00", tz="utc")
t3 = pd.Timestamp("1971-01-02 07:00:00", tz="... | 52,446 |
def GetGClientCommand(platform=None):
"""Returns the executable command name, depending on the platform.
"""
if not platform:
platform = sys.platform
if platform.startswith('win'):
# Windows doesn't want to depend on bash.
return 'gclient.bat'
else:
return 'gclient' | 52,447 |
def do_histtestbasic() -> bool:
"""Run this unit test with hard coded, default parameters."""
file = "sample.txt"
par = [5, 0, 15]
test = HistTestBasic(txtfile=file, params=par)
return test.test(False) | 52,448 |
def log_param_shapes(params: Any) -> int:
"""
# Maybe could be useful:
https://github.com/google-research/scenic/blob/ab3083d8cbfe3216119a0f24fce23ca988e20355/scenic/common_lib/debug_utils.py
Prints out shape of parameters and total number of trainable parameters.
Args:
params: PyTree of model ... | 52,449 |
def static(**kwargs):
"""
Return a predefined ``dict`` when the given regex matches.
"""
return lambda values: kwargs | 52,450 |
def ring_background_estimate(pos, on_radius, inner_radius, outer_radius, events):
"""Simple ring background estimate
No acceptance correction is applied
TODO : Replace with AnnulusSkyRegion
Parameters
----------
pos : `~astropy.coordinates.SkyCoord`
On region radius
inner_radius :... | 52,451 |
def get_user_profile(email): # GET
"""Get user profile
Fetches from the user collection by using the user's email as key.
Args:
User's email (str)
Returns:
User profile object (dict)
"""
# NOTE: This method previously called LCS with director credentials in order to retrieve ... | 52,452 |
def sha1(string):
"""Compute the sha1 hexdigest of the string."""
return hashlib.sha1(string.encode('utf-8')).hexdigest() | 52,453 |
def generate_rss():
""" Generate the RSS feed pages on a daily basis """
import cgi
import re
def parse():
try:
form = cgi.FieldStorage()
form_play = form.getfirst('play', '')
form_date = form.getfirst('start', '')
# alphanumeric only for play
... | 52,454 |
def test_create_ocrd_file_with_defaults_basename_wo_extension(local_filename, wo_extension):
"""Behavior for ocrd_file_with_defaults
"""
f = create_ocrd_file_with_defaults(local_filename=local_filename)
assert f.basename_without_extension == wo_extension | 52,455 |
def find_unassigned_data(self, data, stop):
"""
Return the unassigned_data
"""
keep = ((data[2,:] > stop*data[3,:]))
self.unassigned_data = data[:,keep]
sortidx = argsort(self.unassigned_data[2,:], reversed=True)
self.unassigned_data = self.unassigned_data[:,sortidx]
self.cluster_arr =... | 52,456 |
def current_weather():
"""
Get all stations
render template to client
"""
global last_updated_weather_time, last_updated_weather_data, first_run_weather
if (((last_updated_weather_time - datetime.datetime.now())).total_seconds() < -900 or first_run_weather):
first_run_weather = False
... | 52,457 |
def parse_timedelta(time_str):
"""
Parse a time string e.g. (2h13m) into a timedelta object. Stolen on the web
"""
regex = re.compile(r'^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$')
time_str=replace(time_str,{
'sec':'s',
'second'... | 52,458 |
def gmtime(space, w_seconds=None):
"""gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead... | 52,459 |
def nested_defaultdict(default_factory: Callable, depth: int = 1) -> defaultdict:
"""Creates a nested default dictionary of arbitrary depth with a specified callable as leaf."""
if not depth:
return default_factory()
result = partial(defaultdict, default_factory)
for _ in repeat(None, depth - 1)... | 52,460 |
def main(client_id, client_secret):
"""Console script for boxcast_python_sdk."""
client = BoxCastClient(client_id, client_secret)
account = client.get_account()
print(account)
return 0 | 52,461 |
def publish_video(video_file):
"""
Publish given video file to a specified Kafka topic.
Kafka Server is expected to be running on the localhost. Not partitioned.
:param video_file: path to video file <string>
"""
# Start up producer
producer = KafkaProducer(bootstrap_servers='localhost:9092... | 52,462 |
def now(timezone):
"""Get the current time in the given timezone
Args:
timezone: The desired timezone as a string. eg 'US/Eastern'
"""
utc = pytz.timezone('UTC').localize(datetime.utcnow())
return utc.astimezone(pytz.timezone(timezone)) | 52,463 |
def ReadBlackList(path):
"""Read a blacklist of forbidden directories and files.
Ignore lines starting with a # so we can comment the datafile.
Args:
path: file to load the blacklist from.
Returns:
dictionary of path:True mappings
"""
blacklist_file = open(path, 'r')
catalog = []
for entry in ... | 52,464 |
def height_water_critical(FlowRate, Width):
"""Return the critical local water height.
:param FlowRate: flow rate of water
:type FlowRate: u.m**3/u.s
:param Width: width of channel (????????)
:type Width: u.m
:return: critical water height
:rtype: u.m
"""
ut.check_range([FlowRate.m... | 52,465 |
def getRBPartInfo(api_key, part_id):
"""
Get part information from rebrickable.com.
FIXME: Could be issues with too many requests per second? We are
sending two requests per part.
"""
urls = ["https://rebrickable.com/api/v3/lego/parts/" + str(part_id) + "/?key=" + str(api_key),
... | 52,466 |
def author_number_of_files_owned(results):
""" Number of files owned by author.
:param results: results from author_file_owned()
:return: {author: number of files owned}
:rtype: dict
"""
authors = defaultdict(int)
for item in results:
authors[item.name] += 1
return authors | 52,467 |
def test_do_put_independent_read_write():
"""Ensure that separate threads can read/write on a DoPut."""
# ARROW-6063: previously this would cause gRPC to abort when the
# writer was closed (due to simultaneous reads), or would hang
# forever.
data = [
pa.array([-10, -5, 0, 5, 10])
]
... | 52,468 |
def updateBounds(bounds, (x, y), min=min, max=max):
"""Return the bounding recangle of rectangle bounds and point (x, y)."""
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y) | 52,469 |
def check_link(link, attempts):
"""
Check if the link is online trying to open it
:param link: the link to check
:param attempts: the max number of attempts
:return: True if the link is online, False otherwise
"""
i = 0
for i in range(0, attempts):
try:
# try to open ... | 52,470 |
def test_flatten(generator: Generator, distribution_info: DistributionInfo[Any, Any, Any]) -> None:
"""
Test that the methods produce the correct shapes.
"""
shape = (3, 4)
p = distribution_info.exp_parameter_generator(generator, shape=shape)
q = distribution_info.nat_parameter_generator(genera... | 52,471 |
def _mock_entry_points(group=None):
"""Mocking funtion of entrypoints."""
data = {
'invenio_access.actions': [
MockEntryPointAction('open', 'demo.actions'),
MockEntryPointAction('close', 'demo.actions')
],
'invenio_access.system_roles': [
MockEntryPoin... | 52,472 |
def prepare_metadata(devkit_archive):
"""Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2012 development kit.
Returns
-------
... | 52,473 |
async def rname(event):
"""Renaming Directory/File"""
cat = str(event.pattern_match.group(1)).strip()
new_name = str(event.pattern_match.group(2)).strip()
if not exists(cat):
await event.edit(f"file path : {cat} not exists!")
return
new_path = join(dirname(cat), new_name)
shutil.... | 52,474 |
def optimize_results(sample_names,
control_samples,
FPs_per_genome,
plot_roc=False,
plot_tuning_curve=False,
filtered_results_file=None,
output_dir=None,
mutations_dataframe... | 52,475 |
def get_detections(
args,
config: DictConfig,
module: ModuleType,
model: nn.Module,
geoscreens_data: LightningDataModule,
video_id: str,
):
"""
Returns:
Dict: keys = frame index, value = a dict of detections that looks something like::
{
"frame_idx": ... | 52,476 |
def _append_build_id(base_name):
"""Returns base_name with BQ-friendly `GITHUB_SHA` appended"""
build_id = os.environ.get("GITHUB_SHA", None)
if not build_id:
raise Exception("Unable to get build id; env var GITHUB_SHA not set")
# valid BQ table names only allow underscores and alphanumeric ch... | 52,477 |
def gen_format_string(a: np.array):
"""
Generates a matrix format in the shape of a.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(gen_format_string(a))
┌ ┐
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
└ ┘
The template can be rendered with the help of... | 52,478 |
def test_get_method():
"""Test .get() on a Pokemon."""
pkmn = Pokemon(name="spinda", moves=["tackle"], level=50)
assert pkmn.get("name") == "spinda"
assert pkmn.get("DOOT") is None | 52,479 |
def learn_categories(links, **kwargs):
""" learns word categories (clusters)
:param links: pd.DataFrame(columns = ['word', 'link', 'count'])
:param kwargs: disclosed below in kwa(...)
:return: (categories, re)
"""
logger = logging.getLogger(__name__ + ".learn_categories")
cats_file... | 52,480 |
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.append(cirq.... | 52,481 |
def get_completeness_coef(iocs_per_feed: int, total_iocs: int) -> float:
"""
This function wrapper is intended for
calculate feed completeness factor
Parameters:
iocs_per_feed: int — Number of IoCs in the CTI feed
total_iocs: int — Number of IoCs across all CTI feeds
... | 52,482 |
def test_rowduction_dataset_c(
path = os.path.dirname(os.path.realpath(__file__)) + "/data/clean_abalone.csv",
epsilon = 0.05
):
"""Test the rowduction on a 0 and 1 values of the label of the Dataset B. There are less tests
than with Dataset A because the DF is too heavy to "one shot" rowduct it.... | 52,483 |
def valid_model(model):
"""Check if the model is valid."""
if model is None:
raise ValueError("The SaraBotTagger model can not be None")
path_to_model = f'{absolute_path}/bot_model/{model}'
model = load(path_to_model)
return True | 52,484 |
def mock_massive_ftp_response(monkeypatch):
"""Patch ftplib to use a local file as a response"""
def null(*args, **kwargs):
pass
def mock_dir(fun):
with open("tests/data/massive_ftp_response.txt") as ref:
[fun(line) for line in ref]
monkeypatch.setattr(ftplib.FTP, "login",... | 52,485 |
def getApi(token_path):
""" Логинится в вк и возвращает готовую к работе сессию """
with open(token_path) as f:
token = f.read().strip()
session = vk_api.VkApi(token=token, api_version="5.52")
return session.get_api() | 52,486 |
def projects():
"""
General purpose provider of paths to test projects with the conventional layout
"""
base_path = PROJECT_ROOT / "tests" / "fixtures"
projects = {
re.match(r"^([_\w]+)_project", path.name).groups()[0]: path.resolve()
for path in base_path.glob("*_project")
}
... | 52,487 |
def qair2rh(qair: xr.DataArray, temp: xr.DataArray, pres: xr.DataArray) -> xr.DataArray:
"""
Get the relative humdity from the specific humidity.
Args:
qair (xr.DataArray): The specific humidity (dimensionless).
temp (xr.DataArray): The temperature (kelvin).
pres (xr.DataArray): The... | 52,488 |
def test_unclear():
"""The bot should ask clarifying question/noncommital statement if userinput can't be parsed"""
sent = "1234"
resp = analyze_input(sent)
assert resp == UNCLEAR_RESPONSES[3] | 52,489 |
def filter_categories_pvoc(
ann_dir: str,
img_dir: str,
out_dir: str,
link_images: bool = True,
drop: List[str] = None,
keep: List[str] = None
):
"""filter_categories_pvoc
This function allows to filter object annotations in a PascalVOC dataset according to their
assigned category. ... | 52,490 |
def read_trees(input_dir, features, signals, backgrounds, selection=None,
negative_weight_treatment="passthrough",
equalise_signal=True, branch_w="EvtWeight",
col_w="MVAWeight", col_target="Signal"):
"""
Read in Ttrees.
Files in the input directory should be nam... | 52,491 |
def package_form(request):
"""
Upload a new package
"""
return render(request, 'packages/package_form.html', {
'form': PackageForm(),
}) | 52,492 |
def short_term_operation_uems(universal_mg, local_mg, socket_upload, socket_download, info, session, logger):
"""
Short term operation for universal energy management system
:param universal_mg: universal ems model
:param local_mg:local ems model
:param socket_upload: online socket
:param socket... | 52,493 |
def destory(list_id):
"""Delete list."""
list = db_session.query(List).filter(List.id == list_id).first()
if(list.user_id != login_session['user_id']):
flash("This list does not belong to your account")
return redirect(url_for('list.index'))
db_session.delete(list)
db_session.commit(... | 52,494 |
def specs_to_ir(specs, version='0.1b1', debug=False, route_whitelist_filter=None):
"""
Converts a collection of Stone specifications into the intermediate
representation used by Stone backends.
The process is: Lexer -> Parser -> Semantic Analyzer -> IR Generator.
The code is structured as:
... | 52,495 |
def expectedtime(fn):
"""Calculate the expected time for conversion.
Based on my machine, the average conversion speed is 75 kiB/s. The range is between
60 kiB/s and 90 kiB/s.
Arguments:
fn: file path.
Returns:
A 3-tuple of datetime.timedelta objects representing the minimal, aver... | 52,496 |
def categorize_os():
"""
Categorize operating system by its parent distribution.
Args:
None
Raises:
None
Returns:
None
"""
os_name = get_system_name()
if os_name in ["ubuntu", "kali", "backtrack", "debian"]:
return "debian"
# elif some other OS, add... | 52,497 |
def has_names_directive(block: FencedBlock) -> bool:
"""Does the code block have a share-names or clear-names directive."""
assert block.role == Role.CODE, "must be a Python code block."
return block.has_directive(Marker.SHARE_NAMES) or block.has_directive(
Marker.CLEAR_NAMES
) | 52,498 |
def make_reber_classification(n_samples, invalid_size=0.5,
return_indeces=False):
"""
Generate random dataset for Reber grammar classification.
Invalid words contains the same letters as at Reber grammar, but
they are build whithout grammar rules.
Parameters
------... | 52,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.