content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def login(): """ login an existing user """ try: username = json.loads(request.data.decode())['username'].replace(" ", "") password = json.loads(request.data.decode())['password'].replace(" ", "") user = User(username, "", "") user = user.exists() i...
8e09725c37ac897efefd3cd546ce929cdf799716
3,656,978
def soma_radius(morph): """Get the radius of a morphology's soma.""" return morph.soma.radius
2f9991a2f9240965bdb69a1a14814ed99bf60f86
3,656,979
async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server.""" return AuthorizationServer( authorize_url=AUTHORIZATION_ENDPOINT, token_url=TOKEN_ENDPOINT, )
99d7c0d25168d07d0d27ee95e6ee0b59cb6d48c0
3,656,980
from typing import Optional def check_proposal_functions( model: Model, state: Optional[flow.SamplingState] = None, observed: Optional[dict] = None, ) -> bool: """ Check for the non-default proposal generation functions Parameters ---------- model : pymc4.Model Model to sample posteri...
3d0d14f800f3d499de0c823dd2df8b852573c56f
3,656,981
def smaller_n(n1, n2): """ Compare two N_Numbers and returns smaller one. """ p1, s1 = n1 p2, s2 = n2 p1l = len(str(p1)) + s1 p2l = len(str(p2)) + s2 if p1l < p2l: return n1 elif p1l > p2l: return n2 p1 = p1.ljust(36, '9') p2 = p2.ljust(36, '9') if p1 <= p2: ...
1f5922b74bdb8e5ee4dba7a85a9a70efdb024c59
3,656,982
def sortDict(dictionary: dict): """Lambdas made some cringe and stupid thing some times, so this dirty thing was developed""" sortedDictionary = {} keys = list(dictionary.keys()) keys.sort() for key in keys: sortedDictionary[key] = dictionary[key] return sortedDictionary
ed61adf95f2b8c1c4414f97d84b8863596681478
3,656,983
def elina_linexpr0_alloc(lin_discr, size): """ Allocate a linear expressions with coefficients by default of type ElinaScalar and c_double. If sparse representation, corresponding new dimensions are initialized with ELINA_DIM_MAX. Parameters ---------- lin_discr : c_uint Enum of typ...
56bbaa01ba3b9bbe657240abdf8fb92daa527f29
3,656,984
def FrameTag_get_tag(): """FrameTag_get_tag() -> std::string""" return _RMF.FrameTag_get_tag()
21392f22a0b67f86c5a3842ab6befc4b1e3938c6
3,656,985
def noise4(x: float, y: float, z: float, w: float) -> float: """ Generate 4D OpenSimplex noise from X,Y,Z,W coordinates. """ return _default.noise4(x, y, z, w)
75b5911e9b8b4a08abba9540992e812d2a1dee83
3,656,986
def damerau_levenshtein_distance(word1: str, word2: str) -> int: """Calculates the distance between two words.""" inf = len(word1) + len(word2) table = [[inf for _ in range(len(word1) + 2)] for _ in range(len(word2) + 2)] for i in range(1, len(word1) + 2): table[1][i] = i - 1 for i in range...
7b75bb94fe66897c1807ac185d8602ea2b3ebd67
3,656,987
from typing import Any def ga_validator(value: Any) -> str | int: """Validate that value is parsable as GroupAddress or InternalGroupAddress.""" if isinstance(value, (str, int)): try: parse_device_group_address(value) return value except CouldNotParseAddress: ...
84845c9dbf5db041e243bf462dec4533ff7e0e3e
3,656,988
import time import re from datetime import datetime def getTime(sim): """ Get the network time @param sim: the SIM serial handle """ sim.write(b'AT+CCLK?\n') line = sim.readline() res = None while not line.endswith(b'OK\r\n'): time.sleep(0.5) matcher = re.match(br'^\+C...
77c889a41b214046a5965126927ca7e7ee043129
3,656,989
import makehuman def defaultTargetLicense(): """ Default license for targets, shared for all targets that do not specify their own custom license, which is useful for saving storage space as this license is globally referenced by and applies to the majority of targets. """ return makehuman.get...
a638129f1674b14fbf0d72e5323c1725f6fb5035
3,656,990
import json def get_repo_info(main_path): """ Get the info of repo. Args: main_path: the file store location. Return: A json object. """ with open(main_path + '/repo_info.json') as read_file: repo_info = json.load(read_file) return repo_info
f4a538819add0a102f6cbe50be70f2c9a0f969b6
3,656,991
import yaml def parse_settings(settings_file: str) -> dict: """ The function parses settings file into dict Parameters ---------- settings_file : str File with the model settings, must be in yaml. Returns ------- ydict : dict Parsed settings used for m...
1aec2a8be51376209db81d60115814ddefca7ea6
3,656,992
def get_mac_address(path): """ input: path to the file with the location of the mac address output: A string containing a mac address Possible exceptions: FileNotFoundError - when the file is not found PermissionError - in the absence of access rights to the file TypeError - If t...
814a530b63896103adcb8fbc84d17939644b9bbe
3,656,993
def jwt_get_username_from_payload_handler(payload): """ Override this function if username is formatted differently in payload """ return payload.get('name')
92d60ce714632571346e93459729dcf1d764617b
3,656,994
import shlex def grr_uname(line): """Returns certain system infornamtion. Args: line: A string representing arguments passed to the magic command. Returns: String representing some system information. Raises: NoClientSelectedError: Client is not selected to perform this operation. """ args ...
5e671fcffe415397edc3b7c6011cc4e21b72cb5a
3,656,995
import requests import warnings def stock_szse_summary(date: str = "20200619") -> pd.DataFrame: """ 深证证券交易所-总貌-证券类别统计 http://www.szse.cn/market/overview/index.html :param date: 最近结束交易日 :type date: str :return: 证券类别统计 :rtype: pandas.DataFrame """ url = "http://www.szse.cn/api/report...
6544b0d78baa76858c13a001287b35d2a0faf7ba
3,656,996
def find_all_movies_shows(pms): # pragma: no cover """ Helper of get all the shows on a server. Args: func (callable): Run this function in a threadpool. Returns: List """ all_shows = [] for section in pms.library.sections(): if section.TYPE in ('movie', 'show'):...
ca4a8a5f4b2c1632ea6e427c748ef790c896b3ba
3,656,997
def parse_vars(vars): """ Transform a list of NAME=value environment variables into a dict """ retval = {} for var in vars: key, value = var.split("=", 1) retval[key] = value return retval
e2c6ae05cdf0151caaf8589eb7d7df90dcdd99a1
3,656,998
from typing import List import collections def find_dup_items(values: List) -> List: """Find duplicate items in a list Arguments: values {List} -- A list of items Returns: List -- A list of duplicated items """ dup = [t for t, c in collections.Counter(values).items() if c > 1] ...
3a84c2f3b723bed9b7a82dc5f0cfd81d99c2bf48
3,656,999
def circle_location_Pass(circle_, image_, margin=0.15): """ Function for check if the circle_ is overlapping with the margin of the image_. """ cy, cx, rad, accum = circle_ image_sizeY_, image_sizeX_ = image_.shape[0], image_.shape[1] margin_min_x = int(image_sizeX_ * margin) margin_max_...
4ad94552bc1bf06282a691edede89a65f8b9c328
3,657,000
def calculate_molecular_mass(symbols): """ Calculate the mass of a molecule. Parameters ---------- symbols : list A list of elements. Returns ------- mass : float The mass of the molecule """ mass = 0 for i in range(len(symbols)): mass =...
7ac18cffc02652428b51009d2bf304301def96dd
3,657,002
def _color_str(string, color): """Simple color formatter for logging formatter""" # For bold add 1; after "[" start_seq = '\033[{:d}m'.format(COLOR_DICT[color]) return start_seq + string + '\033[0m'
715b0b597885f1cffa352cc01bdb743c3ed23dd4
3,657,003
def parser_tool_main(args): """Main function for the **parser** tool. This method will parse a JSON formatted Facebook conversation, reports informations and retrieve data from it, depending on the arguments passed. Parameters ---------- args : Namespace (dict-like) Arguments passe...
1e07a60e78b042c6c229410e5d1aaf306e692f61
3,657,004
from functools import reduce def merge(from_args): """Merge a sequence of operations into a cross-product tree. from_args: A dictionary mapping a unique string id to a raco.algebra.Operation instance. Returns: a single raco.algebra.Operation instance and an opaque data structure suitable for pas...
e3690a26fc9e3e604984aab827617ffc535f63d3
3,657,005
def graph(task_id): """Return the graph.json results""" return get_file(task_id, "graph.json")
4d8728d3b61cf62057525054d8eafa127b1c48ff
3,657,007
def parse_components_from_aminochange(aminochange): """ Returns a dictionary containing (if possible) 'ref', 'pos', and 'alt' characteristics of the supplied aminochange string. If aminochange does not parse, returns None. :param aminochange: (str) describing amino acid change :return: dict or Non...
69877d635b58bdc3a8a7f64c3c3d86f59a7c7548
3,657,008
import random import string import csv def get_logs_csv(): """ get target's logs through the API in JSON type Returns: an array with JSON events """ api_key_is_valid(app, flask_request) target = get_value(flask_request, "target") data = logs_to_report_json(target) keys = data[...
f9296cfc7c6559ebccbfa29268e3b22875fb9fed
3,657,009
def _cache_key_format(lang_code, request_path, qs_hash=None): """ função que retorna o string que será a chave no cache. formata o string usando os parâmetros da função: - lang_code: código do idioma: [pt_BR|es|en] - request_path: o path do request - qs_hash: o hash gerado a partir dos parametro...
365b1ff144f802e024da5d6d5b25b015463da8b3
3,657,010
from typing import Iterable from pathlib import Path from typing import Callable from typing import Any from typing import List def select_from(paths: Iterable[Path], filter_func: Callable[[Any], bool] = default_filter, transform: Callable[[Path], Any] = None, order_fun...
d952d7d81932c5f6d206c39a5ac12aae1e940431
3,657,011
import torch from typing import Counter def dbscan(data:torch.Tensor, epsilon:float, **kwargs) -> torch.Tensor: """ Generate mask using DBSCAN. Note, data in the largest cluster have True values. Parameters ---------- data: torch.Tensor input data with shape (n_samples, n_features) ...
0121b8b9dceaf9fc8399ffd75667afa6d34f66e1
3,657,012
import copy def simulate_multivariate_ts(mu, alpha, beta, num_of_nodes=-1,\ Thorizon = 60, seed=None, output_rejected_data=False): """ Inputs: mu: baseline intesnities M X 1 array alpha: excitiation rates of multivariate kernel pf HP M X M array beta: decay rates of kernel of multivariate HP ...
85ab71fa3f2b16cbe296d21d6bc43c15c94aa40a
3,657,013
import base64 def token_urlsafe(nbytes): """Return a random URL-safe text string, in Base64 encoding. The string has *nbytes* random bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_urlsafe(16) #doctest:+SKIP 'Drmhze6EPcv0fN_81Bj-nA' """ tok = to...
1855dc44cec1ddd0c6c83d0f765c15fd98d1ec98
3,657,014
def sha206a_get_pk_useflag_count(pk_avail_count): """ calculates available Parent Key use counts Args: pk_avail_count counts available bit's as 1 (int) Returns: Status Code """ if not isinstance(pk_avail_count, AtcaReference): status = Status.ATCA_BAD_PARAM e...
389174a21efe1ca78037b479895035b4bdd66b87
3,657,015
from typing import Tuple def rotate_points_around_origin( x: tf.Tensor, y: tf.Tensor, angle: tf.Tensor, ) -> Tuple[tf.Tensor, tf.Tensor]: """Rotates points around the origin. Args: x: Tensor of shape [batch_size, ...]. y: Tensor of shape [batch_size, ...]. angle: Tensor of shape [batch_si...
8d4bf5f94964271f640def7d7e2b4242fbfe8e7b
3,657,016
import inspect def form_of(state): """Return the form of the given state.""" if hasattr(state, "__form__"): if callable(state.__form__) and not inspect.isclass(state.__form__): return state.__form__() else: return state.__form__ else: raise ValueError(f"{st...
e39aa7db7b324ab38b65232b34b987b862812c54
3,657,017
def poly_to_geopandas(polys, columns): """ Converts a GeoViews Paths or Polygons type to a geopandas dataframe. Parameters ---------- polys : gv.Path or gv.Polygons GeoViews element columns: list(str) List of columns Returns ------- gdf : Geopandas dataframe ""...
889fc5b1bf5bf15cd9612c40e7bf14b1c05043f6
3,657,018
def get_sequences(query_file=None, query_ids=None): """Convenience function to get dictionary of query sequences from file or IDs. Parameters: query_file (str): Path to FASTA file containing query protein sequences. query_ids (list): NCBI sequence accessions. Raises: ValueError: Did...
8056ce1c98b7a4faa4bb5a02505d527df31c7c8b
3,657,019
def random_show_date(database_connection: mysql.connector.connect) -> str: """Return a random show date from the ww_shows table""" database_connection.reconnect() cursor = database_connection.cursor(dictionary=True) query = ("SELECT s.showdate FROM ww_shows s " "WHERE s.showdate <= NOW() "...
e3afdf9aa1fe9a02adab72c424caa80d60280699
3,657,021
def get_output_tensor(interpreter, index): """Returns the output tensor at the given index.""" output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details["index"])) return tensor
158db3fc7ba13ee44d422248a9b96b7738a486e3
3,657,022
def make_d_mappings(n_dir, chain_opts): """Generate direction to solution interval mapping.""" # Get direction dependence for all terms. dd_terms = [dd for _, dd in yield_from(chain_opts, "direction_dependent")] # Generate a mapping between model directions gain directions. d_map_arr = (np.arange(...
fd9eddf81b4388e3fa40c9b65a591af9aabf9014
3,657,023
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV): """ Function to calculate the volumes of a cell intersecting a mesh. Uses a boolean polydata filter to calculate the intersection, a general implementation but slow. """ # Triangulate polygon and calc normals baseC = vtkTools.datas...
a2c30133973527fb339c9d1e33cc2a937b35d958
3,657,025
def WebChecks(input_api, output_api): """Run checks on the web/ directory.""" if input_api.is_committing: error_type = output_api.PresubmitError else: error_type = output_api.PresubmitPromptWarning output = [] output += input_api.RunTests([input_api.Command( name='web presubmit', cmd=[ ...
5fb828cc98da71bd231423223336ec81e02505ff
3,657,026
from HUGS.Util import load_hugs_json def synonyms(species: str) -> str: """ Check to see if there are other names that we should be using for a particular input. E.g. If CFC-11 or CFC11 was input, go on to use cfc-11, as this is used in species_info.json Args: species (str): Input string ...
31013464ce728cc3ed93b1a9318af3dbcf3f65ec
3,657,027
def _blkid_output(out): """ Parse blkid output. """ flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split("\n\n")): dev = {} for items in flt(dev_meta.strip().split("\n")): key, val = items.split("=", 1) dev[key.lower...
2cbcbb3ec9b732c3c02183f43ca5a5d5e876af71
3,657,028
def as_iso_datetime(qdatetime): """ Convert a QDateTime object into an iso datetime string. """ return qdatetime.toString(Qt.ISODate)
8dba5d1d6efc0dc17adc26a5687923e067ca3c29
3,657,029
def spec_means_and_magnitudes(action_spec): """Get the center and magnitude of the ranges in action spec.""" action_means = tf.nest.map_structure( lambda spec: (spec.maximum + spec.minimum) / 2.0, action_spec) action_magnitudes = tf.nest.map_structure( lambda spec: (spec.maximum - spec.minimum) / 2.0,...
119054966a483bb60e80941a6bf9dc5a4a0778f6
3,657,030
def clean_data(df): """ Clean Data : 1. Clean and Transform Category Columns from categories csv 2.Drop Duplicates 3.Remove any missing values Args: INPUT - df - merged Dataframe from load_data function OUTPUT - Returns df - cleaned Dataframe """ # Split categories into...
752d675d8ac5e27c61c9b8c90acee4cdab8c08fc
3,657,031
def all_pairs_shortest_path_length(G,cutoff=None): """ Compute the shortest path lengths between all nodes in G. Parameters ---------- G : NetworkX graph cutoff : integer, optional depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- lengths :...
1d312a71bd97d4f1a51a8b1e24331d54055bc156
3,657,033
def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None): """ Figure out based on the possible columns inputs which columns to keep. Args: gctoo (GCToo object): cid (list of strings): col_bool (boolean array): cidx (list of integers): exclude_cid...
1215a392ecb068e2d004c64cf56f2483c722f3f6
3,657,034
import shutil def check_zenity(): """ Check if zenity is installed """ warning = '''zenity was not found in your $PATH Installation is recommended because zenity is used to indicate that protonfixes is doing work while waiting for a game to launch. To install zenity use your system's package ...
decea9be11e0eb1d866ed295cb33a06aa663a432
3,657,035
def get_auth_token(): """ Return the zerotier auth token for accessing its API. """ with open("/var/snap/zerotier-one/common/authtoken.secret", "r") as source: return source.read().strip()
bd74fde05fbb375f8899d4e5d552ad84bcd80573
3,657,036
def sph_harm_transform(f, mode='DH', harmonics=None): """ Project spherical function into the spherical harmonics basis. """ assert f.shape[0] == f.shape[1] if isinstance(f, tf.Tensor): sumfun = tf.reduce_sum def conjfun(x): return tf.conj(x) n = f.shape[0].value else: s...
a88f9a71fa19a57441fdfe88e8b0632cc08fb413
3,657,037
def create_model(experiment_settings:ExperimentSettings) -> OuterModel: """ function creates an OuterModel with provided settings. Args: inner_settings: an instannce of InnerModelSettings outer_settings: an instannce of OuterModelSettings """ model = OuterModel(experiment_settings.ou...
e6af03c5afd53a39e6929dba71990f91ff8ffbb3
3,657,038
import pickle def LoadTrainingTime(stateNum): """ Load the number of seconds spent training """ filename = 'time_' + str(stateNum) + '.pth' try: timeVals = pickle.load( open(GetModelPath() + filename, "rb")) return timeVals["trainingTime"] except: print("ERROR: Faile...
1db59103bf3e31360237951241b90b3a85dae2bc
3,657,039
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 15 epochs""" lr = args.lr * (0.1 ** (epoch // args.lr_epochs)) print('Learning rate:', lr) for param_group in optimizer.param_groups: if args.retrain and ('mask' in param_group['key']): # ...
dc08034b0176ac0062d6fc7640a115f916a663a8
3,657,040
def disk_status(hardware, disk, dgtype): """ Status disk """ value = int(float(disk['used']) / float(disk['total']) * 100.0) if value >= 90: level = DiagnosticStatus.ERROR elif value >= 70: level = DiagnosticStatus.WARN else: level = DiagnosticStatus.OK # Make boa...
f248ccb0ba07106c3ed923f9ac7bc2e85d9b5e63
3,657,041
def hr_admin(request): """ Views for HR2 Admin page """ user = request.user # extra_info = ExtraInfo.objects.select_related().get(user=user) designat = HoldsDesignation.objects.select_related().get(user=user) if designat.designation.name =='hradmin': template = 'hr2Module/hradmin.h...
1b2c1027f8f4caf716019d9e5500223f76119a0b
3,657,042
import six def test_extra(): """Returns dict of extrapolation testing modules.""" return {name: module.test_extra() for name, module in six.iteritems(all_)}
5538f81891c0388ae0f5e312cb6c521ee19d18a5
3,657,043
import torch def _switch_component( x: torch.Tensor, ones: torch.Tensor, zeros: torch.Tensor ) -> torch.Tensor: """ Basic component of switching functions. Args: x (torch.Tensor): Switch functions. ones (torch.Tensor): Tensor with ones. zeros (torch.Tensor): Zero tensor R...
8d60c09428440be704e8ced9b8ac19219a0d0b04
3,657,044
def get_vector(x_array, y_array, pair): """This function is for calculating a vector of a bone from the openpose skelleton""" x = x_array[:,pair[0]]-x_array[:,pair[1]] y = y_array[:,pair[0]]-y_array[:,pair[1]] return [x, y]
e2bfcce3952c6b0a2c8cd9c67c4cd7b52547694d
3,657,045
def update_bar(tweets_json, handle): """ Pull data from signal and updates aggregate bar graph This is using thresholds that combine toxicity and severe toxicity models suggested by Lucas. """ if not tweets_json: raise PreventUpdate('no data yet!') tweets_df = pd.read_json(tweets_j...
1c523a455393ce211b8ef6483ee25b981e028bd0
3,657,046
from typing import List from typing import Dict def render_foreign_derivation(tpl: str, parts: List[str], data: Dict[str, str]) -> str: """ >>> render_foreign_derivation("bor", ["en", "ar", "الْعِرَاق", "", "Iraq"], defaultdict(str)) 'Arabic <i>الْعِرَاق</i> (<i>ālʿrāq</i>, “Iraq”)' >>> render_foreign...
af3c37664e683d9bff610ad1fa53a167f5390988
3,657,048
def create_from_ray(ray): """Converts a ray to a line. The line will extend from 'ray origin -> ray origin + ray direction'. :param numpy.array ray: The ray to convert. :rtype: numpy.array :return: A line beginning at the ray start and extending for 1 unit in the direction of the ray. ...
6d0429abbacd235f95636369985bea8a17117409
3,657,049
def opts2dict(opts): """Converts options returned from an OptionParser into a dict""" ret = {} for k in dir(opts): if callable(getattr(opts, k)): continue if k.startswith('_'): continue ret[k] = getattr(opts, k) return ret
cfa828f0248ff7565aabbb5c37a7bc6fa38c6450
3,657,052
def combined_directions(a_list, b_list): """ Takes two NoteList objects. Returns a list of (3)tuples each of the form: ( int: a dir, int: b dir, (int: bar #, float: beat #) ) """ onsets = note_onsets(a_list, b_list) a_dirs = directions(a_list) b_dirs = directi...
8b66d4de725c51b1abdedb8a8e4c48e78f4ca953
3,657,053
def _naive_csh_seismology(l, m, theta, phi): """ Compute the spherical harmonics according to the seismology convention, in a naive way. This appears to be equal to the sph_harm function in scipy.special. """ return (lpmv(m, l, np.cos(theta)) * np.exp(1j * m * phi) * np.sqrt(((2 * l + 1)...
ba2a17f0dfa6035a05d16c8af79310657fe6ecd7
3,657,054
def is_room_valid(room): """Check if room is valid.""" _, names, checksum = room letters = defaultdict(int) complete_name = ''.join(names) for letter in complete_name: letters[letter] += 1 sorted_alphabetic = sorted(letters) sorted_by_occurrences = sorted( sorted_alphabetic, ...
b893cf97ee28b033741e4b2797b2a4aef485324f
3,657,055
def _mag_shrink_hard(x, r, t): """ x is the input, r is the magnitude and t is the threshold """ gain = (r >= t).float() return x * gain
da795bcfc2a6e4bfa3e54d1334c9d8865141a4f1
3,657,057
def wiki_data(request, pro_id): """ 文章标题展示 """ data = models.Wiki.objects.filter(project_id=pro_id).values('id', 'title', 'parent_id').order_by('deepth') return JsonResponse({'status': True, 'data': list(data)})
6dfbb79b78133935356bd87cc24a294ed0001b73
3,657,059
def many_capitalized_words(s): """Returns a function to check percentage of capitalized words. The function returns 1 if percentage greater then 65% and 0 otherwise. """ return 1 if capitalized_words_percent(s) > 66 else 0
cc82a2708defd545a1170bfeabb5848e3092fc39
3,657,061
def cmd_te_solution_build(abs_filename,wait=False,print_output=False,clear_output=False): """ソリューションをビルドする(テキストエディタ向け) ファイルが含まれるVisual Studioを探し出してソリューションをビルドする。 VisualStudioの「メニュー -> ビルド -> ソリューションのビルド」と同じ動作。 abs_filename- ファイル名の絶対パス (Ex.) c:/project/my_app/src/main.cpp ...
db48988d483da6ae9a012460e0d5fdd326d5ae40
3,657,062
def log_ratio_measure( segmented_topics, accumulator, normalize=False, with_std=False, with_support=False): """ If normalize=False: Popularly known as PMI. This function calculates the log-ratio-measure which is used by coherence measures such as c_v. This is defined as: ...
73fec59f84402066ccbbcd25d30cc69698f6b721
3,657,063
def _calculate_monthly_anomaly(data, apply_filter=False, base_period=None, lat_name=None, lon_name=None, time_name=None): """Calculate monthly anomalies at each grid point.""" # Ensure that the data provided is a data array data = rdu.ensure_data_array(data) # Get coordi...
397bffb8f22ae26cf2c41cd8c056951ef55d692d
3,657,064
import pprint def oxe_system_alaw_to_mulaw(host, token, mode): """Summary Args: host (TYPE): Description token (TYPE): Description mode (TYPE): Description Returns: TYPE: Description """ payload = { 'T0_Mu_Law': mode } packages.urllib3.disa...
19bb98f8326e84cde83691028a2fc2585a7abe6e
3,657,067
def update_weights(comment_weights, comment_usage): """Updates the weights used to upvote comments so that the actual voting power usage is equal to the estimated usage. """ desired_usage = 1.0 - VP_COMMENTS / 100.0 actual_usage = 1.0 - comment_usage / 100.0 scaler = np.log(desired_usage) / np.l...
19d2f0a9ec790c26000946c0b91ef3bc00f36905
3,657,068
import math def smaller2k(n): """ Returns power of 2 which is smaller than n. Handles negative numbers. """ if n == 0: return 0 if n < 0: return -2**math.ceil(math.log2(-n)) else: return 2**math.floor(math.log2(n))
0d0bbbf95cb22bf1b9ffb29012075534bcc9646d
3,657,069
import opcode def modeify(intcode, i): """Apply a mode to a parameter""" j = i + 1 _opcode = opcode(intcode[i]) params = intcode[j: j + _opcode['param_count']] modes = _opcode['modes'] mode_covert = { 0: lambda x: intcode[x], # position mode 1: lambda x: x ...
230fb2e43c33558d94a7d60c6dd16978098421aa
3,657,072
def unwind(g, num): """Return <num> first elements from iterator <g> as array.""" return [next(g) for _ in range(num)]
59b724ca27729b4fc20d19a40f95d590025307c4
3,657,073
import re def CPPComments(text): """Remove all C-comments and replace with C++ comments.""" # Keep the copyright header style. line_list = text.splitlines(True) copyright_list = line_list[0:10] code_list = line_list[10:] copy_text = ''.join(copyright_list) code_text = ''.join(code_list) # Remove */ ...
0dd490f5497c073534abc30944bd49d0a3cf7e3e
3,657,075
def get_bulk_statement( stmt_type, table_name, column_names, dicts=True, value_string="%s", odku=False ): """Get a SQL statement suitable for use with bulk execute functions Parameters ---------- stmt_type : str One of REPLACE, INSERT, or INSERT IGNORE. **Note:** Backend support for ...
ba2277fc6f84d79a97d70cf98d2e26f308b8fa82
3,657,076
def map_remove_by_value_range(bin_name, value_start, value_end, return_type, inverted=False): """Creates a map_remove_by_value_range operation to be used with operate or operate_ordered The operation removes items, with values between value_start(inclusive) and value_end(exclusive) from the map Args: ...
42a49aefb92f61a3064e532390bdcf26b6266f40
3,657,077
def rationalApproximation(points, N, tol=1e-3, lowest_order_only=True): """ Return rational approximations for a set of 2D points. For a set of points :math:`(x,y)` where :math:`0 < x,y \\leq1`, return all possible rational approximations :math:`(a,b,c) \\; a,b,c \\in \\mathbb{Z}` such that :math:`...
614c230ad7fd68cb60d0203cba2bd15e30f3f36a
3,657,078
def to_dict(doc, fields): """Warning: Using this convenience fn is probably not as efficient as the plain old manually building up a dict. """ def map_field(prop): val = getattr(doc, prop) if isinstance(val, list): return [(e.to_dict() if hasattr(e, 'to_dict') else e) for e i...
cb51e3dfdf8c313f218e38d8693af9e7c6bf5045
3,657,080
import time def _auto_wrap_external(real_env_creator): """Wrap an environment in the ExternalEnv interface if needed. Args: real_env_creator (fn): Create an env given the env_config. """ def wrapped_creator(env_config): real_env = real_env_creator(env_config) if not isinstanc...
ef7f0c7ecdf3eea61a4e9dc0ad709e80d8a09e08
3,657,081
def _get_binary_link_deps( base_path, name, linker_flags = (), allocator = "malloc", default_deps = True): """ Return a list of dependencies that should apply to *all* binary rules that link C/C++ code. This also creates a sanitizer configuration rule if necessary, s...
06a52934a0c121b606c79a6f5ae58863645bba34
3,657,082
def double2pointerToArray(ptr, n, m_sizes): """ Converts ctypes 2D array into a 2D numpy array. Arguments: ptr: [ctypes double pointer] n: [int] number of cameras m_sizes: [list] number of measurements for each camera Return: arr_list: [list of ndarrays] list of numpy ...
f556c5a36f645c6047c3b487b7cd865edc3b76db
3,657,084
def read_varint(stream: bytes): """ 读取 varint。 Args: stream (bytes): 字节流。 Returns: tuple[int, int],真实值和占用长度。 """ value = 0 position = 0 shift = 0 while True: if position >= len(stream): break byte = stream[position] value += (byte...
58c8187501dc08b37f777256474f95412649bf04
3,657,085
def any(array, mapFunc): """ Checks if any of the elements of array returns true, when applied on a function that returns a boolean. :param array: The array that will be checked, for if any of the elements returns true, when applied on the function. \t :type array: [mixed] \n :param mapFunc: The fun...
1e635da691fd1c2fc9d99e15fd7fa0461a7bdf0e
3,657,087
def qt_point_to_point(qt_point, unit=None): """Create a Point from a QPoint or QPointF Args: qt_point (QPoint or QPointF): The source point unit (Unit): An optional unit to convert values to in the output `Point`. If omitted, values in the output `Point` will be plain `i...
595dacc2d39d126822bf680e1ed1784c05deb6d7
3,657,088
import requests import json def apiRequest(method, payload=None): """ Get request from vk server :param get: method for vkApi :param payload: parameters for vkApi :return: answer from vkApi """ if payload is None: payload = {} if not ('access_token' in payload): pay...
b60c77aec5ae500b9d5e9901216c7ff7c93676ad
3,657,089
def page_required_no_auth(f): """Full page, requires user to be logged out to access, otherwise redirects to main page.""" @wraps(f) def wrapper(*args, **kwargs): if "username" in session: return redirect("/") else: return f(*args, **kwargs) return wrapper
7d7d314e10dcaf1d81ca5c713afd3da6a021247d
3,657,090
import sympy def generate_forward(): """ Generate dataset with forward method It tries to integrate random function. The integral may not be symbolically possible, or may contains invalid operators. In those cases, it returns None. """ formula = symbolic.fixed_init(15) integrated = sympy.integrate(fo...
91a91e5b23f3f59b49d8f7102585ff7fbfbbf6c4
3,657,092
import pickle def load_agent(agent_args, domain_settings, experiment_settings): """ This function loads the agent from the results directory results/env_name/method_name/filename Args: experiment_settings Return: sarsa_lambda agent """ with open('results...
a5769c952d9fcc583b8fb909e6e772c83b7126ca
3,657,093
def unpickle_robust(bytestr): """ robust unpickle of one byte string """ fin = BytesIO(bytestr) unpickler = robust_unpickler(fin) return unpickler.load()
42fee03886b36aef5ab517e0abcb2cc2ecfd6a8b
3,657,094
def build_ins_embed_branch(cfg, input_shape): """ Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME`. """ name = cfg.MODEL.INS_EMBED_HEAD.NAME return INS_EMBED_BRANCHES_REGISTRY.get(name)(cfg, input_shape)
4d8242614426a13f9e93a241184bd3d8f57ef648
3,657,095
def atl03sp(ipx_region, parm, asset=icesat2.DEFAULT_ASSET): """ Performs ATL03 subsetting in parallel on ATL03 data and returns photon segment data. See the `atl03sp <../api_reference/icesat2.html#atl03sp>`_ function for more details. Parameters ---------- ipx_region: Query ...
8c822af0d2f9b6e42bd6a1efeb29249a04079e66
3,657,096
def get_sample_activity_from_batch(activity_batch, idx=0): """Return layer activity for sample ``idx`` of an ``activity_batch``. """ return [(layer_act[0][idx], layer_act[1]) for layer_act in activity_batch]
0302fdf215e63d6cbcd5dafc1bd36ae3d27712f2
3,657,097