content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def loadData(data_source, loc, run, indexes, ntry=0, __text__=None, __prog__=None): """ Loads the data from a remote source. Has hooks for progress bars. """ if __text__ is not None: __text__.emit("Decoding File") if data_source.getName() == "Local WRF-ARW": url = d...
d06fd6fb6194dac63911a5b9c3ad267525098cd2
3,718
def comp_psip_skin(self, u): """psip_skin for skin effect computation Parameters ---------- self : Conductor An Conductor object Returns ------- None """ y = (1 / u) * (sinh(u) + sin(u)) / (cosh(u) + cos(u)) # p257 Pyrhonen # y[u==0]=1 return y
23fe18a13b56f38c49fd3ca14b557983064c65b3
3,719
import random def homepage(var=random.randint(0, 1000)): """ The function returns the homepage html template. """ return render_template("index.html", var=var)
17e9033b8abeaa990cd31008861e5c412e35d1d7
3,720
import numbers def tier(value): """ A special function of ordinals which does not correspond to any mathematically useful function. Maps ordinals to small objects, effectively compressing the range. Used to speed up comparisons when the operands are very different sizes. In the current vers...
851b36cf22c09d8f94168a0aa55292754451e351
3,721
from .models import Sequence def get_next_value( sequence_name="default", initial_value=1, reset_value=None, *, nowait=False, using=None, overrite=None, ): """ Return the next value for a given sequence. """ # Inner import because models cannot be imported before their app...
0770c8d4a4bea732bacfe6b7eaa404546bb79699
3,722
def expected_shd(posterior, ground_truth): """Compute the Expected Structural Hamming Distance. This function computes the Expected SHD between a posterior approximation given as a collection of samples from the posterior, and the ground-truth graph used in the original data generation process. Pa...
5e0daf39a13fc0a4cb7a4f5d0a9fe692fdae82db
3,723
import json def package_list_read(pkgpath): """Read package list""" try: with open(PACKAGE_LIST_FILE, 'r') as pkglistfile: return json.loads(pkglistfile.read()) except Exception: return []
afb97afd20823563ecfda3b5c908f7ad70322868
3,724
import pandas import types def hpat_pandas_series_le(self, other, level=None, fill_value=None, axis=0): """ Pandas Series method :meth:`pandas.Series.le` implementation. .. only:: developer Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_op8 Parameters --------...
f2969e17dd79b71a033e3c84ffd82e3bf2448554
3,725
def map_view(request): """ Place to show off the new map view """ # Define view options view_options = MVView( projection='EPSG:4326', center=[-100, 40], zoom=3.5, maxZoom=18, minZoom=2 ) # Define drawing options drawing_options = MVDraw( ...
5d037262b2c93c538b5a5b6fe076ee04a9d9b5ee
3,727
def decompose_jamo(compound): """Return a tuple of jamo character constituents of a compound. Note: Non-compound characters are echoed back. WARNING: Archaic jamo compounds will raise NotImplementedError. """ if len(compound) != 1: raise TypeError("decompose_jamo() expects a single characte...
56eb503b47a966d7f88750f7fdc1bcc55ba1aa1b
3,728
from typing import Optional def cp_in_drive( source_id: str, dest_title: Optional[str] = None, parent_dir_id: Optional[str] = None, ) -> DiyGDriveFile: """Copy a specified file in Google Drive and return the created file.""" drive = create_diy_gdrive() if dest_title is None: dest_title...
981cfa18da78a160447778cab5f3326f35dbfc59
3,729
def label_tuning( text_embeddings, text_labels, label_embeddings, n_steps: int, reg_coefficient: float, learning_rate: float, dropout: float, ) -> np.ndarray: """ With N as number of examples, K as number of classes, k as embedding dimension. Args: 'text_embeddings': flo...
83e4181c6600065bfb2cc98b4ca4957ea920ad7c
3,730
def create_nan_filter(tensor): """Creates a layer which replace NaN's with zero's.""" return tf.where(tf.is_nan(tensor), tf.zeros_like(tensor), tensor)
4e03c4c4c275430e5228e2d73b09e24f8c787e71
3,731
def requestor_is_superuser(requestor): """Return True if requestor is superuser.""" return getattr(requestor, "is_superuser", False)
7b201601cf8a1911aff8271ff71b6d4d51f68f1a
3,732
from typing import Dict def process(business: Business, # pylint: disable=too-many-branches filing: Dict, filing_rec: Filing, filing_meta: FilingMeta): # pylint: disable=too-many-branches """Process the incoming historic conversion filing.""" # Extract the filing informat...
78f5033251cb90023c2e0c0ad064b92af5212e65
3,733
def est_const_bsl(bsl,starttime=None,endtime=None,intercept=False,val_tw=None): """Performs a linear regression (assuming the intercept at the origin). The corresponding formula is tt-S*1/v-c = 0 in which tt is the travel time of the acoustic signal in seconds and 1/v is the reciprocal of the harmonic ...
906119dcc66f4ab536d4a89c9c9b633bb6835058
3,734
def SeasonUPdate(temp): """ Update appliance characteristics given the change in season Parameters ---------- temp (obj): appliance set object for an individual season Returns ---------- app_expected_load (float): expected load power in Watts app_expected_dur (float): expected ...
7fdfa932bedf2ac17490df6aaeedb547e1774c4d
3,735
def pad_and_reshape(instr_spec, frame_length, F): """ :param instr_spec: :param frame_length: :param F: :returns: """ spec_shape = tf.shape(instr_spec) extension_row = tf.zeros((spec_shape[0], spec_shape[1], 1, spec_shape[-1])) n_extra_row = (frame_length) // 2 + 1 - F extension ...
097bc2e8f58f1e947b8f69a6163d1c64d2197f9e
3,736
def GetExclusiveStorageForNodes(cfg, node_uuids): """Return the exclusive storage flag for all the given nodes. @type cfg: L{config.ConfigWriter} @param cfg: cluster configuration @type node_uuids: list or tuple @param node_uuids: node UUIDs for which to read the flag @rtype: dict @return: mapping from n...
b93625bc2b865530bef0c648885f5615905e54c1
3,737
import csv def get_read_data(file, dic, keys): """ Assigns reads to labels""" r = csv.reader(open(file)) lines = list(r) vecs_forwards = [] labels_forwards = [] vecs_reverse = [] labels_reverse = [] for key in keys: for i in dic[key]: for j in lines: ...
355c44cbf83ab9506755bda294723bfd1e8a15c1
3,738
def removeDuplicates(listToRemoveFrom: list[str]): """Given list, returns list without duplicates""" listToReturn: list[str] = [] for item in listToRemoveFrom: if item not in listToReturn: listToReturn.append(item) return listToReturn
8265e7c560d552bd9e30c0a1140d6668abd1b4d6
3,739
def check_hms_angle(value): """ Validating function for angle sexagesimal representation in hours. Used in the rich_validator """ if isinstance(value, list): raise validate.ValidateError("expected value angle, found list") match = hms_angle_re.match(value) if not match: raise...
bf1b6ec14cc131263913c331cb1d3cb9a06cdc76
3,740
def stats(): """Retrives the count of each object type. Returns: JSON object with the number of objects by type.""" return jsonify({ "amenities": storage.count("Amenity"), "cities": storage.count("City"), "places": storage.count("Place"), "reviews": storage.count("Re...
31ebd630381fe33cdbff507a3d34497423dfd621
3,742
def addflux2pix(px,py,pixels,fmod): """Usage: pixels=addflux2pix(px,py,pixels,fmod) Drizel Flux onto Pixels using a square PSF of pixel size unity px,py are the pixel position (integers) fmod is the flux calculated for (px,py) pixel and it has the same length as px and py pixels is the imag...
808f99dac20cda962146fee8f2b9878a07804f9b
3,743
def get_dea_landsat_vrt_dict(feat_list): """ this func is designed to take all releveant landsat bands on the dea public database for each scene in stac query. it results in a list of vrts for each band seperately and maps them to a dict where band name is the key, list is the value pair. """ ...
79009cc9fbcd085c8e95cf15f4271419d598d1ce
3,744
def is_zh_l_bracket(uni_ch): """判断一个 unicode 是否是中文左括号。""" if uni_ch == u'\uff08': return True else: return False
3ba18418005824a51de380c898726d050d464ec2
3,746
def petlink32_to_dynamic_projection_mMR(filename,n_packets,n_radial_bins,n_angles,n_sinograms,time_bins,n_axial,n_azimuthal,angles_axial,angles_azimuthal,size_u,size_v,n_u,n_v,span,n_segments,segments_sizes,michelogram_segments,michelogram_planes, status_callback): """Make dynamic compressed projection from list-mo...
9764da2a2fb0c021274133fdd46661a44cf0dc31
3,747
from typing import Dict def is_core_recipe(component: Dict) -> bool: """ Returns True if a recipe component contains a "Core Recipe" preparation. """ preparations = component.get('recipeItem', {}).get('preparations') or [] return any(prep.get('id') == PreparationEnum.CORE_RECIPE.value for prep...
451798c6f31297a80ac43db00243fb2dd85ced46
3,748
def build_estimator(output_dir, first_layer_size, num_layers, dropout, learning_rate, save_checkpoints_steps): """Builds and returns a DNN Estimator, defined by input parameters. Args: output_dir: string, directory to save Estimator. first_layer_size: int, size of first hidden layer of ...
339e26fd910aa7412b8e2b66845718e440ccada6
3,749
import json def importConfig(): """設定ファイルの読み込み Returns: tuple: str: interface, str: alexa_remote_control.sh path list: device list """ with open("config.json", "r", encoding="utf-8") as f: config = json.load(f) interface = config["interface"] ...
84f8fc0deec4aebfe48209b01d1a35f7373d31e6
3,750
from typing import List from typing import Dict from typing import Any def create_local_command(opts: Options, jobs: List[Dict[str, Any]], jobs_metadata: List[Options]) -> str: """Create a terminal command to run the jobs locally.""" cmd = "" for meta, job in zip(jobs_metadata, jobs): input_file =...
f5d23c1fb2271b44a323d1d17e9dda35df29fcd7
3,752
import time def time_for_log() -> str: """Function that print the current time for bot prints""" return time.strftime("%d/%m %H:%M:%S - ")
0f964d5c827782ff8cc433e57bb3e78d0a7c7cba
3,753
import math def _is_int(n) -> bool: """ is_int 是判断给定数字 n 是否为整数, 在判断中 n 小于epsilon的小数部分将被忽略, 是则返回 True,否则 False :param n: 待判断的数字 :return: True if n is A_ub integer, False else """ return (n - math.floor(n) < _epsilon) or (math.ceil(n) - n < _epsilon)
076a82d245333890d6790f65a58e5507905ca68f
3,754
def _cpp_het_stat(A, t_stop, rates, t_start=0. * pq.ms): """ Generate a Compound Poisson Process (CPP) with amplitude distribution A and heterogeneous firing rates r=r[0], r[1], ..., r[-1]. Parameters ---------- A : np.ndarray CPP's amplitude distribution. A[j] represents the probabilit...
adc00577e9a6cb1ff7f9e0313befe98c81332ab1
3,755
def return_bad_parameter_config() -> CloudSettings: """Return a wrongly configured cloud config class.""" CloudSettingsTest = CloudSettings( # noqa: N806 settings_order=[ "init_settings", "aws_parameter_setting", "file_secret_settings", "env_settings", ...
06f8af87873d571be9c5ae7fd2e563402e57b2d0
3,756
def update(isamAppliance, instance_id, id, filename=None, contents=None, check_mode=False, force=False): """ Update a file in the administration pages root :param isamAppliance: :param instance_id: :param id: :param name: :param contents: :param check_mode: :param force: :return:...
af0b95096638fb34af130623b0929c4394a1a845
3,757
def view_deflate_encoded_content(): """Returns Deflate-encoded data. --- tags: - Response formats produces: - application/json responses: 200: description: Defalte-encoded data. """ return jsonify(get_dict("origin", "headers", method=request.method, deflated=True))
ff8d39f75a6cb526b3a61e85234e71efa174a208
3,758
def predict_from_word_vectors_matrix(tokens, matrix, nlp, POS="NOUN", top_number=constants.DEFAULT_TOP_ASSOCIATIONS): """ Make a prediction based on the word vectors :param tokens: :param matrix: :param nlp: :param POS: :param top_number: :return: """ vector_results = collect_wor...
6a491e481238af932994bb8d383baca4da1ebd55
3,759
def blendImg(img_a, img_b, α=0.8, β=1., γ=0.): """ The result image is computed as follows: img_a * α + img_b * β + γ """ return cv2.addWeighted(img_a, α, img_b, β, γ)
f60918ba424b0d59e9025c088c0f2c9a3f739fde
3,762
def genoimc_dup4_loc(): """Create genoimc dup4 sequence location""" return { "_id": "ga4gh:VSL.us51izImAQQWr-Hu6Q7HQm-vYvmb-jJo", "sequence_id": "ga4gh:SQ.-A1QmD_MatoqxvgVxBLZTONHz9-c7nQo", "interval": { "type": "SequenceInterval", "start": { "valu...
3ea1b39fed22487bebffc78d45cb493b7d7afa4a
3,764
def compare_versions(a, b): """Return 0 if a == b, 1 if a > b, else -1.""" a, b = version_to_ints(a), version_to_ints(b) for i in range(min(len(a), len(b))): if a[i] > b[i]: return 1 elif a[i] < b[i]: return -1 return 0
0b22589164f7d3731edc34af97d306186e677371
3,765
def get_machine_action_data(machine_action_response): """Get machine raw response and returns the machine action info in context and human readable format. Notes: Machine action is a collection of actions you can apply on the machine, for more info https://docs.microsoft.com/en-us/windows/sec...
1e0ffc37d8d3b5662b64ec28cb850c6277b1bad2
3,766
import torch def convolutionalize(modules, input_size): """ Recast `modules` into fully convolutional form. The conversion transfers weights and infers kernel sizes from the `input_size` and modules' action on it. n.b. This only handles the conversion of linear/fully-connected modules, altho...
5693a17bac0f39538bfcada3280ce06ef91230a3
3,768
def is_unique2(s): """ Use a list and the int of the character will tell if that character has already appeared once """ d = [] for t in s: if d[int(t)]: return False d[int(t)] = True return True
b1a1bdea8108690a0e227fd0b75f910bd6b99a07
3,769
import random def uncomplete_tree_parallel(x:ATree, mode="full"): """ Input is tuple (nl, fl, split) Output is a randomly uncompleted tree, every node annotated whether it's terminated and what actions are good at that node """ fl = x fl.parent = None add_descendants_ancestors...
f59e0f0279c9c439034116f769f51d60a924c4af
3,770
def stations_by_river(stations): """Give a dictionary to hold the rivers name as keys and their corresponding stations' name as values""" rivers_name = [] for i in stations: if i.river not in rivers_name: rivers_name.append(i.river) elif i.river in rivers_name: contin...
66fd928415619d175b7069b8c3103a3f7d930aac
3,771
def QA_SU_save_huobi(frequency): """ Save huobi kline "smart" """ if (frequency not in ["1d", "1day", "day"]): return QA_SU_save_huobi_min(frequency) else: return QA_SU_save_huobi_day(frequency)
cdea45afe6d7e0b61dea517adb8fc484e8eafa38
3,772
def inverse(a): """ [description] calculating the inverse of the number of characters, we do this to be able to find our departure when we arrive. this part will be used to decrypt the message received. :param a: it is an Int :return: x -> it is an Int """ x = 0 while a * x % 9...
2893d2abda34e4573eb5d9602edc0f8e14246e09
3,774
from typing import Optional from typing import Union def currency_column_to_numeric( df: pd.DataFrame, column_name: str, cleaning_style: Optional[str] = None, cast_non_numeric: Optional[dict] = None, fill_all_non_numeric: Optional[Union[float, int]] = None, remove_non_numeric: bool = False, ) ...
e382752e5aff389872da69f42a3ec62785df336f
3,775
async def subreddit_type_submissions(sub="wallstreetbets", kind="new"): """ """ comments = [] articles = [] red = await reddit_instance() subreddit = await red.subreddit(sub) if kind == "hot": submissions = subreddit.hot() elif kind == "top": submissions = subreddit.top()...
9cc8655575ca8fd3729e220b0ee3fc8e45e4ed56
3,776
import typing import json def _get_bundle_manifest( uuid: str, replica: Replica, version: typing.Optional[str], *, bucket: typing.Optional[str] = None) -> typing.Optional[dict]: """ Return the contents of the bundle manifest file from cloud storage, subject to the rules...
7881e1514a9a645c1f7ee6479baa6e74bae4dabb
3,778
def handler400(request, exception): """ This is a Django handler function for 400 Bad Request error :param request: The Django Request object :param exception: The exception caught :return: The 400 error page """ context = get_base_context(request) context.update({ 'message': { ...
0dc1b81ec86d675f348728863dfe07efbd936e8e
3,779
def _gather_topk_beams(nested, score_or_log_prob, batch_size, beam_size): """Gather top beams from nested structure.""" _, topk_indexes = tf.nn.top_k(score_or_log_prob, k=beam_size) return _gather_beams(nested, topk_indexes, batch_size, beam_size)
ebdaf391104a3f271a42549708f3e7adfaf8b0b0
3,781
import scipy import numpy def _traceinv_exact(K, B, C, matrix, gram, exponent): """ Finds traceinv directly for the purpose of comparison. """ # Exact solution of traceinv for band matrix if B is not None: if scipy.sparse.isspmatrix(K): K_ = K.toarray() B_ = B.toa...
3637a5aa726ef1bf8489783c435c429b59422240
3,782
def create_feature_vector_of_mean_mfcc_for_song(song_file_path: str) -> ndarray: """ Takes in a file path to a song segment and returns a numpy array containing the mean mfcc values :param song_file_path: str :return: ndarray """ song_segment, sample_rate = librosa.load(song_file_path) mfccs...
8992feafd483bfe7b4af5e715ba1455884e1b710
3,783
def stations_highest_rel_level(stations, N): """Returns a list containing the names of the N stations with the highest water level relative to the typical range""" names = [] # create list for names levels = [] # create list for levels for i in range(len(stations)): # iterate through stat...
780a03a424c9b2f0dedee2e93eb9bd27cc1fce36
3,784
def add_global_nodes_edges(g_nx : nx.Graph, feat_data: np.ndarray, adj_list: np.ndarray, g_feat_data: np.ndarray, g_adj_list: np.ndarray): """ :param g_nx: :param feat_data: :param adj_list: :param g_feat_data: :param g_adj_list: :return: """ feat_da...
1097becfe88f05008541aaa6c3c074fcd5c3149a
3,786
def get_data_collector_instance(args, config): """Get the instance of the data :param args: arguments of the script :type args: Namespace :raises NotImplementedError: no data collector implemented for given data source :return: instance of the specific data collector :rtype: subclass of BaseDat...
75fda1231e1489da4b0c10473c9f657b143047c1
3,788
def timeIntegration(params): """Sets up the parameters for time integration :param params: Parameter dictionary of the model :type params: dict :return: Integrated activity variables of the model :rtype: (numpy.ndarray,) """ dt = params["dt"] # Time step for the Euler intergration (ms) ...
24d6702a92f82c6cc7fc1a337cd351b54c567e8b
3,789
def is_role_user(session, user=None, group=None): # type: (Session, User, Group) -> bool """ Takes in a User or a Group and returns a boolean indicating whether that User/Group is a component of a service account. Args: session: the database session user: a User object to check ...
3d6b62b1708882b734031d737fa00f29ba9a9f95
3,790
def argCOM(y): """argCOM(y) returns the location of COM of y.""" idx = np.round(np.sum(y/np.sum(y)*np.arange(len(y)))) return int(idx)
197ac25043b10575efb7405dba12c0d2e6f9976f
3,791
def fringe(z, z1, z2, rad, a1): """ Approximation to the longitudinal profile of a multipole from a permanent magnet assembly. see Wan et al. 2018 for definition and Enge functions paper (Enge 1964) """ zz1 = (z - z1) / (2 * rad / pc.pi) zz2 = (z - z2) / (2 * rad / pc.pi) fout = ( (1 / ...
b1d0138937d1c622809d6f559f17430e89259fed
3,792
import random def random_param_shift(vals, sigmas): """Add a random (normal) shift to a parameter set, for testing""" assert len(vals) == len(sigmas) shifts = [random.gauss(0, sd) for sd in sigmas] newvals = [(x + y) for x, y in zip(vals, shifts)] return newvals
07430572c5051b7142499bcbdbc90de5abfcbd4d
3,793
def compute_encrypted_request_hash(caller): """ This function will compute encrypted request Hash :return: encrypted request hash """ first_string = get_parameter(caller.params_obj, "requesterNonce") or "" worker_order_id = get_parameter(caller.params_obj, "workOrderId") or "" worker_id = ge...
cf87c354df550b142030781e8b84ec1cb385489f
3,794
def translate_line_test(string): """ Translates raw log line into sequence of integer representations for word tokens with sos and eos tokens. :param string: Raw log line from auth_h.txt :return: (list) Sequence of integer representations for word tokens with sos and eos tokens. """ data = strin...
d311eb9c6b398391724e868071d89f2f6c442912
3,795
def preprocess_signal(signal, sample_rate): """ Preprocess a signal for input into a model Inputs: signal: Numpy 1D array containing waveform to process sample_rate: Sampling rate of the input signal Returns: spectrogram: STFT of the signal after resampling to 10kHz and adding ...
d2b6c5cb700ae877f7bf8bd4b5a772471e69a75d
3,796
def get_frameheight(): """return fixed height for extra panel """ return 120
3bd810eea77af15527d3c1df7ab0b788cfe90000
3,797
def default_heart_beat_interval() -> int: """ :return: in seconds """ return 60
58171c8fb5632aa2aa46de8138828cce2eaa4d33
3,798
import re def email_valid(email): """test for valid email address >>> email_valid('test@testco.com') True >>> email_valid('test@@testco.com') False >>> email_valid('test@testco') False """ if email == '': return True email_re = re.compile( r"(^[-!#$%&'*+/=?^_...
c76a621647595c741b1da71734a34372919e800f
3,799
from typing import Any def get_node_data(workspace: str, graph: str, table: str, node: str) -> Any: """Return the attributes associated with a node.""" return Workspace(workspace).graph(graph).node_attributes(table, node)
0ac48d715fd31876b62d837d5b18b2ee75c791dd
3,800
def siso_optional(fn, h_opt, scope=None, name=None): """Substitution module that determines to include or not the search space returned by `fn`. The hyperparameter takes boolean values (or equivalent integer zero and one values). If the hyperparameter takes the value ``False``, the input is simply ...
187a292c8dba59d5d4d7f67d54cdd087ee2b6582
3,801
def saconv3x3_block(in_channels, out_channels, stride=1, pad=1, **kwargs): """ 3x3 version of the Split-Attention convolution block. Parameters: ---------- in_channels : int Number of input channels. out_cha...
bda938d53bbb56a7035ae50125743e4eb9aa709b
3,802
def add_hook(**_kwargs): """Creates and adds the import hook in sys.meta_path""" hook = import_hook.create_hook( transform_source=transform_source, hook_name=__name__, extensions=[".pyfr"], ) return hook
20c7e37aead055e32bfcb520a579b66069a3e26c
3,803
def mul(n1, n2): """ multiply two numbers """ return n1 * n2
c137432dd2e5c6d4dbded08546e3d54b98fe03df
3,804
import torch def pytorch_normalze(img): """ https://github.com/pytorch/vision/issues/223 return appr -1~1 RGB """ normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) img = normalize(torch.from_numpy(img)) return img.numpy(...
7667d6fa3da69d89973bb804ad08a139ae7f3564
3,805
def get_nic_capacity(driver_info, ilo_fw): """Gets the FRU data to see if it is NIC data Gets the FRU data in loop from 0-255 FRU Ids and check if the returned data is NIC data. Couldn't find any easy way to detect if it is NIC data. We should't be hardcoding the FRU Id. :param driver_info: Co...
cc20e1b35a47bec1242ed5dba60da8473527ca4f
3,806
import re def isValidInifileKeyName(key): """ Check that this key name is valid to be used in inifiles, and to be used as a python property name on a q or i object """ return re.match("^[\w_]+$", key)
9e68b987d6ac9af3c40e053c2347b01f737f0665
3,807
def installed_pkgs(): """ Return the list of installed packages on the machine Returns: list: List of installed packages CLI Example: .. code-block:: bash salt '*' macpackage.installed_pkgs """ cmd = "pkgutil --pkgs" return __salt__["cmd.run"](cmd).split("\n")
b9a66600327ea8eb0ec63745cacd8509a0f757d9
3,808
import math def extract_feature(audio, sr=44100): """ extract feature like below: sig: rmse: silence: harmonic: pitch: audio: audio file or audio list return feature_list: np of [n_samples, n_features] """ feature_list = [] y = [] if isinstance(audio, str): ...
d4eca914605bc87c57dbaf846a9a01d79a953c56
3,809
from typing import OrderedDict import six def BuildPartialUpdate(clear, remove_keys, set_entries, field_mask_prefix, entry_cls, env_builder): """Builds the field mask and patch environment for an environment update. Follows the environments update semantic which applies operations in an ...
320c589cd45dcec9a3ebba4b295075e23ef805ed
3,811
def create_schema_usb(): """Create schema usb.""" return vol.Schema(CONFIG_SCHEMA_USB)
e543a5950788ad629ed3986cc7a6c5a58931a478
3,813
def _build_field_queries(filters): """ Builds field queries. Same as _build_field_query but expects a dict of field/values and returns a list of queries. """ return [ _build_field_query(field, value) for field, value in filters.items() ]
9b1241cce6c421a79cd5ea26dd134d5fd93d6fde
3,814
def bycode(ent, group): """ Get the data with the given group code from an entity. Arguments: ent: An iterable of (group, data) tuples. group: Group code that you want to retrieve. Returns: The data for the given group code. Can be a list of items if the group code occu...
c5b92f2bbd1cd5bc383a1102ccf54031222d82c3
3,815
from typing import List from typing import Tuple def get_midi_programs(midi: MidiFile) -> List[Tuple[int, bool]]: """ Returns the list of programs of the tracks of a MIDI, deeping the same order. It returns it as a list of tuples (program, is_drum). :param midi: the MIDI object to extract tracks programs...
7249baa46b80b8b42400068edacf5ce9e829c71f
3,817
def is_depth_wise_conv(module): """Determine Conv2d.""" if hasattr(module, "groups"): return module.groups != 1 and module.in_channels == module.out_channels elif hasattr(module, "group"): return module.group != 1 and module.in_channels == module.out_channels
27127f54edbf8d0653cab6c7dbfb1448f33ecab4
3,818
def list_all_routed(): """ List all the notifications that have been routed to any repository, limited by the parameters supplied in the URL. See the API documentation for more details. :return: a list of notifications appropriate to the parameters """ return _list_request()
d67141d6fa5908d99292d898a5a77df3e80d47aa
3,819
def Lstart(gridname='BLANK', tag='BLANK', ex_name='BLANK'): """ This adds more run-specific entries to Ldir. """ # put top level information from input into a dict Ldir['gridname'] = gridname Ldir['tag'] = tag Ldir['ex_name'] = ex_name # and add a few more things Ldir['gtag'] = gridn...
92d992c3a7eba7bbba9146018060bca7844d4a78
3,822
def rfe_w2(x, y, p, classifier): """RFE algorithm, where the ranking criteria is w^2, described in [Guyon02]_. `classifier` must be an linear classifier with learn() and w() methods. .. [Guyon02] I Guyon, J Weston, S Barnhill and V Vapnik. Gene Selection for Cancer Classification using Support...
9176ee36c1180ab862b23be9d9a09584abea50ca
3,823
from typing import List def compress_timeline(timeline: List, salt: bytes) -> List: """ Compress the verbose Twitter feed into a small one. Just keep the useful elements. The images are downloaded per-request. Args: timeline (List): The Twitter timeline. salt (bytes): The salt to appl...
aff1364714d7e83685ab2257167fcd8bc7e10436
3,824
def createFinalCompactedData(compacted_data,elevations): """ This function creates a dataframe that combines the RGB data and the elevations data into a dataframe that can be used for analysis Parameters ---------- compacted_data : list of compacted data returned from condensePixels. elevat...
0d8b6a5e10504c32988e05e7450ebcf077305949
3,825
def get_sorted_nodes_edges(bpmn_graph): """ Assure an ordering as-constant-as-possible Parameters -------------- bpmn_graph BPMN graph Returns -------------- nodes List of nodes of the BPMN graph edges List of edges of the BPMN graph """ graph = bpmn...
879d7e8e3e5e4e9a8db3fc01622b96dde2b7af25
3,826
from typing import Optional from typing import Dict from typing import Any def list_commits( access_key: str, url: str, owner: str, dataset: str, *, revision: Optional[str] = None, offset: Optional[int] = None, limit: Optional[int] = None, ) -> Dict[str, Any]: """Execute the OpenAP...
be3899be0b77de069c7d32ca39aaec2039fe89e4
3,827
import heapq def dijkstra(graph, start, end=None): """ Find shortest paths from the start vertex to all vertices nearer than or equal to the end. The input graph G is assumed to have the following representation: A vertex can be any object that can be used as an index into a dictionary. G is...
b2a1ee983534c0a4af36ae7e3490c3b66949609b
3,828
def tournament_selection(pop, size): """ tournament selection individual eliminate one another until desired breeding size is reached """ participants = [ind for ind in pop.population] breeding = [] # could implement different rounds here # but I think that's almost the same as calling tour...
78bebc2de25d0744f3f8dabd67f70136d5f020b5
3,830
import math def bond_number(r_max, sigma, rho_l, g): """ calculates the Bond number for the largest droplet according to Cha, H.; Vahabi, H.; Wu, A.; Chavan, S.; Kim, M.-K.; Sett, S.; Bosch, S. A.; Wang, W.; Kota, A. K.; Miljkovic, N. Dropwise Condensation on Solid Hydrophilic Surfaces. Science Advances 2...
2098a762dd7c2e80ff4a570304acf7cfbdbba2e5
3,831
def spatial_conv(inputs, conv_type, kernel, filters, stride, is_training, activation_fn='relu', data_format='channels_last'): """Performs 1x1 conv followed by 2d or depthwise conv. Args: input...
e87820eaa5b8ed13157fe0790c4e09b1bc546a0d
3,832
async def timeron(websocket, battleID): """Start the timer on a Metronome Battle. """ return await websocket.send(f'{battleID}|/timer on')
f1601694e2c37d41adcc3983aa535347dc13db71
3,833
import numpy def to_unit_vector(this_vector): """ Convert a numpy vector to a unit vector Arguments: this_vector: a (3,) numpy array Returns: new_vector: a (3,) array with the same direction but unit length """ norm = numpy.linalg.norm(this_vector) assert norm > 0.0, "vector ...
ae46bf536b8a67a1be1e98ae051eebf1f8696e37
3,834
import base64 def decode(msg): """ Convert data per pubsub protocol / data format Args: msg: The msg from Google Cloud Returns: data: The msg data as a string """ if 'data' in msg: data = base64.b64decode(msg['data']).decode('utf-8') return data
32e85b3f0c18f3d15ecb0779825941024da75909
3,835
def pivot_longer_by_humidity_and_temperature(df: pd.DataFrame) -> pd.DataFrame: """ Reshapes the dataframe by collapsing all of the temperature and humidity columns into an temperature, humidity, and location column Parameters ---------- df : pd.DataFrame The cleaned and renamed datafra...
d60b92b523c31b3f7db799f58a42bd9ca810d258
3,836