content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def formula(formula: str, formula_param: str, cols: List[str]) -> Aggregation:
""" Create a user defined formula aggregation.
Args:
formula (str): the user defined formula to apply to each group
formula_param (str): the parameter name within the formula
cols (List[str]): the columns to ... | 5,347,900 |
def num_false_positives(df):
"""Total number of false positives (false-alarms)."""
return df.noraw.Type.isin(['FP']).sum() | 5,347,901 |
def repmot(instr, marker, value, repcase, lenout=None):
"""
Replace a marker with the text representation of an ordinal number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/repmot_c.html
:param instr: Input string.
:type instr: str
:param marker: Marker to be replaced.
:type mar... | 5,347,902 |
def check_for_pending_actions(
user: IdPUser, ticket: SSOLoginData, sso_session: SSOSession
) -> Optional[WerkzeugResponse]:
"""
Check whether there are any pending actions for the current user,
and if there are, redirect to the actions app.
:param user: the authenticating user
:param ticket: S... | 5,347,903 |
def emulatte_RESOLVE(
thicks, resistivity, freqs, nfreq, spans, height,
vca_index=None, add_noise=False, noise_ave=None, noise_std=None
):
"""
return : ndarray
[
Re(HCP1), Re(HCP2), Re(HCP3), (Re(VCX)), Re(HCP4), Re(HCP5),
Im(HCP1), I... | 5,347,904 |
def metadata_dict_chex_mimic(metadata_location):
"""Reads whole csv to find image_name, creates dict with nonempty bboxes
Output:
Bboxes dictionary with key the img_name and values the bboxes themselves."""
bboxes = {}
with open(metadata_location) as f_obj:
reader = csv.reader(f_obj, d... | 5,347,905 |
def test_clear_players():
"""Test clear_players()."""
app = GameShow(__name__)
app.players['foo'] = 'bar'
app.clear_players()
assert isinstance(app.players, dict)
assert not app.players | 5,347,906 |
def create_feature_df(cnv_dict, feature_type, labels, csv=False):
"""Creates a pandas Dataframe containing cnvs as rows and features as columns"""
# get features for each CNV
cnv_features = []
if csv:
for chrom in cnv_dict:
for cnv in cnv_dict[chrom]:
if cnv.tads:
... | 5,347,907 |
def test_get_ring_and_fgroup_ortho(input_smiles, bond_smarts, expected_pattern):
"""Ensure that FGs and rings attached to ortho groups are correctly
detected.
The expected values were generated using fragmenter=0.0.7
"""
molecule, _, functional_groups, ring_systems = Fragmenter._prepare_molecule(
... | 5,347,908 |
def recalculate_order(order: Order, **kwargs):
"""Recalculate and assign total price of order.
Total price is a sum of items in order and order shipping price minus
discount amount.
Voucher discount amount is recalculated by default. To avoid this, pass
update_voucher_discount argument set to Fals... | 5,347,909 |
def simulationcell_from_axes(axes, bconds='p p p', rckc=15.):
""" construct the <simulationcell> xml element from axes
Args:
axes (np.array): lattice vectors
bconds (str, optional): boundary conditions in x,y,z directions.
p for periodic, n for non-periodic, default to 'p p p'
rckc: long-rang... | 5,347,910 |
def diff_seq(seq1, seq0):
"""Returns the difference of two sequences: seq1 - seq0.
Args:
seq1: The left operand.
seq0: The right operand.
Returns:
The difference of the two sequences.
"""
return (seq1 - seq0) % MAX_SEQ | 5,347,911 |
def method_menu():
"""Method menu items
1. Add a new method
2. Duplicate selected method
3. Remove selected method
------------------------------
4. Clear methods
"""
message_method = "You are about to delete all methods. Do you want to continue?"
method_items = [
menu_item(i... | 5,347,912 |
def shapeanalysis_OuterWire(*args):
"""
* Returns the outer wire on the face <Face>. This is replacement of the method BRepTools::OuterWire until it works badly. Returns the first wire oriented as outer according to FClass2d_Classifier. If none, last wire is returned.
:param face:
:type face: TopoDS_Face... | 5,347,913 |
def is_numeric(val: str) -> bool:
"""Check whether an unparsed string is a numeric value"""
if val in MISSING_VALUES:
return True
try:
float(val)
except Exception:
return False
else:
return True | 5,347,914 |
def safeRun( commandArgs ):
"""
Runs the given command and reads the output
"""
errTmp = tempfile.mkstemp()
errStream = os.fdopen( errTmp[0] )
process = Popen( commandArgs, stdin = PIPE,
stdout = PIPE, stderr = errStream )
process.stdin.close()
processStdout = proce... | 5,347,915 |
def python_cat(infiles: typing.List[str],
outfile: str,
remove: bool=False,
error_file: typing.TextIO=sys.stderr,
verbose: bool=False):
"""
This is very plain Python, except for the os.remove() call.
"""
start_time: float = 0
if verbose:
... | 5,347,916 |
def test_client_exists():
"""Pass."""
assert inspect.isclass(axonapi.connect.Connect) | 5,347,917 |
def commandline_options():
# TODO: complete docstring
"""
:return:
"""
# Instantiate and add parser options:
parser = OptionParser(usage="%prog [OPTIONS] FILENAME",
version="%prog 1.0")
parser.add_option("-l",
"--largest-per-folder",
... | 5,347,918 |
def add_command_line_options(
parser: Union[argparse.ArgumentParser, optparse.OptionParser],
transport_argument: bool = False,
) -> None:
"""Add command line options for all available transport layer classes."""
if transport_argument:
known_transports = list(get_known_transports())
if is... | 5,347,919 |
def test_init_no_params():
"""Test the creator by passing no parameters. Should cause a TypeError exception"""
success = False
try:
testPlane = ComplexPlane()
except TypeError:
"""test passes"""
success = True
message = 'Creator should have generated a TypeError exception,... | 5,347,920 |
def expand_options(sent, as_strings=True):
"""
['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']]
For example:
Will it (rain|pour) (today|tomorrow|)?
---->
Will it rain today?
Will it rain tomorrow?
Will it rain?
Will it pour today?
Will it pour tomorrow?
Will it pour?... | 5,347,921 |
def gcd_recursive_by_divrem(m, n):
"""
Computes the greatest common divisor of two numbers by recursively getting remainder from
division.
:param int m: First number.
:param int n: Second number.
:returns: GCD as a number.
"""
if n == 0:
return m
return gcd_recursive_by_div... | 5,347,922 |
def repeat(atoms, coord):
"""
Repeat atoms (:class:`AtomArray` or :class:`AtomArrayStack`)
multiple times in the same model with different coordinates.
Parameters
----------
atoms : AtomArray, shape=(n,) or AtomArrayStack, shape=(m,n)
The atoms to be repeated.
coord : ndarray, dtype... | 5,347,923 |
def get_mzi_delta_length(m, neff=2.4, wavelength=1.55):
""" m*wavelength = neff * delta_length """
return m * wavelength / neff | 5,347,924 |
def yagzag2radec(yag, zag, q):
"""
Given ACA Y-ang, Z-ang and pointing quaternion determine RA, Dec. The
input ``yag`` and ``zag`` values can be 1-d arrays in which case the output
``ra`` and ``dec`` will be corresponding arrays of the same length.
:param yag: ACA Y angle (degrees)
:param zag: ... | 5,347,925 |
def load_image(
path: str,
color_mode="rgb",
target_size: Union[None, ImageSize] = None,
normalize=False,
) -> np.ndarray:
"""Load an RGB image from the given path, optionally resizing it.
:param path: Path to the image
:param color_mode: "rgb", "bgr" or "grayscale"
:param target_size: ... | 5,347,926 |
def test_check_for_runs():
"""
Test check_for_runs
"""
response = {
"_items": [
{
"non_static_inputs": ["INPUT_1"],
"assay_name": "assay 1",
"workflow_location": "https://github.com/CIMAC-CIDC/proto",
"_id": "123",
... | 5,347,927 |
def deit_base_patch16_384():
"""
DeiT base model @ 384x384 from paper (https://arxiv.org/abs/2012.12877).
ImageNet-1k weights from https://github.com/facebookresearch/deit.
"""
cfg = ViTConfig(
name="deit_base_patch16_384",
url="",
input_size=(384, 384),
patch_size=16... | 5,347,928 |
def update_output(
event_id,
event_dividers,
light_dividers,
filename,
geometry,
do_plot_tracks,
do_plot_opids,
figure,
):
"""Update 3D event display end event id"""
fig = go.Figure(figure)
if event_dividers is None:
return no_update, no_update, no_update, no_update,... | 5,347,929 |
def get_containerports(marathon_url, app_id):
"""
Get containerports if we have portmapping.
marathon_url : [string] the URL of the marathon service
app_id : [string] ID of the running marathon app
Method : GET
Return : list of ports
"""
api_endpoint = '/v2/apps/'
headers = {'Conten... | 5,347,930 |
def backward_algorithm(O, HMM_model):
"""HMM Backward Algorithm.
Args:
O: (o1, o2, ..., oT), observations
HMM_model: (pi, A, B), (init state prob, transition prob, emitting prob)
Return:
prob: the probability of HMM_model generating O.
"""
pi, A, B = HMM_model
T = len(O)
... | 5,347,931 |
def test_risky_user_get_command(requests_mock) -> None:
"""
Scenario: Get Risky User.
Given:
- User has provided valid credentials.
- Headers and JWT token have been set.
When:
- risky_user_get_command is called.
Then:
- Ensure outputs prefix is correct.
- Ensure outputs key... | 5,347,932 |
def scan_codes(code_type, image):
"""Get *code_type* codes from a PIL Image
*code_type* can be any of zbar supported code type [#zbar_symbologies]_:
- **EAN/UPC**: EAN-13 (`ean13`), UPC-A (`upca`), EAN-8 (`ean8`) and UPC-E (`upce`)
- **Linear barcode**: Code 128 (`code128`), Code 93 (`code93`), Code 3... | 5,347,933 |
def validate_user_defined_info(user_defined_info):
"""
Validate user defined info, delete the item if its key is in lineage.
Args:
user_defined_info (dict): The user defined info.
Raises:
LineageParamTypeError: If the type of parameters is invalid.
LineageParamValueError: If us... | 5,347,934 |
def data_write(fname, keys, values, path='data', exists=0):
"""DEPRECATED; USE :func:`save`.
Parameters
----------
fname : str
File name.
keys : str or list of str
Name(s) of the values to store in file.
values : anything
Values to store with keys in file.
path :... | 5,347,935 |
def add_immediate_alert(context: dict, severity: str,
message: Union[str, dict], title: Optional[str] = None,
dismissable: bool = True, safe: bool = False) -> None:
"""Add an alert for immediate display."""
if safe and isinstance(message, str):
message = M... | 5,347,936 |
def get_summoner_masteries(summoner_ids):
"""
https://developer.riotgames.com/api/methods#!/1017/3450
Args:
summoner_ids (int | list<int>): the summoner ID(s) to get mastery pages for
Returns:
dict<str, MasteryPages>: the requested summoners' mastery pages
"""
# Can only have 4... | 5,347,937 |
def _patch_tornado():
"""
If tornado is imported before nest_asyncio, make tornado aware of
the pure-Python asyncio Future.
"""
if 'tornado' in sys.modules:
import tornado.concurrent as tc
tc.Future = asyncio.Future
if asyncio.Future not in tc.... | 5,347,938 |
def test_query_my_project(db, clients, user_group, allowed):
"""
Test if users may see a project that is in one of their studies
"""
client = clients.get(user_group)
project = ProjectFactory()
user = User.objects.get(groups__name=user_group)
study = StudyFactory()
project.study = study... | 5,347,939 |
def make_pod_spec(
name,
image_spec,
image_pull_policy,
image_pull_secret,
port,
cmd,
node_selector,
run_as_uid,
fs_gid,
env,
working_dir,
volumes,
volume_mounts,
labels,
cpu_limit,
cpu_guarantee,
mem_limit,
mem_guarantee,
lifecycle_hooks,
... | 5,347,940 |
def preprocess(text, remove_punct=False, remove_num=True):
"""
preprocess text into clean text for tokenization
"""
# 1. normalize
text = normalize_unicode(text)
# 2. to lower
text = text.lower()
# 3. space
text = spacing_punctuation(text)
text = spacing_number(text)
# (optio... | 5,347,941 |
def verify_ptp_calibration_states(
device, states, domain, max_time=15, check_interval=5
):
""" Verify ptp parent values in show ptp parent command
Args:
device (`obj`): Device object
states ('str): PTP calibration state
domain ('str): PTP domain
max_time... | 5,347,942 |
def test_padding():
"""
Test for checking the padding of a single
linear constraint set
"""
C_0 = np.eye(3)
C_out = cons.pad_constraints(C_0, 4, 9)
assert C_out.shape == (3, 9)
with pytest.raises(cons.PaddingError):
C_out = cons.pad_constraints(C_0, 4, 6) | 5,347,943 |
def get_auth_use_case():
"""Get use case instance."""
return auth_use_case | 5,347,944 |
def remove_border(curset, direct):
"""
Remove the cells on a given border.
"""
border = get_border(curset, direct)
curset.difference_update(border) | 5,347,945 |
def convert_file_link(file):
"""Reads the content of all files matching the file specification (removing
YAML metadata blocks is required) for insertion into the calling file.
Optionally add a separator between each file and/or add a prefix to each
line of the included files.
Args:
file (Ma... | 5,347,946 |
def example_extract_reference_primitives():
"""
Extract primitives from VertexGroupReference (.ply) file.
"""
vertex_group_reference = VertexGroupReference(filepath=dir_tests / 'test_data' / 'test_mesh.ply', num_samples=10000)
# save extracted primitives to both a Vertex Group (.vg) file and a bina... | 5,347,947 |
def pagerank(G, alpha=0.85, personalization=None,
max_iter=100, tol=1.0e-6, nstart=None, weight='weight',
dangling=None):
"""Returns the PageRank of the nodes in the graph.
PageRank computes a ranking of the nodes in the graph G based on
the structure of the incoming links. It was... | 5,347,948 |
def fetch_file(name, chunksize=16 * 1024):
"""
Fetch a datafile from a compressed/gzipped URL source.
Parameters
----------
name : :class:`str`
Name of the file to fetch.
chunksize : :class:`int`
Number of bytes to read in a chunk.
"""
fp, url, compressed = [
... | 5,347,949 |
def create_include(workflow_stat):
"""
Generates the html script include content.
@param workflow_stat the WorkflowInfo object reference
"""
include_str = """
<script type='text/javascript' src='bc_action.js'>
</script>
<script type='text/javascript' src='bc_""" + workflow_stat.wf_uuid +"""_data.js'>
</script>
"... | 5,347,950 |
def choose_sample_from_group(
group: general.ParameterListType,
) -> general.ParameterValuesType:
"""
Choose single sample from group DataFrame.
"""
# Make continous index from 0
indexes = [idx for idx in range(len(group))]
assert len(indexes) > 0
# Choose from indexes
choice = rand... | 5,347,951 |
def path_available(filepath):
# type: (str) -> bool
"""Return true if filepath is available"""
parent_directory = dirname(filepath)
if not exists(parent_directory):
raise ParentDirectoryDoesNotExist(parent_directory, filepath)
return not exists(filepath) | 5,347,952 |
def memory_item_to_resource(urn: URN, items: Dict[str, Any] = None, loader: Callable = None) -> CloudWandererResource:
"""Convert a resource and its attributes to a CloudWandererResource.
Arguments:
urn (URN): The URN of the resource.
items (dict): The dictionary of items stored under this URN.... | 5,347,953 |
def generate_csv_spreadsheet(spreadsheet_location, mappings_location):
"""Reads the main XSLX mappings file and creates a spreadsheet for the
mappings in CSV"""
sheets = get_sheets(spreadsheet_location)
now = datetime.datetime.utcnow()
strf_time = now.strftime("%y/%m/%d")
relationship_type = "re... | 5,347,954 |
def sample_user(email='test@something.dev', password='testpass'):
"""Create a sample user"""
return get_user_model().objects.create_user(email, password) | 5,347,955 |
def ShearX(img: Image, magnitude: float) -> Image:
"""Shear the image on x-axis."""
return img.transform(
img.size,
PIL.Image.AFFINE,
(1, magnitude * random.choice([-1, 1]), 0, 0, 1, 0),
PIL.Image.BICUBIC,
fillcolor=FILLCOLOR,
) | 5,347,956 |
def py_test(name=None,
srcs=[],
deps=[],
visibility=None,
main=None,
base=None,
testdata=[],
**kwargs):
"""python test."""
target = PythonTest(
name=name,
srcs=srcs,
deps=deps,
vis... | 5,347,957 |
def run_command_unchecked(command, cwd, env=None):
"""Runs a command in the given dir, returning its exit code and stdio."""
p = subprocess.Popen(
command,
cwd=cwd,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)
stdout, _ = p.communica... | 5,347,958 |
def read_onsets(onsets_path: PathLike) -> numpy.array:
"""
Read a text file containing onsets. Return it as a list of floats.
"""
with open(onsets_path, "r") as io:
lines = io.readlines()
onsets = numpy.array([float(line) for line in lines])
return onsets | 5,347,959 |
def resolve(path):
"""Resolve a command to help understanding where a command comes from"""
cmd, resolver = get_command(path, True)
click.echo(
f"The command {path} is resolved by the resolver {resolver.name}"
) | 5,347,960 |
def format_specific_efficacy(method, type_1: str, type_2: str = None):
""" Format the efficacy string specifically for defense or attack. """
effective, ineffective, useless = format_damage(method, type_1, type_2)
type_name = format_type(type_1, type_2)
s = "**{}** \N{EN DASH} **{}**\n".format(type_name... | 5,347,961 |
def postfix(itemString):
"""transform infixExpre into postfixExpre
Algorithm:
step1: if operator, stack in;
step2: if "(", stack in.
step3: if variable, pop out the all continued unary operator until other operator or "("
step4: if ")", pop out all operators until "(", then pop a... | 5,347,962 |
def validate_authorization(sender, instance, **kwargs):
"""Authorizations are generated by app code instead of ModelForm, so full_clean() before saving."""
instance.full_clean() | 5,347,963 |
def main():
"""Main entry point for the default bot command."""
launch.main(config_path=args.config_path) | 5,347,964 |
def getSuffixes(algorithm, seqType) :
""" Get the suffixes for the right algorithm with the right
sequence type
"""
suffixes = {}
suffixes['LAST'] = {}
suffixes['BLAST'] = {}
suffixes['BLAST']['nucl'] = ['nhr', 'nsq', 'nin']
suffixes['BLAST']['prot'] = ['phr', 'psq', 'pin']
s... | 5,347,965 |
def make_numbered_in_temp(
keep: int = 10,
lock_timeout: float = -1,
tmpdir: Optional[Path] = None,
register=None,
) -> Path:
"""
Helper to create a numbered directory in the temp dir with automatic disposal
of old contents.
"""
import tempfile
from robocorp_code.path_operations ... | 5,347,966 |
def handle_server_api(output, kwargs):
""" Special handler for API-call 'set_config' [servers] """
name = kwargs.get('keyword')
if not name:
name = kwargs.get('name')
if name:
server = config.get_config('servers', name)
if server:
server.set_dict(kwargs)
... | 5,347,967 |
def compare_names(namepartsA, namepartsB):
"""Takes two name-parts lists (as lists of words) and returns a score."""
complement = set(namepartsA) ^ set(namepartsB)
intersection = set(namepartsA) & set(namepartsB)
score = float(len(intersection))/(len(intersection)+len(complement))
return score | 5,347,968 |
def Normal_VaR(return_matrix, theta,Horizon): #500 datas needed
"""
Compute the Value-at-Risk and Conditional Value-at-Risk
Parameters
----------
risk_returns : np.ndarray
theta : np.float64
Horizon : np.int16
Returns
----------
np.ndarra... | 5,347,969 |
def daemon(queue, asg, interval, namespace, user="guest", password="guest"):
"""Submit EC2 custom metric for jobs waiting to be run."""
logging.info("queue: %s" % queue)
logging.info("interval: %d" % interval)
logging.info("namespace: %s" % namespace)
while True:
try:
job_count ... | 5,347,970 |
def oscillator_amplitude(state, ders, period, floquet, zero_phase_lc, phase_warmup_periods=5, thr=0.0, dt=0.005):
"""calculates the isostable amplitude of the oscillator from dynamical equations
:param state: state of the system
:param ders: a list of state variable derivatives
:param period: oscillator period
:... | 5,347,971 |
def commonprefix(a, b):
"""Find longest common prefix of `a` and `b`."""
pos = 0
length = min(len(a), len(b))
while pos < length and a[pos] == b[pos]:
pos += 1
return pos, b | 5,347,972 |
def parse_datetime(strtime):
"""
Parse a string date, time & tz into a datetime object:
2003-03-20 05:00:00-07
"""
offset = int(strtime[-3:])
date_time = dt.strptime(strtime[:-4], '%Y-%m-%d %H:%M:%S')
offset = timedelta(hours=offset)
return (date_time + offset).replace(tzinfo=utc) | 5,347,973 |
def traverse_depth_first(base: AnyDependency) -> List[AnyDependency]:
"""Performs a depth first traversal of the dependency tree.
"""
def _traverse_tree_2(base: AnyDependency) -> List[AnyDependency]:
queue: List[AnyDependency] = []
current_idx = 0
queue.append(base)
while len... | 5,347,974 |
def _store_span(item, span):
"""Store span at `pytest.Item` instance."""
setattr(item, "_datadog_span", span) | 5,347,975 |
def test_invalid_a_b_setter(a):
"""Test setting invalid a, b values."""
ellipse = Ellipse(1, 1)
with pytest.raises(ValueError):
ellipse.a = a
with pytest.raises(ValueError):
ellipse.b = a | 5,347,976 |
def update_config(
client,
key,
*,
value=None,
remove=False,
global_only=False,
commit_message=None
):
"""Add, update, or remove configuration values."""
section, section_key = _split_section_and_key(key)
if remove:
value = client.remove_value(
section, sectio... | 5,347,977 |
def AcCheckTargetTools(context, programs, value_if_not_found=None,
path=None, pathext=None, reject=[]):
"""Corresponds to AC_CHECK_TARGET_TOOLS_ autoconf macro.
.. _AC_CHECK_TARGET_TOOLS: http://www.gnu.org/software/autoconf/manual/autoconf.html#index-AC_005fCHECK_005fTARGET_005fTOOLS-314
... | 5,347,978 |
def parse_time(t):
""" parse a date time string, or a negative number as
the number of seconds ago.
returns unix timestamp in MS
"""
try:
tint = int(t)
if tint <= 0:
return int(nowms() + (tint * 1000))
except ValueError:
pass
#the parsed date may or may no... | 5,347,979 |
def _get_duration(tmin: np.datetime64, tmax: np.datetime64) -> str:
"""
Determine the duration of the given datetimes.
See also: `ISO 8601 Durations <https://en.wikipedia.org/wiki/ISO_8601#Durations>`_
:param tmin: Time minimum
:param tmax: Time maximum
:return: Temporal resolution formatted a... | 5,347,980 |
def inplace_freeze(model: nn.Module):
"""Freezes the modle by turning off its parameter's
require_grad attributes. In-place operation.
"""
for p in model.parameters():
p.requires_grad_(False) | 5,347,981 |
def get_polyend_circle_angles(a, b, isLeft):
"""
theta0 = pi/2 + betta, theta1 = 2 * pi + betta;
betta = pi/2 - alpha;
alpha = atan(a)
"""
if a is None and b is None:
return None, None
alpha = math.pi / 2.0 if a is None else math.atan(a)
betta = math.pi / 2.0 - alpha
shift... | 5,347,982 |
def main():
"""Main entrypoint."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("file", nargs="+", type=pathlib.Path)
args = parser.parse_args()
hooks.utils.check_executable("packer")
return hooks.utils.bulk_check(
packer_fix,
args.file,
) | 5,347,983 |
def descompact_zip(file_path: str, dest_path: str) -> None:
"""Descompact the GlassFish .zip file."""
zip_file = zipfile.ZipFile(f'{file_path}')
try:
zip_file.extractall(dest_path)
except Exception as err:
print('Error unzipping Glassfish: ', str(err)) | 5,347,984 |
def add_entry(entries):
"""Add a new task"""
new_task = input('\nTo do: ')
protect = 'No'
tasklimit = str(ToDo.timestamp)
taskinfo = (new_task, 'undone', protect, random.randint(0,10000000), tasklimit)
cur.execute("INSERT INTO mytodos VALUES(?,?,?,?,?)" , taskinfo)
entries = cur.execute('SE... | 5,347,985 |
def main(args):
"""Main entry point allowing external calls
Args:
args ([str]): command line parameter list
"""
if isinstance(args, list):
args = parse_args(args)
setup_logging(args.loglevel)
_logger.debug("Starting confluence...")
args.func(args)
_logger.info("Confluence ... | 5,347,986 |
def get_search_cache_key(prefix, *args):
""" Generate suitable key to cache twitter tag context
"""
key = '%s_%s' % (prefix, '_'.join([str(arg) for arg in args if arg]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
return key | 5,347,987 |
def main(argv=None):
"""Run pragma-no-mutate filter with specified command line arguments.
"""
return PragmaNoMutateFilter().main(argv) | 5,347,988 |
def patch_requests():
"""Stub out services that makes requests."""
patch_client = patch("homeassistant.components.meteo_france.MeteoFranceClient")
with patch_client:
yield | 5,347,989 |
def independence_single_value(values, sigma=0.70):
"""
This calculates the independence of the models for a given metric
where the metric is single valued, e.g. the slope of a gradient.
------Input------
values (list) : The single values for each model.
sigma (float) : The value of sigma_s
-... | 5,347,990 |
def extract_fingerprints(atoms, i_jbond_dict, radius):
"""Extract the r-radius subgraphs (i.e., fingerprints)
from a molecular graph using Weisfeiler-Lehman algorithm."""
if (len(atoms) == 1) or (radius == 0):
fingerprints = [fingerprint_dict[a] for a in atoms]
else:
nodes = at... | 5,347,991 |
def GetUniqueClassMembers(Class, Ignore = [], AllowedOverrides = []):
"""
Args:
- Class {object}: reference to the class
- Ignore {List[str]}:
- AlwaysAllow {List[str]}: Always allowed members named x, even if they exists in the parent class
Returns: tuple("Name", Reference)
"... | 5,347,992 |
def set_categories(ax, labels, categories):
"""Applies gradient coloring for rewards
Params:
* ax: matplotlib.axes._subplots.AxesSubplot
Axis object
* labels: array-like
One or Two sized array with x and y labels.
* categories: dict<tuple(str, str), list<float>>
... | 5,347,993 |
def get_condition_keys_available_to_raw_arn(db_session, raw_arn):
"""
Get a list of condition keys available to a RAW ARN
:param db_session: SQLAlchemy database session object
:param raw_arn: The value in the database, like arn:${Partition}:s3:::${BucketName}/${ObjectName}
"""
rows = db_session... | 5,347,994 |
def get_reviewer(form):
""" Gets reviewer info, or adds if necessary
"""
reviewer = Reviewer.query.filter_by(email=form.get("reviewer-email")).first()
if reviewer:
reviewer_id = reviewer.reviewer_id
else:
reviewer_id = add_reviewer(form)
return reviewer_id | 5,347,995 |
def read_xyz(using):
"""Reads coordinates of an xyz file and return a list of |Atom| objects, one for each atom"""
coords = []
with open(using, "r") as f:
for coord in f.readlines()[2:]:
line = coord.split()
for val in PT.ptable.values():
if line[0] == val[0]:... | 5,347,996 |
def train_agent_real_env(
problem_name, agent_model_dir, event_dir, world_model_dir, epoch_data_dir,
hparams, epoch=0, is_final_epoch=False):
"""Train the PPO agent in the real environment."""
gym_problem = registry.problem(problem_name)
ppo_hparams = trainer_lib.create_hparams(hparams.ppo_params)
ppo_... | 5,347,997 |
def initialize_classification(model_name: str,
num_classes: int,
use_pretrained: bool =True
) -> (Module, int):
""" Initialize these variables which will be set in this if statement. Each of these
variables is mo... | 5,347,998 |
def get_csc():
"""get Configuration Client"""
config_host = enstore_functions2.default_host()
config_port = enstore_functions2.default_port()
return configuration_client.ConfigurationClient((config_host,config_port)) | 5,347,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.