content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gen_certs():
""" Generate self-signed TLS certtificate
"""
os.mkdir("./remote/certs")
cmd = 'cd ./remote/certs && openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 -subj "/C=US/ST=Denial/L=Springfield/O=Dis/CN=workspace.com" -keyout cert.key -out cert.crt'
subprocess.Popen(cmd, shell=Tru... | 5,344,900 |
def prune_deg_one_nodes(sampled_graph):
""" prune out degree one nodes from graph """
deg_one_nodes = []
for v in sampled_graph.nodes():
if sampled_graph.degree(v) == 1:
deg_one_nodes.append(v)
for v in deg_one_nodes:
sampled_graph.remove_node(v)
return sampled_graph | 5,344,901 |
def process_all_bpch_files_in_dir(folder=None, ext_str=None):
"""
Process all bpch files in a given directory
(Warpper of process_bpch_files_in_dir2NetCDF for *ts*bpch* and *ctm*bpch*
files)
folder (str): directory address for folder contain files
ext_str (str): extra str to inc. in monthly fil... | 5,344,902 |
def reduce_clauses(clauses):
"""
Reduce a clause set by eliminating redundant clauses
"""
used = []
unexplored = clauses
while unexplored:
cl, unexplored = unexplored[0], unexplored[1:]
if not subsume(used, cl) and not subsume(unexplored,cl):
used.append(cl)
return ... | 5,344,903 |
def get_pretrained_t2v(name, model_dir=MODEL_DIR):
"""
It is a good idea if you want to switch token list to vector earily.
Parameters
----------
name:str
select the pretrained model
e.g.:
d2v_all_256,
d2v_sci_256,
d2v_eng_256,
d2v_lit_256,
w2... | 5,344,904 |
def get_np_io(arr, **kwargs) -> BytesIO:
"""Get the numpy object as bytes.
:param arr: Array-like
:param kwargs: Additional kwargs to pass to :func:`numpy.save`.
:return: A bytes object that can be used as a file.
"""
import numpy as np
bio = BytesIO()
np.save(bio, arr, **kwargs)
b... | 5,344,905 |
def get_deep_attr(obj, keys):
""" Helper for DeepKey"""
cur = obj
for k in keys:
if isinstance(cur, Mapping) and k in cur:
cur = cur[k]
continue
else:
try:
cur = getattr(cur, k)
continue
except AttributeError:
... | 5,344,906 |
def fork_node_item_inline_editor(item, view, pos=None) -> bool:
"""Text edit support for Named items."""
@transactional
def update_text(text):
item.subject.joinSpec = text
return True
def escape():
item.subject.joinSpec = join_spec
subject = item.subject
if not subject... | 5,344,907 |
def get_selfies_alphabet(smiles_list):
"""Returns a sorted list of all SELFIES tokens required to build a
SELFIES string for each molecule."""
selfies_list = list(map(sf.encoder, smiles_list))
all_selfies_symbols = sf.get_alphabet_from_selfies(selfies_list)
all_selfies_symbols.add('[nop]')
self... | 5,344,908 |
def update_dependencies_simple():
"""
Updates all parameter dependencies
"""
# Number of input neurons
par['n_input'] = par['num_motion_tuned'] + par['num_fix_tuned'] + par['num_rule_tuned']
# General network shape
par['shape'] = (par['n_input'], par['n_hidden'], par['n_output'])
# If... | 5,344,909 |
def get_face_angular_dataloader(dataset_path, input_size, batch_size, num_workers, train_portion=1):
""" Prepare dataset for training and evaluating pipeline
Args:
dataset_path (str)
input_size (int)
batch_size (int)
num_workers (int)
train_portion (float)
Return:
... | 5,344,910 |
def compile_sql_numericize(element, compiler, **kw):
"""
Turn common number formatting into a number. use metric abbreviations, remove stuff like $, etc.
"""
arg, = list(element.clauses)
def sql_only_numeric(text):
# Returns substring of numeric values only (-, ., numbers, scientific notati... | 5,344,911 |
def run_sgd(model, epochs):
"""
Runs SGD for a predefined number of epochs and saves the resulting model.
"""
print("Training full network")
weights_rand_init = model.optimize(epochs=epochs)
# weights_rand_init = model.optimize(epochs=epochs, batch_size=55000, learning_rate=0.1)
print("M... | 5,344,912 |
def get_all_outcome_links_for_context_courses(request_ctx, course_id, outcome_style=None, outcome_group_style=None, per_page=None, **request_kwargs):
"""
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param course_id: (required) ID
:type course_id:... | 5,344,913 |
def GetContentResourceSpec():
"""Gets Content resource spec."""
return concepts.ResourceSpec(
'dataplex.projects.locations.lakes.content',
resource_name='content',
projectsId=concepts.DEFAULT_PROJECT_ATTRIBUTE_CONFIG,
locationsId=LocationAttributeConfig(),
lakesId=LakeAttributeConfig()... | 5,344,914 |
def softplus(
x: oneflow._oneflow_internal.BlobDesc, name: Optional[str] = None
) -> oneflow._oneflow_internal.BlobDesc:
"""This operator computes the softplus value of Blob.
The equation is:
.. math::
out = log(e^x+1)
Args:
x (oneflow._oneflow_internal.BlobDesc): A Blob
... | 5,344,915 |
def test_basic_knn(alg_list, datasets, textkey="cv-basic", testname="BASIC", seed=28):
"""
Evaluates the algorithms specified in the datasets provided.
Parameters
----------
alg_list : list
The list of algorithms. Each item must be a quadruple (alg, name, key, ks, cons), where 'alg' is the... | 5,344,916 |
def diff_gcs_directories(
base_directory_url: str, target_directory_url: str
) -> Tuple[List[str], List[str], List[str]]:
"""
Compare objects under different GCS prefixes.
:param base_directory_url: URL for base directory
:param target_directory_url: URL for target directory
:returns: Tuple wi... | 5,344,917 |
def main():
"""Run devappserver and the user's application in separate containers.
The application must be started with the proper environment variables,
port bindings, and volume bindings. The devappserver image runs a
standalone api server.
"""
logging.getLogger('appstart').setLevel(logging.I... | 5,344,918 |
def load_compatible_apps(file_name: str) -> List[Product]:
"""Loads from file and from github and merges results"""
local_list = load_installable_apps_from_file(file_name)
try:
github_list = load_compatible_apps_from_github()
except (URLError, IOError):
github_list = []
return list... | 5,344,919 |
def delete(page_id):
"""Delete a page."""
page = _get_page(page_id)
page_name = page.name
site_id = page.site_id
success, event = page_service.delete_page(page.id, initiator_id=g.user.id)
if not success:
flash_error(
gettext('Page "%(name)s" could not be deleted.', name=pa... | 5,344,920 |
async def test_config_schema(hass):
"""Test that config schema is imported properly."""
config = {
konnected.DOMAIN: {
konnected.CONF_API_HOST: "http://1.1.1.1:8888",
konnected.CONF_ACCESS_TOKEN: "abcdefgh",
konnected.CONF_DEVICES: [{konnected.CONF_ID: "aabbccddeeff"}... | 5,344,921 |
def save_mission(aFileName):
"""
Save a mission in the Waypoint file format
(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
"""
print "\nSave mission from Vehicle to file: %s" % export_mission_filename
#Download mission from vehicle
missionlist = downl... | 5,344,922 |
def drift_var():
"""
Concept drift:
1. n_drifts
2. concept_sigmoid_spacing (None for sudden)
3. incremental [True] or gradual [False]
4. recurring [True] or non-recurring [False]
"""
return [(10, None, False, False), (10, 5, False, False), (10, 5, True, False)] | 5,344,923 |
def get_generators(matrix):
"""
Given a matrix in H-rep, gets the v-rep
Turns out, the code is the same as get_inequalities,
since lrs determines the directions based on the input.
Left like this for readability.
"""
return get_inequalities(matrix) | 5,344,924 |
def num_instances(diff, flag=False):
"""returns the number of times the mother and daughter have
pallindromic ages in their lives, given the difference in age.
If flag==True, prints the details."""
daughter = 0
count = 0
while True:
mother = daughter + diff
if are_reversed(daught... | 5,344,925 |
def bench(args):
"""
Run game of life benchmarks.
"""
raise ConsoleError("not implemented yet") | 5,344,926 |
def get_dipy_workflows(module):
"""Search for DIPY workflow class.
Parameters
----------
module : object
module object
Returns
-------
l_wkflw : list of tuple
This a list of tuple containing 2 elements:
Worflow name, Workflow class obj
Examples
--------
... | 5,344,927 |
def test_service_to_rdf_without_identifier_should_raise_error(
minimal_spec: str,
) -> None:
"""It raises a RequiredFieldMissingError."""
with pytest.raises(RequiredFieldMissingError):
catalog = Catalog()
catalog.identifier = "http://example.com/catalogs/1"
url = "http://example.com... | 5,344,928 |
def azel_fit(coo_ref, coo_meas, nsamp=2000, ntune=2000, target_accept=0.95, random_seed=8675309):
"""
Fit full az/el pointing model using PyMC3. The terms are analogous to those used by TPOINT(tm). This fit includes
the eight normal terms used in `~pytelpoint.transform.azel` with additional terms, az_sigma ... | 5,344,929 |
def repository_path(relative_path: str) -> Path:
"""
Resolve `relative_path` relative to the root of the repository.
"""
return Path(os.path.join(REPOSITORY_ROOT), relative_path).resolve() | 5,344,930 |
def geojson_to_labels(geojson_dict, crs_transformer, extent=None):
"""Convert GeoJSON to ObjectDetectionLabels object.
If extent is provided, filter out the boxes that lie "more than a little
bit" outside the extent.
Args:
geojson_dict: dict in GeoJSON format
crs_transformer: used to c... | 5,344,931 |
def processed_transcript(df):
"""
Cleans the Transcript table by splitting value fileds and replacing nan values, drop extra columns
PARAMETERS:
transcript dataframe
RETURNS:
Cleaned transcript dataframe
"""
#expand the dictionary to coulmns (reward, amount, offre... | 5,344,932 |
def _TestSuiteName(dash_json_dict):
"""Extracts a test suite name from Dashboard JSON.
The dashboard JSON may contain a field "test_suite_name". If this is not
present or it is None, the dashboard will fall back to using "benchmark_name"
in the "chart_data" dict.
"""
name = None
if dash_json_dict.get('te... | 5,344,933 |
def create_default_prior(name, default_priors_file=None):
"""Make a default prior for a parameter with a known name.
Parameters
----------
name: str
Parameter name
default_priors_file: str, optional
If given, a file containing the default priors.
Return
------
prior: Pr... | 5,344,934 |
def set_polling_interval(duthosts, enum_rand_one_per_hwsku_frontend_hostname):
""" Set CRM polling interval to 1 second """
duthost = duthosts[enum_rand_one_per_hwsku_frontend_hostname]
wait_time = 2
duthost.command("crm config polling interval {}".format(CRM_POLLING_INTERVAL))["stdout"]
logger.info... | 5,344,935 |
def client():
"""Provide the client session used by tests."""
with app.app.test_client() as client:
yield client | 5,344,936 |
def clean_data(list_in):
"""
Inputs:
list_in - filtered list of ticket orders
Outputs:
Return list of tuples, each tuple contains
(last name, first name, note,[tickets])
"""
notes_list = []
data_out = []
for row in list_in:
trimmed_row = row[row.index('Purcha... | 5,344,937 |
def adfuller(
vdf,
column: str,
ts: str,
by: list = [],
p: int = 1,
with_trend: bool = False,
regresults: bool = False,
):
"""
---------------------------------------------------------------------------
Augmented Dickey Fuller test (Time Series stationarity).
Parameters
----------
vdf: ... | 5,344,938 |
def get_routes_bend180(
ports: Union[List[Port], Dict[str, Port]],
bend: ComponentOrFactory = bend_euler,
cross_section: CrossSectionFactory = strip,
bend_port1: Optional[str] = None,
bend_port2: Optional[str] = None,
**kwargs,
) -> Routes:
"""Returns routes made by 180 degree bends.
Ar... | 5,344,939 |
def list_datasets(github_repo="Ouranosinc/xclim-testdata", branch="main"):
"""Return a DataFrame listing all xclim test datasets available on the GitHub repo for the given branch.
The result includes the filepath, as passed to `open_dataset`, the file size (in KB) and the html url to the file.
This uses an... | 5,344,940 |
def make_layerwise_projection_unshrink(*, server_state_type,
client_update_output_type,
server_update_fn, server_model_fn,
client_model_fn, shrink_unshrink_info):
"""Creates an unshrink function which ... | 5,344,941 |
def main(fasta_in, fasta_out, report):
"""Insert repetitive sequences into a fasta file."""
tbls = []
recs = [rec for rec in parse(fasta_in, 'fasta') if len(rec.seq) >= TENMIL]
with click.progressbar(recs) as seq_recs:
for rec in seq_recs:
tbls.append(insert_repetitive_regions(rec))
... | 5,344,942 |
def embed_terms(args, classes, dest, use_cache=True, path_to_json='ebd_cache.json'):
"""
Embeds class strings into word representations.
:param args
:param classes: (list of str) topic classes
:param dest: (str) path to destination file
:param path_to_json: (str) path to json file contai... | 5,344,943 |
def wf_paths(reachable):
"""
Construct all well-formed paths satisfying a given condition.
The condition is as follows: all the paths have height equal to
the ceiling of log_2(`reachable` + 1). `reachable` is interpreted
as a bitfield, with 1 meaning that the corresponding leaf on the
floor of ... | 5,344,944 |
def get_imagemodel_in_rar(rar_path, mode):
""" 압축파일(rar_path)의 이미지파일의 name, width, height를 모아서 반환한다."""
image_models = []
with rarfile.RarFile(rar_path) as rf:
for name in rf.namelist():
if is_hidden_or_trash(name):
continue
if is_extensions_allow_image(name)... | 5,344,945 |
async def test_create_new_credential(provider: SynologyAuthProvider):
"""Test that we create a new credential."""
credentials = await provider.async_get_or_create_credentials(
{
"account": "test-user",
}
)
assert credentials.is_new is True
assert credentials.data["account... | 5,344,946 |
def run_single(i,threshold_area_fraction,death_to_birth_rate_ratio,domain_size_multiplier,return_history=False):
"""run a single voronoi tessellation model simulation"""
rates = (DEATH_RATE,DEATH_RATE/death_to_birth_rate_ratio)
rand = np.random.RandomState()
history = lib.run_simulation(simulation,L,TIM... | 5,344,947 |
def matrixmult (A, B):
"""Matrix multiplication function
This function returns the product of a matrix multiplication given two matrices.
Let the dimension of the matrix A be: m by n,
let the dimension of the matrix B be: p by q,
multiplication will only possible if n = p,
thus creating a matr... | 5,344,948 |
def TorsLattice(data = None, *args, **kwargs):
"""
Construct a lattice of torsion classes from various forms of input data
This raises an error if the constructed lattice is not semidistributive,
since the lattice of torsion classes is semidistributive.
INPUT:
- ``data``, ``*args``, ``**kwarg... | 5,344,949 |
def test_dupes_no_cache(mock_DirInfo):
"""
dupes command does populate if necessary.
"""
mock_DirInfo.cached.return_value.file_count = 0
with pytest.raises(SystemExit, match='0'):
main()
mock_DirInfo.cached.assert_called_once_with(os.path.abspath('.'))
mock_DirInfo.cached.return_valu... | 5,344,950 |
def get_accumulated_report(trigger_id, mission='fermi'):
"""
Return the last value for each keyword on the summary page for a given trigger_id
:param trigger_id:
:param mission: 'fermi' or 'swift'
:return:
"""
if 'fermi' in mission:
site = fermi_grb_site
elif 'swift' in mission:
... | 5,344,951 |
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike an RNN tha... | 5,344,952 |
def get_numbers(number, size, *, fg=DEFAULT_FGCHARACTER, bg=DEFAULT_BGCHARACTER):
"""Creates a shape of numbers.
Positional arguments:
number - number to print.
size - size of the shape.
Keyword arguments:
fg - foreground character.
bg - background character.
... | 5,344,953 |
def load_external_data_for_model(model, base_dir): # type: (ModelProto, Text) -> None
"""
Loads external tensors into model
@params
model: ModelProto to load external data to
base_dir: directory that contains external data
"""
for tensor in _get_all_tensors(model):
if uses_external... | 5,344,954 |
def config_from_env(key, config_schema=None):
"""Read config from a file path in os.env.
Args:
key (str) : Key represents an evironment variable to read config path
config_schema (trafaret): Trafaret object that defines the schema of the config.
If None, then trafaret validation i... | 5,344,955 |
def to_cmyk(r: int, g: int, b: int) -> _cmyk:
"""
Takes RGB values 0->255 and returns their values
in the CMYK namespace.
https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
"""
r, g, b = to_float(r, g, b)
k = 1 - max(r, g, b)
c = (1 - r - k) / (1 - k)
m = (1 - g - k) / (1 -... | 5,344,956 |
def GetHostsInClusters(datacenter, clusterNames=[], connectionState=None):
"""
Return list of host objects from given cluster names.
@param datacenter: datacenter object
@type datacenter: Vim.Datacenter
@param clusterNames: cluster name list
@type clusterNames: string[]
@param connectionSta... | 5,344,957 |
def get_gfa_targets(tiles, gfafile, faintlim=99, gaiadr="dr2"):
"""Returns a list of tables of GFA targets on each tile
Args:
tiles: table with columns TILEID, RA, DEC; or Tiles object
targets: table of targets with columsn RA, DEC
gaiadr: string, must be either "dr2" or "edr3" (d... | 5,344,958 |
def test_set_str_value():
"""Test that a string option can have its value set"""
config = Configuration()
config.add_option('test', option_type=str)
with pytest.raises(ConfigurationError):
config.test
config.test = "1"
assert config.test == "1"
config.test = 1
assert config.tes... | 5,344,959 |
def main():
"""Entrypoint of application"""
version = sb.utils.get_version()
parser = argparse.ArgumentParser(description=f"Shape Bruteforce CLI v{version}")
parser.add_argument("image", type=str, nargs='?', default="", help="Image to be processed")
parser.add_argument("-s", "--size", default=64, ty... | 5,344,960 |
def meijerint_indefinite(f, x):
"""
Compute an indefinite integral of ``f`` by rewriting it as a G function.
Examples
========
>>> from sympy.integrals.meijerint import meijerint_indefinite
>>> from sympy import sin
>>> from sympy.abc import x
>>> meijerint_indefinite(sin(x), x)
-c... | 5,344,961 |
def fit_size(
img: IMG,
size: Tuple[int, int],
mode: FitSizeMode = FitSizeMode.INCLUDE,
direction: FitSizeDir = FitSizeDir.CENTER,
bg_color: Union[str, float, Tuple[float, ...]] = (255, 255, 255, 0),
) -> IMG:
"""
调整图片到指定的大小,超出部分裁剪,不足部分设为指定颜色
:params
* ``img``: 待调整的图片
* ``siz... | 5,344,962 |
def load_iot_config(ini: dict):
"""
"""
if not verify_params(ini, 'iot', ['file', 'filedir']):
return {}
# Set file directory
iot_params = ini['iot']
filedir = iot_params['filedir']
filedir = filedir.strip(" ")
if filedir == "":
# HOME directory set
filedir = os... | 5,344,963 |
def test_submit_except8(mock_ssh):
"""
Check that jobsubmit exception is raised on generic SSH failure.
"""
job = {
"destdir": "/path/to/destdir",
"subfile": "submit.file"
}
mock_ssh.side_effect = exceptions.SSHError("Error", ("out", "err", 0))
mock_ssh.return_value = ("su... | 5,344,964 |
def recordDevice(*args, **kwargs):
"""
Starts and stops server side device recording.
Returns: None
"""
pass | 5,344,965 |
def test_guitab_loadall():
"""Confirm that the custom shell program can correctly load tab data"""
test_file = Path(__file__).parent / "test_guitab_file.txt"
guitab_shell = GuitabShell()
guitab_shell.do_loadall(str(test_file))
assert str(guitab_shell.user_tab) == global_test_data.str_tab_file_load
... | 5,344,966 |
def supports_colour():
"""
Return True if the running system's terminal supports colour,
and False otherwise.
Adapted from https://github.com/django/django/blob/master/django/core/management/color.py
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the Windows Registry ... | 5,344,967 |
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int:
"""
Returns the value of the next code given the value of the current code
The first code is `20151125`.
After that, each code is generated by taking the previous one, multiplying it by `252533`,
and then keeping the remainder... | 5,344,968 |
def main() -> int:
"""Runs a program specified by command-line arguments."""
args = argument_parser().parse_args()
if not args.command or args.command[0] != '--':
return 1
env = os.environ.copy()
# Command starts after the "--".
command = args.command[1:]
if args.args_file is not ... | 5,344,969 |
def read_csv_to_lol(full_path, sep=";"):
"""
Read csv file into lists of list.
Make sure to have a empty line at the bottom
"""
with open(full_path, 'r') as ff:
# read from CSV
data = ff.readlines()
# New line at the end of each line is removed
data = [i.replace("\n", "") for... | 5,344,970 |
def read_experiment(path):
"""
Discovers CSV files an experiment produced and construct columns
for the experiment's conditions from the sub-directory structure.
Args:
path: path to the experiment's results.
Returns:
pd.DataFrame
"""
objects = list(path.rglob('*.csv'))
... | 5,344,971 |
def single_keyword_search(keyword):
"""
구글에 keyword 검색결과를 html로 받아온뒤에 그 안에 일반 게시물 분류에 속하는
class='r' 부분만 모아서 return해주는 함수 입니다.
Args:
Keyword (String) : 구글에 검색할 Keyword
Returns:
title_list (bs4.element.ResultSet) : 구글 검색에서 확인된 일반게시물(class='r')들의 모음
"""
URL = 'https://www... | 5,344,972 |
def test_cluttered_table_place_get_gt_nsrts():
"""Tests for get_gt_nsrts in ClutteredTablePlaceEnv."""
test_cluttered_table_get_gt_nsrts(place_version=True) | 5,344,973 |
def partial_list(ys, xs, specified_shapes=None):
"""
Args:
ys: A list of tensors. Each tensor will be differentiated with the partial_nd
xs: A Tensor to be used for differentiation, or a list of tensors to be used for differentiation with the smae length as ys
specified_shapes: A list of... | 5,344,974 |
def _GuessBrowserName(bisect_bot):
"""Returns a browser name string for Telemetry to use."""
default = 'release'
browser_map = namespaced_stored_object.Get(_BOT_BROWSER_MAP_KEY)
if not browser_map:
return default
for bot_name_prefix, browser_name in browser_map:
if bisect_bot.startswith(bot_name_prefi... | 5,344,975 |
def compile_train_function(network, batch_size, learning_rate):
"""Compiles the training function.
Args:
network: The network instance.
batch_size: The training batch size.
learning_rate: The learning rate.
Returns:
The update function that takes a batch of images and targets an... | 5,344,976 |
def json_loads(data):
"""Load json data, allowing - to represent stdin."""
if data is None:
return ""
if data == "-":
return json.load(sys.stdin)
elif os.path.exists(data):
with open(data, 'r') as handle:
return json.load(handle)
else:
return json.loads(d... | 5,344,977 |
def filter_values(freq, values, nthOct: int = 3):
"""
Filters the given values into nthOct bands.
Parameters
----------
freq : ndarray
Array containing the frequency axis.
values : ndarray
Array containing the magnitude values to be filtered.
nthOct : int, optional
F... | 5,344,978 |
def create_project(request):
"""View to create new project"""
user = request.user
if user.is_annotator:
error = ErrorMessage(header="Access denied", message="Only admin and managers can create projects")
return render(request, 'error.html', {'error':error})
if request.method == "POST":
... | 5,344,979 |
def limit(
observed_CLs: np.ndarray,
expected_CLs: np.ndarray,
poi_values: np.ndarray,
figure_path: Optional[pathlib.Path] = None,
close_figure: bool = False,
) -> mpl.figure.Figure:
"""Draws observed and expected CLs values as function of the parameter of interest.
Args:
observed_C... | 5,344,980 |
def get_genlu_code(cursor, label):
"""Find or create the code for this label."""
if label not in GENLU_CODES:
cursor.execute("SELECT max(id) from general_landuse")
row = cursor.fetchone()
newval = 0 if row[0] is None else row[0] + 1
LOG.debug("Inserting new general landuse code: ... | 5,344,981 |
def main():
"""
Combines all subprograms.
:return:
"""
# Tests ftp connection.
ftp,success = connectToFTP(FTP_HOST, FTP_USER, FTP_PASS,1)
if not success:
return
# Creates a queue that will end all other threads when necessary.
killThread = queue.Queue()
# Initializes t... | 5,344,982 |
def make_predictions(clf_object,predictors_str,data_source):
"""make_predictions comes up with predictions
from given input data
Input:
clf_object
object
constructed classification model
predictors_str
nd str array
... | 5,344,983 |
def ticket_queue_asnauto_skipvq(request, org, net, rir_data):
"""
queue deskro ticket creation for asn automation action: skip vq
"""
if isinstance(net, dict):
net_name = net.get("name")
else:
net_name = net.name
if isinstance(org, dict):
org_name = org.get("name")
... | 5,344,984 |
def no_span_nodes(tree, debug=False, root_id=None):
"""Return True, iff there is no span node in the given ParentedTree."""
assert isinstance(tree, ParentedTree)
if root_id is None:
root_id = tree.root_id
span_label = debug_root_label('span', debug=debug, root_id=root_id)
if tree.label() =... | 5,344,985 |
def get_token_annualized(address, days):
"""Return annualized returns for a specific token.
Args:
days [int]: Days ago for which to display annualized returns.
address [str]: Ethereum token address.
Return:
dict: Annualized returns for a specified token.
key [str]: Day... | 5,344,986 |
def generate_random_string(N):
"""
Generate a random string
Parameters
-------------
N
length of the string
Returns
-------------
random_string
Random string
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N)) | 5,344,987 |
def test_cmat2aset():
"""Test cmat2aset."""
assert True | 5,344,988 |
def _save_owner_edge(obj_ver_key, info_tup):
"""Save the ws_owner_of edge."""
username = info_tup[5]
from_id = 'ws_user/' + sanitize_arangodb_key(username)
to_id = 'ws_object_version/' + obj_ver_key
logger.debug(f'Saving ws_owner_of edge from {from_id} to {to_id}')
save('ws_owner_of', [{
... | 5,344,989 |
def derive_related_properties():
"""Derive the list of related properties from property statistics."""
logger.info('Deriving related properties ...')
data = statistics.get_json_data('properties')
related = {}
for pid in data:
if 'r' in data[pid] and data[pid]['r']:
related[pid]... | 5,344,990 |
def extract_charm_name_from_url(charm_url):
"""Extract the charm name from the charm url.
E.g. Extract 'heat' from local:bionic/heat-12
:param charm_url: Name of model to query.
:type charm_url: str
:returns: Charm name
:rtype: str
"""
charm_name = re.sub(r'-[0-9]+$', '', charm_url.spl... | 5,344,991 |
def class_name(service_name: str) -> str:
"""Map service name to .pyi class name."""
return f"Service_{service_name}" | 5,344,992 |
def interesting_columns(df):
"""Returns non-constant column names of a dataframe."""
return sorted(set(df.columns) - set(constant_columns(df))) | 5,344,993 |
def liberty_str(s):
"""
>>> liberty_str("hello")
'"hello"'
>>> liberty_str('he"llo')
Traceback (most recent call last):
...
ValueError: '"' is not allow in the string: 'he"llo'
>>> liberty_str(1.0)
'"1.0000000000"'
>>> liberty_str(1)
'"1.0000000000"'
>>> liberty_... | 5,344,994 |
def is_valid_dm(D, tol=0.0, throw=False, name="D", warning=False):
"""
Return True if input array is a valid distance matrix.
Distance matrices must be 2-dimensional numpy arrays.
They must have a zero-diagonal, and they must be symmetric.
Parameters
----------
D : ndarray
The cand... | 5,344,995 |
def solve_gradwavefront(data, excludeself=False, predict_at=None,
fix_covar=False, **kw):
"""Find turbulent contributions to measured fiber positions.
Assumes that the turbulent contributions can be modeled as the
gradient of a wavefront error. i.e., they are curl free.
Args:
... | 5,344,996 |
def str_to_py(value: str):
"""Convert an string value to a native python type."""
rv: Any
if is_boolean_state(value):
rv = get_boolean(value)
elif is_integer(value):
rv = get_integer(value)
elif is_float(value):
rv = get_float(value)
else:
rv = value
return rv | 5,344,997 |
def action(request: Dict[str, Any]) -> Tuple[str, int]:
"""Triggered from Slack action via an HTTPS endpoint.
Args:
request (dict): Request payload.
"""
if request.method != 'POST':
return 'Only POST requests are accepted', 405
print('Triggered Slack action.')
form = json.load... | 5,344,998 |
def inmemory():
"""Returns an xodb database backed by an in-memory xapian
database. Does not support spelling correction.
"""
return open(xapian.inmemory_open(), spelling=False, inmem=True) | 5,344,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.