content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def update_user(old_email, new_email=None, password=None): """Update the email and password of the user. Old_email is required, new_email and password are optional, if both parameters are empty update_user() will do nothing. Not asking for the current password is intentional, creating and updating are ...
cb8f23ccd2d9e0d0b390358ef440af28d67e549d
29,360
from typing import Optional def get_text(text_node: Optional[ET.Element]) -> Optional[str]: """Return stripped text from node. None otherwise.""" if text_node is None: return None if not text_node.text: return None return text_node.text.strip()
2bb7c8ae6500d9a8ca5ef6be09dbf3abfc04a013
29,361
def function_d(d, d1, d2=1): """doc string""" return d + d1 + d2
92d3bb788191612c6a67f67a05bd703a02f43a04
29,362
from unittest.mock import patch def qgs_access_control_filter(): """ Mock some QgsAccessControlFilter methods: - __init__ which does not accept a mocked QgsServerInterface; - serverInterface to return the right server_iface. """ class DummyQgsAccessControlFilter: def __init__(self, s...
df84f1ff78c52376777c9238a3ee857c8c31f3d2
29,363
def ppmv2pa(x, p): """Convert ppmv to Pa Parameters ---------- x Gas pressure [ppmv] p total air pressure [Pa] Returns ------- pressure [Pa] """ return x * p / (1e6 + x)
974d79d022a7fb655040c7c2900988cd4a10f064
29,364
def make_elastic_uri(schema: str, user: str, secret: str, hostname: str, port: int) -> str: """Make an Elasticsearch URI. :param schema: the schema, e.g. http or https. :param user: Elasticsearch username. :param secret: Elasticsearch secret. :param hostname: Elasticsearch hostname. :param port...
be959e98330913e75485006d1f4380a57e990a05
29,365
def _truncate(s: str, max_length: int) -> str: """Returns the input string s truncated to be at most max_length characters long. """ return s if len(s) <= max_length else s[0:max_length]
52c49c027057024eaa27a705a0d2c013bff7a2ce
29,366
def verify_days_of_week_struct(week, binary=False): """Given a dictionary, verify its keys are the correct days of the week and values are lists of 24 integers greater than zero. """ if set(DAYS_OF_WEEK) != set(week.keys()): return False # Each day must be a list of ints for _, v in we...
57b4b23d0b492f2fc25a0bdb9d218c6fd9deefc0
29,367
def create_attention_mask_from_input_mask(from_tensor, to_mask): """Create 3D attention mask from a 2D tensor mask. Args: from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...]. to_mask: int32 Tensor of shape [batch_size, to_seq_length]. Returns: float Tensor of shape [batch_size, from_seq_...
d0a5c11108717c1e389d0940c9740d7a0c2671f0
29,368
def execute_inspection_visits_data_source(operator_context, return_value, non_data_function_args) -> BackendResult: """Execute inspections when the current operator is a data source and does not have parents in the DAG""" # pylint: disable=unused-argument inspection_count = len(singleton.inspections) it...
f42ce3cb7b0900a5e7458bf0ad478843860db0f9
29,369
def parse(template, delimiters=None, name='<string>'): """ Parse a template string and return a ParsedTemplate instance. Arguments: template: a template string. delimiters: a 2-tuple of delimiters. Defaults to the package default. Examples: >>> parsed = parse(u"Hey {{#who}}{{name}}...
51a9da21831afb0b124cc9481f49b546a51a587a
29,370
def get_phases(t, P, t0): """ Given input times, a period (or posterior dist of periods) and time of transit center (or posterior), returns the phase at each time t. From juliet =] """ if type(t) is not float: phase = ((t - np.median(t0)) / np.median(P)) % 1 ii = np.where(phase >...
8d5e821112c7fffd0766dbb0158fd2f4034ef313
29,371
async def my_profile(current_user: User = Depends(get_current_active_user)): """GET Current user's information.""" return current_user
fd03fe06b9737565e338b3b3ccd5999b0da32cc1
29,372
def are_2d_vecs_collinear(u1, u2): """Check that two 2D vectors are collinear""" n1 = np.array([-u1[1], u1[0]]) dot_prod = n1.dot(u2) return np.abs(dot_prod) < TOL_COLLINEAR
2861b6316a5125799a91a471129bfc1ce2e91992
29,373
from datetime import datetime import time def TimeFromTicks(ticks: int) -> datetime.time: # pylint: disable=invalid-name """ Constructs an object holding a time value from the given ticks value. Ticks should be in number of seconds since the epoch. """ return Time(*time.gmtime(ticks)[3:6])
a53564b2890080a7fbe0f406ae76c7237c92c34a
29,374
import importlib def load_model(opt, dataloader): """ Load model based on the model name. Arguments: opt {[argparse.Namespace]} -- options dataloader {[dict]} -- dataloader class Returns: [model] -- Returned model """ model_name = opt.model model_path = f"lib.models.{...
8ad05c4a0f51c40851a9daecf81ed8bf9862979c
29,375
def process(cntrl): """ We have all are variables and parameters set in the object, attempt to login and post the data to the APIC """ if cntrl.aaaLogin() != 200: return (1, "Unable to login to controller") rc = cntrl.genericGET() if rc == 200: return (0, format_content(cn...
8e20f4b81314436e53713a418447072820e5c55b
29,376
from typing import Callable from typing import Iterator def create_token_swap_augmenter( level: float, respect_ents: bool = True, respect_eos: bool = True ) -> Callable[[Language, Example], Iterator[Example]]: """Creates an augmenter that randomly swaps two neighbouring tokens. Args: level (float...
1fc41e75d96ea7d4153802f4e86f8ab25d7227c3
29,377
def getUnigram(str1): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ words = str1.split() assert type(words) == list return words
d540ee199ab62c383461893e91034399d22fe6d6
29,378
def expval_and_stddev(items, exp_ops=''): """Compute expectation values from distributions. .. versionadded:: 0.16.0 Parameters: items (list or dict or Counts or ProbDistribution or QuasiDistribution): Input distributions. exp_ops (str or dict or list): String or...
c024797f00d87ece0b0e871530c747a93d151f3c
29,379
def newton_polish(polys,root,niter=100,tol=1e-8): """ Perform Newton's method on a system of N polynomials in M variables. Parameters ---------- polys : list A list of polynomial objects of the same type (MultiPower or MultiCheb). root : ndarray An initial guess for Newton's met...
cdf2b993bb34142cf82de9f7a2a003f7eb9a0a24
29,380
def COUNT(logic, n=2): """ 统计满足条件的周期数 :param logic: :param n: :return: """ return pd.Series(np.where(logic, 1, 0), index=logic.index).rolling(n).sum()
e175629e301152978e5d9a46caa4921e080048a8
29,381
import yaml def get_model(name): """ Get the warpped model given the name. Current support name: "COCO-Detection/retinanet_R_50_FPN"; "COCO-Detection/retinanet_R_101_FPN"; "COCO-Detection/faster_rcnn_R_50_FPN"; "COCO-Detection/faster_rcnn_R_101_FPN"; "COCO-InstanceSegmentation/mask_rcnn_...
fe1842950c93d790623d6ba072c5cab48eb03eb9
29,382
def energy_sensor( gateway_nodes: dict[int, Sensor], energy_sensor_state: dict ) -> Sensor: """Load the energy sensor.""" nodes = update_gateway_nodes(gateway_nodes, energy_sensor_state) node = nodes[1] return node
8e2560aa8b442c94fb39d602b100a7aa8757de84
29,384
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos): """Computes the average of all the metric for one decoding. Args: iterator: dataset iterator. feed_dict: feed dict to initialize iterator. num_videos: number of videos. Returns: all_psnr: 2-D Numpy array, shape=(num_samples...
8acd5cd1b564d22b26ebfd0ddd40fb76e90aa9a4
29,385
def geocode_locations(df: gpd.GeoDataFrame, loc_col: str): """ Geocode location names into polygon coordinates Parameters ---------- df: Geopandas DataFrame loc_col:str name of column in df which contains locations Returns ------- """ locations = geocode(df.loc[:, loc_col]) ...
c1ba4edfa31ca4d7d6a2e01a5c3342025936b085
29,388
import json def get_data(): """Get dummy data returned from the server.""" jwt_data = get_jwt() data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(data) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='applic...
c3df0a63dbb06822bbea1278c539ab1386e59d99
29,389
import pandas def coerce_integer(df): """ Loop through the columns of a df, if it is numeric, convert it to integer and fill nans with zeros. This is somewhat heavy-handed in an attempt to force Esri to recognize sparse columns as integers. """ # Numeric columns to not coerce to integer ...
d4b5963378a10a4bde6f7e1e2111908b83d90b7d
29,390
def read_cfg(floc, cfg_proc=process_cfg): """ Reads the given configuration file, returning a dict with the converted values supplemented by default values. :param floc: The location of the file to read. :param cfg_proc: The processor to use for the raw configuration values. Uses default values when t...
1ec276ad434ce36e32fab73b1cc65c05a14e032a
29,391
from datetime import datetime def convert_date(raw_date: str, dataserver=True): """ Convert raw date field into a value interpretable by the dataserver. The date is listed in mddyy format, """ date = datetime.strptime(raw_date, "%Y%m%d") if not dataserver: return date.strftime("%m/%d/%...
6fc9ec6bf5a336998e4bd9752abb8804251d8c33
29,393
from re import VERBOSE def getComputerMove(board): """ Given a board and the computer's letter, determine where to move and return that move. \n Here is our algorithm for our Tic Tac Toe AI: """ copy = getBoardCopy(board) for i in range(1, NUMBER_SPACES): if isSpaceFree(copy, i): ...
83328215ca64170ec88c577ae41fcbd0e2076c47
29,394
from .. import Plane def triangular_prism(p1, p2, p3, height, ret_unique_vertices_and_faces=False): """ Tesselate a triangular prism whose base is the triangle `p1`, `p2`, `p3`. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. Args: p1 (np....
99ecdc6054dba1f2b955b08bf082636cac546fb8
29,395
def chain_species_base(base, basesite, subunit, site1, site2, size, comp=1): """ Return a MonomerPattern representing a chained species, chained to a base complex. Parameters ---------- base : Monomer or MonomerPattern The base complex to which the growing chain will be attached. basesi...
b7b619a810b7d84ee64a92bcda4b4578d797be63
29,396
def find_one_item(itemname): """ GET the one item in the shop whose title matches itemname. :param itemname: The title to look for in the shop. :type itemname: str :return: dict(str, Decimal, int). A dict representing the requested item. :raise: werkzeug.exceptions.NotFound """ try: ...
cec13fec0489489660da375e7b7fc2168324909f
29,397
import string def PromGraph(data_source, title, expressions, **kwargs): """Create a graph that renders Prometheus data. :param str data_source: The name of the data source that provides Prometheus data. :param title: The title of the graph. :param expressions: List of tuples of (legend, expr)...
7a2a8d0902bc9ef2fcc03e16678c4a40976bdb0e
29,398
def get_maxlevel(divs, maxlevel): """ Returns the maximum div level. """ for info in divs: if info['level'] > maxlevel: maxlevel = info['level'] if info.get('subdivs', None): maxlevel = get_maxlevel(info['subdivs'], maxlevel) return m...
b7153ef84cb260a4b48c58315aa63fc5179fc06c
29,400
def prenut(ra, dec, mjd, degrees=True): """ Precess coordinate system to FK5 J2000. args: ra - arraylike, right ascension dec- arraylike, declination mjd- arraylike """ if degrees: c = np.pi/180. else: c = 1. raout = ra.astype(np.float)*c decout = dec.as...
99cedddc4beacc99c2360ba835f39d927118c683
29,401
def make_model_and_optimizer(conf): """Function to define the model and optimizer for a config dictionary. Args: conf: Dictionary containing the output of hierachical argparse. Returns: model, optimizer. The main goal of this function is to make reloading for resuming and evaluation ...
93a0a7c8f5b31571c5d8a5130c5fd1de0f046adc
29,402
from re import T import numpy def trange(start: int, end: int, step: int=1, dtype: T.Dtype = None) -> T.Tensor: """ Generate a tensor like a python range. Args: start: The start of the range. end: The end of the range. step: The step of the range. Returns: tensor: A v...
140a88069503f2bb372b8f18796a56bb41e465f3
29,403
def get_molecules(topology): """Group atoms into molecules.""" if 'atoms' not in topology: return None molecules = {} for atom in topology['atoms']: idx, mol_id, atom_type, charge = atom[0], atom[1], atom[2], atom[3] if mol_id not in molecules: molecules[mol_id] = {'a...
4bf63000c9d5b56bb9d35922ed521ce81cf3a6c1
29,404
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
9c888e365fbd43bacb7ae2a9e025abdf14efcbff
29,405
from typing import Literal def simple_dataset() -> Dataset: """ This is a simple dataset with no BNodes that can be used in tests. Assumptions/assertions should not be made about the quads in it, other than that it contains no blank nodes. """ graph = Dataset() graph.default_context.add((E...
ee897b222d95bc1e92160f925679b9c864c3674a
29,406
import unicodedata import re def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, unde...
45a01d4552de0094b56b40a9c13102e59af32b5b
29,407
def is_between(start, stop, p): """Given three point check if the query point p is between the other two points Arguments: ---------- start: array(shape=(D, 1)) stop: array(shape=(D, 1)) p: array(shape=(D, 1)) """ # Make sure that the inputs are vectors assert_col_ve...
f7cf20420115a71fb66ce5f8f8045163fa34c7ff
29,408
def get_elasticsearch_type(): """ Getting the name of the main type used """ return settings.ELASTICSEARCH_TYPE
889cb6e698f88c38229b908dd92d8933ec36ba8e
29,409
def run_cmd_code(cmd, directory='/'): """Same as run_cmd but it returns also the return code. Parameters ---------- cmd : string command to run in a shell directory : string, default to '/' directory where to run the command Returns ------- std_out, std_err, return_code ...
0e001d36df6e0b9b39827f36e1bda369e2185adf
29,410
def unpack_le32(data): """ Unpacks a little-endian 32-bit value from a bytearray :param data: 32-bit little endian bytearray representation of an integer :return: integer value """ _check_input_array(data, 4) return data[0] + (data[1] << 8) + (data[2] << 16) + (data[3] << 24)
c1cdd8f71dbb03769a2e681948300436e6cd735f
29,411
def InductionsFromPrescribedCtCq_ST(vr_bar,Ct,Cq,Lambda,bSwirl): """ Returns the stream tube theory inductions based on a given Ct and Cq. Based on script fGetInductions_Prescribed_CT_CQ_ST """ lambda_r=Lambda*vr_bar # --- Stream Tube theory a_ST = 1/2*(1-np.sqrt(1-Ct)) if bSwirl:...
6b254056b70d65dc20f89811e4938dd7ad5323f6
29,412
from typing import get_origin from typing import Union from typing import get_args def unwrap_Optional_type(t: type) -> type: """ Given an Optional[...], return the wrapped type """ if get_origin(t) is Union: # Optional[...] = Union[..., NoneType] args = tuple(a for a in g...
6ffd9fa6dc95ba669b0afd23a36a2975e29c10da
29,413
def _normalize_angle(x, zero_centered=True): """Normalize angles. Take angles in radians and normalize them to [-pi, pi) or [0, 2 * pi) depending on `zero_centered`. """ if zero_centered: return (x + np.pi) % (2 * np.pi) - np.pi else: return x % (2 * np.pi)
2e73a9fb20743f4721c954a48ca838c1eaca5edd
29,415
def g_fam(arr): """ Returns the next array """ aux = 0 hol = [] while(aux +1 < arr.__len__()): if arr[aux] or arr[aux + 1]: hol.append(True) else: hol.append(False) aux += 1 return hol
4f0ed0d4ba205ef205579a2b150250760e7b38fe
29,416
import time def main_archive(args, cfg: Configuration): """Start running archival""" jobs = Job.get_running_jobs(cfg.log) print('...starting archive loop') firstit = True while True: if not firstit: print('Sleeping 60s until next iteration...') time.sleep(60) ...
17bc1c63896edae46f2db60bd9bbcbd699d6f1ab
29,417
def k2j(k, E, nu, plane_stress=False): """ Convert fracture Parameters ---------- k: float E: float Young's modulus in GPa. nu: float Poisson's ratio plane_stress: bool True for plane stress (default) or False for plane strain condition. Returns ...
7fb34149c7fc9b557ab162632884f605693aa823
29,418
def get_worker_bonus(job_id, worker_id, con=None): """ :param job_id: :param worker_id: :param con: """ bonus_row = _get_worker_bonus_row(job_id, worker_id, con) if bonus_row is None: return 0 return bonus_row["bonus_cents"]
2b58723f275f26c9208a36b650d75596a21354b2
29,419
def get_attribute_distribution(): """ Attribute weights based on position and prototype, in this order: [potential, confidence, iq, speed, strength, agility, awareness, stamina, injury, run_off, pass_off, special_off, run_def, pass_def, special_def] """ attr_dist = { 'QB': { ...
25dc83ba2f4bec4caaa88423e2607af300dcfbc4
29,420
def predict(product: Product): """Return ML predictions, see /docs for more information. Args: product: (Product) the parsed data from user request Returns: A dictionnary with the predicted nutrigrade and the related probability """ sample = { "energy": round(float(...
ca2456989b5cc82f56ed908c5d51471237c68d73
29,421
def get_stock_historicals(symbol, interval="5minute", span="week"): """Returns the historical data for a SYMBOL with data at every time INTERVAL over a given SPAN.""" assert span in ['day', 'week', 'month', '3month', 'year', '5year'] assert interval in ['5minute', '10minute', 'hour', 'day', 'week'] historicals = r...
62612a94e385c8c3703e42f2ace49d4a37d598ef
29,422
import re def re_match_both2( item, args ): """Matches a regex with a group (argument 2) against the column (number in argument 1)""" # setup (re_col1, re_expr1, re_col2, re_expr2 ) = args if re_expr1 not in compiled_res: compiled_res[re_expr1] = re.compile(re_expr1) if re_expr2 not in co...
13ac911e71324f54cde60f8c752603d21df98918
29,423
def at_least(actual_value, expected_value): """Assert that actual_value is at least expected_value.""" result = actual_value >= expected_value if result: return result else: raise AssertionError( "{!r} is LESS than {!r}".format(actual_value, expected_value) )
6897c863d64d1e4ce31e9b42df8aba04f1bbdd7a
29,424
import re import string def clean_text(text): """ Clean text : lower text + Remove '\n', '\r', URL, '’', numbers and double space + remove Punctuation Args: text (str) Return: text (str) """ text = str(text).lower() text = re.sub('\n', ' ', text) text = re.sub('\r', ' ', t...
2d9ddf56a9eeb1a037ec24a8907d3c85c9bbee43
29,425
import fnmatch def fnmatch_list(filename, pattern_list): """ Check filename against a list of patterns using fnmatch """ if type(pattern_list) != list: pattern_list = [pattern_list] for pattern in pattern_list: if fnmatch(filename, pattern): return True return False
72204c3168c0a97ad13134dcb395edf5e44e149f
29,426
def math_div_str(numerator, denominator, accuracy=0, no_div=False): """ 除法 :param numerator: 分子 :param denominator: 分母 :param accuracy: 小数点精度 :param no_div: 是否需要除。如3/5,True为3/5,False为1/1.6 :return: """ if denominator == 0 or numerator == 0: return 0 if abs(numerator) < ab...
bbcead0ec0f79d8915289b6e4ff23b0d6e4bf8ed
29,427
from datetime import datetime def create_comments(post): """ Helper to create remote comments. :param post: :return: """ comment_list = list() post = post.get('posts')[0] for c in post.get('comments'): comment = Comment() comment.author = create_author(c.get('author'))...
48bbad23a60efdd0ad47b2dfeb2e5b943a2743af
29,428
def zero_fuel(distance_to_pump, mpg, fuel_left): """ You were camping with your friends far away from home, but when it's time to go back, you realize that you fuel is running out and the nearest pump is 50 miles away! You know that on average, your car runs on about 25 miles per gallon. There are 2 gal...
67a69b59d6f35a872f87e18ee0e8693af886c386
29,429
import itertools def get_routing_matrix( lambda_2, lambda_1_1, lambda_1_2, mu_1, mu_2, num_of_servers_1, num_of_servers_2, system_capacity_1, system_capacity_2, buffer_capacity_1, buffer_capacity_2, routing_function=get_weighted_mean_blocking_difference_between_two_syst...
fad50cb2a160ba569788ea4f546eb4f0292d47c0
29,430
def astrange_to_symrange(astrange, arrays, arrname=None): """ Converts an AST range (array, [(start, end, skip)]) to a symbolic math range, using the obtained array sizes and resolved symbols. """ if arrname is not None: arrdesc = arrays[arrname] # If the array is a scalar, return None...
eca988aac1d0b69ad45907b4d3dd1c6be2e914b3
29,431
def get_union(*args): """Return unioin of multiple input lists. """ return list(set().union(*args))
18025cfd37d64f15daf92aa2ae3e81176cae6e39
29,432
def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup """ @wraps(func) def wrapped_f(self, *args, **kwargs): """ Returns result of _retrieve_data() func's return value is p...
8a2b441f42e26c69e39d1f22b7624350f3bef8b0
29,433
def specificity(y, z): """True negative rate `tn / (tn + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return tn / (tn + fp+pseudocount)
bf1c835072463e14420939ef56aade365863f559
29,434
def get_model_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ c1 = conn.cursor() new_stor_costs = c1.execut...
b77e4155f89ecae0b0bc5e2517aa05a4291f73b5
29,437
def pad_image(image, padding): """ Pad an image's canvas by the amount of padding while filling the padded area with a reflection of the data. :param image: Image to pad in either [H,W] or [H,W,3] :param padding: Amount of padding to add to the image :return: Padded image, padding uses reflection al...
ac797a201191c78a912f43908b214b3374de45d1
29,438
def delta_obj_size(object_image_size, model_image_size): """To compute the delta (scale b/w -inf and inf) value of object (width, height) from the image (width, height) using sigmoid (range [0, 1]). Since sigmoid transform the real input value between 0 and 1 thus allowing model to learn unconstrained. Paramet...
4ba5935a8b87391ba59623d5de5a86f40f35cacd
29,439
def get_relname_info(name): """ locates the name (row) in the release map defined above and returns that objects properties (columns) """ return RELEASES_BY_NAME[name]
538d564d6d0a67101fa84931fd7f7e69ac83f8b2
29,440
def swap(bee_permutation, n_bees): """Foraging stage using the swap mutation method. This function simulates the foraging stage of the algorithm. It takes the current bee permutation of a single bee and mutates the order using a swap mutation step. `n_bees` forager bees are created by swapping two uni...
4679ebe27cba51c095cd0ece3a4aabfcdb6531a8
29,441
def update_boundaries(x=None): """ This is the main processing code. Every time a slider on a trackbar moves this procedure is called as the callback """ # get current positions of four trackbars maxHSV[0] = cv2.getTrackbarPos('Hmax', 'image') maxHSV[1] = cv2.getTrackbarPos('Smax', 'image') ...
d484d242007f906f5cd707ee02d28c9cd580c844
29,442
def get_stream(stream_id, return_fields=None, ignore_exceptions=False): """This function retrieves the information on a single publication when supplied its ID. .. versionchanged:: 3.1.0 Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly. :param stream_id:...
14adff8dcff2bd89ace9a5ef642898e15b7eeaa7
29,443
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
ab44e7cbf67a050bdb08366ebe933cb62eb9b04c
29,444
def flatten_dict_join_keys(dct, join_symbol=" ", simplify_iterables=False): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :param simplify_iterables: each element of lists and ndarrays is represented as one key :return: """ ...
a133d1a621e4c1fa7ccce78576527a0cf212c0e3
29,445
import logging def prev_factor(target, current): """Given a target to factorise, find the next highest factor above current""" assert(current<=target) candidates = factors(target) if len(candidates) == 1: return 1 logging.info("Selecting previous factor %d of %d given %d" % (candidates[candidates.index(current...
8190d48ec210670adb8dd0c2d72b1738561191ae
29,446
def compute_weight_BTEL1010(true_energy, simtel_spectral_slope=-2.0): """Compute the weight from requirement B-TEL-1010-Intensity-Resolution. Parameters ---------- true_energy: array_like simtel_spectral_slope: float Spectral slope from the simulation. """ target_slope = -2.62 # sp...
64e126822dda2d6ece24cf95e4aef48a656ba4c6
29,447
def blog_post(post_url): """Render post of given url.""" post = Post.query.filter_by(url=post_url).first() if post is None: abort(404) timezone_diff = timedelta(hours=post.timezone) return render_template('blog_post.html', post=post, tz_diff=timezone_diff)
a87068d4fb6394b452b96b83465529681737fc31
29,448
def l2_normalization( inputs, scaling=False, scale_initializer=init_ops.ones_initializer(), reuse=None, variables_collections=None, outputs_collections=None, data_format='NHWC', trainable=True, scope=None): """Implement L2 normalization on ever...
b595699dcae6efd5c18fddc070905b1f41cc832b
29,449
def generate_com_filter(size_u, size_v): """ generate com base conv filter """ center_u = size_u // 2 center_v = size_v // 2 _filter = np.zeros((size_v, size_u, 2)) # 0 channel is for u, 1 channel is for v for i in range(size_v): for j in range(size_u): _filter[i, j, 0] =...
9797739b05724b104c932e07662278443e15eefb
29,450
from typing import List def retrieve_scores_grouped_ordered_pair_by_slug(panelist_slug: str, database_connection: mysql.connector.connect ) -> List[tuple]: """Returns an list of tuples containing a score and the c...
b8efd970a8adcbcbe6bdf8a737502ce174e01531
29,451
from datetime import datetime def set_job_id(): """Define job id for output paths. Returns: job_id: Identifier for output paths. """ job_id = FLAGS.job_id if not job_id: job_id = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') return job_id
974fa455de363a4c5f3fbcb598a3a002c00c2942
29,452
def is_owner(obj, user): """ Check if user is owner of the slice """ return obj and user in obj.owners
f0c49ffe8a8879d1d052f6fc37df596efa021a84
29,453
from typing import Dict from typing import List from typing import Optional def boxplot_errors_wrt_RUL( results_dict: Dict[str, List[PredictionResult]], nbins: int, y_axis_label: Optional[str] = None, x_axis_label: Optional[str] = None, ax=None, **kwargs, ): """Boxplots of difference betwe...
793f17df520c6474744b7d38055f717e9dfec287
29,454
def create_client(admin_user: str, key_file: str) -> CloudChannelServiceClient: """Creates the Channel Service API client Returns: The created Channel Service API client """ # [START channel_create_client] # Set up credentials with user impersonation credentials = service_account.Credent...
b1af051982ad737bdf66b609416c182e675d91f7
29,455
import string import random def password_generator(length=12, chars=None): """ Simple, naive password generator """ if not chars: chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(length))
e94754e8d8ee3cf806ddbe092033f8cbc89496f7
29,457
def get_node_hint(node): """Return the 'capabilities:node' hint associated with the node """ capabilities = node.get('properties').get('capabilities') capabilities_dict = capabilities_to_dict(capabilities) if 'node' in capabilities_dict: return capabilities_dict['node'] return None
8fb28b38238d5c59db5fd42336d18292f4214963
29,458
def execPregionsExactCP(y, w, p=2,rho='none', inst='none', conseq='none'): #EXPLICAR QUÉ ES EL P-REGIONS """P-regions model The p-regions model, devised by [Duque_Church_Middleton2009]_, clusters a set of geographic areas into p spatially contiguous regions while minimizing within cluster heterogeneit...
ea5d165918c6f203cf3cc42f9a1422a538ff133a
29,459
def generate_scale(name, octave, major=True): """ Generates a sequence of MIDI note numbers for a scale (do re mi fa sol la si do). `name` specifies the base note, `octave` specifies in which octave the scale should be, and `major` designates whether the produced scale should be major or minor. ...
8276101a3ec7ddd340f5fa2c24e13b9b321e4307
29,460
def tensor_product(a, b, reshape=True): """ compute the tensor protuct of two matrices a and b if a is (n, m_a), b is (n, m_b), then the result is (n, m_a * m_b) if reshape = True. or (n, m_a, m_b) otherwise Parameters --------- a : array-like of shape (n, m_a) b :...
f7891d1cffa19fb8bdfd2adaa23d2aa94367b8ab
29,461
def disable_user( request, username ): """ Enable/disable an user account. If the account is disabled, the user won't be able to login. """ userModel = get_user_model() try: user = userModel.objects.get( username= username ) except userModel.DoesNotExist: raise Http...
6500c053ee637cd47a4cec6feb7ec72001ccfb6a
29,462
from datetime import datetime def get_next_event(user: User) -> Event | None: """ Get event that provided user has next. """ current_time = datetime.datetime.now().hour*60 + datetime.datetime.now().minute return Event.query \ .join(Event.subject, aliased=True) \ .filter(Subject.use...
ac52bb2a5b0e9f368fccbf93d05fbcc6184462dd
29,463
import math def affineToText(matrix): """ Converts a libcv matrix into human readable text """ tiltv = matrix[0,0] * matrix[1,1] rotv = (matrix[0,1] - matrix[1,0]) / 2.0 if abs(tiltv) > 1: tilt = degrees(math.acos(1.0/tiltv)) else: tilt = degrees(math.acos(tiltv)) if tilt > 90.0: tilt = tilt - 180.0 if...
14a754d804d509b1029c00ae40fbef70735d072f
29,464
import numpy def createBridgeSets(blocksize,operating,MPSS): """Use this function to create the iidx sets for bridges.""" sets = tuple() xul = blocksize[0]-operating xdl = operating yul = int(blocksize[0]/2+operating) ydl = int(blocksize[0]/2-operating) xts = xul xbs = xdl for i in...
a97f44a44e00f4375c3aae0162edca5b78bcd5f1
29,465
def get_uniq_id_with_dur(meta, deci=3): """ Return basename with offset and end time labels """ bare_uniq_id = get_uniqname_from_filepath(meta['audio_filepath']) if meta['offset'] is None and meta['duration'] is None: return bare_uniq_id if meta['offset']: offset = str(int(round(...
62d93703a8b33bbc3e1a533aedac11fec8d59fb1
29,466
def delete(table, whereclause = None, **kwargs): """Return a ``DELETE`` clause element. This can also be called from a table directly via the table's ``delete()`` method. table The table to be updated. whereclause A ``ClauseElement`` describing the ``WHERE`` condition of the ``U...
49d6d98083d4dee0cf7dac62e30ddf90cd383955
29,467
import random import string def oversized_junk(): """ Return a string of random lowercase letters that is over 4096 bytes long. """ return "".join(random.choice(string.ascii_lowercase) for _ in range(4097))
a7bbaadde1948e1644f708c0166aa7833bb25037
29,468