content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def list_ga4_entities(admin_api):
"""Get a dictionary of GA4 entity settings based on type.
Args:
admin_api: The Admin API object.
Returns:
A dictionary of GA4 entity setting lists.
"""
entities = {
'ga4_account_summaries': [],
'ga4_accounts': [],
'ga4_properties': [],
'ga4_d... | 5,358,900 |
def text_detection_background(text, background=None, hsize=15, vsize=15):
""" Given a string TEXT, generate a picture with text in it
arguments:
TEXT -- a string to be displayed
HSIZE -- maximum number of characters in one line
VSIZE -- maximum number of lines
background -- a file for background. If None... | 5,358,901 |
def print_sig(expr):
"""
Arguments:
- `expr`:
"""
return "{0!s} × {1!s}".format(expr.dom, expr.body) | 5,358,902 |
def is_grounded_concept(c: Concept) -> bool:
""" Check if a concept is grounded """
return (
"UN" in c.db_refs
and c.db_refs["UN"][0][0].split("/")[1] != "properties"
) | 5,358,903 |
def _get_form(app, parent_form, factory_method, force_disable_csrf=False):
"""Create and fill a form."""
class AForm(parent_form):
pass
with app.test_request_context():
extra = _update_with_csrf_disabled() if force_disable_csrf else {}
RF = factory_method(AForm)
rf = RF(**... | 5,358,904 |
def get_root_disk_size():
""" Get size of the root disk """
context = pyudev.Context()
rootfs_node = get_rootfs_node()
size_gib = 0
for device in context.list_devices(DEVTYPE='disk'):
# /dev/nvmeXn1 259 are for NVME devices
major = device['MAJOR']
if (major == '8' or major =... | 5,358,905 |
def convert_to_premultiplied_png(file):
"""
http://stackoverflow.com/questions/6591361/method-for-converting-pngs-to-premultiplied-alpha
"""
logger.info("converting to premultiplied alpha")
im = Img.open(file).convert('RGBA')
a = numpy.fromstring(im.tobytes(), dtype=numpy.uint8)
a = a.astyp... | 5,358,906 |
def DSQuery(dstype, objectname, attribute=None):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the optional attribute to query.
Returns:
If an attribute is specified, the value of the attribute. Otherwise, the
... | 5,358,907 |
def main(cfg: DictConfig) -> None:
"""
This is a main function for `arachne.driver.cli`.
"""
logger.info(OmegaConf.to_yaml(cfg))
# Check the specified tool is valid
tools = list(cfg.tools.keys())
try:
assert len(tools) == 1
except AssertionError as err:
logger.exceptio... | 5,358,908 |
def calculate_offset(lon, first_element_value):
"""
Calculate the number of elements to roll the dataset by in order to have
longitude from within requested bounds.
:param lon: longitude coordinate of xarray dataset.
:param first_element_value: the value of the first element of the longitude array ... | 5,358,909 |
def plot_instcat_dists(phosim_file, figsize=(12, 12)):
"""
Create a multipanel plot of histograms of various columns in the
phosim instance catalog.
Parameters
----------
phosim_file: str
Instance catalog file containing includeobj references for each
object type.
figsize: t... | 5,358,910 |
def min_mean_col(m: ma.MaskedArray) -> int:
"""Calculate the index of the column with the smallest mean.
"""
if ma.count_masked(m) == m.size:
return -1
col_mean = np.nanmean(m, axis=0)
return np.argmin(col_mean) | 5,358,911 |
def load_simclrv2(init_args):
"""
Load pretrained SimCLR-v2 model.
"""
ckpt_file = init_args["ckpt_file"]
model_dir = init_args["model_dir"]
# Load the resnet.py that comes with the SimCLR-v2's PyTorch converter
sys.path.insert(
0,
os.path.join(
model_dir,
... | 5,358,912 |
def minekey_read(request, mk_hmac, mk_fid, mk_fversion, mk_iid, mk_depth, mk_type, mk_ext, **kwargs):
"""
arguments: request, mk_hmac, mk_fid, mk_fversion, mk_iid, mk_depth, mk_type, mk_ext, **kwargs
implements: GET /key/(MK_HMAC)/(MK_FID)/(MK_FVERSION)/(MK_IID)/(MK_DEPTH)/(MK_TYPE).(MK_EXT)
returns: a ... | 5,358,913 |
def get_file_metadata(folder, video_relative_path):
""" """
# SAMPLE FILENAME: XXCam_01_20180517203949574.mp4
# XXXXX_XX_YYYYMMDDHHMMSSmmm.mp4
# 2019/01/01/XXCam-20180502-1727-34996.mp4
# XXCam-01-20180502-1727-34996.mp4
video_filename = os.pat... | 5,358,914 |
def assert_array_almost_equal(x: numpy.ndarray, y: numpy.ndarray, decimal: int):
"""
usage.matplotlib: 4
usage.scipy: 260
usage.skimage: 14
usage.sklearn: 226
usage.statsmodels: 38
"""
... | 5,358,915 |
def test_data_alignment(role_value, should_pass, check_model):
"""Test a custom model which returns a good and alignments from data().
qtmodeltest should capture this problem and fail when that happens.
"""
class MyModel(qt_api.QAbstractListModel):
def rowCount(self, parent=qt_api.QtCore.QModel... | 5,358,916 |
def cov(a, b):
"""Return the sample covariance of vectors a and b"""
a = flex.double(a)
b = flex.double(b)
n = len(a)
assert n == len(b)
resid_a = a - flex.mean(a)
resid_b = b - flex.mean(b)
return flex.sum(resid_a*resid_b) / (n - 1) | 5,358,917 |
def beautify(soup: BeautifulSoup, rich_terminal: bool = True) -> str:
"""
Cleans up the raw HTML so it's more presentable.
Parse BeautifulSoup HTML and return prettified string
"""
beautifiedText = str()
for i in soup:
if rich_terminal:
term = Terminal()
span_sub ... | 5,358,918 |
def design_complexity(design: Design) -> int:
"""Returns an approximation of the design's complexity to create."""
diversity = 3 * len(design.required)
abundance = 2 * sum(design.required.values())
return diversity + abundance + design.additional | 5,358,919 |
def approx_q_y(q_z, mu_lookup, logvar_lookup, k=10):
"""
refer to eq.13 in the paper
"""
q_z_shape = list(q_z.size()) # (b, z_dim)
mu_lookup_shape = [mu_lookup.num_embeddings, mu_lookup.embedding_dim] # (k, z_dim)
logvar_lookup_shape = [logvar_lookup.num_embeddings, logvar_lookup.embedding_dim... | 5,358,920 |
def check_net_numpy(net_ds, num_ds, currents):
"""
Check that an ambient.Profile object is created correctly and that the
methods operate as expected.
"""
chem_names = net_ds.f_names
chem_units = net_ds.f_units
# Check the chemical names and units are correct
for i in range(3):... | 5,358,921 |
def svn_repos_get_logs2(*args):
"""
svn_repos_get_logs2(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start,
svn_revnum_t end, svn_boolean_t discover_changed_paths,
svn_boolean_t strict_node_history,
svn_repos_authz_func_t authz_read_func,
svn_log_message_receiver_t... | 5,358,922 |
def error_function(theta, X, y):
"""Error function J definition"""
diff = np.dot(X, theta) - y
return (1. / 2 * m) * np.dot(np.transpose(diff), diff) | 5,358,923 |
def register(operation_name):
"""
Registers the decorated class as an Operation with the supplied operation name
:param operation_name: The identifying name for the Operation
"""
def wrapper(clazz):
if operation_name not in OPERATIONS:
OPERATIONS[operation_name] = clazz
... | 5,358,924 |
def url_exists(video):
"""
check each source for a url for this video; return True as soon as one is found. If none are found, return False
"""
max_timeout = int(kodi.get_setting('source_timeout'))
logger.log('Checking for Url Existence: |%s|' % (video), log_utils.LOGDEBUG)
for cls in relevant_s... | 5,358,925 |
def test(loader):
"""Evaluate images with best weights."""
net.eval()
try:
filename = osp.join(cfg.OUTPUT_DIR, 'best_val_acc_weights.pth')
net.load_state_dict(torch.load(filename))
except FileNotFoundError:
net.load_state_dict(torch.load(cfg.OPTIM_SNAPSHOT))
bar = tqdm(enumer... | 5,358,926 |
def test_actions_explicit_get_collector_action_for_unexisting_terminal():
"""
Test for situation when `get_collector` has an action for un-existing
terminal.
"""
action = get_collector()
@action
def INT(context, value):
return int(value)
@action
def STRING(context, value):... | 5,358,927 |
def log2_grad(orig, grad):
"""Returns [grad * 1 / (log(2) * x)]"""
x = orig.args[0]
ones = ones_like(x)
two = const(2.0, dtype=x.checked_type.dtype)
return [grad * ones / (log(two) * x)] | 5,358,928 |
def test_anim_pairwise_maxmatch():
"""Test generation of NUCmer pairwise comparison command with maxmatch.
"""
cmd = anim.construct_nucmer_cmdline("file1.fna", "file2.fna",
maxmatch=True)
assert_equal(cmd, "nucmer -maxmatch -p ./nucmer_output/file1_vs_file2 " +
... | 5,358,929 |
def _stream_annotation(file_name, pn_dir):
"""
Stream an entire remote annotation file from Physionet.
Parameters
----------
file_name : str
The name of the annotation file to be read.
pn_dir : str
The PhysioNet directory where the annotation file is located.
Returns
--... | 5,358,930 |
def get_scenarios():
"""
Return a list scenarios and values for parameters in each of them
:return:
"""
# Recover InteractiveSession
isess = deserialize_isession_and_prepare_db_session()
if isess and isinstance(isess, Response):
return isess
scenarios = get_scenarios_in_state(i... | 5,358,931 |
def download() -> str:
""" Returns a download of the active files.
:return: the zip files needs to be downloaded.
"""
file_manager = utility.load_file_manager()
response = make_response(file_manager.zip_active_files(
"scrubbed_documents.zip"))
# Disable download caching
response.h... | 5,358,932 |
def evaluate_test_arff(model_path, test_arff_path, out_path):
"""
Obtain predictions of test_file using the trained model in model_path
:param output_folder:
:param output_name:
:param model_path:
:param test_file:
"""
# PREDICTIONS FILE HEADERS: INSTANCE, ACTUAL, PREDICTED, ERROR
ba... | 5,358,933 |
def main(root_dir: str,
train_dir: str,
model_info_dir: str) -> None:
"""
Main function for receiving args, and passing them through to form recognizer training function
Parameters
----------
root_dir: str
Root datastore being used
train_dir: str
Path on blob c... | 5,358,934 |
def load_from_pickle_file(filepath):
""" Loads a pickle file into a python variable """
with open(filepath, "rb") as f:
python_obj = pickle.load(f)
return python_obj | 5,358,935 |
def download_y(id:str, table):
"""
下载数据,主要放在线程里面跑,可以理解成每个线程单独跑一个
:param id: 股票代码
:param table: mongo里面的数据表
:return:
"""
date = datetime.datetime.now().strftime("%Y%m%d")
# date = "20200228"
ndate = datetime.datetime.now().strftime("%Y-%m-%d")
# ndate = "2020-02-28"
if id.s... | 5,358,936 |
def generate_inputs_pw(fixture_code, generate_structure, generate_kpoints_mesh, generate_upf_data):
"""Generate default inputs for a `PwCalculation."""
def _generate_inputs_pw():
"""Generate default inputs for a `PwCalculation."""
from aiida.orm import Dict
from aiida_quantumespresso.ut... | 5,358,937 |
def test_private_access_through_caller_object(enable_accessify):
"""
Case: access to private member, which do not follow naming conv., through member's class object in another class.
Expect: inaccessible due to its protection level error message.
"""
tesla = Tesla()
expected_error_message = INA... | 5,358,938 |
def connected_components(edge_index, num_nodes=None):
"""Find the connected components of a given graph.
Args:
edge_index (LongTensor): Edge coordinate matrix.
num_nodes (int, optional): Number of nodes. Defaults to None.
Returns:
LongTensor: Vector assigning each node to i... | 5,358,939 |
def assembly2graph(path=DATA_PATH):
"""Convert assemblies (assembly.json) to graph format"""
"""Return a list of NetworkX graphs"""
graphs = []
input_files = get_input_files(path)
for input_file in tqdm(input_files, desc="Generating Graphs"):
ag = AssemblyGraph(input_file)
graph ... | 5,358,940 |
def test_check_metadata_italic_style():
""" METADATA.pb font.style "italic" matches font internals ? """
from fontbakery.constants import MacStyle
from fontbakery.profiles.googlefonts import (com_google_fonts_check_metadata_italic_style as check,
family_metadata,
... | 5,358,941 |
def _get_default_backing(backing):
"""
_get_default_backing(backing)
Returns the prefered backing store
- if user provides a valid Backing object, use it
- if there is a default_backing object instantiated, use it
- if the user provided a configuration dict, use it to create
a new de... | 5,358,942 |
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query ... | 5,358,943 |
def pie(args):
"""Plots populational pie charts for desired groups"""
# get basename of file for writing outputs
name = [os.path.splitext(os.path.basename(args.file))[0]]
# read file into anndata obj
if args.verbose:
print("Reading {}".format(args.file), end="")
a = sc.read(args.file)
... | 5,358,944 |
def get_ps(sdfits, scan, ifnum=0, intnum=None, plnum=0, fdnum=0, method='vector', avgf_min=256):
"""
Parameters
----------
sdfits :
scan : int
Scan number.
plnum : int
Polarization number.
method : {'vector', 'classic'}, optional
Method used to compute t... | 5,358,945 |
def choiceprompt(variable: Variable) -> Binding:
"""Prompt to choose from several values for the given name."""
if not variable.choices:
raise ValueError("variable with empty choices")
choices = {str(number): value for number, value in enumerate(variable.choices, 1)}
lines = [
f"Select... | 5,358,946 |
def test_edge_betweenness_centrality_k_full(
graph_file,
directed,
subset_size,
normalized,
weight,
subset_seed,
result_dtype,
use_k_full,
edgevals
):
"""Tests full edge betweenness centrality by using k = G.number_of_vertices()
instead of k=None, checks that k scales properl... | 5,358,947 |
def GetCLInfo(review_host, change_id, auth_cookie='', include_messages=False,
include_detailed_accounts=False):
"""Get the info of the specified CL by querying the Gerrit API.
Args:
review_host: Base URL to the API endpoint.
change_id: Identity of the CL to query.
auth_cookie: Auth cookie... | 5,358,948 |
def revoke_jti(jti):
"""Revoke the given jti"""
revoked_token = RevokedToken(jti=jti)
DB.session.add(revoked_token)
DB.session.commit() | 5,358,949 |
def rehash(file_path):
"""Return (hash, size) for a file with path file_path. The hash and size
are used by pip to verify the integrity of the contents of a wheel."""
with open(file_path, 'rb') as file:
contents = file.read()
hash = base64.urlsafe_b64encode(hashlib.sha256(contents).digest())... | 5,358,950 |
def set_token_auth():
"""Set authorisation header for JWT token using the Bearer schema."""
global AUTH
if not JWT_DISABLED:
api_jwt = get_token(AUTH_API_ENDP, URI_API_USER, URI_API_PASS)
AUTH = f'Bearer {api_jwt}' | 5,358,951 |
def _magpie_update_services_conflict(conflict_services, services_dict, request_cookies):
# type: (List[Str], ServicesSettings, AnyCookiesType) -> Dict[Str, int]
"""
Resolve conflicting services by name during registration by updating them only if pointing to different URL.
"""
magpie_url = get_magpi... | 5,358,952 |
def export_inference_model(
model: TinyImageNetModel, out_path: str, tmpdir: str
) -> None:
"""
export_inference_model uses TorchScript JIT to serialize the
TinyImageNetModel into a standalone file that can be used during inference.
TorchServe can also handle interpreted models with just the model.p... | 5,358,953 |
def configure_app(app, config):
"""read configuration"""
app.config.from_object(DefaultConfig())
if config is not None:
app.config.from_object(config)
app.config.from_envvar('APP_CONFIG', silent=True) | 5,358,954 |
def rtc_runner(rtc):
"""Resolved tool contract runner."""
return run_main(polish_chunks_pickle_file=rtc.task.input_files[0],
sentinel_file=rtc.task.input_files[1],
subreads_file=rtc.task.input_files[2],
output_json_file=rtc.task.output_files[0],
... | 5,358,955 |
def dict_to_json_str(o: Any) -> str:
"""
Converts a python object into json.
"""
json_str = json.dumps(o, cls=EnhancedJSONEncoder, sort_keys=True)
return json_str | 5,358,956 |
def paramid_to_paramname(paramid):
"""Turn a parameter id number into a parameter name"""
try:
return param_info[paramid]['n']
except KeyError:
return "UNKNOWN_%s" % str(hex(paramid)) | 5,358,957 |
def write_left_aligned_text(text: str,
parent_surface,
font_size: int=FONT_SIZE,
font_color: Color=FONT_COLOR) -> None:
"""Draw the given text at the left border of the parent surface."""
font = pygame.font.Font(pygame.font.mat... | 5,358,958 |
def max_dist_comp(G, cc0, cc1):
""" Maximum distance between components
Parameters
----------
G : nx.graph
Graph
cc0 : list
Component 0
cc1 : list
Compoennt 1
Returns
-------
threshold : float
Maximum distance
""" ... | 5,358,959 |
def convert_examples_to_features(
examples,
label_list,
max_seq_length,
tokenizer,
cls_token_at_end=False,
cls_token="[CLS]",
cls_token_segment_id=1,
sep_token="[SEP]",
sep_token_extra=False,
pad_on_left=False,
pad_token=0,
pad_token_segment_id=0,
pad_token_label_id=-... | 5,358,960 |
def upload(images, host):
"""Upload an image file or rehost an image URL."""
uploaded_urls = []
for img_url, del_url in upload_images(images, host):
uploaded_urls.append(img_url)
click.echo(f'{img_url}', nl=False)
click.echo(f' | Delete: {del_url}' if del_url else '')
if conf.cop... | 5,358,961 |
def sync_instrument(target_session, instruments):
"""
Inserts / updates all supplied instruments into the target database.
Parameters
----------
target_session : sqlalchemy session
The sqlalchemy session into which we will insert instruments.
instrument : list
The list of instr... | 5,358,962 |
def exp(var):
"""
Returns variable representing exp applied to the input variable var
"""
result = Var(np.exp(var.val))
result.parents[var] = var.children[result] = np.exp(var.val)
return result | 5,358,963 |
def format_now(frmt):
""" Formats the current time according to the frmt string """
print(datetime.datetime.now().strftime(frmt))
return | 5,358,964 |
def invalidate_cache(
key: str = None,
keys: List = [],
obj: Any = None,
obj_attr: str = None,
namespace: str = None,
):
"""Invalidates a specific cache key"""
if not namespace:
namespace = HTTPCache.namespace
if key:
keys = [key]
def wrapper(func: Callable):
... | 5,358,965 |
def read_dataset(filename):
"""Reads in the TD events contained in the N-MNIST/N-CALTECH101 dataset file specified by 'filename'"""
# NMIST: 34×34 pixels big
f = open(filename, 'rb')
raw_data = np.fromfile(f, dtype=np.uint8)
f.close()
raw_data = np.uint32(raw_data)
all_y = raw_data[1::5]
... | 5,358,966 |
def prge_annotation():
"""Returns an annotation with protein/gene entities (PRGE) identified.
"""
annotation = {"ents": [{"text": "p53", "label": "PRGE", "start": 0, "end": 0},
{"text": "MK2", "label": "PRGE", "start": 0, "end": 0}],
"text": "p53 and MK2",
... | 5,358,967 |
def inner_points_mask(points):
"""Mask array into `points` where ``points[msk]`` are all "inner" points,
i.e. `points` with one level of edge points removed. For 1D, this is simply
points[1:-1,:] (assuming ordered points). For ND, we calculate and remove
the convex hull.
Parameters
----------
... | 5,358,968 |
def array2list(X_train: Union[np.ndarray, torch.Tensor],
y_train: Union[np.ndarray, torch.Tensor],
X_test: Union[np.ndarray, torch.Tensor],
y_test: Union[np.ndarray, torch.Tensor],
batch_size: int, memory_alloc: float = 4
) -> Union[Tuple[List[n... | 5,358,969 |
def livecoding_redirect_view(request):
"""
livecoding oath2 fetch access token after permission dialog
"""
code = request.GET.get('code')
if code is None:
return HttpResponse("code param is empty/not found")
try:
url = "https://www.livecoding.tv/o/token/"
data = dict(cod... | 5,358,970 |
def test_nonKeywordAfterKeywordSyntaxError():
"""Source which has a non-keyword argument after a keyword argument
should include the line number of the syntax error
However these exceptions do not include an offset
"""
source = """\
foo(bar=baz, bax)
"""
sourcePath = make_temp_file(source)
... | 5,358,971 |
def test_list_time_min_length_1_nistxml_sv_iv_list_time_min_length_2_5(mode, save_output, output_format):
"""
Type list/time is restricted by facet minLength with value 6.
"""
assert_bindings(
schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-minLength-2.xsd",
instanc... | 5,358,972 |
def sort_dict(value):
"""Sort a dictionary."""
return OrderedDict((key, value[key]) for key in sorted(value)) | 5,358,973 |
def withdraw_worker():
"""
Checks every address in database for withdrawals and executes them.
Afterward burns assets
"""
while True:
try:
data = json.dumps({"password":publicserverpassword})
r = post(url + "get/withdrawdata", data).json()
address_data = r... | 5,358,974 |
def hyb_stor_capacity_rule(mod, prj, prd):
"""
Power capacity of a hybrid project's storage component.
"""
return 0 | 5,358,975 |
def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None, HttpMethod=None):
"""
Generate a presigned url given a client, its method, and arguments
:type ClientMethod: string
:param ClientMethod: The client method to presign for
:type Params: dict
:param Params: The paramet... | 5,358,976 |
def gilr_layer_cpu(X, hidden_size, nonlin=tf.nn.elu,
name='gilr'):
"""
g_t = sigmoid(Ux_t + b)
h_t = g_t h_{t-1} + (1-g_t) f(Vx_t + c)
"""
with vscope(name):
n_dims = X.get_shape()[-1].value
act = fc_layer(X, 2 * hidden_size, nonlin=tf.identity)
gate, impulse =... | 5,358,977 |
def append_freecad_path():
"""Append the FreeCAD path."""
global path_to_freecad
if os.path.exists(path_to_freecad):
if os.path.isfile(path_to_freecad):
path_to_freecad = os.path.dirname(path_to_freecad)
print("Configured FreeCAD path:", path_to_freecad)
if path_to_freeca... | 5,358,978 |
async def retry(f: Callable[..., Awaitable[A]], schedule: Schedule[Exception, Tuple[OpinionT, float]]):
"""
Run an awaitable computation,
retrying on failures according to a schedule.
"""
while True:
try:
result = await f()
except Exception as ex:
try:
... | 5,358,979 |
def save_layer_mask_debug(gia, out_file, bitmap_data, img_rect):
""" Similar to save_rect_mask(), but for an entire layer. Since layer-mask might be a rectangle smaller
than the full image, expand to full size. Also for debugging (in case the function names aren't a clue...)
"""
pic_width = gia['wi... | 5,358,980 |
def dual_solve_u(v, s, alpha, eps, verbose=False, n_iters=100, gtol=0):
"""
min_{u>=0} max_pi L(pi, u, v)
= E_xy [ u(x)alpha(x) + v(y)beta(y) + Softplus(1/eps)(s-u-v) ],
where u = min{u>=0 : E_y[pi(x,y)] <= alpha(x)}
find exact u s.t. E_y[pi(x,y)] == alpha(x)
"""
alpha = torch.as... | 5,358,981 |
def activation(formula=None, instrument=None,
flux=None, cdratio=0, fastratio=0,
mass=None, exposure=24, getdata=False):
"""Calculate sample activation using the FRM II activation web services.
``formula``:
the chemical formula, see below for possible formats
... | 5,358,982 |
def displayToolTips():
"""force display tool tips in maya as these are turned off by default"""
cmds.help(popupMode=True) | 5,358,983 |
def set_dashboard_conf(config):
"""
Write to configuration
@param config: Input configuration
"""
with open(DASHBOARD_CONF, "w", encoding='utf-8') as conf_object:
config.write(conf_object) | 5,358,984 |
def wrap_parfor_blocks(parfor, entry_label = None):
"""wrap parfor blocks for analysis/optimization like CFG"""
blocks = parfor.loop_body.copy() # shallow copy is enough
if entry_label == None:
entry_label = min(blocks.keys())
assert entry_label > 0 # we are using 0 for init block here
# ... | 5,358,985 |
def crawl_lyrics(art_id):
"""抓取一整个歌手的所有歌词"""
html = get_html(start_url.format(art_id)) # 先抓该歌手的专辑列表
soup = BeautifulSoup(html, 'lxml')
artist = soup.find('h2', id='artist-name').text.strip().replace(' ', '_')
artist_dir = 'data/' + artist
if not os.path.exists(artist_dir): # 歌手目录
os.m... | 5,358,986 |
def frequency_of_occurrence(words, specific_words=None):
"""
Returns a list of (instance, count) sorted in total order and then from most to least common
Along with the count/frequency of each of those words as a tuple
If specific_words list is present then SUM of frequencies of specific_words is return... | 5,358,987 |
def cache_remove_all(
connection: 'Connection', cache: Union[str, int], binary=False,
query_id=None,
) -> 'APIResult':
"""
Removes all entries from cache, notifying listeners and cache writers.
:param connection: connection to Ignite server,
:param cache: name or ID of the cache,
:param bin... | 5,358,988 |
def transform_bundle(bundle_uuid, bundle_version, bundle_path, bundle_manifest_path, extractor=None):
"""
This function is used with the ETL interface in dcplib.etl.DSSExtractor.extract.
Given a bundle ID and directory containing its medatata JSON files, it produces an intermediate representation
of the... | 5,358,989 |
def visualize(o, r, p):
"""visualize the camera trajction by picture
Args:
o ([array]): [f,2]
r ([array]): [f]
p ([array]): [f,2]
"""
import matplotlib.pyplot as plt
i = 5
o = o[::i]
r = r[::i]
plt.plot(p[:,0],p[:,1])
plt.plot(o[:,0],o[:,1])
plt.show(... | 5,358,990 |
def choices_function() -> List[str]:
"""Choices functions are useful when the choice list is dynamically generated (e.g. from data in a database)"""
return ['a', 'dynamic', 'list', 'goes', 'here'] | 5,358,991 |
def validate_resource_identifier(rid):
"""Check that the input is a valid resource identifier."""
raise ValidationError | 5,358,992 |
def GetInfraPythonPath(hermetic=True, master_dir=None):
"""Returns (PythonPath): The full working Chrome Infra utility path.
This path is consistent for master, slave, and tool usage. It includes (in
this order):
- Any environment PYTHONPATH overrides.
- If 'master_dir' is supplied, the master's python p... | 5,358,993 |
def dl(outdir: Path = Path("data"), version: str = "v1.0"):
"""Checks that the segments in the given batch are valid."""
metadata_dir = f"https://dl.fbaipublicfiles.com/laser/CCMatrix/{version}"
file_list = [l.strip() for l in open_remote_file(metadata_dir + "/list.txt")]
outdir.mkdir(exist_ok=True)
... | 5,358,994 |
def nodeid():
"""nodeid() -> UUID
Generate a new node id
>>> nodeid()
UUID('...')
:returns: node id
:rtype: :class:`uuid.UUID`
"""
return uuid.uuid4() | 5,358,995 |
def stackedensemble_validation_frame_test():
"""This test checks the following:
1) That passing in a validation_frame to h2o.stackedEnsemble does something (validation metrics exist).
2) It should hopefully produce a better model (in the metalearning step).
"""
# Import training set
df = h2o.im... | 5,358,996 |
def test_config_groups(api):
""" Verify the ``config_groups`` method call """
PROJECT_ID = 15
api._session.request.return_value = [CG1, CG2, CG3]
cg_list = list(api.config_groups(PROJECT_ID))
exp_call = mock.call(method=GET, path=AP['get_configs'].format(project_id=PROJECT_ID))
assert all(map(... | 5,358,997 |
def drop_redundant_cols(movies_df):
"""
Drop the following redundant columns:
1. `release_data_wiki` - after dropping the outlier
2. `revenue` - after using it to fill `box_office` missing values
3. `budget_kaggle` - after using it to fill `budget_wiki` missing values
4. `duration` - after usin... | 5,358,998 |
def print_default_settings():
"""
Print ``default_settings.py``.
"""
path = join(dirname(default_settings.__file__), 'default_settings.py')
print(open(path).read()) | 5,358,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.