content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def apply_initial_boundary_conditions(mesh: Mesh, boundary_name, vector_v):
"""
Performs the evaluation of boundary conditions and applies initial values to the vector.
:param mesh: The Mesh object that defines the geometry of the problem and the boundary conditions associated.
:param vector_v: The vect... | 56,700 |
def test_generate_config_template():
"""Verify the generate_config_template() function works correctly."""
filename = 'build-magic_template.yaml'
template = pathlib.Path(__file__).parent.parent / 'build_magic' / 'static' / filename
ref = template.read_text()
config = generate_config_template()
... | 56,701 |
def h(P, T, region = 0):
"""Specific enthalpy [kJ / kg]"""
if region is 0:
region = idRegion(P, T)
if region is 1:
return region1.h(P, T)
elif region is 2:
return region2.h(P, T)
else:
return 0.000 | 56,702 |
def instagram_posts(username, limit=12):
"""
Put a list of Instagram posts into the template context.
"""
CACHE_KEY = "instagram_%s" % username
posts = cache.get(CACHE_KEY)
# Serve from cache if available
if posts is not None:
return posts[:limit]
# Else, fetch and store in cac... | 56,703 |
def unary_math_function_unittest(func, func_expected=None, label_expected=None,
make_data=None):
"""Decorator for testing unary mathematical Chainer functions.
This decorator makes test classes test unary mathematical Chainer
functions. Tested are forward and backward compu... | 56,704 |
def establish_connection() -> storage.client.Client:
"""
Establish a connection to Google Cloud Storage storing agriculture data.
:return: client connection
"""
storage_client = storage.Client.from_service_account_json(find('Agriculture.json', '/home'))
return storage_client | 56,705 |
def is_authenticated_decorator(function):
"""Декоратор, чтобы не пускать неавторизованных пользователей"""
def wrapper(request, *args, **kwargs):
"""Если пользователь авторизован -> вернем функцию, иначе переведем на страницу логина"""
if is_authenticated_user(request):
return functi... | 56,706 |
def preprocess_text(sentence):
"""
前處理,處理奇怪的輸入。例如:'i',需要轉成大寫。
"""
cleaned = []
words = sentence.split(' ')
for w in words:
if w == 'i':
w = 'I'
if w == "i'm":
w = "I'm"
cleaned.append(w)
return ' '.join(cleaned) | 56,707 |
def POTFInfo (inOTF, err):
""" Get file info for extant OTF data object
Fills in information on object, useful for scratch files
inOTF = Python OTF object
err = Python Obit Error/message stack
"""
################################################################
# Checks
if not PIsA... | 56,708 |
def start_generator(name):
"""
Start a generator, given its partial name.
* Closes stdin
* Redirects stdout to stderr (so that it doesn't conflict with i3bar)
Returns a Popen object of the started process.
"""
exename = find_generator(name)
proc = subprocess.Popen(
[exename],
... | 56,709 |
def plot_S(args):
""" evaluates the experiment for a given method """
# setup directory.
sim_dir = os.path.abspath(args.sim_dir)
mas_obj = '%s/mas.cpickle' % sim_dir
res_obj = '%s/res.cpickle' % sim_dir
c_lbls = np.load(args.c_lbls)
b_lbls = np.load(args.b_lbls)
# extract method in... | 56,710 |
def compact(number):
"""Convert the number to the minimal representation. This strips
surrounding whitespace and separation dash."""
return clean(number, '.,- ').upper().strip() | 56,711 |
def predict_bert_multitask(
inputs,
problem='weibo_ner',
model_dir='',
params=None,
problem_type_dict={},
processing_fn_dict={},
model=None):
"""Evaluate Multi-task Bert model
Available eval_scheme:
ner, cws, acc
Keyword Arguments:
pr... | 56,712 |
def get_season_team_pbp_folder(season):
"""
Returns the folder containing team pbp logs for given season
:param season: int, current season
:return: str, /scrape/data/teams/pbp/[season]/
"""
return os.path.join(get_team_data_folder(), 'pbp', str(season)) | 56,713 |
def get_resource_files(dist, exList=None, incList=None, dirname=''):
"""A generator that retrieves resource file pathnames from
within a distribution.
"""
exlist = exList or []
inclist = incList or ['*']
for res in dist.resource_listdir(dirname):
if dirname != '':
... | 56,714 |
def _xml_print(xml):
""" Pretty print xml """
print etree.tostring(xml, pretty_print=True) | 56,715 |
def draw_candidate_matchings(members, min_size, n_candidates, initial_seed=0):
"""Create multiple random groupings in list-format.
Args:
members (pd.Series): Integer series with indeces over which we group.
min_size (int): Minimum group size.
n_candidates (int): Number of candidate grou... | 56,716 |
def get_module_name():
"""
モジュール名取得
Return:
モジュール名
"""
return __name__ | 56,717 |
def _override_config(args, cfg):
""" call _cfg_import_export in override mode, update cfg from:
(1) contents of config_json (taken from (a) loadpath if not auto, or (2) savepath)
(2) from command line args
"""
config_json = vars(args).get('config_json', '')
_cfg_import_export(args, cfg, ... | 56,718 |
def torch_ravel_multi_index(multi_index, dims=None, device=None, strides_=None):
"""
Implementation of `numpy.ravel_multi_index` for torch Tensors
Args:
multi_index (List[Tensor] | Tensor) : either a list of indices for
each dimension, or a tensor containing the same information as
... | 56,719 |
def get_base_folder(image_file):
"""The base folder"""
return '/'.join(image_file.split('/')[:-6]) | 56,720 |
def parse(fname):
"""
XMLファイルから内容をパースしてフィールドと値を格納した辞書を返す
"""
tree = ET.parse(fname)
root = tree.getroot()
parsed = []
for e in root.getiterator():
cur_dict = e.attrib.copy()
cur_dict['elem'] = e.tag
parsed.append(cur_dict)
# for child in root:
# ... | 56,721 |
def download(url, dst, verbosity=True):
"""
@param: url to download file
@param: dst place to put the file
"""
file_size = int(requests.head(url).headers["Content-Length"])
if os.path.exists(dst):
first_byte = os.path.getsize(dst)
else:
first_byte = 0
if first_byte >= fil... | 56,722 |
def test_consistent_merge():
""" Test that merge() calls do not modify the argument sketch.
"""
s1 = GKArray(test_eps)
s2 = GKArray(test_eps)
d = Normal(100)
for v in d.data:
s1.add(v)
s1.merge(s2)
# s2 is still empty
np.testing.assert_equal(s2.num_values, 0)
d = Normal(... | 56,723 |
def optimization_hyperopt_loo(imgs, grades, args, loss, groups=None):
"""Optimizes hyperparameters for MRELBP and local standardization using tree of Parzen estimators
and leave-one-out split for training multiple optimizations.
Parameters
----------
imgs : list
List of input images.
gr... | 56,724 |
def make_head_model(anat_img, out_dir):
""" create head models including skin and skull.
Note that rawavg.mgz should be specified ( not orig.mgz) to create head models for the purpose of visualizaiton"""
if not os.path.exists(out_dir):
os.makedirs(out_dir)
if not os.path... | 56,725 |
def latex_plt(matplotlib):
""" This function updates the matplotlib library to use Latex and changes some default plot parameters
:param matplotlib: Matplotlib instance
:return: Updated matplotlib instance
"""
# Use Latex for matplotlib
pgf_with_latex = {
"font.family": "serif",
... | 56,726 |
def _str_n_grade(df: pd.DataFrame, grade: str) -> str:
"""Print the number of cards with grade `grade`."""
n_cards = len(df)
n_grade = len(df[(df["grade"]) == grade])
perc = round((n_grade / n_cards) * 100, 2)
return (
f"– The number of cards with grade {grade} is {n_grade} "
f"of {... | 56,727 |
def add_nodes_elements_from_bmesh(structure, bmesh, line_type=None, mesh_type=None, thermal=False):
"""
Adds the Blender mesh's nodes, edges and faces to the Structure object.
Parameters
----------
structure : obj
Structure object to update.
bmesh : obj
Blender mesh object.
... | 56,728 |
def _makefilename(lidvid: str, ts: datetime, kind: str, ext: str) -> str:
"""Make a filename.
Make a PDS filename for the given ``lidvid`` by dropping its URN prefix, splitting it into
LID and VID, adding the date part of the ``ts`` timestamp, slapping on the ``kind`` of file it
is, and the given ``ext... | 56,729 |
def extract(client, output_path, index):
"""
Scroll an index with a match-all query, dumping document source to ``outdir/documents.json``.
:param client: Elasticsearch client used to extract data
:param output_path: Destination directory for corpus dump
:param index: Name of index to dump
:retu... | 56,730 |
def write_to_template(parvals,tpl_file,in_file):
""" write parameter values to model input files using template files
Parameters
----------
parvals : dict or pandas.Series
a way to look up parameter values using parameter names
tpl_file : str
template file
in_file : str
... | 56,731 |
def mock_transformer(mocked_transform) -> None:
"""Sets up the transformer mock."""
def transform(_: Batch) -> None:
pass
mocked_transform.side_effect = transform | 56,732 |
def gaia_log_in(gaia_user = None, gaia_paswd = None):
"""
This routine log in to the Gaia archive.
"""
from astroquery.gaia import Gaia
import getpass
while True:
try:
Gaia.login(user=gaia_user, password=gaia_paswd)
print("Welcome to the Gaia server!")
break
ex... | 56,733 |
def parse_class(name, doc):
"""
Extract a class declaration from a docstring.
"""
match = re.search(r"class ({}(\([^)]*\))?):".format(name), doc)
csig = match.group(1)
start = match.start()
end = doc.find("```", start)
doc = doc[start:end]
variables = []
start = doc.find("Attri... | 56,734 |
def is_acceptable_smiles(smile: str, allowed_chars=SMILES_ENCODING_['indices_token'].values(),
min_len=SMILES_ENCODING_['min_smiles_len'], max_len=SMILES_ENCODING_['max_smiles_len']):
""" Checks which smiles
Args:
smile: (str) smiles string
allowed_chars: (lst) list of ... | 56,735 |
def parse_planes(
planes_to_parse: List[Union[int, str]], n_planes: int, default: Union[int, List[int]] = 0,
name: str = 'planes'
) -> List[int]:
"""
Get a set of planes from a list of plane indexes and ranges.
Parameters
----------
planes_to_parse
List of plane indexes and ranges t... | 56,736 |
def get_api(api_id):
"""Get a single api.
Args:
api_id (int): The id of the api.
Returns:
dict: The api.
"""
api = API.query.get(api_id)
if not api:
abort(404)
return api.to_dict() | 56,737 |
def calc_distance(x1, y1, x2, y2):
"""
Calculate the distance between 2 point given the coordinates
:param x1: Point 1 X coordinate
:param y1: Point 1 Y coordinate
:param x2: Point 2 X coordinate
:param y2: Point 2 Y coordinate
:return: Double. Distance between point 1 and point 2
"""
... | 56,738 |
def list_perceel_adapter(obj, request):
"""
Adapter for rendering a list of
:class: `crabpy.gateway.capakey.Perceel` to json.
"""
return {
'id': obj.id,
'sectie': obj.sectie,
'capakey': obj.capakey,
'percid': obj.percid
} | 56,739 |
def ar(
array: np.ndarray,
name: Optional[str] = None,
lim: Union[int, str, None] = None,
lw: int = 200,
minimal: bool = False,
) -> None:
"""Debug `ar`ray.
Print helper for `numpy.ndarray`, will print like so:
```
my_array [<class 'numpy.ndarray'>] [dtype=float32]:
SHAPE: (3, 3)... | 56,740 |
def shell_http(url, shell_type):
"""
Connect to an HTTP shell
:param url: The URL to connect to
:param shell_type: The type of shell to connect to
"""
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection": "keep-alive",
... | 56,741 |
def parse_fqdn(session, fqdn):
""" Break an fqdn (string) and get some useful information from it.
Returns a tuple of the shortname (string), and DnsDomain object
"""
if not fqdn:
raise ArgumentError("No fully qualified name specified.")
(short, _, dns_domain) = fqdn.partition(".")
... | 56,742 |
def uniform_pdf(x):
""" Uniform Distribution(균등 분포) 확률 밀도 함수 """
return 1 if 0 <= x < 1 else 0 | 56,743 |
def read_package_data_files():
"""Read package data files and return the text."""
with open(package_data_file(DATA_HTML_BASE),
'rt', encoding='utf-8') as f:
base_html = f.read()
with open(package_data_file(DATA_HTML_LICENSE),
'rt', encoding='utf-8') as f:
lic... | 56,744 |
def unit(value, unit, parenthesis=True):
"""Formats the numeric value of a unit into a string in a consistent way."""
formatted = f"{value:,g} {unit}"
if parenthesis:
formatted = f"({formatted})"
return formatted | 56,745 |
def getDataFromFile(params, firstLine, lastLine,
prefix="", ftype="catalog", getXY=True, CV=False):
"""
Returns an iterator to parse an input catalog file.
Returns the fluxes, redshifts, etc, and also GP inputs if getXY=True.
"""
if ftype == "gpparams":
with open(params... | 56,746 |
def apply_along_axis(
func1d: Callable[[PolyLike], PolyLike],
axis: int,
arr: PolyLike,
*args: Any,
**kwargs: Any,
) -> ndpoly:
"""
Apply a function to 1-D slices along the given axis.
Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a` is
a 1-D slice of `arr` a... | 56,747 |
def get_matrix(vocab, token_pairs):
"""Get normalized matrix"""
# Build matrix
vocab_size = len(vocab)
g = np.zeros((vocab_size, vocab_size), dtype='float')
for word1, word2 in token_pairs:
i, j = vocab[word1], vocab[word2]
g[i][j] = 1
# Get Symmetric matrix
g = symmetrize(g... | 56,748 |
def test_clevr_extract_bbox_and_label(
_open_mock, _load_mock, sample_scene_and_annotation
):
"""Verify if bbox and label is extracted from scene properly."""
scene, exp_ann = sample_scene_and_annotation
ds = CLEVR(data_dir=".", subset="train")
ann = ds.extract_bbox_and_label(scene)
assert ann["... | 56,749 |
def test_import():
"""Test import."""
import cfgenvy # pylint: disable=import-outside-toplevel
assert cfgenvy.Env is not None
assert cfgenvy.Parser is not None | 56,750 |
def decode_landm_in_numpy(pre, priors, variances):
"""Decode landm from predictions using priors to undo
the encoding we did for offset regression at train time.
Args:
pre (tensor): landm predictions for loc layers,
Shape: [num_priors,10]
priors (tensor): Prior boxes in center-of... | 56,751 |
def bulk_add_songs_to_playlist(playlist_id, songs, *args, **kwargs):
"""
"""
playlist = Playlist.objects.get(id=playlist_id)
songs_added = 0
failures = 0
failure_details = []
for song in songs:
try:
platform = get_platform(song.get('platform', 'revibe'))
so... | 56,752 |
def execute_query(spec, connection_string=None):
"""
Setup a connection to a mongodb server and execute the given query.
:param spec: Mongo query spec.
:returns: Mongo curser.
"""
if connection_string is None:
connection_string = "mongo://localhost:27017/test"
if connection_string:
... | 56,753 |
def untlpydict2xml(untl_filename, untl_dict):
"""Return a UNTL file.
Takes a UNTL filename and a UNTL Python dictionary.
"""
return pydict2xml(untl_filename, untl_dict) | 56,754 |
def cityInit(ifInput, cityInput, *txtPath):
"""
随机产生城市矩阵
:param ifInput: 是否输入城市数量 bool
:param cityInput: 如果第一个参数为True, 填任意值, 否则填城市数量 int
:param txtPath: (可选)如果第一个参数为False, 也可以选择文件输入, 文件有三列, 第一列是序号, 第二列是横坐标, 第三列是纵坐标 string
:return: 城市数量 int, 城市坐标 list, 城市之间的距离矩阵 ndarray
city.txt示例:
1 9860 14152
... | 56,755 |
def deduce_left_margin(properties_of_keywords_in_resume, structural_properties_of_resume):
"""Takes the smallest left margin that has more than 2 occurrences in all_caps_properties and
entire_match_properties. If both left_margin matched it returns the left_margin immediately. If not,
it returns the left_ma... | 56,756 |
def __datetime_representer(dumper, data):
"""
Ensures that datetime objects are represented correctly."""
value = data.isoformat("T")
return dumper.represent_scalar("tag:yaml.org,2002:timestamp", value) | 56,757 |
def test_fails_without_template_or_string(app, context):
"""A template or string must be provided to render"""
with app.test_request_context():
with pytest.raises(RuntimeError):
render_response(context=context, method="text") | 56,758 |
def normalize_val_list(val_list):
"""Returns a list of numeric values by the size of their maximum
value."""
max_val = float(max(val_list))
return [ val/max_val if max_val != 0 else 0 for val in val_list ] | 56,759 |
def policy_threshold(threshold, belief, loc):
"""
chooses whether to switch side based on whether the belief on the current site drops below the threshold
Parameters
----------
threshold (float): the threshold of belief on the current site,
when the belief is lower than the... | 56,760 |
def run(torrent, output_location):
"""Console script for pytorrent.cli.run."""
click.echo("Replace this message by putting your code into " "pytorrent.cli.run")
pt = PyTorrent(torrent)
pt.start()
pt.create_files(output_location)
return 0 | 56,761 |
def test_daq_delay_scan(RE, daq, hw, time_motor):
"""Check that daq_delay_scan's arguments all work."""
logger.debug('test_daq_delay_scan')
msgs = list(nbp.daq_delay_scan([hw.det], time_motor, [0, 1], 1,
duration=0.01, record=True))
configure_message = None
for ms... | 56,762 |
def create_standard_serializer_class(model_cls):
"""Creates serializer class for the Django model specified.
Created serializer will declare all model fields,
will have "url" #HyperlinkedIdentityField pointing at detail view for the entity
and will inherit #OptimizeUrlFieldsSerializer and #JsFriendlyFi... | 56,763 |
def filter_edges_by_edge_kind(g, edges_to_keep):
"""Keep only edges of specified kinds and then remove unconnected nodes.
UNTESTED
"""
edges_to_keep = set(edges_to_keep)
for node, neighbor, key in g.edges_iter(keys=True):
edge_set = {(node, neighbor, key), (neighbor, node, key)}
if n... | 56,764 |
def choose_representation(adata,
rep=None,
n_pcs=None):
"""Get representation of multivariate data.
Args:
adata (anndata.AnnData): Multidimensional morphological data.
rep (str): Key in .obsm.
n_pcs (int): Number of principal component... | 56,765 |
def sieve(iterable, indicator):
"""Split an iterable into two lists by a boolean indicator function. Unlike
`partition()` in iters.py, this does not clone the iterable twice. Instead,
it run the iterable once and return two lists.
Args:
iterable: iterable of finite items. This function will sca... | 56,766 |
def Flowers_dataloader(root, quat_data, img_size, normalize, batch_size, num_workers=2, eval=False):
"""102 Oxford Flowers dataloader with resized and normalized images."""
name = '102 Oxfrod Flowers'
print('Dataset:', name)
if not eval:
dataset = datasets.ImageFolder(root=root, transform=prepro... | 56,767 |
def main():
"""Plot accuracy and loss with mxnet
"""
# construct the argument parse and parse the arguments
args = argparse.ArgumentParser()
args.add_argument("-n", "--network", required=True,
help="name of network")
args.add_argument("-d", "--dataset", required=True,
... | 56,768 |
def test_del_request_others_researcher(client):
"""Unit admin tries to delete unit user from different unit"""
email_to_delete = "unituser1@mailtrap.io"
# with pytest.raises(ddserr.UserDeletionError):
response = client.delete(
tests.DDSEndpoint.USER_DELETE,
headers=tests.UserAuth(tests... | 56,769 |
def documents(title):
"""Document page."""
logging.debug("Calling document page endpoint...")
logging.info("Get textfiles...")
text = get_textfile(title)
logging.info("Get document-topics distributions...")
document_topic = pd.read_json(get_document_topic_distributions(), orient="index")
log... | 56,770 |
def write_crunch(entries, ostream, prompt_fun=None, **kwargs):
"""
Write a Crunch-format statement
:type entries: list of StatementEntry
"""
entries = _fixup_balance(entries, prompt_fun)
w = writer(ostream)
w.writerow(_HEADER_FIELDS)
for e in entries:
w.writerow(tuple(e)) | 56,771 |
async def add_subscription(e):
""" Add a subscription pattern. Whenever this pattern
is matched in the current chat you will be notified """
params = e.pattern_match.group(1)
if not is_mongo_alive() or not is_redis_alive():
await e.edit("`Database connections failing!`", delete_in=3)
re... | 56,772 |
def setup_custom_logger(path, level):
"""Custom logger
Args:
path (str): the path to write logs to (note, in addition to stdout/stderr)
level (str): the log level
"""
level_config = {
'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING
}... | 56,773 |
def test_set_profile_data_missing_last_name_field(api_client, user):
"""Test profile data cannot be set if last name field is missing."""
api_client.login(username=user.username, password="test_password")
response = api_client.post("/v1/users/set_profile/", {"first_name": "Heather", },)
assert response.... | 56,774 |
def property_to_snake_case(property_type):
"""Converts a property type to a snake case name.
Parameters
----------
property_type: type of PhysicalProperty of str
The property type to convert.
Returns
-------
str
The property type as a snake case string.
"""
if not ... | 56,775 |
def get_args():
"""
Supports the command-line arguments listed below.
function to parse through args for connecting to ESXi host or
vCenter server function taken from getallvms.py script
from pyvmomi github repo
"""
parser = argparse.ArgumentParser(
description='Process args for retr... | 56,776 |
def test_with_statement(first_node_with_tokens):
"""
A single node is returned - the `with` statement.
"""
result = filter_arrange_nodes(first_node_with_tokens.body, 6)
assert len(result) == 1
assert 'with open(' in result[0].first_token.line | 56,777 |
def standardize(data: np.ndarray) -> list:
"""
Standardize input values
(x - x.mean) / x.standard_deviation
Args:
data (np.ndarray): Input data
Returns:
[type]: Standardized input data
"""
return np.array((data - np.mean(data)) / np.std(data), dtype=np.float32) | 56,778 |
def test(model: tf.keras.Model, train_data: List[Tuple[int, int, int]], test_data: List[Tuple[int, int, int]],
topk_data: TopkData, loss_object=None, batch=512) -> None:
"""
通用测试流程。
:param model: 模型
:param train_data: 训练集
:param test_data: 测试集
:param topk_data: 用于topk评估数据
... | 56,779 |
def add_component(componentName, entityId, entity_type=entity.EntityType().Game):
"""
Given a component name, finds component TypeId, adds to given entity, and verifies successful add/active state.
:param componentName: String of component name to add.
:param entityId: Entity to add component to.
:r... | 56,780 |
def pad_sequence(sequence, max_length, embeddings_dict, pad_token = 'EOS'):
""" Adds EOS tokens until sequence length is max_length. """
n = len(sequence)
padded = sequence.copy()
if n < max_length:
if type(padded) is np.ndarray:
padded = np.append(padded, [embeddings_dict[pad_toke... | 56,781 |
def cli(feature_list, chrom_sizes_file):
"""
Validate feature_list file.
"""
FeatureListCheck(feature_list, chrom_sizes_file) | 56,782 |
def _parse_frequencies(result: Tuple, frequency_ids: List[int], frequencies: List[float], amplitudes: List[float]) -> df:
"""
Parses the list of frequencies from the result of FCombLibrary. The resulting frequencies are simply a list of
combinations, where the first combination in this list is always the be... | 56,783 |
def read_binary(filepath):
"""return bytes read from filepath"""
with open(filepath, "rb") as file:
return file.read() | 56,784 |
def swift_syntax_deps():
"""Fetches dependencies of SwiftSyntax"""
if not native.existing_rule("build_bazel_rules_swift"):
fail("error: this depends on rules_swift but that wasn't setup")
http_archive(
name = "com_github_keith_lib_internalswiftsyntaxparser",
sha256 = "65566d949ecefa... | 56,785 |
def sra_valid_accession(accession):
""" Test whether a string is an SRA accession """
if accession.startswith('SRR') and len(accession) == 10:
return True
return False | 56,786 |
def get_model_names():
"""Helper function that abstracts logic for getting names of all models
associated with the function"""
if 'models' in session:
models = pickle.loads(session.get('models'))
else:
models = {}
return list(models.keys()) | 56,787 |
def promo(student: str = None):
"""Get student's promotions."""
wrapper = config.setup_api()
promo_data = wrapper.get_user_promotion(student)
header = ('ID', 'promotion', 'name', 'start', 'end', 'spe')
final_list = []
for i, _ in enumerate(promo_data):
promo_list = []
promo_list.... | 56,788 |
def alaska_transform(xy):
"""Transform Alaska's geographical placement so fits on US map"""
x, y = xy
return (0.3*x + 1000000, 0.3*y-1100000) | 56,789 |
def train(model, iterator, optimizer, criterion, epoch, augmentation_class=None,
augmentation_methods=None, lr_decay=False, include_length=False):
"""
train method is written for train model
:param model: your creation model
:param iterator: train iterator
:param optimizer: your optimizer
... | 56,790 |
async def mb(bucket: str) -> bool:
""" Make bucket """
async with _create_client() as client:
try:
await client.create_bucket(Bucket=bucket)
logger.info(f'Make bucket "{bucket}".')
except ClientError:
return False
return True | 56,791 |
def get_user_simple_list(access_token, dept_id):
"""
获取部门用户信息
:return:
{
"errcode": 0, # 返回码
"errmsg": "ok", # 对返回码的文本描述内容
"hasMore": false, # 在分页查询时返回,代表是否还有下一页更多数据
"userlist": [
{
"userid": "zhangsan", # 员工id
"name": "张三" # 成员名称
}
... | 56,792 |
def err_resp(code: int, msg: str, err_subcode=None):
"""
generate error response
:param code: error code
:param msg: error msg
:param err_subcode: specific error details
:return: JsonResponse
"""
return json({
"ok": False,
"code": code,
"msg": msg,
"error_... | 56,793 |
def test_logs_startup_cfg_created_snapshot_enabled():
"""
Validates that access logs are getting created correctly.
"""
logs_created(no_config_snapshots=False)
global NUM_STARTUP_CFG
assert len(glob.glob('logs/config/*startup.cfg')) == NUM_STARTUP_CFG + 1
NUM_STARTUP_CFG += 1 | 56,794 |
def req(reqrep, address, rep):
"""The REQ socket."""
req, rep = reqrep
req.connect(address)
return req | 56,795 |
def networkIPv4_deploy(request, network_id):
"""Deploy network L3 configuration in the environment routers for network ipv4
Receives optional parameter equipments to specify what equipment should
receive network configuration
"""
log.debug("networkIPv4_deploy")
networkipv4 = NetworkIPv4.get_by_... | 56,796 |
def install_eventlabel(eventlabel_dict: dict):
"""
Executes the install_script within an EventLabel while recording a changeset
:param eventlabel_dict: the EventLabel.__dict__ of the EventLabel to be installed
"""
import os
import subprocess
from time import time
from platform import li... | 56,797 |
def _recover_forcei_rod(xb, dof_map, elem, prop):
"""get the static rod force"""
nid1, nid2 = elem.nodes
# axial
i11 = dof_map[(nid1, 1)]
i12 = dof_map[(nid1, 2)]
i13 = dof_map[(nid1, 3)]
i21 = dof_map[(nid2, 1)]
i22 = dof_map[(nid2, 2)]
i23 = dof_map[(nid2, 3)]
# torsion
... | 56,798 |
def assign_segid_to_crashes(max_dist, usrap_segment_layer, input_crash_fc, out_gdb):
"""
This function first creates the Field mapping and then performs a
spatial join between Crash Feature Class and Segment Feature Class
"""
try:
add_formatted_message("Assigning {0} to crashes... ", S... | 56,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.