content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_vertices_intrinsics(disparity, intrinsics): """3D mesh vertices from a given disparity and intrinsics. Args: disparity: [B, H, W] inverse depth intrinsics: [B, 4] reference intrinsics Returns: [B, L, H*W, 3] vertex coordinates. """ # Focal lengths fx = intrinsics[:, 0] fy = int...
d476767c71fb1a8cefe121a3aaf8cbf9a19e7943
16,000
def _find_smart_path(challbs, preferences, combinations): """Find challenge path with server hints. Can be called if combinations is included. Function uses a simple ranking system to choose the combo with the lowest cost. """ chall_cost = {} max_cost = 1 for i, chall_cls in enumerate(pref...
96f55288bfa08de32badd9f1a96b3decd76573c8
16,001
def run_generator_and_test(test_case, mlmd_connection, generator_class, pipeline, task_queue, use_task_queue, service_job_manager, ...
c7f03b5db9f100c8c5eec029e843ce4ab1cdb84e
16,002
def sort_func(kd1, kd2): """ Compares 2 key descriptions :param kd1: First key description :param kd2: Second key description :return: -1,0,1 depending on whether kd1 le,eq or gt then kd2 """ _c = type_order(kd1, kd2) if _c is not None: return _c return kid_order(kd1, kd2)
2ac9100f9c69c283266cc4ba4f6d6262551ce1b5
16,003
def sumdigits(a: int): """Sum of the digits of an integer""" return sum(map(int, str(a)))
018bcc429e6ea3842fd9e9e2580820aed29bc0aa
16,004
from datetime import datetime def nth_weekday_of_month(y, m, n, w): """ y = 2020; m = 2 assert nth_weekday_of_month(y, m, -1, 'sat') == dt(2020, 2, 29) assert nth_weekday_of_month(y, m, -2, 'sat') == dt(2020, 2, 22) assert nth_weekday_of_month(y, m, 1, 'sat') == dt(2020, 2, 1) assert nth_weekd...
2f422b3fac4d97db64f541b54158248c44afad14
16,005
def getBits(val, hiIdx: int, loIdx: int) -> int: """Returns a bit slice of a value. Args: val: Original value. hiIdx: Upper (high) index of slice. loIdx: Lower index of slice. Returns: The bit slice. """ return (~(MASK_32<<(hiIdx-loIdx+1)) & (val>>loIdx))
acaf1a36fceb12ee99140aca0769dde084ee08d6
16,006
def get_hostname(): """Returns the hostname, from /etc/hostname.""" hostname = "" try: with open('/etc/hostname') as f: hostname = f.read().rstrip() if len(hostname) == 0: hostname = "Unknown" except: hostname = "Unknown" return hostname
4cd4ffc1c8c56bc2e440443fdbc315d27fb94033
16,007
def is_valid_body(val): """Body must be a dictionary.""" return isinstance(val, dict)
ef3a605e1e84ce9d74f77c07799d1abb58aaf61a
16,008
def _vba_to_python_op(op, is_boolean): """ Convert a VBA boolean operator to a Python boolean operator. """ op_map = { "Not" : "not", "And" : "and", "AndAlso" : "and", "Or" : "or", "OrElse" : "or", "Eqv" : "|eq|", "=" : "|eq|", ">" : ">", ...
a6ed0c65c6c2d2635f14fb664540eaf283ee4065
16,009
def file_diff_format(filename1, filename2): """ Inputs: filename1 - name of first file filename2 - name of second file Output: Returns a four line string showing the location of the first difference between the two files named by the inputs. If the files are identical, the fun...
c2027767ac6694620d895ef1565a03e7b706c2e7
16,010
import six def _check_assembly_string(base_asm, instr_type, target, operands): """ :param base_asm: :type base_asm: :param instr_type: :type instr_type: :param target: :type target: :param operands: :type operands: """ LOG.debug("Start checking assembly string: %s", base_...
64e6e812d037c6e9576ee5db0c3d06468a7b6414
16,011
def get_label_number(window): """This method assigns to each label of a window a number.""" mode_list = ["bike", "car", "walk", "bus", "train"] current_label_number = 0 for mode in enumerate(mode_list): if window[1] == mode[1]: current_label_number = mode[0] return current_labe...
5ed3c683e8619e1b07857992f54079bc68fdfa58
16,012
def midi_array_to_event(midi_as_array): """ Take converted MIDI array and convert to array of Event objects """ # Sort MIDI array midi = sorted(midi_as_array, key=itemgetter(2)) # Init result result = [] # Accumulators for computing start and end times active_notes = [] curr_time = 0 # For comparing velociti...
63391a1fa045f2185ce22c3ab5da186169d445e7
16,013
from typing import Dict from typing import Type def find_benchmarks(module) -> Dict[str, Type[Benchmark]]: """Enumerate benchmarks in `module`.""" found = {} for name in module.__all__: benchmark_type = getattr(module, name) found[benchmark_type.name] = benchmark_type return found
4b456a44963629da0b6072dcb9e6e8946cbaef23
16,014
def out_folder_android_armv8_clang(ctx, section_name, option_name, value): """ Configure output folder for Android ARMv8 Clang """ if not _is_user_input_allowed(ctx, option_name, value): Logs.info('\nUser Input disabled.\nUsing default value "%s" for option: "%s"' % (value, option_name)) return ...
b713642879cfcffe78fc415adbbea7c13c319925
16,015
import copy import json import os def remap_classes(dataset, class_map): """ Replaces classes of dataset based on a dictionary""" class_new_names = list(set(class_map.values())) class_new_names.sort() # NOTE sort() is a NoneType return method, it sorts the list without outputting new vars class_origin...
fd3c971221a102f296c76f72d6296ebf0a0e4763
16,016
def MCTS(root, verbose = False): """initialization of the chemical trees and grammar trees""" run_time=time.time()+600*2 rootnode = Node(state = root) state = root.Clone() maxnum=0 iteration_num=0 start_time=time.time() """----------------------------------------------------------------...
686a412c0f4cc4cd81d96872e9929d1ce51e7ed8
16,017
def update_internalnodes_MRTKStandard() -> bpy.types.NodeGroup: """定義中のノードグループの内部ノードを更新する Returns: bpy.types.NodeGroup: 作成ノードグループの参照 """ # データ内に既にMRTKStandardのノードグループが定義されているか確認する # (get関数は対象が存在しない場合 None が返る) get_nodegroup = bpy.data.node_groups.get(def_nodegroup_name) # ノードグ...
14d152377b58de842ff6cc228e80fbb0c48c5128
16,018
def _ensure_consistent_schema( frame: SparkDF, schemas_df: pd.DataFrame, ) -> SparkDF: """Ensure the dataframe is consistent with the schema. If there are column data type mismatches, (more than one data type for a column name in the column schemas) then will try to convert the data type if pos...
653f2740fa2ba090c1a1ace71b09523848d52be7
16,019
def shave_bd(img, bd): """ Shave border area of spatial views. A common operation in SR. :param img: :param bd: :return: """ return img[bd:-bd, bd:-bd, :]
4b822c5e57787edb74955fd350ad361080b8640b
16,020
import os def get_raw_dir(args): """ Archived function. Ignore this for now """ root = "C:\\Workspace\\FakeNews" if os.name == "posix": root = '..' path = osp.join(root, "Demo", "data", f"{args.dataset}", "raw") return path
34e1f9277bac24e3dc6938b7bf854e7fd018ee41
16,021
def plotly_single(ma, average_type, color, label, plot_type='line'): """A plotly version of plot_single. Returns a list of traces""" summary = list(np.ma.__getattribute__(average_type)(ma, axis=0)) x = list(np.arange(len(summary))) if isinstance(color, str): color = list(matplotlib.colors.to_rgb...
b568d0e4496fc424aa5b07ff90bf45880a374d56
16,022
from pathlib import Path def create_task(className, *args, projectDirectory='.', dryrun=None, force=None, source=False): """Generates task class from the parameters derived from :class:`.Task` Fails if the target file already exists unless ``force=True`` or ``--force`` in the CLI is set. Setting the ``-...
028e751a43930e167f000d5ff0d0c76d1340cec4
16,023
def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i i...
d65e0dfef94060db243de2a3a4f162aa01e12537
16,024
def __resolve_key(key: Handle) -> PyHKEY: """ Returns the full path to the key >>> # Setup >>> fake_registry = fake_reg_tools.get_minimal_windows_testregistry() >>> load_fake_registry(fake_registry) >>> # Connect registry and get PyHkey Type >>> reg_handle = ConnectRegistry(None, HKEY_CURR...
70344ac3b068793a0c40e4151fb210c269dba743
16,025
def vec3f_unitZ(): """vec3f_unitZ() -> vec3f""" return _libvncxx.vec3f_unitZ()
dd0b6e28333a8d72918113b0f5caf788fb51bd43
16,026
import os def _BotNames(source_config, full_mode=False): """Returns try bot names to use for the given config file name.""" platform = os.path.basename(source_config).split('.')[0] assert platform in PLATFORM_BOT_MAP bot_names = PLATFORM_BOT_MAP[platform] if full_mode: return bot_names return [bot_nam...
c514e2534d57ce5867b72e3cfd182854e99c1bf6
16,027
def get_public_key(public_key_path=None, private_key_path=None): """get_public_key. Loads public key. If no path is specified, loads signing_key.pem.pub from the current directory. If a private key path is provided, the public key path is ignored and the public key is loaded from the private key. ...
f37bb64e9a0971c77986b6c82b8519153f3f8eaa
16,028
def InitializeState(binaryString): """ State initializer """ state = np.zeros(shape=(4, 4), dtype=np.uint8) plaintextBytes = SplitByN(binaryString, 8) for col in range(4): for row in range(4): binary = plaintextBytes[col * 4 + row] state[row, col] = int(binary, 2)...
b8de68bba8837865f9e74c43be1b6144774d69ad
16,029
from typing import Dict from typing import Any def _apply_modifier(s: str, modifier: str, d: Dict[Any, str]) -> str: """ This will search for the ^ signs and replace the next digit or (digits when {} is used) with its/their uppercase representation. :param s: Latex string code :param modifier: Mo...
c54a2c66ff6ee768e588b14472fa5707edf9bc56
16,030
import concurrent def threaded_polling(data, max_workers): """ Multithreaded polling method to get the data from cryptocompare :param data: dictionary containing the details to be fetched :param max_workers: maximum number of threads to spawn :return list: containing the high low metrics for each ...
587a07912b8ea6d0267638c72a98fdbeb6b0ebf0
16,031
from typing import Dict from typing import Any from typing import List def sub(attrs: Dict[str, Any], in_xlayers: List[XLayer]) -> Dict[str, List[int]]: """Return numpy-style subtraction layer registration information (shape) NOTE: https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html""" asser...
ebe4160dc92c259d2d6fd58a96eb78c697c0a5e4
16,032
import re def word_column_filter_df(dataframe, column_to_filter, column_freeze, word_list): # La fonction .where() donne une position qu'il faut transformer en index # Il faut entrer le nom d'une colonne repère (exemple: code produit) pour retrouver l'index, ou construire un colonne de re-indexée. """Filtre les c...
f58acf2188a192c1aa6cedecbfeeb66d7d073ba5
16,033
def adjust_learning_rate(optimizer, iteration, epoch_size, hyp, epoch, epochs): """adjust learning rate, warmup and lr decay :param optimizer: optimizer :param gamma: gamma :param iteration: iteration :param epoch_size: epoch_size :param hyp: hyperparameters :param epoch: epoch :param e...
c90c61fcecca99d31214c96cdf7d96b6ba682daa
16,034
import numpy as np from scipy.io import loadmat import numpy as np import h5py from numpy import fromfile, empty, append def reading_data(data_file): """ Read in a data file (16 bit) and obtain the entire data set that is multiplexed between ECG and Pulse data. The data is then extracted and appended ...
0ba4980db08a8877fabdfcc282d45c18d868a0a3
16,035
from typing import Callable def two_body_mc_grad(env1: AtomicEnvironment, env2: AtomicEnvironment, d1: int, d2: int, hyps: 'ndarray', cutoffs: 'ndarray', cutoff_func: Callable = cf.quadratic_cutoff) \ -> (float, 'ndarray'): """2-body multi-element kernel between t...
8cba89674c5e1dea999d026aad8f9b393a57f5cc
16,036
import types def get_task_name(task): """Gets a tasks *string* name, whether it is a task object/function.""" task_name = "" if isinstance(task, (types.MethodType, types.FunctionType)): # If its a function look for the attributes that should have been # set using the task() decorator provi...
181682d930cf358f2532406f1558b007aa09a41f
16,037
def EventAddPublication(builder, publication): """This method is deprecated. Please switch to AddPublication.""" return AddPublication(builder, publication)
39cf5facf251370fd86a004477f848dafd41976c
16,038
def convModel(input1_shape, layers): """" convolutional model defined by layers. ith entry defines ith layer. If entry is a (x,y) it defines a conv layer with x kernels and y filters. If entry is x it defines a pool layer with size x""" model = Sequential() for (i, layer) in enumerate(layers): ...
d1a49a42ab0fc4eecd40783345f09121a773ae02
16,039
def cached_open_doc(db, doc_id, cache_expire=COUCH_CACHE_TIMEOUT, **params): """ Main wrapping function to open up a doc. Replace db.open_doc(doc_id) """ try: cached_doc = _get_cached_doc_only(doc_id) except ConnectionInterrupted: cached_doc = INTERRUPTED if cached_doc in (None, ...
82118a5c9c43aaf339e7ca3ab8af9680fbd362d1
16,040
import os def Voices_preload_and_split(subset='room-1', test_subset='room-2', seconds=3, path=None, pad=False, splits=None, trim=True): """Index and split librispeech dataset. Args: subset (string): LibriSpeech subset to parse, load and split. Currently can on...
46bd0234dbc006b7f5fdb53d3e032bddc679a6f0
16,041
import torch def dense2bpseq(sequence: torch.Tensor, label: torch.Tensor) -> str: """converts sequence and label tensors to `.bpseq`-style string""" seq_lab = dense2seqlab(sequence, label) return seqlab2bpseq
ec0a5d681fef518068042aa2830ee4d2ef3231c8
16,042
from datetime import datetime def _base_app(config): """ init a barebone flask app. if it is needed to create multiple flask apps, use this function to create a base app which can be further modified later """ app = Flask(__name__) app.config.from_object(config) config.init_app(app) ...
f5f40ed9ea740c5b9bc9ebb8490136179d06f777
16,043
def applyC(input_map,nbar,MAS_mat,pk_map,Y_lms,k_grids,r_grids,v_cell,shot_fac,include_pix=True): """Apply the fiducial covariance to a pixel map x, i.e. C[x] = S[x]+N[x]. We decompose P(k;x) = \sum_l P_l(k) L_l(k.x) where x is the position of the second galaxy and use spherical harmonic decompositions. P_...
91346d935217f540a91947b0a00e91e0125794ef
16,044
def invert_injective_mapping(dictionary): """ Inverts a dictionary with a one-to-one mapping from key to value, into a new dictionary with a one-to-one mapping from value to key. """ inverted_dict = {} for key, value in iteritems(dictionary): assert value not in inverted_dict, "Mapping i...
c8cba85f542c5129892eeba4168edf6d9715b54e
16,045
def biosql_dbseqrecord_to_seqrecord(dbseqrecord_, off=False): """Converts a DBSeqRecord object into a SeqRecord object. Motivation of this function was two-fold: first, it makes type testing simpler; and second, DBSeqRecord does not have a functional implementation of the translate method. :param DBSeq...
9129c5efd9025a04f0693fd2d35f420b28c2ea91
16,046
def loadConfig(fileName): """ Attempt to load the specified config file. If successful, clean the variables/data the config file has setup """ if not os.path.isfile(fileName): return False if not os.access(fileName, os.R_OK): warn('Unable to read config file: ' + fileName) retur...
eb959a65743a1e73732f8226a55a69582fe4ac20
16,047
import re def parse_rpsbproc(handle): """Parse a results file generated by rpsblast->rpsbproc. This function takes a handle corresponding to a rpsbproc output file. local.rpsbproc returns a subprocess.CompletedProcess object, which contains the results as byte string in it's stdout attribute. """...
64be049b5cb96a3e59f421327d1715cee84e2300
16,048
from typing import get_type_hints def _invalidate(obj, depth=0): """ Recursively validate type anotated classes. """ annotations = get_type_hints(type(obj)) for k, v in annotations.items(): item = getattr(obj, k) res = not_type_check(item, v) if res: return f"{...
a1881d45414a4a034456e0078553e4aa7bf6471a
16,049
import os def maybe_download(filename, expected_bytes, force=False): """Download a file if not present, and make sure it's the right size.""" if force or not os.path.exists(filename): print('Attempting to download:', filename) filename, _ = urlretrieve(url + filename, filename, reporthook=download_progre...
a9af221b98647792a92749a901ecc70f09a388ff
16,050
def convtranspose2d_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1, out_pad=0): """Calculates the output height and width of a feature map for a ConvTranspose2D operation.""" h_w, kernel_size, stride, pad, dilation, out_pad = num2tuple(h_w), num2tuple(kernel_size), num2tuple(stride), num2tuple(pad...
e1ded212929e7e24b138335ae3d9006b1dcfb759
16,051
def set_multizone_read_mode(session, read_mode, return_type=None, **kwargs): """ Modifies where data is read from in multizone environments. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type read_mode: str :param read_mode: For mu...
0831bfd722514cab792eef38838e357209a0971f
16,052
import re def get_name_convert_func(): """ Get the function to convert Caffe2 layer names to PyTorch layer names. Returns: (func): function to convert parameter name from Caffe2 format to PyTorch format. """ pairs = [ # ------------------------------------------------------...
4e3cbe0885a0d23d5af151bc0cea7127156aa9c9
16,053
def generate_dict_entry(key, wordlist): """Generate one entry of the python dictionary""" entry = " '{}': {},\n".format(key, wordlist) return entry
57ab3c063df0bde1261602f0c6279c70900a7a88
16,054
def record_to_dict(record): """ Transform string into bovespa.Record :param record: (string) position string from bovespa. :return: parsed Record """ try: record = bovespa.Record(record) except: return None return { 'date': record.date, 'year': record.date.year, ...
3065d233a0186a72330165c9b082c819369ef449
16,055
def sample_product(user, **params): """Create and return a custom product""" defaults = { 'name': 'Ron Cacique', 'description': 'El ron cacique es...', 'price': 20, 'weight': '0.70', 'units': 'l', 'featured': True, } defaults.update(params) return Pro...
310b2ee775e5497597dd68cf6737623e40b78932
16,056
def _find_op_path_(block, outputs, inputs, no_grad_set): """ no_grad_set will also be changed """ input_names = set([inp.name for inp in inputs]) output_names = set([out.name for out in outputs]) relevant_op_flags = [True] * len(block.ops) # All the inputs of the block are used if inputs i...
05d1b18f883906cc41fa84f6f27f061b30ced4b8
16,057
def clean_gltf_materials(gltf): """ 未使用のglTFマテリアルを削除する :param gltf: glTFオブジェクト :return: 新しいマテリアルリスト """ return filter(lambda m: m['name'] in used_material_names(gltf), gltf['materials'])
7e429dceb84d48298897589172f976ea907ddcab
16,058
def create_root(request): """ Returns a new traversal tree root. """ r = Root() r.add('api', api.create_root(request)) r.add('a', Annotations(request)) r.add('t', TagStreamFactory()) r.add('u', UserStreamFactory()) return r
ebc64f7f49bf6b3405b9971aa0b30e72b3d13c5f
16,059
def sort_basis_functions(basis_functions): """Sorts a set of basis functions by their distance to the function with the smallest two-norm. Args: basis_functions: The set of basis functions to sort. Expected shape is (-1, basis_function_length). Returns: sorted_basis: The so...
18b11f80c7d08eb6435d823e557ec9ea4e028b92
16,060
import os def to_zgrid(roms_file, z_file, src_grid=None, z_grid=None, depth=None, records=None, threads=2, reftime=None, nx=0, ny=0, weight=10, vmap=None, cdl=None, dims=2, pmap=None): """ Given an existing ROMS history or average file, create (if does not exit) a new z-grid file...
305b25c6e98cf50c4784d4eaa18b3306b415aea3
16,061
def info_materials_groups_get(): """ info_materials_groups_get Get **array** of information for all materials, or if an array of &#x60;type_ids&#x60; is included, information on only those materials. :rtype: List[Group] """ session = info_map.Session() mat = aliased(info_map.Material) ...
49dcf0785be8d9a94b4bb730af6326d493e79000
16,062
import os def TestFSSH(): """ molcas test 1. FSSH calculation """ pyrai2mddir = os.environ['PYRAI2MD'] testdir = '%s/fssh' % (os.getcwd()) record = { 'coord' : 'FileNotFound', 'energy' : 'FileNotFound', 'energy1' : 'FileNotFound', 'energy2' : 'FileNotFo...
be7f26eb2a398996a87e756905b596c26c428332
16,063
def relu(x): """ Compute the relu of x Arguments: x -- A scalar or numpy array of any size. Return: s -- relu(x) """ s = np.maximum(0,x) return s
40b838889b62abca0a88788436b5d648261a3c67
16,064
def kane_frstar_alt(bodies, coordinates, speeds, kdeqs, inertial_frame, uaux=Matrix(), udep=None, Ars=None): """Form the generalized inertia force.""" t = dynamicsymbols._t N = inertial_frame # Derived inputs q = Matrix(coordinates) # q u = Matrix(speeds) # u udot = u.diff(t) qdot_u_ma...
a42d8c902f7a27cb3867e9c85f8a844129293f7d
16,065
def line(value): """ | Line which can be used to cross with functions like RSI or MACD. | Name: line\_\ **value**\ :param value: Value of the line :type value: float """ def return_function(data): column_name = f'line_{value}' if column_name not in data.columns: ...
07b4f9671ae06cf63c02062a9da4eb2a0b1a265a
16,066
import json import requests def goodsGetSku(spuId,regionId): """ :param spuId: :param regionId: :return: """ reqUrl = req_url('goods', "/goods/getGoodsList") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', ...
23c3960384529c7a45e730a612cc7999fa316bd4
16,067
import os def build_model(config, model_dir=None, weight=None): """ Inputs: config: train_config, see train_celery.py model_dir: a trained model's output dir, None if model has not been trained yet weight: class weights """ contents = os.listdir(model_dir) print(contents) ...
d526404b5b5ad73c16a3bbb12af9c03f6099a17b
16,068
def get_scheduler(config, optimizer): """ :param config: 配置参数 :param optimizer: 优化器 :return: 学习率衰减策略 """ # 加载学习率衰减策略 if config.scheduler_name == 'StepLR': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=config.StepLR['decay_step'], ...
1e4be51c74ed6c35bde3343547c4a7a88736179a
16,069
def pipeline_dict() -> dict: """Pipeline config dict. You need to update the labels!""" pipeline_dictionary = { "name": "german_business_names", "features": { "word": {"embedding_dim": 16, "lowercase_tokens": True}, "char": { "embedding_dim": 16, ...
d9e15fb1a09678d65b30a49b7c7c811843420c57
16,070
def _is_hangul_syllable(i): """ Function for determining if a Unicode scalar value i is within the range of Hangul syllables. :param i: Unicode scalar value to lookup :return: Boolean: True if the lookup value is within the range of Hangul syllables, otherwise False. """ if i in range(0xAC00, 0...
793519ec33a8920ea13328b0e5a4f814c859b0d3
16,071
def shape14_4(tik_instance, input_x, res, input_shape, shape_info): """input_shape == ((32, 16, 14, 14, 16), 'float16', (1, 1), (1, 1))""" stride_w, stride_h, filter_w, filter_h, dilation_filter_w, dilation_filter_h = shape_info pad = [0, 0, 0, 0] l1_h = 14 l1_w = 14 c1_index = 0 jump_stride...
5606e2e6445ea5415960e1784009bcc75de29669
16,072
from typing import Dict from typing import Any from typing import Optional from typing import Iterator from typing import Union from typing import List def read_json( downloader: Download, datasetinfo: Dict, **kwargs: Any ) -> Optional[Iterator[Union[List, Dict]]]: """Read data from json source allowing for J...
77183992d42d9c3860965222c3feda23aca588dc
16,073
import json def json_dumps_safer(obj, **kwargs): """Convert obj to json, with some extra encodable types.""" return json.dumps(obj, cls=WandBJSONEncoder, **kwargs)
816e97051553f1adc4c39a7c5e4559fb3a354197
16,074
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
74707af8839b37de80d682d715ed8000375cdd7c
16,075
from uuid import uuid4 from redis import Redis from qiita_core.configuration_manager import ConfigurationManager from qiita_db.sql_connection import SQLConnectionHandler from moi.job import submit_nouser def test(runner): """Test the environment * Verify redis connectivity indepedent of moi * Verify data...
ea4f8f50e3d85c3df6f7c890b5b91140a63bac65
16,076
import os def reset_database(): """仅限开发阶段使用,请不要在发布阶段开启这样的危险命令 """ if app.config['ADMIN_KEY']: if request.args.get('key') == app.config['ADMIN_KEY']: if request.args.get('totp') == pyotp.TOTP(app.config['TOTP_SECRET']).now(): os.remove(app.config['SQLALCHEMY_DATABASE_PAT...
b3059fe9e2e3671803d01a7fd8521e58e315f19e
16,077
def validate_model(model): """ Validate a single data model parameter or a full data model block by recursively calling the 'validate' method on each node working from the leaf nodes up the tree. :param model: part of data model to validate :type model: :graphit:GraphAxis :return: ov...
009c629fe80af65f574c698567cb6b5213e9c888
16,078
def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ filename = "{0}.html".format(url.split("/").pop().lower()) filepath = abspath(join(dirna...
60b7714a439d949f42b1b8de6064c8ba087ccfdc
16,079
def ensemble_tsfresh(forecast_in, forecast_out, season, perd): """ Create rolled time series for ts feature extraction """ def tsfresh_run(forecast, season, insample=True, forecast_out=None): df_roll_prep = forecast.reset_index() if insample: df_roll_prep = df_roll_prep.drop...
3bcef19cd495c043e51a591118c1ae8e043290b5
16,080
import os def __modules_with_root_module_path(path): """ Returns all modules beneath the root module path. This treats all directories as packages regardless of whether or not they include a __init__.py. """ modules = [] if os.path.isfile(path) and os.path.splitext(path)[1] == '.py' and os...
96086c8f8e7a277033086c2da6a3bdad16c41756
16,081
from affine import Affine def transform_from_latlon(lat, lon): """ Tranform from latitude and longitude NOTES: - credit - Shoyer https://gist.github.com/shoyer/0eb96fa8ab683ef078eb """ lat = np.asarray(lat) lon = np.asarray(lon) trans = Affine.translation(lon[0], lat[0]) scale = A...
1f6fccfddd23423c0a621efa74a62cdb61b53665
16,082
from typing import OrderedDict def xml_to_json(xml_text: str) -> OrderedDict: """Converts xml text to json. Args: xml_text (str): xml text to be parsed Returns: OrderedDict: an ordered dict representing the xml text as json """ return xmltodict.parse(xml_text)
243156c6f0b3b0f0bf92d8eeaa3ecf52f5846fc8
16,083
import sys def get_calendar_future_events(api_service): """Se trae todos los eventos del calendario de Sysarmy. Args: api_service (googleapiclient.discovery.Resource): servicio ya autenticado para pegarle a la API de calendar. Returns: list: lista de diccionarios con los even...
f3b077f3af700c70c54e017a991118e81bbdb99a
16,084
import requests def getWeather(city, apikey): """ 天気を取得する リクエストにAPIKeyと都市をパラメーターに入れる https://openweathermap.org/forecast5 """ payload = { 'APIKEY': APIKEY, 'q': CITY } r = requests.get( APIBASE, params=payload ) return r
41a61d1bd9d1bd5d835963c305d0692babd6b64a
16,085
def func1(xc): """Function which sets the data value""" s = .1 res = np.exp(-xc**2/(2*s**2)) return res
75ab06abf5b348746e322cf41660cfb908d69b62
16,086
def GetEnabledDiskTemplates(*args): """Wrapper for L{_QaConfig.GetEnabledDiskTemplates}. """ return GetConfig().GetEnabledDiskTemplates(*args)
c07707de13be5c055386659be620831b2f057d64
16,087
def is_pull_request_merged(pull_request): """Takes a github3.pulls.ShortPullRequest object""" return pull_request.merged_at is not None
0fecf82b96f7a46cfb4e9895897bd4998d6f225b
16,088
def arraytoptseries(arr, crs={'epsg': '4326'}): """Convert an array of shape (2, ...) or (3, ...) to a geopandas GeoSeries containing shapely Point objects. """ if arr.shape[0] == 2: result = geopandas.GeoSeries([Point(x[0], x[1]) for x in arr.reshape(2, -1).T...
b193f9bcb4144b81becca1acaa8285f8cafaaff2
16,089
async def get_kml_network_link(): """ Return KML network link file """ logger.info('/c-haines/network-link') headers = {"Content-Type": kml_media_type, "Content-Disposition": "inline;filename=c-haines-network-link.kml"} return Response(headers=headers, media_type=kml_media_type, content=...
699ac59529ce085264a79dfdd048c96b3771e0a8
16,090
def splitToPyNodeList(res): # type: (str) -> List[pymel.core.general.PyNode] """ converts a whitespace-separated string of names to a list of PyNode objects Parameters ---------- res : str Returns ------- List[pymel.core.general.PyNode] """ return toPyNodeList(res.split())
44e8780833ed2a5d7418c972afb9e184ca82670b
16,091
def get_jira_issue(commit_message): """retrieve the jira issue referenced in the commit message >>> get_jira_issue(b"BAH-123: ") {b'BAH-123'} >>> messages = ( ... b"this is jira issue named plainly BAH-123", ... b"BAH-123 plainly at the beginning", ... b"in parens (BAH-123)", ... b"(BAH...
b0bf47319c492ec297dd9898645a10ce8a53b43f
16,092
import os import urllib def hello(event, context): """ This is my awesome hello world function that encrypts text! It's like my first web site, only in Lambda. Maybe I can add a hit counter later? What about <blink>? Args: event: context: Returns: """ # General run of t...
2e60f86bfcbfaf1433954077a2c19f0941d4aeee
16,093
def get_mean_std(dataloader): """Compute mean and std on the fly. Args: dataloader (Dataloader): Dataloader class from torch.utils.data. Returns: ndarray: ndarray of mean and std. """ cnt = 0 mean = 0 std = 0 for l in dataloader: # Now in (batch,...
d943ae5244743749fa6a2186aacfbf0ea160d17b
16,094
import os def do_retrieve(url, fname): """Retrieve given url to target filepath fname.""" folder = os.path.dirname(fname) if not os.path.exists(folder): os.makedirs(folder) print(f"{folder}{os.path.sep} created.") if not os.path.exists(fname): try: with open(fname, ...
a5df667e8d2eec5458ff09bcbb7dfcf3147973de
16,095
import random import math def create_random_camera(bbox, frac_space_x, frac_space_y, frac_space_z): """ Creates a new camera, sets a random position for it, for a scene inside the bbox. Given the same random_seed the pose of the camera is deterministic. Input: bbox - same rep as output from get_scene...
8cfa86127d569493a2456e13ae5924da886640a9
16,096
def temp2(): """ This is weird, but correct """ if True: return (1, 2) else: if True: return (2, 3) return (4, 5)
c63f5566a6e52a3b5d175640fce830b7aad33ebe
16,097
from typing import Tuple def compute_blade_representation(bitmap: int, firstIdx: int) -> Tuple[int, ...]: """ Takes a bitmap representation and converts it to the tuple blade representation """ bmp = bitmap blade = [] n = firstIdx while bmp > 0: if bmp & 1: blade.ap...
3bf6672280629dee8361ee3c0dbf5920afa4edda
16,098
import filecmp import os def are_dir_trees_equal(dir1, dir2): """ Compare two directories recursively. Files in each directory are assumed to be equal if their names and contents are equal. @param dir1: First directory path @param dir2: Second directory path @return: True if the directory trees are the same a...
77973e2dc494aa8f4636f633b0810d9370de7076
16,099