content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import sys def sync_source(source): """ This celery task will sync the specified source. :param source: :return: """ function = f"{__name__}.{sys._getframe().f_code.co_name}" task_id = None if celery.current_task: task_id = celery.current_task.request.id log_data = { ...
20c1adddcec8d0bbd4b83dc67ed2d1a73549bda6
53,300
import configparser import os def parse_config(configfile): """Parse the given config file and return configuration settings as a dictionary for further use. :param str configfile: the path to the configuration file. :returns: parsed configuration values. :rtype: dict """ parser = co...
d8c2704e1d356579dad6144fad4608fcbc9b0351
53,301
def add_list(): """ Add new list """ # User reached route via PODT (as by submitting a form via POST) if request.method == "POST": # Ensure title was submitted if not request.form.get("title"): return apology("must provide title", 400) # Add new list into the database ...
f6c7d4268352be811f60abe3b8cb147519a79461
53,302
from typing import Iterable from typing import List def tensorise_token_sequence( vocab: Vocabulary, length: int, token_seq: Iterable[str], ) -> List[int]: """ Tensorise a single example. Args: vocab: Vocabulary to use for mapping tokens to integer IDs length: Length to truncate/pad s...
fa554810d8ab604d68be8ba59ce2157954bb1fe8
53,303
def power_flow_2_bus(v1, theta1, v2, theta2, g, b): """ Calculate the power flow from bus 1 to bus 2 across the line with admittance g+jb from the given voltages and angles. """ p = 0 q = 0 # Build admittance matrix values g12, b12 = -g, -b g11, b11 = g, b p += v1 * v2 * (g12 *...
b8f871b485d251b0ba3f1695f57d06c5c4b1fd5e
53,304
import zipfile import json def _GetExtensionInfoFromCRX(crx_path): """Parse an extension archive and return information. Note: The extension name returned by this function may not be valid (e.g. in the case of a localized extension name). It's use is just meant to be informational. Args: crx_path...
8a5f2ef2547c67d65195334df89d589fbff54dcf
53,305
def update_state(td_state, job_results): """ Updates the torsiondrive state with the compute jobs. The state is updated inplace Parameters ---------- td_state : dict The current torsiondrive state job_results : dict A dictionary of completed jobs and job ID's Returns --...
476d19fb9946045dc555f815d680d0475f253003
53,306
import inspect def extract_script_classes(module, target_kls): """ Returns list of classes (`Script`) detected from the module. """ return iter(kls for name, kls in inspect.getmembers(module) if is_class_and_subclass(kls, target_kls))
debb2187d2b0c6632b4d268063763ce7892e7510
53,307
def to_obj(cls, obj_data=None, *fields, **field_map): """ prioritize obj_dict when there are conficts """ obj_dict = obj_data.__dict__ if hasattr(obj_data, '__dict__') else obj_data if not fields: fields = obj_dict.keys() obj = cls() update_obj(obj_dict, obj, *fields, **field_map) return...
e4781d6d3229e69ba4eb5ba8efd574435b66c4fa
53,308
def V_NN(mol): """ Compute Nuclear-Nuclear repulsion energy """ nn = 0 for i in range(mol.num_atoms): for j in range(i+1, mol.num_atoms): # Select atoms from molecule Ri = mol.coordinates[i] Rj = mol.coordinates[j] Zi = mol.charges[i] ...
22ccc5d05e3c954da2418312a7bb0d149c1afbd5
53,309
import json def report(request): """ 通过csrf_exempt装饰器,跳过Django的csrf安全机制,让post的数据能被接收,但这又会带来新的安全问题。 可以在客户端,使用自定义的认证token,进行身份验证。这部分工作,请根据实际情况,自己进行。 :param request: :return: """ if request.method == "POST": asset_data = request.POST.get('asset_data') data = json.loads(asset_d...
7761404cab007bf7328c657d0f8882be79a83c3f
53,310
def find_adjacent(kmeans_img, start_row, start_col, width, height): """Start start_row, start_col, search LR then up for matching values, repeat. Return end col, return list of matching row,col ie x,y. Simple version of the "fill" command in Photoshop. These matching row,col will be used later to curv...
84d14821ea3658e98b9f38fe3155773d6fd1c51a
53,311
from typing import Dict def parse_profile(obj: Element, profile: Element) -> Dict[str,str]: """Parses model profile and related object element. Function is called once per object element and profile information is repeated per object. Arguments: obj {Element} -- Profile object profile {E...
b849058678865f2e1365bc6e1af2855f41c0ace2
53,312
def _format_rangeyaxis( axis: plt.axis, pdata: dict, rg_converter: bool = False, **kwargs ) -> plt.axis: """Zoom to a specific range interval and format yaxis. Args: axis: plot axis pdata: plot structure data rg_converter: if True convert range from meter...
2efe6c85a152079f313e1ae3e1dcafab44cba753
53,313
from datetime import datetime def now_str(pattern=TIME_FMT): """Return a formatted timestring for the current time.""" # return time.strftime(pattern, time.gmtime()) return datetime.utcnow().strftime(pattern)
828fe7a15a160402a337a8498acfbcf53211c8e2
53,314
def categorical_crossentropy(Y, Yhat, eps=1e-8): """ Computes the categorical cross-entropy for one hot encoded labels Y - (m,dim_y) array of labels m=examples Yhat - (m,dim_y) array of logits """ m = np.shape(Y)[0] Yhat = np.clip(Yhat, eps, 1 - eps) # for numerical stability if this is us...
d69070fddb92b366d02344ba325652ae8f8bc22a
53,315
from typing import Tuple def yaml_remove_split(docstr: str) -> Tuple[str, str]: """Extract parameter summary within :yaml: tags in docstring, and clean up the :yaml: tag for the full docstring. Return cleaned up docstring, and summary version.""" key = ":yaml:" summary = "" i_start = docstr.fi...
e0e3e34871c56c5cc176fcd371e5402846771078
53,316
from typing import Iterator from typing import Any def isdictreversediterator(object: Iterator[Any]) -> bool: """Returns True or False based on whether the given object is a reversed dict iterator. Parameters ---------- object: Any The object to see if it's a reversed dict iterator. Retu...
b3e0733a876c3f1faf16269ed4343503ac64d3ce
53,317
def create_regex(s: str, initials: bool = True) -> str: """ Given a string representation of either a channel or marker, generate a standard regex string to be used in a panel template Parameters ---------- s: str String value of channel or marker to generate regex term for initials...
4289acfa614a45eabf06742aafc3d62b311d603f
53,318
from operator import or_ def verify_password(email_or_token, password): """ verifies the credentials provided by HTTP Auth, is invoked before endpoint is accessed Args: email_or_token: email address of user or authentication token password: user password (only required in case of login via...
f260408547ba22fea3bbe4f20bd905a5243ac252
53,319
import http def dataverse_config_get(node_addon, auth, **kwargs): """API that returns the serialized node settings.""" return { 'result': serialize_settings(node_addon, auth.user), }, http.OK
6f05d6addc62bbc60383ab5525a16fc3a114267a
53,320
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19'): """Oxford Net VGG 19-Layers version E Example. Note: All the fully_connected layers have been transformed to conv2d layers. To use in c...
042b1f4fcb58fe64d6dd4915959e2bb53ddf72a5
53,321
import requests def get_metadata_param(param_name): """Fetch value of metadata parameter. Args: param_name: str. Name of the parameter to be fetched. """ # Send a request to get param details. resp = requests.get( '%s/%s' % (METADATA_ATTRIBUTES_URL, param_name), headers=M...
e49e4da99d87f9261a016767ad870da13be93b18
53,322
def trace_size_converter(value, params, key): """ Converts trace size from seconds to samples """ params = params[key] if value is None: return None if not value: return value if not params['frequency']: raise AttributeError('No frequency specified for trace-size argu...
87ec3707b36ee76bed365c4a91d4af829161b4b5
53,323
def get_instances_for_module(app, module, additional_xpaths=None): """ This method is used by CloudCare when filtering cases. """ modules = list(app.get_modules()) helper = DetailsHelper(app, modules) details = DetailContributor(None, app, modules).get_section_elements() detail_mapping = {de...
24558c6f22393948c7dbe5019652eab34fc9a3d9
53,324
def base_10_to_alphabet(number): """Convert a decimal number to its base alphabet representation""" return "".join(chr(A_UPPERCASE + part) for part in _decompose(number))[::-1]
3ffae0a103390c1e94ca2a40787f9a9167e39d0a
53,325
import sys def LINE(back=0): """ Prints the line number where this method is called from. :param back: the context of the call, typically you can omit """ return sys._getframe(back + 1).f_lineno
60561044012e1b071d06d85e322128cc3ee20742
53,326
def plausibly_scopes(m: mrs.MRS) -> bool: """ Quickly test if MRS *m* can plausibly resolve a scopal reading. This tests a number of things: - Is the MRS's top qeq to a label - Do any EPs scope over themselves - Do multiple EPs use the handle constraint - Is the lo handle o...
de4a4df640a7073f95f38d22b4c2b9a1979cd5a4
53,327
def decode_chrome_leveldb_bytes(value): """ decode the encoded localstorage values from the leveldb file """ if value[0] == 0: return value[1:].decode('utf-16le') elif value[0] == 1: return value[1:].decode('utf-8') else: msg = "Unable to process Chrome LevelDB bytes in u...
e200c3da3a2f75c215fa13fc12eb12f1034b3e14
53,328
def generate_password() : """ Generate random characters to form the password. """ charSets = [ 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789', '^!\$%&/()=?{[]}+~#-_.:,;<>|\\', ] length = user_input() pwd = [] charset = cho...
12490971aba15afa8e738d47b13d251f386b869b
53,329
def generate_output_paths( output_dir: str, file_name: str, subset_name: str, extension: str ) -> list: """ Generate output paths for results files based on the given output directory, file name, subset name, and extension. :param output_dir: Output directory to which results should be output :para...
46ede2cbaa294326f6553115e883828462421dbb
53,330
import subprocess def attack(attack_rsa_obj, publickey, cipher=[]): """use elliptic curve method, may return a prime or may never return only works if the sageworks() function returned True """ logger.warning( "[*] ECM Method can run forever and may never succeed, timeout set to %ssec. Hit ...
22358ca259b5794842f38ed36eb31087b624d8ff
53,331
def tau_screened_coulomb(energy: np.ndarray, mass_c: np.ndarray, screen_len: np.ndarray, n_imp: np.ndarray, dielectric: float) -> np.ndarray: """ Electron-ion scattering rate — Brook-Herring model Note that for highly doped semiconductors, screen length plays a significant role, ...
5ed656b4271215ef6bf5ccb154897c8fb321eebe
53,332
import torch def test_multiple_optimizers_manual_return_and_log(tmpdir): """ Tests that only training_step can be used """ class TestModel(BoringModel): def __init__(self): super().__init__() self.automatic_optimization = False def training_step(self, batch, ...
af7edda9cb508396c5c0674bb941184b7582b348
53,333
def primary_fuel_ferc1(fuel_df, fuel_thresh=0.5): """ Determine the primary fuel for plants listed in the PUDL fuel_ferc1 table. Given a selection of records from the PUDL fuel_ferc1 table, determine the primary fuel type for each plant (as identified by a unique combination of report_year, respond...
153a91495cfd180f9556d7cb154e761496e48e88
53,334
def simulate_SPRT_fixedtime(sigma, stop_time, true_dist=1): """ Simulate a Sequential Probability Ratio Test with fixed time stopping rule. Two observation models are 1D Gaussian distributions N(1,sigma^2) and N(-1,sigma^2). Args: sigma (float): standard deviation stop_time (int): numb...
4c63d8ee6c426ed67ca7430bdf994c37fe99bf2a
53,335
import requests import logging def get_url_descriptor(url): """ Returns an url descriptor or None on failure """ try: resp = requests.get(url) except requests.exceptions.ConnectionError: logging.error("Error connecting to {}".format(url)) return None if resp.ok: ...
8e09711e08200980c1778fd47673dcaaba67c47b
53,336
import scipy def butter_lowpass(cutoff, freq, order=5): """Butterworth lowpass filter""" nyq = 0.5 * freq normal_cutoff = cutoff / nyq numerator, denominator = scipy.signal.butter(order, normal_cutoff, btype='low', analog=False) return numerator, denominator
3fdee3e8673d87724ad8e594c93f728b422634db
53,337
def year_isnt_int(YEARS): """A funciton to test if years are integers""" return any(type(x) != int for x in YEARS)
d23d093f4655846d07228019b4110e2ef3180c69
53,338
def similarity_matrix(DAG, similarity="intersection", neighbours="successors"): """ Function to produce a similarity matrix based on neighbourhoods of nodes in DAG. Input ----- DAG - networkx directed acyclic graph similarity - type of similarity of sets. Currently only implemented for the size...
e1fb1649465173f0753332bdde49440f306e1c3e
53,339
import sys def A12_2_Classification(CompType, Build, D, b, tw, Fy, E, sigma1 = 0.5, sigma2 = 0.5, alpha = 1.0): """ A.12.2 Classification definitions """ # print("") print ("A.12.2.3 Classification definitions") # # A.12.2.3.1 Tubular member classification ...
6c654edddf63742b28483003161176a3f33ab169
53,340
import logging def open_mail(email: str): """Open up draft email tab in your default browser Args: email (str): email of the person Returns: bool, str: method status, empty string """ url_mail_people = f"mailto:{email}" command_success = True try: open_browser(ur...
e144751d73a3063743c94cb50b2dedca1bb54fee
53,341
import pandas def offset_to_timedelta(offset): """ Convert a pandas-compatible offset (e.g. '3H') to a Timedelta object. """ return pd.to_timedelta(pandas.tseries.frequencies.to_offset(offset))
be470852c5109ede67b2d494456fb4b1447fc2ca
53,342
import os def get_pictures(pictures_dir): """Return a list of picture files found in pictures_dir""" pictures = [] for directory, subdirs, files in os.walk(pictures_dir): for fname in files: if fname.lower().endswith(('.jpg', '.png')): pictures.append(os.path.join(dire...
5bb257fdf3bb910d8c0b45bbc8368a23d17ca7bf
53,343
import json def isJsonDict(s): """ Take a string and determine if valid JSON. """ try: data = json.loads(s) return type(data) == dict except ValueError: return False
222841fc39f78a45f0c682a83282e714a26dc0ed
53,344
from numpy import eye, hstack, ones, vstack, zeros def solve_safer_qp(P, q, G, h, sw, reg=1e-8, solver='mosek', initvals=None, sym_proj=False): """ Solve the Quadratic Program defined as: .. math:: \\begin{split}\\begin{array}{ll} \\mbox{minimize} & ...
add54dc8ea7b9c00bc25d3a57c0fbe78ea8fea0d
53,345
def get_config_constant_file(): """Contiene la obtencion del objeto config para setear datos de constantes en archivo configurador :rtype: object """ # TEST _constants_file = "constants/constants.yml" # PROD # _constants_file = "constants/constants.yml" cfg = Const...
797a0861e8e37f602dc316fe70e1c915614ff22b
53,346
import os def list_dir(data_dir, allowed_extensions=['.json']): """ List files in directory Args: data_dir: data directory allowed_extensions: File extensions were accepted Returns: file_paths: list of files """ file_paths = [] # anot_paths = [] # List files in ...
8de27b39e9d9cc8d17a6b8722c193854e121973c
53,347
def weighted_rmsd(x, y, dim=None, weights=None): """ Compute weighted root mean square deviation between two xarray DataArrays Parameters ---------- x, y : xarray.DataArray xarray DataArray for which to compute `weighted_rmsd`. dim : str or sequence of str, optional Dimension(s) ove...
a4de28d80ff40809eed130e3db5514cdf9724f5b
53,348
def pretty_color_palette(identifiers, keep_zero_black=True): """Return dictionary with pretty colors. :param identifiers: set of unique identifiers :param keep_zero_black: whether or not the background should be black :returns: dictionary """ color_dict = {} for i in identifiers: i...
ba258fe85da7d3516fc2045fffbc1d7b6876b376
53,349
def get_second_derivative_matrix(n): """ :param n: The size of the time series :return: A matrix D such that if x.size == (n,1), D * x is the second derivate of x """ m = n - 2 D = spmatrix(list(chain(*[[1, -2, 1]] * m)), list(chain(*[[i] * 3 for i in range(m)])), ...
e2346da97a073f11eab223097122d939f6813ec3
53,350
def LastIndexOf(s, substr): """Retrieve the last index of substring within a string""" ctx = None ctx = _get_ctx2(s, substr, ctx) s = _coerce_seq(s, ctx) substr = _coerce_seq(substr, ctx) return ArithRef(Z3_mk_seq_last_index(s.ctx_ref(), s.as_ast(), substr.as_ast()), s.ctx)
d560662ba3faffe44dc7fd04e5c4f783b1f2b142
53,351
from ..latent_features import LOSS_REGISTRY, REGULARIZER_REGISTRY, MODEL_REGISTRY, \ def _remove_unused_params(params): """ Removed unused parameters considering the registries. For example, if the regularization is None, there is no need for the regularization parameter lambda. Parameters -----...
a8560054bd005d1bad64ccdced99418b8d5f9931
53,352
def multi_batch_apply(f, num_batch_dims, *args, **kwargs): """Vectorized application of f on tensors with multiple batch dims. Batch dims must be the same for every tensor in args/kwargs. Args: f: Callable, needs only expect one batch dim in input tensors. num_batch_dims: Integer, the number of batch di...
da5ea73c688722e562fe0328bd4fdd351b8bafc9
53,353
import torch def get_similar_comments(embedder, dataset, corpus, sarcasm_embeddings, query, n): """ Returns the most similar comments in terms of cosine similarity of their respective embeddings Parameters: embedder (SentenceTransformer): chosen model from HuggingFace dataset (DataFrame): com...
63de8e5c5f4b0476437c68b48f30a14a28cfe452
53,354
def build_pr_review_line_comment(context, violation): """ Creates a Markdown representation of the comment to be posted to a pull request. :return: The comment """ template = env.get_template("pr_review_line_comment.txt") return template.render( violation=violation, context=context, LINT...
51f08b39077a4d97cf87a71f4e6c43802b9165eb
53,355
def fetch(table, cols="*", where=(), group=(), order=(), limit=(), **kwargs): """ Convenience wrapper for database SELECT and fetch one. Keyword arguments are added to WHERE. """ return init().fetch(table, cols, where, group, order, limit, **kwargs)
e9e3634bc71548a006f14add0a7ed3b308db9a4d
53,356
def gradient_descent(optfun, x0, iterations=100, tolerance=1e-5): """ Given an OptFunction `optfun` and a starting point `x0`, and given parameters `iterations` and `tolerance`, perform the gradient descent algorithm using backtracking line search to minimize `optfun`. This implementation should re...
45b83b31f287b2d2bf97d98a1d1f7b426607d592
53,357
from typing import Optional from typing import Set def list_files( *, storage_bucket_name: str, prefix: Optional[str] = None, ) -> Set[Blob]: """List all files in a given storage bucket.""" client = get_client() return set(client.list_blobs(storage_bucket_name, prefix=prefix))
9b1f8f6b0a3fcb5950f9f758dff7e43b22b6d590
53,358
def position_list_view(request): """ We actually don't want to see PositionForFriends entries in this view :param request: :return: """ # admin, partner_organization, political_data_manager, political_data_viewer, verified_volunteer authority_required = {'partner_organization', 'verified_vol...
326bf422889dab0f2864bbbeaf13109d36d01753
53,359
def _transparent_cmap(cmap, n=255): """transparent heat map color map""" mycmap = cmap mycmap._init() mycmap._lut[:, -1] = np.linspace(0, 0.8, n + 4) return mycmap
90f5ec501f3b3aa9359f4b459d4c0cb533d8e9bd
53,360
import os import pathlib def get_topo_min(soln_dir: os.PathLike, frame_bg: int, frame_ed: int, level: int): """Get the minimum elevation during runtime among the time frames at a specific AMR level. Arguments --------- soln_dir : pathlike Path to where the solution files are. frame_bg, fr...
2562d1c6d0d06eb7b833b9d1e6109e58d32205bb
53,361
import requests from bs4 import BeautifulSoup import re def scrape(): """Scrape the UD project page for metadata of the treebanks. """ session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount("http://", adapter) sessio...
655a7613d97fd9a52b264efc120548a96be0a7be
53,362
from typing import List from typing import Dict def getProjectsPayload(user_id) -> List[Dict]: """ Returns a list of project information accessible to a given user. :return: list of objects containing project information """ global loadedProjects return [{ 'id': p.id, 'name': p...
f4c6bad5ac647125dba085c39c10b7eaecefa274
53,363
def QuantileMerge(feature, nan = -1, n_bins = None, q = None ,min_samples = 1): """Merge by quantile Args: feature (array-like) nan (number): value will be used to fill nan n_bins (int): n groups that will be merged into q (array-like): list of percentage split points Retur...
bab4cd0869df16c075181336dfe9b75851ced8a2
53,364
from datetime import datetime def blog(): """ The blog section will show the user an infinite cascade of blog posts that will load based on the user scroll. """ return dict( title="Blog", year=datetime.now().year )
51a6447ef8081cf8053afbbacfcd145efefca5e4
53,365
from typing import Optional from pathlib import Path import subprocess import json def parse_dhall(content: str, cwd: Optional[Path] = None) -> JSONType: """Takes Dhall content and parses it to JSON compatible data.""" cwd = cwd or Path(".") result = subprocess.run( ["dhall-to-json"], cwd=cwd, ...
d67b2ba3d159b6ff3ce11b536a5e0269abde11ba
53,366
def getMediaTime(sourceName: str): """ Get the current timestamp of media in milliseconds. Supports ffmpeg and vlc media sources (as of OBS v25.0.8) :param sourceName: String - Source name. """ return __createJSON("GetMediaTime", {'sourceName': sourceName})
b28f4ce8c9c696b81fecabc7f927ed4ed6148146
53,367
import random def randbetween(ctx, bottom, top): """ Returns a random integer number between the numbers you specify """ bottom = conversions.to_integer(bottom, ctx) top = conversions.to_integer(top, ctx) return random.randint(bottom, top)
c4e5bf97ee98454aa2802826773f1431800c3f68
53,368
import json def read_dependencies(file_path): """Reads a json file and creates an iterable of unique dependencies. Args: file_path: The path to the runtime dependencies file. Returns: An iterable with unique dependencies. """ deps = None with open(file_path) as deps_file: deps = json.load(de...
52756a443b3a7b0ee6ed1a932b3d1b7984fe4189
53,369
from datetime import datetime def is_inactive( person_data: dict, keyword: str = COMPANIES_HOUSE_RESIGNATION_KEYWORD, date_format: str = COMPANIES_HOUSE_DATE_FORMAT, ) -> bool: """Tests whether board members (default) or controllers are inactive.""" return ( keyword in person_data ...
b2037de136debeca92d7024fd1319ca2d5709bed
53,370
def get_day_menu(which, url): """Parses the day menu from the given url.""" # Assumptions: # - The #content-core contains only <li> items belonging to the menu and <h3> elements that indicate a type. # - All menu items have a price, except vegetables. # - Priced items are of the form "NAME - € X,XX"...
d1f3cc3135e45c3811e8cf1f5f20faa48920dae5
53,371
def _create_heatmap(image_shape, heatmap_shape, annotation_points, kernel): """ Creates density map. annotation_points : ndarray Nx2, annotation_points[:, 0] -> x coordinate annotation_points[:, 1] -> y coordinate """ assert (kernel....
2887102ebb9733d7698fa415f96eedae4c2bb59e
53,372
import random def LabelList(ratio=1, root='~/.mxnet/datasets', name='market1501'): """Load the Label List for Market 1501 dataset. Parameters ---------- ratio : float, default 1 Split label into train and test. root : str, default '~/.mxnet/datasets' Path to the folder stored the ...
382008e530980c279b67e9ad98bb5b6588d1c366
53,373
def get_tags_by_month_for_users(data , usernames): """ initialize list of months and sets for each list of data in data slice out twitter information if username in username list for each tag in hashtags in tweet add hashtag to set in data list :param data - l...
ca2fbfb2137b47fe23c7d113f002e528cb55b3ae
53,374
def customer_edit(request, cid): """ 新增客户 :return: """ obj = models.Customer.objects.get(id=cid) if request.method == 'GET': form = CustomerForm(instance=obj) return render(request, 'customer_add.html', {'form': form}) form = CustomerForm(data=request.POST, instance=obj) ...
bdd4013fae723fc0839451f61d4bf547a65c83ae
53,375
def dynamic_pricing(tfr_dfs): """ Transform the EIA 861 Dynamic Pricing table. Args: tfr_dfs (dict): A dictionary of transformed EIA 861 DataFrames, keyed by table name. It will be mutated by this function. Returns: dict: A dictionary of transformed EIA 861 dataframes, keye...
3898ddbc8cbb1714524bf1f2d5e6307e49fb964c
53,376
def get_annotation(annotation_file, annotation_name, sampling_freq=64): """ Extract annotation from an EDF file annotation_file : EDF handle annotation_name :(str) name of the annoation to get sampling_freq : (int) sampling freq to use to build the event binary representation """ annotation...
b8a75ea245434314162d60fb9a0a471c5bfe4f4e
53,377
import os def get_current_theme_assets_dirs(): """ Returns a path which is the directory root of static assets for a theme. """ roots = [] site = get_current_site() if site is not None: # ``site`` could be ``None`` when this code is used through # a manage.py command (ex: colle...
6af9ed243371fa5b9bcec86ac34ae8f97ca1f930
53,378
def set_header_path(*args): """ set_header_path(path, add) -> bool Set or append a header path. IDA looks for the include files in the appended header paths, then in the ida executable directory. @param path: list of directories to add (separated by ';') may be NULL, in this case nothing i...
7e21d368728720e1150821bbc2895dc9896df72e
53,379
import random def randomString(stringLength=10): """Generate a random string of fixed length """ letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!" return ''.join(random.choice(letters) for i in range(stringLength))
778b7ac606286877eb9f8757d2ad4138bbf1a87e
53,380
def color_balance (input: Tensor, weight: Tensor) -> Tensor: """ Apply color balance adjustment (temperature and tint) on an RGB image. Parameters: input (Tensor): Input RGB image with shape (N,3,H,W) in range [-1., 1.]. weight (Tensor): Scalar weight with shape (N,2) in range [-1., 1.]. ...
98023baa37e84f56d066bcb0fc0973567f2fa0b1
53,381
import json def sort_num(request): """ Sort some numbers from Request """ num_str = request.GET["numbers"] num_lst = [int(n) for n in num_str.split(",")] data = { "num": sorted(num_lst), "status": "ok", "msg": "Integer soarted Succesfully!" } return HttpResponse(json.du...
e39e69403e419e6f98dd182179e7b01f6f5d8edf
53,382
import os def uwsgi(): """Entry point for uwsgi""" config = load_config(os.environ.get("LANAUTH_CONFIG")) if config is not None: app = load_app(config) return app
e5dc44ead76ef95b139df63ca8a61e870b0256c4
53,383
from typing import Dict from typing import Any async def async_setup(hass: HomeAssistant, config: Dict[str, Any]): """Import integration from config.""" if DOMAIN in config: for entry in config[DOMAIN]: hass.async_create_task( hass.config_entries.flow.async_init( ...
c7c4269577b7ab9c9169bbb0ec390bc21e2ae948
53,384
def get_cephfs_data_pool_name(): """ Fetches ceph fs datapool name from Ceph Returns: str: fs datapool name """ ct_pod = pod.get_ceph_tools_pod() out = ct_pod.exec_ceph_cmd('ceph fs ls') return out[0]['data_pools'][0]
5344974df8cb23c45bd9696abef6f5c7ae3f19e0
53,385
def no_identical_digits_in_same_block(): """Returns a list of clauses, stating that if a digit appears in a cell, the same digit cannot appear elsewhere in the same row, column, or 3x3 square.""" bigi = 0 bigj = 0 list = [] for big in range(9):# The 9 big boxes if (bigj > 2): ...
16a47e272e256bc0b0eac20d301d8271e4421e28
53,386
def xgb_average_recalln_curve_score(n): """evaluate average recall-n curve score for xgb""" def feval(preds, labels): labels = labels.get_label() trials = np.argsort(preds)[::-1] ranks = get_rank(labels[trials]) curve = recall_curve(ranks) return "a-recall@%d" % n, np.su...
111de0aa1e50f1b46a4d05cfde9e69271010dd3a
53,387
def view_organization(organization_id): """ Function enables user to view an Organization from the database. """ try: organization_id = int(organization_id) if not organization_controller.query_organization(organization_id): return jsonify({ 'message': 'Organi...
625621e3bd881cdac7408291490bfc6db2ab6494
53,388
def get_face_rectangles(azure_response): """ Returns the rectangles corresponding to the faces detected by Azure :param azure_response: Response from Azure Face request as dictionary. :return: The rectangles of any detected face with the format: (width, height, left, top) """ result = [] for...
d07e40f1b4c648c52ea660179f8d8c1f4957f0db
53,389
import math def SchaffersF7(arr: np.ndarray, seed: int = 0) -> float: """Implementation for BBOB Weierstrass function.""" dim = len(arr) arr.shape = (dim, 1) if dim == 1: return 0.0 z = np.matmul(_R(dim, seed, b"R"), arr) z = Tasy(z, 0.5) z = np.matmul(_R(dim, seed, b"Q"), z) z = np.matmul(LambdaA...
997c6d34e3dafb1151399d03f8aee59469761785
53,390
def retr_spacegroup_number(xtalstr,ini0): """ Retrieve the space group number. When choosing real space grids some space groups imply restrictions on the number of points along the different lattice vectors. To impose the correct restrictions we need to know the space group number of the curren...
f86827aa089b79c054fe8c4d78c5a6da48f0463e
53,391
def GetLocationFlag(): """Anthos location flag.""" return base.Argument( '--location', required=False, help='Specifies the Google Cloud location to use. If not' 'specified will use the current compute/zone property.')
db4754bbb31429e2e743d48eabffcff60d68076a
53,392
def get_user_credentials(env_ctx, upgrades): """ Prompt for snaplogic user credentials. If upgrades required then ask for admin user. """ credentials = None print "" user = 'admin' password = input_value("Please specify the SnapLogic admin Password:", "", False, True) env_ctx['SNAPLOGIC_...
d693c4001688166095a6531e96bf6ec3418ef5f8
53,393
def rmse(y_true, y_pred): """ Calculates the RMSE value for forecast Values Args: y_true: True time series type: np.array y_pred: Predicted time series type: np.array Return: score: RMSE value for forecast values ...
f7702f3638482fcb8a2d638f942ab12d244e105d
53,394
def build_yolo_augmentation(cfg, is_train): """ Train Augmentations: - YOLOFJitterCrop - YOLOFResize - YOLOFRandomDistortion - RandomFlip Test: - YOLOFResize """ augmentation = [] if is_train: if cfg.INPUT.JITTER_CROP.ENABLED: augmentat...
b8ef6bbd4068131d37d736d065b94d2c2a5b68b9
53,395
def get_mean_expression(fnames, name, sep="\t", gene_set=[]): """Get mean expression for replicates of one time point.""" dfs = [get_expression(fname, sep=sep, gene_set=gene_set) for fname in fnames] joined = pd.concat(dfs, axis=1, join="inner") return joined.mean(axis=1).rename(name)
2ead6d81fa378b091dbb96aeffec769856ee8146
53,396
def find_random_monster(min_cr=None, max_cr=None, environment=None): """ Find a random monster """ filters = [ {'$sample': {'size': 1}} ] if min_cr: query = {'$match': {'challenge_rating': {"$gte": float(min_cr)}}} filters.insert(0, query) if max_cr: query ...
a1a9560cc3702c867bffb19e662079b2a795ec08
53,397
import re def make_vowelify(words): """Chop off consonant ala nautica if second to last letter is a vowel.""" new_arr = [] for word in words: if re.search(_regexes['all_vowels'], word[:-2]): new_arr.append(word[:-1]) return new_arr
4d674bd9b031720768d6109a3ca8f864a6d7788b
53,398
def sketch_by_name(sketches: adsk.fusion.Sketches, name: str) -> adsk.fusion.Sketch: """ Finds a sketch by name in a list of sketches Useful for parsing a collection of sketches such as DXF import results. :param sketches: A list of sketches. :type sketches: adsk.fusion.Sketches :param name: Th...
1051785c48aaad0833c7786d5a9152c716e18cd2
53,399