content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional from typing import Union def get_numeric_roles_stat_gpu(train: GpuDataset, subsample: Optional[Union[float, int]] = 100000, random_state: int = 42, manual_roles: Optional[RolesDict] = None, n_jobs: int = 1) -> pd.DataFrame: """Calculate s...
f4bc92b523eabe1a270faf9dd69e31202b6ed59a
56,400
from typing import Iterable from typing import Optional def draw_mayavi_line_segment( fig: Figure, points: Iterable[np.ndarray], color: Color = (1, 0, 0), line_width: Optional[Number] = 1, tube_radius: Optional[Number] = None, ) -> Figure: """Draw a single line segment with Mayavi. Args: ...
7fe95bfa5a6fbed88ec66239f2c71bf757497fc4
56,401
import requests def get_quotes(): """ Function that gets the json response to our url request """ quotes = requests.get('http://quotes.stormconsultancy.co.uk/random.json').json() return quotes
f2a1c733b163518f5652e4e0862ade0f813bfb39
56,402
from pathlib import Path import io def hello_kitty_container(tmp_path: Path, hello_kitty: Path) -> Path: """The `hello_kitty` fixture further embedded in a zip container.""" hello_kitty_container = tmp_path / "container" container_zip = io.BytesIO() with ZipFile(container_zip, "w") as zf: zf.w...
7c2e8cf60024fcd0bf19a51f285ffa86e388b09b
56,403
def common_chain_res(model1, model2): """ Given a pair of Bio.PDB.Chain objects, returns the common residues and their respective CA atoms. Returns a tuple with two lists: The first one contains the list of atoms corresponding to the first chain. The second list contains the list of atoms of the second ...
8809e23d23237310ef530fb0c4d4509c93553a2a
56,404
def _filter_out(message: str) -> bool: """Return True when message should be ignored. Args: message (str): message to analyze Returns: bool: True when message should be ignored, False otherwise """ for authorized_function in ("input", "print", "pprint"): if f"Found wrong fu...
461c0f36aed22d80384202093bc1cfc40b88242c
56,405
def cdgmm(A, B, inplace=False): """Complex pointwise multiplication. Complex pointwise multiplication between (batched) numpy array A and numpy array B. Parameters ---------- A : numpy array A is a complex numpy array of size (B, C, M, N). B : numpy arra...
1cf1bfa4b8b832a9f9af6a88e48d03e98f817edd
56,406
import re def byteform_to_num(byte_format): """Converts a string expressing a size of a file in bytes into the corresponding number of bytes. Accepts commas and decimal points in nums. Allows 'b', 'mb', 'gb', and variants like 'bytes', but not 'tb', 'zb', etc. Note that format_bytes is a lossy...
300ede4ef120b9e3a8db85effcb6611dd9299953
56,407
def get_english_language_name(lang_scr): """Get the name of a language/script in the en-US locale.""" _parse_english_labels() try: return _ENGLISH_LANGUAGE_NAMES[lang_scr] except KeyError: if "-" in lang_scr: lang, script = lang_scr.split("-") try: ...
3ee81cde5d631bd5d8c228468c2e0cd5dc6f4c02
56,408
import time from re import A def cache_in_ram(): """cache the output of the lambda function in ram""" t = cache.ram('time', lambda : time.ctime(), time_expire=5) return dict(time=t, link=A('click to reload', _href=URL(r=request)))
e9a0b864e3d0b52153c2b62afd2741d62b8de5b1
56,409
def dict_values(): """ get values from dict """ mydict = {'cow': 1, 'dog': 2, 'lion': 3} return mydict.values()
d94d2b6524e8e46630058ed5733dc212be1e0a50
56,410
def normalize(image): """ Normalizes an image to the range 0-1 :param image: :return: """ image = image.astype(np.float32) image -= image.min() image /= image.max() return image
81b14446b4dcd52703f7dff54a7d8312c11f5663
56,411
async def async_setup(hass: HomeAssistant, config: dict): """Set up the MyQ component.""" hass.data.setdefault(DOMAIN, {}) # Replace default HTTP headers from pymyq for name, value in config.get(DOMAIN, {}).get(CONF_PYMYQ_HEADERS, {}).items(): if value: if name in PYMYQ_HEADERS: ...
90be8bfe41f767f7b36dbe488ccd5dbebd773c07
56,412
import psutil from typing import List def a_proc_children(proc: psutil.Process, recursive: bool = False) -> List[psutil.Process]: """Get the children of a process asyncly Args: proc: The process recursive: Whether get the children recursively Returns: The chil...
e4d35d89f20833af79328c348cdf61e77c0cb6f7
56,413
import io import sys def open_file(filename, mode='r', encoding=None, newline=None, strip_utf_bom=False): """Opens a file. Args: filename: String, the name of the file to open, or '-' to use stdin/stdout, to read/write, depending on the mode par...
55b43c5dd44ebdb04db3e58291dcd157e494796d
56,414
import json def get_dictionary() -> dict: """Loads into memory actus-dictionary.json. """ with open(_DICTIONARY_FILE, "r") as fstream: return json.loads(fstream.read())
4589e526e22f0577324ec0c137780db39ca18d99
56,415
import logging def create_form_parser(headers, on_field, on_file, trust_x_headers=False, config={}): """This function is a helper function to aid in creating a FormParser instances. Given a dictionary-like headers object, it will determine the correct information needed, instantiat...
439749ca135099eabe5f3b4c1136df2a95aef2c9
56,416
def s3_signature(): """ Route for signing the policy document or REST headers. """ response_data = challenge_request(request) if response_data is None: response_data = {'error': 'This file has not been approved for transfer, check upload is to correct dataset.'} return jsonify(response_data)
f0b29d4da2ae06a299c9860bc019818eb64dbf37
56,417
from typing import Optional from typing import Tuple import uuid def create_build( *, product: Product, git_ref: str, github_requester: Optional[str] = None, slug: Optional[str] = None, ) -> Tuple[Build, Optional[Edition]]: """Create a new build. The build is added to the current database...
4f70f70ee693d4d8a579a6dee1a56337a8306b02
56,418
import io def _loadGCSDataFile(file_name): """Get a file handle for a file from GCS.""" file_stream = io.StringIO( gcs.getFetchBucket().blob(file_name).download_as_string().decode(), newline='' ) return file_stream
1983e5e3cb000660d3ef9b7ecd332a4f7d8fd851
56,419
def stat(path, aboutlink = False): """Returns a gfs_stat/gfs_lstat value. It returns None if the operation failed. It uses gfs_lstat if the optional argument is true.""" p = abst_path(path) s = str(p).encode(name_coding) (st, cc) = _gfs_stat_cached(s, aboutlink) return (st, cc)
3ea86e38c9349ce333e8031087fd9c849914216b
56,420
def test_identifier(recipe): """Test recipe identifier for proper construction. Args: recipe: Recipe object. Returns: Tuple of Bool: Failure or success, and a string describing the test and result. """ name = recipe["Input"].get("NAME") if name: # The identifier ...
800b7a9d07ef7094d32a17033da519c9edb5039b
56,421
def _align_vectors(a: np.ndarray, b: np.ndarray) -> np.ndarray: """Produces the rotation needed to align two vectors.""" v = np.cross(a, b).reshape(3, 1) cos = _dot(a, b).reshape(1, 1) vx = np.matmul(TO_SSCP_MATRIX, v) vx = vx.reshape(3, 3) vxvx = np.matmul(vx, vx) transform = np.eye(4, dtyp...
cfc1938a19e1db7e692fe0077918f860909f3835
56,422
def sector_indexmap(kmap, anglemap, angle = 0., sector = 30., kstep = 1.): """Builds indexmap array of integers ranging from -1 (invalid data) and positive integers. Each non-negative integer is a valid k-index computed from sector parameters. Parameters ---------- kmap : ndarray Si...
9b394cd1751502e485663523e3d3299444dc5ae0
56,423
def get_data(table): """Return all from the 'database', most recent first.""" db = psycopg2.connect("dbname={}".format(DBNAME)) c = db.cursor() query = "select * from {}".format(table) c.execute(query) rows = c.fetchall() db.close() return rows
c2a573ea9a5d16699c34b552392c58a6fd1caf7a
56,424
import six def get_probs_for_labels(labels, prediction_results): """ Given ML Workbench prediction results, get probs of each label for each instance. The prediction results are like: [ {'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1}, {'predicted': 'sunflower', '...
f18580a5aba09df56fbb9b45b8ca5753eeba0d62
56,425
import torch def square_distance(src, dst): """ Calculate Euclid distance between each two points. src^T * dst = xn * xm + yn * ym + zn * zm; sum(src^2, dim=-1) = xn*xn + yn*yn + zn*zn; sum(dst^2, dim=-1) = xm*xm + ym*ym + zm*zm; dist = (xn - xm)^2 + (yn - ym)^2 + (zn - zm)^2 = sum(sr...
0c5dfa131e34d9defef6ee68c01d06bec69ee223
56,426
from typing import Sequence from typing import Tuple from typing import List import re def parse_all_signatures(lines: Sequence[str]) -> Tuple[List[Sig], List[Sig]]: """Parse all signatures in a given reST document. Return lists of found signatures for ...
69799aadde0b164da0c18436dc4bfe4fab15c458
56,427
def user_search(request): """Search a user. """ email = request.GET.get('email', '') user_emails = [] # search user from ccnet db users_from_ccnet = ccnet_api.search_emailusers('DB', email, -1, -1) for user in users_from_ccnet: user_emails.append(user.email) # search user from ...
2a348f5a153656faaca0ba0a749df9f7857d54d0
56,428
def global_mad(data, target_col, columns): """Calculates the outliers for the whole dataframe """ df_list = [] for target in set(data[target_col]): target_subset, training_subset = subset_df(data, target_col, columns, target) mad_df = pd...
67ddc73530d47654f672a20cd7f24cb61968faee
56,429
def vonNeumannRatio(mag, magerr): """The von Neumann ratio η was defined in 1941 by John von Neumann and serves as the mean square successive difference divided by the sample variance. When this ratio is small, it is an indication of a strong positive correlation between the successive photometric data po...
bfc6dc17b9488eadfca61f3ad29d455ec88f9fb8
56,430
import websockets import asyncio async def ws_conn(ws_conn_url, ws_timeout): """ websocket连接 """ async with websockets.legacy.client.connect(ws_conn_url) as websocket: try: recv = await asyncio.wait_for(websocket.recv(), ws_timeout) return recv except asyncio.Ti...
a8b7fe5776599a739e366fdfd9406f1baad56e31
56,431
import math def convert_local_to_global_vector(v: list, yaw: float): """ Converts the given vector in vehicle coordinate system to the global one under the given vehicle yaw. """ vx = math.cos(math.radians(yaw)) * v[0] - math.sin(math.radians(yaw)) * v[1] vy = math.sin(math.radians(yaw)) * v[0] + ...
62f96a22c85f22125165e387bfeea76d78e5c519
56,432
def is_display_ycyh_native_menu(driver): """ 是否有有车以后小程序的底部菜单栏 :param driver: :return: """ try: if driver.find_element_by_android_uiautomator('text("资讯")') and \ driver.find_element_by_android_uiautomator('text("选车")'): return True except NoSuchElementExcep...
95ec3907357ebc86da3fa08900ba40bc65bfeeaa
56,433
def parse_line(line): """ line is in the format distance,zipcode,city,state,gender,race,income,price """ line = line.strip().split(",")[3:] state = str(line[0]) gender = str(line[1]) race = str(line[2]) income = str(line[3]) price = str(line[4]) return [state, gender, race, inco...
929971c6a10efe5a40cafca50b405dad01a6f842
56,434
def colorize_log(log_level, msg, should_colorize=True): """ Returns a colored string to log :param should_colorize: boolean that specifies if the log is to be colorized :param log_level: level of message to logged :param msg: message to be logged :return: """ colorize_log_dict = { ...
0acfae0d9f5fadb6d9636e829404a1279359a7f1
56,435
import re def normalize_number(text: str) -> str: """ pattern = r'\d+' replacer = re.compile(pattern) result = replacer.sub('0', text) """ # 連続した数字を0で置換 replaced_text = re.sub(r'\d+', '0', text) return replaced_text
7fe223e9ef03fa681589034df99965fe8ae5c884
56,436
def norm_angle(a): """Normalize angle to (-pi, pi]. Parameters ---------- a : float or array-like, shape (n,) Angle(s) in radians Returns ------- a_norm : float or array-like, shape (n,) Normalized angle(s) in radians """ # Source of the solution: http://stackoverfl...
594951284251de4a03a68b1c2b7379f32ca82f66
56,437
import traceback import sys def excel_get_all_header_columns(excel_path="",sheet_name="Sheet1",header=0): """ Gives you all column header names of the given excel sheet. """ col_lst = [] try: if not excel_path: excel_path,sheet_name,header = gui_get_excel_sheet_header_from_user...
dbe7ee802fd2ad677514b420854be477957e3451
56,438
from typing import Optional def _hessians(models: BinaryLogReg, data: Dataset, data_weights: Optional[jnp.ndarray]) -> jnp.ndarray: """Implementation of the `hessians` method for MultiLogReg""" def f(x): model, targets = x return BinaryLogReg.hessian(model, (data[0], targets), da...
99f98e8a3c1aa2db6f5fa27165e40e37b53901e0
56,439
def darknet53_residual_block(inputs, filters, data_format, strides=1): """Creates a residual block for Darknet.""" shortcut = inputs inputs = Conv2D(inputs, filters=filters, kernel_size=1, strides=strides, data_format=data_format) inputs = BatchNormalization(inputs, data_format=data_format) inputs = LeakyReL...
ab72aaa85017453f21ad64aa3549456efd93177a
56,440
from typing import Optional from typing import Union from typing import Dict from typing import Any def install_req_from_line( name: str, comes_from: Optional[Union[str, InstallRequirement]] = None, use_pep517: Optional[bool] = None, isolated: bool = False, options: Optional[Dict[str, Any]] = None...
654f29a5e05e4bc86b2ef093bccf5b6d42b171b4
56,441
def humanReadable(size_in_bytes): """Returns sizes in human-readable units.""" try: size_in_bytes = int(size_in_bytes) except ValueError: size_in_bytes = 0 units = [(" KB", 10**6), (" MB", 10**9), (" GB", 10**12), (" TB", 10**15)] for suffix, limit in units: if size_in_bytes ...
29dd9e46d535943e83cd65c34f4135af898f0bbc
56,442
import os import tempfile import shutil def _install_with_pip( package_name, env_directory, requirements): """ :param package_name: the name of the package :type package_name: str :param env_directory: the path to the directory in which to install the ...
d08b617dee2a735c1ccd2ab83173dc0adfe72ffe
56,443
def generate_2d_shower_model(centroid, width, length, psi): """Create a statistical model (2D gaussian) for a shower image in a camera. The model's PDF (`model.pdf`) can be passed to `make_mock_shower_image`. Parameters ---------- centroid : (float,float) position of the centroid of the...
20422fc43a2bee2eccbda5ba792d66921b8177a3
56,444
def parse_options(): """ Returns [parser, options, args]. """ parser = OptionParser() opt = parser.add_option # Exactly one of --dynamic or --static MUST be specified. opt("--dynamic", action="store_true", dest="dynamic", default=False, help="Enable dynamic topology") o...
9ce8dff10a5296814fe9d61e982edd77e70e4014
56,445
def make_package_from_paths(paths, zip_folder=None): """ Constrói pacote a partir de caminhos de arquivos Parameters ---------- paths : dict { "xml": "/home/user/fd89fb6a2a0f973016f2de7ee2b64b51ca573999.xml", "renditions": [ "/home/user/aed92928a9b5e0...
b36c19601b498729529283402937b6a6ec2cdacc
56,446
def upload_file(): """Perform depscan through web interface file upload. Returns: [reponse]: 200 if success, 400/204 if failure """ # Authenticate User try: decoded_token = authenticateToken(request) uid = decoded_token["uid"] projectid = request.args.get("projectID"...
e108bb1074be60095ef76e2a962d11b5ad0ff992
56,447
def binSplitDataSet(dataSet, feature, value): """binSplitDataSet(将数据集,按照feature列的value进行 二元切分) Description:在给定特征和特征值的情况下,该函数通过数组过滤方式将上述数据集合切分得到两个子集并返回。 Args: dataMat 数据集 feature 待切分的特征列 value 特征列要比较的值 Returns: mat0 小于等于 value 的数据集在左边 mat1 大于 value 的数据集在右边 ...
5e7be749530bf45470c3c3bfc0517451be556772
56,448
def cdf(x, mu): """ Evaluate cumulative distribution function of continuous Poisson distribution. """ return _gammaincc(x + 1, mu)
190969f04839b950605e517c2d12d22e21da87e3
56,449
import os def _raw_data_file_path(fname): """Absolute path to a data file in the default raw data directory""" return os.path.join(raw_data_dir(), fname)
1b43525f88451dd96d121434a2e7f561296d707f
56,450
import json import uuid import os def reset_realtime(): """ Sets the training configuration in SSM so that the polling lambda trains a new campaign and then deletes the old one. Logic is in that lambda; here we configure the Lambda. Also re-enables that Lambda's polling rule if it has been disabled. ...
d34c18790a6e2015baeca5fd226fd95469bf344b
56,451
def _apply_function(x, fname, **kwargs): """Apply `fname` function to x element-wise. # Arguments x: Functional object. # Returns A new functional object. """ validate_functional(x) res = x.copy() fun = get_activation(fname) lmbd = [Lambda(lambda x: fun(x, **kwargs)) f...
9894f246591464cc7598821b0fc7946c7db02f09
56,452
import os import fnmatch def find_object_files(directory): """ Find binary executables and ``*.so`` files. :param directory: The pathname of the directory to search (a string). :returns: A list of filenames of object files (strings). This function is used by :func:`build_package()` to find files...
e6f0bf9c115666d59fd5eb8b4438cd031ccf903f
56,453
def calc_polynomial(x, a, b, c): """ y = ax^2 + bx + c :param x: :param a: :param b: :param c: :return: """ return a * x ** 2 + b * x + c
42f65f1cff376bf2b84a3ddf8d849743342547a9
56,454
from datetime import datetime import csv def api_export(request, form_id): """ Returns a serialized set of submissions for the form """ forms = Form.objects.filter(form_id=form_id) if "query" in request.GET: params = request.GET.getlist("query") else: first_form_elements = forms.last()...
89195c154d43858f8f3453750a228102100c3aac
56,455
def gen_rsd_cdf(K, S, delta): """The CDF of the RSD on block degree, precomputed for sampling speed""" mu, Z = gen_mu(K, S, delta) cdf = np.cumsum(mu) return cdf, Z
80c1f1d4379940774b88bcce90411f62f657acd5
56,456
def UniqueSequentialName(name_base, template=u'%(name)s.%(num)s'): """ Return a new sequential name based on a naming template and a base name such that the name uniquely identifies an object in the scene. By default, mimicks the names generated by CINEMA 4D when multiple...
509f1aef865b8916b0398ab62eca253e17fbb573
56,457
from typing import Dict def _update_config(old_conf: dict, new_conf: dict, verbose: bool=False, recurs_idx: int=0) -> Dict: """Update a dict recursively.""" assert(recurs_idx < 3) if old_conf is None: return new_conf for key, value in old_conf.items(): if key in new_...
d96d06b4e7a4f394aff12aae4aec3f6549b9146f
56,458
def is_vowel_offset(c_offset): """ Is the offset a vowel """ return (c_offset >= 0x04 and c_offset <= 0x14)
bc17c15e01e9b0c81909721d9f4d59b927601206
56,459
def is_outlier(ground_truth_f0_conf): """Determine if ground truth f0 for audio sample is an outlier.""" ground_truth_f0_conf = squeeze(ground_truth_f0_conf) return np.max(ground_truth_f0_conf) < MIN_F0_CONFIDENCE
2fff7a3f062c70e1393bdd26741134ba2b75acf1
56,460
def project_set_properties(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/setProperties API method. For more info, see: https://documentation.dnanexus.com/developer/api/data-containers/projects#api-method-project-xxxx-setproperties """ return DXHTTPRequest('...
e503e2a3c721d34c2e11fccc615d4b8563ae3859
56,461
from typing import Optional def get_application_global() -> Optional[werkzeug.local.LocalProxy]: """ Get the current application global proxy object. Returns ------- proxy or None """ if g: return g # type: ignore return None
a87a29711c15af96d10e95c68fc84bd59d93f358
56,462
def repeat_ws(rule, from_count, to_count=None): """Same as the repeat rule with allow_whitespace set to True.""" return repeat(rule, from_count, to_count, allow_whitespace=True)
650f6ed4b5ef8ae9f1e684893b038467e60eaee9
56,463
def api_redirect_to_current(): """ Redirect to the root of the most recent API version. """ return redirect(BASEURI + "/api/1.0")
94a7021dcffd1f0cb346a2c05d72658283b08d72
56,464
def stream_function(step: Step) -> Field: """Compute the stream function in 2D geometry. Args: step: a :class:`~stagpy._step.Step` of a StagyyData instance. Returns: the stream function field. """ if step.geom.twod_yz: x_coord = step.geom.y_walls v_x = step.fields['v...
c47c724dd199912eb377bf1f9ad7659f738754db
56,465
def extract_random_example_array(image_list, example_size=[64, 64], n_examples=1, loc=[50, 50], anywhere=False, border_shift=10): """ Randomly extract training examples from image (and corresponding label). Returns an image example array and the corresponding label a...
167e87fa350b854c62b090aa19d9639b6a055ea0
56,466
import time def generate_uid(): """Generate a unique id using a custom salt, alphabet and min length.""" salt = settings.SECRET_KEY alphabet = settings.UID_ALPHABET hashids = Hashids(salt=salt, alphabet=alphabet) unique_id = hashids.encode(int(time() * 1000)) return unique_id
b746baaea3d1c67a585375710c0a367162db55dd
56,467
def _validate_third_parties(draft, errors, is_mandatory): """ Checks all third parties have documents if is_mandatory is True """ third_parties_documents_error = check_parties_documents(draft.third_parties.all(), is_mandatory) if third_parties_documents_error: errors["third_parties_documents"] = [t...
561c2ac562e96689d8d34fde55906cf02960c2f5
56,468
import os def get_cwd(): """Allows use to patch the cwd when needed. """ return os.getcwd()
601ca5210e08c28cc307c1c86414b30ce72bbb50
56,469
def get_database() -> Database: """Get the cached database connection or create and cache a new one Returns: Database: current database connection """ global _database if _database is None: _database = Database(get_psql_connection()) return _database
0fd812d3f7fe5c8eeeffcfead4a588c35247b5bc
56,470
import getopt def parse_options( argv ): """Parse command line options.""" opts = {} urlargs = {} try: user_opts, user_args = getopt.getopt( \ argv, \ 'k:a:c:o:?', \ [ 'key=', 'action=', 'country=', 'options=', 'help=' ] ) except Exception as e: ...
e2550dc1d285bb3e7640e9fa943b0e3b0feb6f63
56,471
from re import X def f_per_particle(m, alpha): """Computes for the objective function per particle Inputs ------ m : numpy.ndarray Binary mask that can be obtained from BinaryPSO, will be used to mask features. alpha: float (default is 0.5) Constant weight for trading-off ...
aaecf1c463a6331822f67fc4dd436e3ee20a079b
56,472
def read_image(path, dtype=np.float32, color=True): """Read an image from a file. This function reads an image from given file. The image is CHW format and the range of its value is :math:`[0, 255]`. If :obj:`color = True`, the order of the channels is RGB. Args: path (str): A path of imag...
b1dfa4f0235a9ce2a0d87ee1440f0ad9f843e5ac
56,473
def _agent_has_email_address(agent_obj): """Check if agent has email. Arguments: agent_obj (list/dict): The specified field from the research dataset. If publisher then dict else list Returns: bool: True if has emails, False if not. """ if agent_obj: if isinstance(agent_ob...
a662a9a874e607d90db644c93515632606ae83fc
56,474
def list_acquisition_dates(dc, product): """Get a list of acquisition dates for a given product""" dataset = dc.load(product, dask_chunks={}) if not dataset: return [] return dataset.time.values.astype('M8[ms]').tolist()
97012b354d835ad94e7037f9c68fcfa72d143930
56,475
def heisenberg_XXZ_spin1_MPO(L, J, D, h): """ Construct spin-1 XXZ Heisenberg Hamiltonian `sum J X X + J Y Y + D Z Z - h Z` on a 1D lattice as MPO. Args: L: number of lattice sites J: J parameter D: Delta parameter h: field strength Returns: MPO: spin-1 ...
3620be55e5d0726a3b5a0fcae5c2123d1eca2e5a
56,476
def login_post(): """Obdelaj izpolnjeno formo za prijavo""" # Uporabniško ime, ki ga je uporabnik vpisal v formo username = request.forms.username # Izračunamo MD5 has gesla, ki ga bomo spravili password = password_md5(request.forms.password) # Preverimo, ali se je uporabnik pravilno prijavil ...
f0282a71744307370f15b872273d478aec319fd5
56,477
import re def arg_to_a(role: str): """ Convert 'ARGM-TMP' form of role label to 'AM-TMP' form. :param role: original role label :return: shortened role, with 'A' instead of 'ARG' """ return re.sub(_ARG_STR, r'\1A\2', role, re.IGNORECASE).upper()
19fa935f71df9d35fa684f53f92e29d0298e483b
56,478
def get_db(): """Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, 'dbConnection'): g.dbConnection = connect_db() return g.dbConnection.signinucsd
cc4f332f69f0b48ed0607b506831da242ed736bd
56,479
import torch def coord_map(shape,device, start=-1, end=1): """ Gives, a 2d shape tuple, returns two mxn coordinate maps, Ranging min-max in the x and y directions, respectively. """ m, n = shape x_coord_row = torch.linspace(start, end, steps=n).to(device) y_coord_row = torch.linspace(start...
056dddd9442cef58dca7cc6cc30fd6b8cca9bc85
56,480
from typing import Tuple from typing import Dict def criar_base_quarentena(dados: dict) -> Tuple[Dict[str, int], Dict[str, int]]: """Criar a estrutura para lidar com função de contenção de adaptações sucessivas no KubeKepam Args: dados (dict): nome do namespace do Kubernetes. ...
7e4124092760575edb963606f88da7c38dfe0455
56,481
def _adjust_elevation(elevtn): """fix elevation on single streamline based on minimum modification elevtn oderdered from up- to downstream """ n = elevtn.size imax, imin = -1, -1 zmax, zmin = elevtn[0], elevtn[0] # local max / min elevation zi_min1, zi_min2 = zmin, zmin # initialize # ...
8610f5695ccb15a78396b8ec4e46d42f69a5c021
56,482
def decode_mappings(line_data, names): """Decodes a mappings line of text. Args: line_data: A string containing the mapping line. names: An array of strings containing the names of the objects. Returns: a list of Tokens """ tokens = [] lines = line_data.split(';') name_id = 0 for dst_lin...
9213310cadc6233df32080e8229636f68d1b93c6
56,483
from typing import Optional def strength(pw: str) -> Optional[str]: """ The function to verify a password's strength. Parameters: pw (str): The password to check. Returns: Optional[str]: A str on faliure, None on success. """ pw_asSet: set[chr] = set(pw) if len(pw) < 8: ...
eb7ef19102cd5b77e8d0bc4d4c2165262c6550e3
56,484
import pkg_resources def getMargSample(num=10,bv=1,eff=1): """ Get samples from the Prospector likelihood distribution for proper marginalization Parameters ---------- num: Integer Number of marginal samples desired bv: Boolean Whether or not bivariate case for code is being used ...
5b6d7820998880e2c002ac3ee705dc92298c15fa
56,485
def heart_speed(speed='half'): """Set the low-health warning beep interval. Keyword Arguments: speed {str} -- Chose the speed at which the low health warning beeps. Options are 'off', 'double', 'normal', 'half', and 'quarter'. (default: {'half'}) Returns: list -- a list of dict...
62bab25f6221e1260048fac3126280cd4791a9b3
56,486
def make_header_str(spc_dct, rxn_lst, pes_idx, temps, pressures): """ Built the head of the MESS input file that contains various global keywords used for running rate calculations. Function determines certain input parameters for the well-extension methodology based on the reaction type st...
69d165344c1c72e1eaab1d942e113d124fb862a1
56,487
def upsample_kernel_size_solver( in_size, out_size, stride=1, padding=0, output_padding=0, dilation=1, ): """ Returns kernel size needed to upsample a tensor of some input size to a desired output size. The implementation solves for kernel size in the equation described the the "Shape" section ...
58bcf58c3781b195801e1239b9fa688d19c89288
56,488
import logging def bqCreateTable(bq_client, dataset_id, table_name): """ Create main table with all cases and the medical text. Args: bq_client: BigQuery client instantiation - dataset_id: str - Reference id for the dataset to use table_name: str - Name of the table to create ...
7f508f6db88c5cfb3f825c66bf95e806b62252d2
56,489
def hog_map(img, winsize, mask=None, output=None): """Histogram of oriented gradients (HOG) texture feature map.""" for pos, win in dwi.util.sliding_window(img, winsize, mask=mask): feats = [hog(win)] if output is None: dtype = dwi.rcParams.texture_dtype output = np.zeros...
fe38e96d9172aa77f94ac53a3dc2b2da268f6458
56,490
import warnings def fit_1d_gaussian(x, y, amplitude=1, mean=0, stddev=1, bounds=None, ignore_bad_fit_warnings=False, **kwargs): """Returns a fitted multiple Gaussian2D models and its extracted parameters. Note, if you get the message of "WARNING: The fit may be unsuccessful", try increasing number of all...
48f5bc9f79313e72544f1eb7c07e8a4947b517fb
56,491
def get_key_from_dict (dictionary, key, group, required=True): """ Grab a value from dictionary :param dictionary: Dictionary to utilize :param key: Key to fetch :param group: Group this key belongs to, used for error reporting purposes :param required: Boolean indicating whether this key is ne...
81245795296c2fe6d21bb84f0cccfa197a966b24
56,492
def upload_imgur_image() -> Response: """ Upload an Image to Imgur Returns ------- Response """ imgur_api_url = "https://api.imgur.com/3/image" headers = dict(Authorization=f"Client-ID {getenv('IMGUR_CLIENT_ID')}") response = post(url=imgur_api_url, headers=heade...
bf25b2b6b0eaf1a8c6366c71d956d68b2f80d755
56,493
def gen_people_table(df_census, demo_cols, m=1.0, alpha=20) : """ Starting from a census file, generate the population and assign rates according to the power-law or Lomax (Pareto type II) distribution). Returns a table of people with demographics and rate of impression generation. """ populati...
f1e82649334f1fba056fb936ed24878bea7f4237
56,494
import tokenize def count_words(training_set): """trainiing set consists of pairs (message, is_spam)""" counts = defaultdict(lambda:[0, 0]) for message, is_spam in trainiing_set: for word in tokenize(message): counts[word][0 if is_spam else 1] += 1 return counts
87eba37e7ea4fe4b7cea7248195c8de7b958835d
56,495
def build_neck(cfg): """Build neck.""" return build_from_cfg(cfg, registry, 'neck')
b230a63957df0b29c5e3cb2e4c8a8d30eec6081e
56,496
def OneDimensionalLineBuffer( pixel_type: Kind, pixel_per_clock: int, window_width: int, image_size: int, output_stride: int, origin: int, first_row: bool = True, last_row: bool = True) -> Circuit: """ :param pixel_type: the type of each pixel. A t...
09bf78d802296c47db81f788a1811f0a3f5b04f4
56,497
from mxnet.gluon.model_zoo.vision import get_model def get_network(name, batch_size, dtype='float32'): """Get the symbol definition and random weight of a network Parameters ---------- name: str The name of the network, can be 'resnet-18', 'resnet-50', 'vgg-16', 'inception_v3', 'mobilenet', ....
4c6d17f606bebd14461e2199ffb16cb9079b1105
56,498
def convertMsg(message, glyphList=[], charList=[], maxChar=maxCustomChar): """ return message and glyph list """ new_msg = '' offset_glyph_list= len(glyphList) - len(charList) for c in message: if c in dictGlyph: if c in charList: # glyph has already been added to the list, so use ...
b9c4ba89afaeac6bf3cbb39afdcee5eb00558589
56,499