content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def version_callback(
value: Optional[bool],
) -> None: # pylint: disable=unsubscriptable-object
"""Provides a version option for the CLI"""
if value:
console.print(
f"{app.info.name.title()} " # type: ignore[union-attr]
f"CLI version: {__version__}"
)
raise... | 11,700 |
def create_schema(hostname='localhost', username=None, password=None,
dbname=None, port=None, schema_name=None):
"""Create test schema."""
cn = create_cn(hostname, password, username, dbname, port)
with cn.cursor() as cr:
cr.execute('DROP SCHEMA IF EXISTS %s CASCADE' % dbname)
... | 11,701 |
def test_load_no_project():
"""Loading a project that does not exist throws an error"""
assert_raises(Exception, inventory.load, PROJECT_NAME) | 11,702 |
def set_color_in_session(intent, session):
""" Sets the color in the session and prepares the speech to reply to the
user.
"""
card_title = intent['name']
session_attributes = {}
should_end_session = False
if 'Color' in intent['slots']:
favorite_color = intent['slots']['Color']['va... | 11,703 |
def fpath_to_pgn(fpath):
"""Slices the pgn string from file path.
"""
return fpath.split('/')[-1].split('.jpeg')[0] | 11,704 |
def scheduler():
"""
The scheduler operation command group.
"""
pass | 11,705 |
def draw_kinetics_plots(rxn_list, path=None, t_min=(300, 'K'), t_max=(3000, 'K'), t_count=50):
"""
Draws plots of calculated rates and RMG's best values for reaction rates in rxn_list
`rxn_list` has a .kinetics attribute calculated by ARC and an .rmg_reactions list with RMG rates
"""
plt.style.use(s... | 11,706 |
def create_germline_samples_file(germline_samples_filepath, inputdata_symlinks):
"""
Writes a file to disk mapping patient IDs to the directories containing their data.
Side effects: Writes a file to disk
:param germline_samples_filepath: str Path to write out germline samples file
:param inpu... | 11,707 |
def convert_to_constant(num):
"""
Convert one float argument to Constant, returning the converted object.
:param float num:
Float number to be converted to Constant
:return:
Float number converted to a Constant object
:rtype: object
"""
return Constant(name=str(num), units... | 11,708 |
def data_zip(data):
"""
输入数据,返回一个拼接了子项的列表,如([1,2,3], [4,5,6]) -> [[1,4], [2,5], [3,6]]
{"a":[1,2],"b":[3,4]} -> [{"a":1,"b":3}, {"a":2,"b":4}]
:param data: 数组 data
元组 (x, y,...)
字典 {"a":data1, "b":data2,...}
:return: 列表或数组
"""
if isinstance(data, tuple):
... | 11,709 |
def _days_in_leap_and_common_years(i_date, f_date):
"""Return the a tuple with number of days in common and leap years (respectively) between initial and final dates.
"""
iy = i_date.year
fy = f_date.year
days_in_leap = 0
days_in_common = 0
if iy == fy:
# same year
... | 11,710 |
async def save_on_shutdown(
app: aiohttp.web.Application
) -> None:
"""Flush the database on shutdown."""
if app["db_conn"] is not None:
await app["db_conn"].close() | 11,711 |
def make_space_kernel(data, background_kernel, trigger_kernel, time,
time_cutoff=None, space_cutoff=None):
"""Produce a kernel object which evaluates the background kernel, and
the trigger kernel based on the space locations in the data, always using
the fixed time as passed in.
:param data: An... | 11,712 |
def send_gmail(from_addr, id_rsa_file, passwd_rsa_file, msg):
"""Send email via gmail
"""
try:
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
### login to gmail with gmail account 'from_addr' and with decripted password file
s.login(from... | 11,713 |
def get_dim_act_curv(args):
"""
Helper function to get dimension and activation at every layer.
:param args:
:return:
"""
if not args.act:
act = lambda x: x
else:
act = getattr(F, args.act)
acts = [act] * (args.num_layers - 1)
dims = [args.feat_dim]
# Check layer... | 11,714 |
def debug():
"""
Function to return exported resources with types as dict.
"""
return exported_res_dict | 11,715 |
def write_charset_executable(mysql_charset_script_name, here):
"""Write to disk as an executable the file that will be used to issue the MySQL
statements that change the character set to UTF-8 -- return the absolute path.
"""
mysql_charset_script = os.path.join(here, mysql_charset_script_name)
if no... | 11,716 |
def readTemperature(file):
"""
Returns the temperature of the one wire sensor.
Pass in the file containing the one wire data (ds18b20+)
"""
lines = read_temp_raw(file)
while lines[0].strip()[-3:] != "YES":
time.sleep(0.2)
lines = read_temp_raw(file)
equals_pos = lines[1].find... | 11,717 |
def test_receipt():
"""
Test event receipt message and attached couplets
"""
# manual process to generate a list of secrets
# root = pysodium.randombytes(pysodium.crypto_pwhash_SALTBYTES)
# secrets = generateSecrets(root=root, count=8)
# Direct Mode coe is controller, val is validator
... | 11,718 |
def layernorm_backward(dout, cache):
"""
Backward pass for layer normalization.
For this implementation, you can heavily rely on the work you've done already
for batch normalization.
Inputs:
- dout: Upstream derivatives, of shape (N, D)
- cache: Variable of intermediates from layernorm_for... | 11,719 |
def energyAct(
grid, deltaE, xA, yA, zA, xB, yB, zB, temp, eList, i, dimensions):
"""Perform swap or not, based on deltaE value"""
kB = 8.617332e-5 # boltzmann constant, w/ ~eV units
kTemp = kB * temp
if deltaE <= 0: # Swap lowers energy, therefore is favourable,
# so perform swap in grid
grid = performSwap(... | 11,720 |
def submit_job(name, index, script_path):
"""
Function that writes the submission settings in the sge files
inputs:
- name: Computations to run names (list)
- script_path: Path to the created SGE scripts (string)
outputs:
- The function has no outputs
"""
print ("Launching computatio... | 11,721 |
def lambda_handler(event, context):
"""
Lambda function that transforms input data and stores inital DB entry
Parameters
----------
event: dict, required
context: object, required Lambda Context runtime methods and attributes
Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-... | 11,722 |
def test_well_rows(experiment):
"""Test experiment well rows."""
rows = [0]
assert experiment.well_rows == rows | 11,723 |
def getModCase(s, mod):
"""Checks the state of the shift and caps lock keys, and switches the case of the s string if needed."""
if bool(mod & KMOD_RSHIFT or mod & KMOD_LSHIFT) ^ bool(mod & KMOD_CAPS):
return s.swapcase()
else:
return s | 11,724 |
def plot_D_dt_histogram(all_samples, lens_i=0, true_D_dt=None, save_dir='.'):
"""Plot the histogram of D_dt samples, overlaid with a Gaussian fit and truth D_dt
all_samples : np.array
D_dt MCMC samples
"""
bin_heights, bin_borders, _ = plt.hist(all_samples, bins=200, alpha=0.5, density=True, e... | 11,725 |
def should_see_link(self, link_url):
"""Assert a link with the provided URL is visible on the page."""
elements = ElementSelector(
world.browser,
str('//a[@href="%s"]' % link_url),
filter_displayed=True,
)
if not elements:
raise AssertionError("Expected link not found.") | 11,726 |
def try_provider(package, provider, domain):
"""Try using a provider."""
downloaded_file = None
data = None
apk_name = f'{package}.apk'
temp_file = Path(gettempdir()) / apk_name
link = find_apk_link(provider, domain)
if link:
downloaded_file = download_file(link, temp_file)
if do... | 11,727 |
def acquire_patents():
"""
from search terms
get search results as a dataframe
save to program_generated
"""
work_completed('acquire_patents', 0)
f = os.path.join(retrieve_path('search_terms'))
print('f = ' + str(f))
df_search_terms = pd.read_csv(f)
search_terms = l... | 11,728 |
def AcceptGroupApplication(request, callback, customData = None, extraHeaders = None):
"""
Accepts an outstanding invitation to to join a group
https://docs.microsoft.com/rest/api/playfab/groups/groups/acceptgroupapplication
"""
if not PlayFabSettings._internalSettings.EntityToken:
raise Pla... | 11,729 |
def test_parse_steps():
"""Simple tests for the PartialParse.parse_step function
Warning: these are not exhaustive
"""
_test_parse_step('shift', PartialParse.shift_id, 'tingle', [0, 1], 2, [],
[0, 1, 2], 3, [])
_test_parse_step('left-arc', PartialParse.left_arc_id, 'tingle', [0,... | 11,730 |
def _plot_line(axis, origin, angle, size_hi, size_lo=0.0, **kwargs):
"""Plot a straight line into ``axis``. The line is described through
the ``origin`` and the ``angle``. It is drawn from ``size_lo`` to
``size_hi``, where both parameters are passed as fractions of said
line. ``kwargs`` are passed to :p... | 11,731 |
def _get_list(sline):
"""Takes a list of strings and converts them to floats."""
try:
sline2 = convert_to_float(sline)
except ValueError:
print("sline = %s" % sline)
raise SyntaxError('cannot parse %s' % sline)
return sline2 | 11,732 |
def test_unionfind_sim(size, Code, errors, faulty, max_rate, extra_keys):
"""Test initialize function for all configurations."""
Decoder_module = getattr(oss.decoders, "unionfind").sim
if hasattr(Decoder_module, Code.capitalize()):
decoder_module = getattr(Decoder_module, Code.capitalize())
... | 11,733 |
def add_number(partitions, number):
"""
Adds to the partition provided `number` in all its combinations
"""
# Add to each list in partitions add 1
prods = partitions.values()
nKeys = [(1,) + x for x in partitions.keys()]
# apply sum_ones on each partition, and add results to partitions
... | 11,734 |
def copy_log_init(chron, new_direct_long):
"""
Function to incrementally update new init.csv file
Args:
chron (list): sorted list of temporally related log directories
new_direct_long (str): path of new log directory
"""
for dr in chron:
local = glob.glob(dr + "/*csv")
... | 11,735 |
def _color_to_rgb(color, input):
"""Add some more flexibility to color choices."""
if input == "hls":
color = colorsys.hls_to_rgb(*color)
elif input == "husl":
color = husl.husl_to_rgb(*color)
color = tuple(np.clip(color, 0, 1))
elif input == "xkcd":
color = xkcd_rgb[colo... | 11,736 |
def run():
"""
如果文件不存在,则创建
:return:
"""
if not os.path.exists('./res'):
os.makedirs('res')
config = get_config()
if not os.path.exists(config['url']) or not os.path.exists(
config['title'] or not os.path.exists(config['content'])):
data_load(config)
if not os.... | 11,737 |
def in_days(range_in_days):
"""
Generate time range strings between start and end date where each range is range_in_days days long
:param range_in_days: number of days
:return: list of strings with time ranges in the required format
"""
delta = observation_period_end - observation_period_star... | 11,738 |
def tags_in_file(path: Path) -> List[str]:
"""Return all tags in a file."""
matches = re.findall(r'@([a-zA-Z1-9\-]+)', path.read_text())
return matches | 11,739 |
def pad_to_longest_in_one_batch(batch):
"""According to the longest item to pad dataset in one batch.
Notes:
usage of pad_sequence:
seq_list = [(L_1, dims), (L_2, dims), ...]
item.size() must be (L, dims)
return (longest_len, len(seq_list), dims)
Args:
... | 11,740 |
def main():
"""
Process the tokenized text of each review by adding a part-of-speech tag,
removing stop words, performing lemmatization, and finally making bigrams.
These bigrams will be used to classify reviews as incentivized or
non-incentivized.
"""
# NLTK corpora are not present on the o... | 11,741 |
def create_instance(c_instance):
""" Creates and returns the Twister script """
return Twister(c_instance) | 11,742 |
def command_handler(command_type: Type[CommandAPI],
*,
name: str = None) -> Callable[[CommandHandlerFn], Type[CommandHandler]]:
"""
Decorator that can be used to construct a CommandHandler from a simple
function.
.. code-block:: python
@command_handler(P... | 11,743 |
def check_ip_in_lists(ip, db_connection, penalties):
"""
Does an optimized ip lookup with the db_connection. Applies only the maximum penalty.
Args:
ip (str): ip string
db_connection (DBconnector obj)
penalties (dict): Contains tor_penalty, vpn_penalty, blacklist_penalty keys with i... | 11,744 |
def scan(fn,
sequences=None,
outputs_info=None,
non_sequences=None,
n_steps=None,
truncate_gradient=-1,
go_backwards=False,
mode=None,
name=None,
options=None,
profile=False):
"""
This function constructs and applies a Sca... | 11,745 |
def stock_analyst(stock_list):
"""This function accepts a list of data P and outputs the best day to
buy(B) and sell(S) stock.
Args:
stock_list: expects a list of stocks as a parameter
Returns:
a string promting to buy stock if one has not bought stock i.e the
value of stock is... | 11,746 |
def is_sync_available(admin_id):
"""Method to check the synchronization's availability about networks connection.
Args:
admin_id (str): Admin privileges flag.
"""
return r_synchronizer.is_sync_available() | 11,747 |
def test_boolean005_1861_boolean005_1861_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : value=0
"""
assert_bindings(
schema="msData/datatypes/boolean.xsd",
instance="msData/datatypes/boolean005.xml",
class_name="Root",
version="1.1",
mod... | 11,748 |
def on_second_thought(divider):
"""sort the characters according to number of times they appears in given text,
returns the remaining word as a string
"""
unsorted_list = list(unsorted_string)
# characters occurence determines the order
occurence = collections.Counter(unsorted_list)
... | 11,749 |
def aiohttp_unused_port(loop, aiohttp_unused_port, socket_enabled):
"""Return aiohttp_unused_port and allow opening sockets."""
return aiohttp_unused_port | 11,750 |
def os_specific_command_line(command_line):
"""
Gets the operating system specific command string.
:param command_line: command line to execute.
:type command_line: str
"""
current_os = os.environ["TEMPLATE_OS"]
command = "/bin/bash -c '{}'" if current_os.lower() == "linux" else "cmd.exe /... | 11,751 |
def test_compare_methods(fake_data):
"""Test that fast and "slow" methods yield same answer."""
data, is_random = fake_data
# define model parameters
zmean = 8.0
alpha = 0.9
k0 = 1.0
boxsize = 10.0
rsmooth = 1.0
deconvolve = True
# use slow function
zre1 = zreion.apply_zrei... | 11,752 |
def multi_voters_example():
""" Example of using a combination of many types of voters, which may be seen as multi-kernel learning (MKL).
This particular dataset is easy to solve and combining voters degrades performance. However, it might be a good
idea for more complex datasets.
"""
# MinCq param... | 11,753 |
def ProgrammingDebug(obj, show_all=False) -> None:
"""return all attributes of a specific objec"""
try:
_LOGGER.debug("%s - ProgrammingDebug: %s", DOMAIN, obj)
for attr in dir(obj):
if attr.startswith('_') and not show_all:
continue
if hasattr(obj, attr ):... | 11,754 |
def font_variant(name, tokens):
"""Expand the ``font-variant`` shorthand property.
https://www.w3.org/TR/css-fonts-3/#font-variant-prop
"""
return expand_font_variant(tokens) | 11,755 |
def with_part_names(*part_names):
"""Add part names for garage.parts.assemble.
Call this when you want to assemble these parts but do not want
them to be passed to main.
"""
return lambda main: ensure_app(main).with_part_names(*part_names) | 11,756 |
def movieServiceProvider(movie_duration_List, flight_duration):
"""
Assuming users will watch exactly two movies.
assuming 2 movies do not have same length
O(n2) time complexity
"""
possible_pairs = []
max_sum = 0
max_sum_max_index = None
for i in range(len(movie_duration_List)):
for j in range(len(movie_... | 11,757 |
def library_view(request):
"""View for image library."""
if request.user.is_authenticated:
the_user = request.user
albums = Album.objects.filter(user=the_user)
context = {'the_user': the_user,
'albums': albums}
return render(request, 'imager_profile/library.html',... | 11,758 |
def combine_html_json_pbp(json_df, html_df, game_id, date):
"""
Join both data sources. First try merging on event id (which is the DataFrame index) if both DataFrames have the
same number of rows. If they don't have the same number of rows, merge on: Period', Event, Seconds_Elapsed, p1_ID.
:param json... | 11,759 |
def CreateAlerts(config):
""""Creates Stackdriver alerts for logs-based metrics."""
# Stackdriver alerts can't yet be created in Deployment Manager, so create
# them here.
alert_email = config.project.get('stackdriver_alert_email')
if alert_email is None:
logging.warning('No Stackdriver alert email specif... | 11,760 |
def read_json_file(path):
"""
Given a line-by-line JSON file, this function converts it to
a Python dict and returns all such lines as a list.
:param path: the path to the JSON file
:returns items: a list of dictionaries read from a JSON file
"""
items = list()
with open(path, 'r') as ... | 11,761 |
def get_boss_wage2(employee):
""" Monadic version. """
return bind3(bind3(unit3(employee), Employee.get_boss), Employee.get_wage) | 11,762 |
def format_history(src, dest, format="basic"):
"""
Formats history based on module
`releases <https://github.com/bitprophet/releases>`_.
@param src source history (file)
@param dest destination (file)
Parameter *format* was added. :epkg:`Sphinx`
extension *release* no long... | 11,763 |
def reverse_migration(apps, schema_editor):
"""There's no need to do anything special to reverse these migrations."""
return | 11,764 |
def keypoint_angle(kp1, kp2):
"""求两个keypoint的夹角 """
k = [
(kp1.angle - 180) if kp1.angle >= 180 else kp1.angle,
(kp2.angle - 180) if kp2.angle >= 180 else kp2.angle
]
if k[0] == k[1]:
return 0
else:
return abs(k[0] - k[1]) | 11,765 |
def get_args_static_distribute_cells():
"""
Distribute ranges of cells across workers.
:return: list of lists
"""
pop_names_list = []
gid_lists = []
for pop_name in context.pop_names:
count = 0
gids = context.spike_trains[pop_name].keys()
while count < len(gids):
... | 11,766 |
def test_ioc_set_ignored(cbcsdk_mock):
"""Tests setting the ignore status of an IOC."""
cbcsdk_mock.mock_request("PUT", "/threathunter/watchlistmgr/v3/orgs/test/reports/a1b2/iocs/foo/ignore",
IOC_GET_IGNORED)
api = cbcsdk_mock.api
ioc = IOC_V2.create_equality(api, "foo", "pr... | 11,767 |
def le(input, other, *args, **kwargs):
"""
In ``treetensor``, you can get less-than-or-equal situation of the two tree tensors with :func:`le`.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> ttorch.le(
... torch.tensor([[1, 2], [3, 4]]),
.... | 11,768 |
def linear_to_srgb(data):
"""Convert linear color data to sRGB.
Acessed from https://entropymine.com/imageworsener/srgbformula
Parameters
----------
data: :class:`numpy.ndarray`, required
Array of any shape containing linear data to be converted to sRGB.
Returns
-------
conver... | 11,769 |
def yices_reset_yval_vector(v):
"""Resets a yval (node descriptor) vector, for storing non atomic values in models."""
libyices.yices_reset_yval_vector(pointer(v)) | 11,770 |
async def test_build_and_deploy_prometheus_tester(ops_test, prometheus_tester_charm):
"""Test that Prometheus tester charm can be deployed successfully."""
app_name = "prometheus-tester"
await ops_test.model.deploy(
prometheus_tester_charm, resources=tester_resources, application_name=app_name
... | 11,771 |
def circuit_to_dagdependency(circuit):
"""Build a ``DAGDependency`` object from a ``QuantumCircuit``.
Args:
circuit (QuantumCircuit): the input circuits.
Return:
DAGDependency: the DAG representing the input circuit as a dag dependency.
"""
dagdependency = DAGDependency()
dagde... | 11,772 |
def node_rgb_color(node_name, linear=True):
"""
Returns color of the given node
:param node_name: str
:param linear: bool, Whether or not the RGB should be in linear space (matches viewport color)
:return:
"""
raise NotImplementedError() | 11,773 |
def tweets_factory(fixtures_factory):
"""Factory for tweets from YAML file"""
def _tweets_factory(yaml_file):
all_fixtures = fixtures_factory(yaml_file)
return [t for t in all_fixtures if isinstance(t, TweetBase)]
return _tweets_factory | 11,774 |
def monte_carlo(ds,duration,n,pval,timevar):
"""
pval: two-tailed pval
"""
x=0
mc = np.empty([ds.shape[1],ds.shape[2],n])
while x<n:
dummy = np.random.randint(0, len(ds[timevar])-duration, size=1) # have to adjust size so total number of points is always the same
mc[:,:,x] = ds[i... | 11,775 |
def num_crl(wf_n):
"""Function computes the autocorrelation function from given vectors\
and the Discrete Fourier transform
Args:
wf_n(numpy array, complex): Wave function over time
Returns:
numpy array, complex: The wave function complex over time.
numpy array, complex: The au... | 11,776 |
def test_dbt_parse_mocked_all_args():
"""Test mocked dbt parse call with all arguments."""
op = DbtParseOperator(
task_id="dbt_task",
project_dir="/path/to/project/",
profiles_dir="/path/to/profiles/",
profile="dbt-profile",
target="dbt-target",
vars={"target": "o... | 11,777 |
def resample_time_series(series, period="MS"):
"""
Resample and interpolate a time series dataframe so we have one row
per time period (useful for FFT)
Parameters
----------
df: DataFrame
Dataframe with date as index
col_name: string,
Identifying the column we will pull out
... | 11,778 |
def _timeliness_todo(columns, value, df, dateFormat=None, timeFormat=None):
"""
Returns what (columns, as in spark columns) to compute to get the results requested by
the parameters.
:param columns:
:type columns: list
:param value
:type value: str
:param df:
:type df: DataFrame
... | 11,779 |
def test_release_non_existant_alloc():
"""Release allocation that doesn't exist"""
with pytest.raises(LauncherError):
slurm.release_allocation(00000000) | 11,780 |
def build_arm(
simulator,
n_elem:int=11,
override_params:Optional[dict]=None,
attach_head:bool=None, # TODO: To be implemented
attach_weight:Optional[bool]=None, # TODO: To be implemented
):
""" Import default parameters (overridable) """
param = _OCTOPUS_PROPERTIES.c... | 11,781 |
def check_user(user, pw, DB):
"""
Check if user exists and if password is valid.
Return the user's data as a dict or a string with an error message.
"""
userdata = DB.get(user)
if not userdata:
log.error("Unknown user: %s", user)
return "Unknown user: %s" % user
elif userdat... | 11,782 |
def get_single_response_value(dom_response_list: list, agg_function):
"""
Get value of a single scenario's response.
:param dom_response_list: Single response provided as a list of one term.
:param agg_function: Function to aggregate multiple responses.
:return: Value of such observation.
"""
... | 11,783 |
def check_gpu_plugin():
""" Check for the gpuCache plugin load
"""
if not cmds.pluginInfo('gpuCache', query=True, loaded=True):
cmds.loadPlugin('gpuCache') | 11,784 |
def sharpe_ratio(returns, periods=252):
"""
Create the Sharpe ratio for the strategy, based on a
benchmark of zero (i.e. no risk-free rate information).
Args:
returns (list, Series) - A pandas Series representing
period percentage returns.
periods (int.... | 11,785 |
def is_validated(user):
"""Is this user record validated?"""
# An account is "validated" if it has the `validated` field set to True, or
# no `validated` field at all (for accounts created before the "account
# validation option" was enabled).
return user.get("validated", True) | 11,786 |
def current_chart_provider_monthly():
""" API for monthly provider chart """
mytime = dubwebdb.CTimes("%Y-%m", request.args.get('time_start'),
request.args.get('time_end'))
myids = dubwebdb.Ids(prv_id=sanitize_list(request.args.get('prvid')),
team_id=san... | 11,787 |
def create_round_meander(radius, theta=0, offset=Point()):
"""
Returns a single period of a meandering path based on radius
and angle theta
"""
deg_to_rad = 2 * pi / 360
r = radius
t = theta * deg_to_rad
# The calculation to obtain the 'k' coefficient can be found here:
# ... | 11,788 |
def get_env_info() -> Dict[str, Any]:
"""Get the environment information."""
return {
"k2-version": k2.version.__version__,
"k2-build-type": k2.version.__build_type__,
"k2-with-cuda": k2.with_cuda,
"k2-git-sha1": k2.version.__git_sha1__,
"k2-git-date": k2.version.__git_da... | 11,789 |
def load_config(path):
"""Loads the config dict from a file at path; returns dict."""
with open(path, "rb") as f:
config = pickle.load(f)
return config | 11,790 |
def _check_year(clinicaldf: pd.DataFrame, year_col: int, filename: str,
allowed_string_values: list = []) -> str:
"""Check year columns
Args:
clinicaldf: Clinical dataframe
year_col: YEAR column
filename: Name of file
allowed_string_values: list of other allowed ... | 11,791 |
def matchups(
sport, datasets, date, file_type, compression, batch_size, groups, output, config, tz, parallel, complete, force
):
"""Retrieves Fox Sports Matchups Data"""
start = time.time()
if force:
os.environ["AUTO_MAKEDIRS"] = "1"
config = config or {}
groups = groups or []
datas... | 11,792 |
def test_increment_version():
"""Run test cases to ensure that increment_version works correctly.
This is critical since running release_build.py with the --auto switch
will automatically increment the release versions without prompting the
user to verify the new versions."""
assert increment_versio... | 11,793 |
def flaskbb_load_migrations():
"""Hook for registering additional migrations.""" | 11,794 |
def lower_strings(string_list):
"""
Helper function to return lowercase version of a list of strings.
"""
return [str(x).lower() for x in string_list] | 11,795 |
def AAprime():
"""
>> AAprime()
aaprime and aprimea
"""
aprimeA = dot(transpose(ATable), ATable)
# Aaprime = dot(ATable1, ATable)
return aprimeA | 11,796 |
def normalize_group_path(group, suffix=None):
"""
:param group:
:param suffix:
:return:
"""
group = os.path.join('/', group)
if suffix is not None:
if not group.endswith(suffix):
group = os.path.join(group, suffix.rstrip('/'))
return group | 11,797 |
def _load_dataset(data_filename_or_set, comm, verbosity):
"""Loads a DataSet from the data_filename_or_set argument of functions in this module."""
printer = _baseobjs.VerbosityPrinter.create_printer(verbosity, comm)
if isinstance(data_filename_or_set, str):
if comm is None or comm.Get_rank() == 0:
... | 11,798 |
def test_blog_pagination(web_server: str, browser: DriverAPI, dbsession: Session, publish_posts):
"""When posts exceed batch size, pagination is activated. Test that it's sane."""
# Direct Splinter browser to the blog showing 5 items per page on page 1
b = browser
b.visit(web_server + "/blog/?batch_num... | 11,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.