content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def objectify(value): """converts almost anything to an Obj()""" if isinstance(value, Obj): return value if hasattr(value, '__float__'): return float(value) if hasattr(value, '__dict__'): value = value.__dict__ if isinstance(value, dict): value = Obj(value) elif i...
5ccb93af73cac891b7a2c92988f432095f026839
65,200
import os import glob def find_package_data(base, globs): """Find all interesting data files, for setup(package_data=) Arguments: root: The directory to search in. globs: A list of glob patterns to accept files. """ rv_dirs = [root for root, dirs, files in os.walk(base)] rv = [] ...
e36d29c6952662ebe0fd9dde036c1e093545fdb3
65,201
import json def recurso_eventos_json(request, pk): """ Retorna en formato JSON una lista de los eventos para una instancia específica de Recurso (cuyo ID está dado por el parámetro 'pk'). Si se especifican los parámetros GET 'start' y 'end' (ambos con formatos de fecha válidos), los eventos a ret...
57a86f4fc62199af2b70ec035f87b71b82d2cbc8
65,202
def model_fn(features, labels, mode, params): """Constructs a spectrogram_lstm model with summaries. Args: features: Dictionary {name: Tensor} of model inputs. labels: Any training-only inputs. mode: Build mode, one of tf.estimator.ModeKeys. params: Dictionary of Model hyperparameters. Returns: ...
72165b12effda02af072aa7a5390ecfb44ecc6bf
65,203
import re def find_IMGT_alignment(filename, HLAtyping, header_line = 8): """ Find the aligned sequence from the database file """ # Read alignment file alignment_list = IMGTdbIO.read_IMGT_alignment(filename, header_line) HLAtyping_pattern = re.compile(re.escape(HLAtyping)) ## pattern - f...
23045feb406d25d00b7ae14325acbc5c9e3a598b
65,204
def rbc_intersects(rbc, rbcs, max_overlap): """Check if `rbc` intersects any rbc in `rbcs`""" if len(rbcs) == 0: return False rs = np.array([x.radius for x in rbcs]) pos = np.array([x.position for x in rbcs]) dists = (((rbc.position - pos))**2).sum(axis=1) ** 0.5 overlaps = linear_spher...
2a39df42188c16089d08b417feb853ba6d4063a8
65,205
import MySQLdb def getCurrentDimm(): """ Return current DIMM measurement """ cnx = MySQLdb.connect(host='eeva',user='select_user',passwd='select_pass',db='SiteData') cursor = cnx.cursor() cursor.execute("""SELECT AVG((fwhmhorl+fwhmvert+fwhmverl)/3) FROM RoboDimmING WHERE DateTi...
b72562dafc490f2165390251da784eb57f839e92
65,206
def grad_eigh(w, v, vg): """Gradient for eigenvalues and vectors of a symmetric matrix. Parameters ---------- w: eigenvalues v: eigenvectors vg: adjoint eigenvectors """ vc = v # real N = 3 # wg, vg = g # Gradient w.r.t. eigenvalues, eigenvectors. w_repeated = np...
9dcdda89efcb84a88ef3b6501091412fbd06b33e
65,207
import os def api_helper(csrf_enabled=True): """ Helper function for handling request and preparing audio download. 1) Processes the request, extracting form data 2) Runs nanotts with requested parameters 3) Returns processed form and audio file """ text = None audio_file = None re...
c625ad0842612bafb9a5a71946539317cee9366f
65,208
def _confusion_matrix(y_true, y_pred): """Creates a confusion matrix.""" cm = np.zeros((10, 10)) for true_digit in range(10): y_pred_digit = y_pred[y_true == true_digit] digits, counts = np.unique(y_pred_digit, return_counts=True) for digit, count in zip(digits, counts): ...
32129d162f3a8196e3b658ab818b2b45316b216c
65,209
from datetime import datetime def get_next_market_open_hours(market='XNYS'): """Get next market open hours. Default market is NYSE for US market hours.""" today_market_open_dict = rs.markets.get_market_today_hours(market=market) current_time = parser.parse(datetime.now(timezone.utc).isoformat()) if to...
e380cec0caa48ddda09d1e5901d217b879f235ef
65,210
import math def increase_worth_reporting(value, new_value=None, *, total=None): """ Make reporting sparser and sparser as values grow larger - report every 1.1**N or so - if we know total, report every percent """ if new_value is None: new_value = value value = new_value - 1 if...
7bb1577f5e73e91ea2e6a46af8db0e74386984cb
65,211
def find_flowline_in_list(aFlowline_in, pFlowline_in): """[find the index of a flowline in a list] Args: aFlowline_in ([type]): [description] pFlowline_in ([type]): [description] Returns: [type]: [description] """ iFlag_exist = 0 lIndex= -1 nFlowline= len(aFlowline_...
4cec86e218f3bab9e4ac73510d908f7fe8271830
65,212
def decov_loss(xs): """Decov loss as described in https://arxiv.org/pdf/1511.06068.pdf 'Reducing Overfitting In Deep Networks by Decorrelating Representation' """ x = tf.reshape(xs, [int(xs.get_shape()[0]), -1]) m = tf.reduce_mean(x, 0, True) z = tf.expand_dims(x-m, 2) corr = tf.reduce_mean(...
c1c58a84f56760a6fb434deca8a764aeebd4603e
65,213
def verify_interface_protocol(device, interface, expected_protocol, invert=False, max_time=60, check_interval=10): """ Verify protocol shown via show interfaces te...
af05814dcc7b8e6a7f7e364dfc27c20bee483c3a
65,214
from typing import Tuple from typing import Dict def calc_stats_around_peak(time: np.ndarray, signal: np.ndarray, peak_bounds: Tuple[int], valley_rel: float = 0.05, time_scale: float = TIME_SCALE, ...
6e937b3ecedddca42e0e350ca433f71a427b248e
65,215
def create_one_hots_from_labels(labels, n_classes): """ Create one-hot vector from the class label distribution. self.one_hots -> np.array([[0,0,1,0], [0,1,0,0], [0,0,0,1], ... ,[0,1,0,0]]) """ length = len(labels) one_hots = np.zeros((length, n_classes), dtype=float) one_hots[(np.arange(len...
8cd94dacc6b38c4a11378f88f5159f72b4580ec3
65,216
def TPrsStd_ConstraintTools_ComputePlacement(*args): """ :param aConst: :type aConst: Handle_TDataXtd_Constraint & :param anAIS: :type anAIS: Handle_AIS_InteractiveObject & :rtype: void """ return _TPrsStd.TPrsStd_ConstraintTools_ComputePlacement(*args)
2e9af45fe4e7289afa3916c91ad23c980207cd71
65,217
from typing import Dict from typing import List import logging def process_clean( data: Dict[str, List[Dict[str, str]]], *, save_pickle=False ) -> Dict[str, pd.DataFrame]: """ Takes a dict with values representing types of data (cases, deaths, tests...). Each value is a list of ordered dictionaries co...
71a80c76e4894a4ccc84158c924d2a5a132bfb62
65,218
def login(): """Login a user.""" form = LoginForm() if form.validate_on_submit(): user = db_session.query(User).filter_by(username=form.username.data).first() if user is None or user.password != form.password.data: user = db_session.query(User).filter_by(email=form.username.data...
4646f36f9ac68e0c8bb3ca9887c75cc0d7e32a7c
65,219
def getConfig(config, key): """ 获取指定key的配置【NC】 :param key: :return: """ return config[key]
cf53e746a5004705b8265024c1ac884fc9c6adce
65,220
import re def explode(collapsed): """Explode collapsed references like 'C1-C3,C7,C10-C13' into [C1,C2,C3,C7,C10,C11,C12,C13]. Args: collapsed (string): String of collapsed references. Returns: list: list of reference strings. """ if collapsed == "": return [] indivi...
1f837c1538a2feda2cfe6a4b4023db20c456f338
65,221
from typing import List from typing import Optional def get_domain_index(query: str, domains: List[Domain]) -> Optional[int]: """Finds the earliest index of a domain in a list of domains, if present.""" for index, domain in enumerate(domains): if query == domain.type: return index retu...
dd10361407d5e8338668406abe5f478be956cc7a
65,222
import calendar def month_delta(date, months): """Add or subtract months from date.""" day = date.day # subtract one because months are not zero-based month = date.month + months - 1 year = date.year + month // 12 # now add it back month = month % 12 + 1 days_in_month = calendar.monthr...
afa064af13c67be776a7f01ce48fc6ed2f33f581
65,223
def flat(num_samples, **kwargs): """ method to run a sampling for a flat distribution IN: num_samples : number of samples to be returned x (float) : The flat value for sampling OUT: a list of num_samples zeros """ x = kwargs['x'] return np.ones(num_samples) * x
30e7fae9623b0ca82629618e014bf073a89ae896
65,224
def patch(img, gt_boxes, gt_landmarks): """Generating random patch and adjusting image and ground truth objects to this patch. After this operation some of the ground truth boxes / objects could be removed from the image. However, these objects are not excluded from the output, only the coordinates are chan...
d1dac57c210dc76c0585003c939297e0a5c865ec
65,225
from typing import Any def detect_flow_directions(exprs): """ Return a mapper from Dimensions to Iterables of IterationDirections representing the theoretically necessary directions to evaluate ``exprs`` so that the information "naturally flows" from an iteration to another. """ exprs = as...
a6dff9a6a5c19265c3a098a0802e2f8688bb4d3d
65,226
def get_config(workflow: "Workflow") -> DictNone: """Returns the compose-flow project config file By default, this will check for a compose-flow file in compose/ with the same name as the project name, e.g. compose/compose-flow.my-project.yml. when a file with the same name as the project is not found...
c71d87a1e7aa7209322c819ba4a4e1f9c2921188
65,227
def private_vars_at_toplevel(abstract_syntax_tree): """Check that private variables defined at the top level are used later.""" errors = [] variables_set = find_all.toplevel_set_private_vars(abstract_syntax_tree) def _not_in_variables_set(node): """Return false if in variables_set.""" ...
8f495e1bfb991c5c5dd4b00e2d6c082635151a65
65,228
def _base_lal_cbc_fd_waveform( frequency_array, mass_1, mass_2, luminosity_distance, theta_jn, phase, a_1=0.0, a_2=0.0, tilt_1=0.0, tilt_2=0.0, phi_12=0.0, phi_jl=0.0, lambda_1=0.0, lambda_2=0.0, eccentricity=0.0, **waveform_kwargs): """ Generate a cbc waveform model using lalsimulation ...
133cad012e533f6dc9c61b78930734b5971e1769
65,229
import os def catch_all(path: str, app, public_folder, title, extend_head, custom_javascript, *args, **kwargs) -> str: """ Catch all routes and redirect them to the index page where the Router takes over the rest of the navigation. """ with app.test_request_context(): if path == "public/in...
d742cd6c88131442110fde29c9fe5f436014dd6e
65,230
async def format_stats(color: str, equip: str): """Formats stats to create a uniform message block. Args: color (str): color of the gem equip (str): the equip slot to use Returns: str: a formatted message with all values and stats """ for stat, stat_values in values[color]...
248690a81dba350a19b6b94092cddce54b5b7e65
65,231
def select_rimed_node(data_cont): """select the rimed nodes from a peaktree data container The nodes are filtered by the rule: ``abs(n['v'][0]-n['v'][-1]) > 1.5`` Args: data_cont: peakTree data container Returns: data_container with selected indices in ``var`` of shape ``(time, ran...
1b6e2dffed07ec54244c67cb9c711f7470d9340f
65,232
def immediateload(*keys): """Return a ``MapperOption`` that will convert the property of the given name or series of mapped attributes into an immediate load. The "immediate" load means the attribute will be fetched with a separate SELECT statement per parent in the same way as lazy loading -...
f57805d0417e546dcfb12292dfe07e951a8a5f4a
65,233
def get_best_worst_cost(petri_net, initial_marking, final_marking, parameters=None): """ Gets the best worst cost of an alignment Parameters ----------- petri_net Petri net initial_marking Initial marking final_marking Final marking Returns ----------- b...
e52838e654b8f35173062d1b3f1a042a2f8f1da5
65,234
def get_vat(env: GymEnv) -> np.ndarray: """ Checks whether gym env exposes a method returning valid action trees :param env: the Gym environment to get masks from :return: A numpy array of the masks """ if isinstance(env, VecEnv): return np.stack(env.env_method(EXPECTED_METHOD_NAME)) ...
e399462b31b3548f2c5a61074d6cbc9897479444
65,235
def animate_line(data, animate_over='t', animate=True, vmin=None, vmax=None, fps=10, save_as=None, sep_pos=None, ax=None, controls=True, **kwargs): """ Plots a line plot which is animated with time. Currently only supports 1D+1 data, which it plots with animatplot's Line a...
4311ea0916f8101056ddead4c259525e9e3ea129
65,236
from typing import Dict def spike_count(data: Dict[int, np.ndarray]) -> int: """ Count the number of total spikes emitted by the neural network in the data. :param data: A dictionary keyed by neuron ID and valued by a numpy array of spike times. :return: The number of spikes. """ num_...
b49a3f2fc75d0a90e1caff4bd49a4c1dfde84a79
65,237
from io import StringIO import re def dqstring2bracestring(dq): """!Converts a bash-style double quote string to a tripple brace string. @param dq The bash-style double quote string, minus the surrounding double quotes.""" output=StringIO.StringIO() for m in re.finditer(r'''(?xs) ( ...
7412d29cd6f4b0c45f503b94abf860f5a94bae19
65,238
def get_attribute(obj, key): """ Get an attribute from an object, regardless of whether it is a dict or an object """ if not isinstance(obj, dict): return getattr(obj, key) return obj[key]
bb20ac5809cf89b8043ff1fc60b9e4775ca95d18
65,239
def make_encoder_layer(inc, outc): """ makes complex encoder layers Parameters ---------- inc: int number of input channel(s) outc: int number of output channel(s) Returns ------- Sequential a sequential neural net consisting a convolution layer, batch normal...
7446ad79a4e956f900873adad72b9054fc498f03
65,240
def m2q(m): """Convert rotation matrix into SPICE quaternion. Parameters ---------- m: np.array 3x3 rotation matrix. Returns ------- np.array SPICE quaternion. Raises ------ ValueError If the rotation matrix does not contains 9 elements. ValueError ...
56602dc92761eaf60ced5ba9003a32a9a8eacfe9
65,241
import requests import time def getData(base, path, parms=None): """ this is a general-purpose query helper """ u = base + path try: r = requests.get(u, timeout=3, params=parms) # print(r.url) except requests.Timeout: print(f"{time.asctime()}: Timeout fetching {u} {parms}") ...
42d6271422c112b6ebf2469d340ae46ebb5a95e4
65,242
def GetMatchingServices(all_services, args_services): """Return a list of services to act on based on user arguments. Args: all_services: list of Services representing all services in the project. args_services: list of string, service IDs to filter for, from arguments given by the user to the comman...
b781f6e147d16778b4fd1085b4283c8a5cb0b451
65,243
def tokenize(text): """Tokenize text into words and keep only some words.""" words = nltk.word_tokenize(text) return list(set([word for word in words if len(word) > 1 and not word in english_stopwords and not (word.isnumeric() and len(word) is n...
9109b319bc446d83b6fce0e3dd29c919acaf9c64
65,244
from web.apps.vibora_app import ViboraApplication from vibora import Request, Response def vibora_app(port): """ With logging """ app = ViboraApplication() class AsyncHandler(Handler): async def __call__(self, request: Request) -> Response: return super().__call__(request...
ec8fc6f879911a4d92c3887a355ecc82081c5a52
65,245
def sales_product(): """ Monthly sales of a plastic manufacturer's product, Jan 2001 - May 2012 """ return _get_df_from_file("monthly-sales-of-product-a-for-a.csv")
ff812d947940d771abd5d8ad9af833176b6800c0
65,246
import os def getParts(path): """ Return the slash-separated parts of a given path as a list """ if path == os.sep: return [os.sep] else: return path.split(os.sep)
ea39dedb08a825f4eada9d8b3d7697746093b8db
65,247
def make_blueprint(db_connection_string=None): """Create blueprint. """ controllers = Controllers(db_connection_string) # Create instance blueprint = Blueprint('taxonomies', 'taxonomies') # Controller Proxies @check_permission([Permissions.taxonomyRead]) def query_taxonomies_(): ...
d16e929dfe0790db764c727cca4cab2ad80c3144
65,248
from typing import List from typing import Tuple def make_mask_ternary(mask): """ Takes 0/1 mask and makes -1/0/1 mask, setting 0 to -1, and those -1, which are far away from 1 to 0 (so we do not look at them) """ useless_cells:List[Tuple[int, int]] = [] for i in range(mask.shape[0]): ...
90518f1db10961c7cb1e0647d491a47786b6caba
65,249
def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): api_token = _find_valid_api_token() if api_token is None: www_authenticate = WWWAuthenticate('Bearer') abort(401, www_authenticate=www_a...
4b7561efec212d28cdb11575034d29f4b2c0d94f
65,250
from datetime import datetime def lease(queue_name, owner, count=1, timeout_seconds=60): """Leases a work item from a queue, usually the oldest task available. Args: queue_name: Name of the queue to lease work from. owner: Who or what is leasing the task. count: Lease up to this many ...
0b01ad2f4871c89073de8b17ef637033bd587f5c
65,251
import html def display_current_user_message(page): """Displays current user message Arguments: page (obj): Page content Returns: str: Welcoming message """ if page and current_user.is_authenticated: return html.Div( children=["Welcome " + current_user.userna...
24090ab8530fe0dcab05905ec3dfb18b5c22ef38
65,252
import argparse def parseArgs(): """Gathers comand line options for the script, generates help text and performs some error checking""" usage = "usage: %prog [options]" parser = argparse.ArgumentParser(description="Create a configlet in CVP CVP") parser.add_argument("--username",required=True, help='U...
00167b8c648876dcc4f39fdd8e5184628a3136d0
65,253
def get_time_range_for_smoothing(user_id): # type: (uuid.UUID) -> emission.storage.timeseries.timequery.TimeQuery # Returns the time range for the trips that have not yet been converted into sections. # Note that this is a query against the trip database, so we cannot search using the # "write_ts" query...
7ba44c569ba04e7aa1e1cf5e58cf1873396de0d4
65,254
import math def check_anomaly(day_data_tuple): """ Find mean, std, and maximum values for the day. Using a single pass (online) mean/std algorithm allows us to only read through the day's data once. Note: M2 = 2nd moment, variance day_data is an iterable, returned from groupby, and we reque...
50cf3820a8839584aafefaba1e3219dbdf6a24d0
65,255
import joblib def generate_data( constants: SimDataGenConfig, run_idx: int = 0, return_raw: bool = True ): """ Generate a training and testing dataset of idealised disease treatment. """ data_path = ( f"data/test/idt_{constants.n}_{constants.p_0}_{constants.mode}_{run_idx}.joblib" ) ...
766787b06f0899074aa5c1212b15607fd988e2f8
65,256
import distutils def _has_command(command: Text) -> bool: """Determines whether a command is available in the user's shell. Args: command: The name of the command. Returns: Whether the command exists. """ return distutils.spawn.find_executable(command) is not None
a696635977999814e146568ca0de6888a900272d
65,257
def search_talks(page=None, sort=None): """ Get Talks from by Topic from ElasticSearch """ client = Elasticsearch([{ 'host': settings.ELASTICSEARCH['default']['HOSTNAME'], 'port': settings.ELASTICSEARCH['default']['PORT'], }]) s = Search(using=client, index="vtalks") # Paginati...
4f652fa5c56e092efacf105d125684a01c6bfdd1
65,258
import lumapi from typing import Optional from typing import Tuple from typing import OrderedDict def run_wavelength_sweep( component: Component, session: Optional[object] = None, port_in: Tuple = None, ports_out: Tuple = None, wavelength_range: Tuple = (1.500, 1.600), n_points: int = 1000, ...
8fcd960dea9946e7cac0c4aab553a178702eaf63
65,259
from typing import Callable from typing import Union from typing import Sequence def grad( fun: Callable, argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False, ) -> Callable: """Create a function that evaluates the gradient of `fun`....
7ba3873c6f7fb15dfa310e956e813daf047d71b7
65,260
def load_room(name): """ There is a potential security problem here. Who gets to set name? Can that expose a variable? """ return globals().get(name)
3673f14c5313b649043e905e4f697669853bd49d
65,261
def root_mean_squared_error(vector): """Calculate the root mean squared error of an error vector""" return np.sqrt(np.mean(np.square(vector)))
c010b2afa3027911da4fe4d2157aeef09953cfb0
65,262
def reload_cmd(virtualenv_conf): # type: (VirtualenvConf) -> unicode """ This returns the command line to reload the webserver after deploying changes. If you set HostConf.reload_once to True, it will be called only once for each host, else it will be called for each virtualenv. :param virtuale...
59ae066a3a7354e08360a4b2a15493a9bea2d94b
65,263
import astropy.units as u def ROI_defCoords(ROI_Lon_Lat_Wd_Ht): """ Define a ROI on Map Coordinates """ lon0, lat0, width, height = ROI_Lon_Lat_Wd_Ht Coords = { "lon": (lon0 * u.deg, (lon0 + width) * u.deg), "lat": (lat0 * u.deg, (lat0 + height) * u.deg), } return Coords
8402cfe81e5803d52adda5d88538b75470e785cf
65,264
def mellowmax(x, t=1.0): """Numerically stable mellow maximum of a vector Unlike softmax, mellowmax is a contraction mapping, which means it has a unique fixed point. Args: x (numpy array): Vector of values to take mellow maximum of t (float): Temperature parameter. As t -> 0, this resemb...
e8e3d0c23653832e2a756e7327bbe0153d3e981f
65,265
def check_log_group_exists(log_group_name, access_key, secret_key, region): """ Check wheter the given cloudwatch log group already exists in AWS account Args: log_group_name (str): Cloudwatch log group name access_key (str): AWS Access Key secret_key (str): AWS Secret Key r...
76673c36654db182ef06ac819814fd43c870aa58
65,266
def is_pem_private(pem, keytype='rsa'): """ <Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_k...
2e65066b8458dc50aefde553cdd9386c015f9956
65,267
def buildModel(): """ Gathers information from the DB and calls creates an HMAC/OMAC Model ..note:: Call this before optimize() This resets/rebuils the global object Model :returns: True if Model was built; False if not. """ global DBConn global OptimizationModel logger.info(Messages.Buildin...
c17c4791704f2e2f92f9e8a23d0e3de1a502a150
65,268
import sqlite3 def csrf_validate_and_comment(username, request) -> bool: """ validator function defined for the CSRF lesson. checks if request came from same host. If not, and the validateReq field contains the right value, insert a comment and complete the lesson request - a flask request object ...
02939c1a908a516e3ea15c8958d93663ed9c50d4
65,269
def float_env(var_name, default=0.0): """ Get an environment variable coerced to a float value. This has the same arguments as bool_env. If a value cannot be coerced to a float, a ValueError will be raised. """ return float(getenv(var_name, default))
4dafb32ef87a710f0a2d5c65f4da82cb9368114c
65,270
def parse_message(message, doc): """ In XNotify settings, you are allowed to add placeholders for the invoice's grand total and the invoice number. This function allows you to 'compile' the message and returns a new string with the placeholders replaced with actual information from the Sales Invoice doctype object...
793e6e5184ae520c35cb33225cde99090acd27de
65,271
from datetime import datetime import csv def clean_data(header, data_list, out_file="cleaned_data.csv", **kwargs): """ Function cleas data, removes rows which don't fit the parameters set in kwargs :param header: list -> Header row for csv output file :param data_list: list(list(), list(), ...) -> Lis...
642de30dd7d3a9b81e34a0419a150de54e6d0b7d
65,272
import tqdm def SCW_II(x_list, y_list, mu, sigma, C, eta): """ Update weight parameter using SCW-I update rule on the given data. Params: x_list(csr_matrix): list of feature vector y_list(list): list of labels mu(csr_matrix): current weight parameters sigma(csr_matrix): current...
7c4ba73f8321765929d4d25db151ded18103cbf7
65,273
def evans_full_combined(): """ compute the evans function for the non-axial non-diagonal case. """ bif = np.loadtxt('evans_full.ode.all_info.dat') # sample evans zeros reA = bif[420,8] imA = bif[420,9] reB = bif[244,8] imB = bif[244,9] fig = plt.figure(figsize=(8,5)) ...
ae1a453c526b3ad88335553e0633b9a0402904b7
65,274
def all_clusters_conf(): """ 获取所有HDFS集群的连接信息,包括区域列表,以及区域对应的hive metastore地址信息。 :return: 字典,包含HDFS集群的连接信息。 """ result = {GEOG_AREAS: [], HIVE_METASTORE_URIS: {}, HDFS_CONF: {}} for geog_area in list(HIVE_METASTORE_SERVER.keys()): port = HIVE_METASTORE_SERVER.get(geog_area, {}).get(HIVE_ME...
dbdb62c3d923b31df75c8c420df4851d2bbd8d99
65,275
async def has(path: str) -> bool: """ Test whether object exists in bucket """ _ = path.strip('/').split('/') bucket = _[0] key = '/'.join(_[1:]) async with _create_client() as client: try: await client.head_object(Bucket=bucket, Key=key) return True except Cl...
1c38da03ce0e4ec3db14ff37a1621151c2b23371
65,276
def gini( array ): """Calculate the Gini coefficient of a numpy array.""" # based on bottom eq: http://www.statsdirect.com/help/content/image/stat0206_wmf.gif # from: http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm array = array.flatten() #all values are treated equally, array...
8b70c23c0d6293972b6be5ce641c17b45e9ade62
65,277
def calculateJacobiMatrixSinj(measurements, nodes_num, Gmatrix, Bmatrix, inj_code, type): """ It calculates the Jacobian for Power Injection Measurements (converted to equivalent rectangualar current measurements) @param measurements: object of class Measurement that contains all measurements (voltages...
8aee9a4272693af09d767571de133cc68c053880
65,278
import requests import io import json def recommend_project(request, person_id): """recommend projects api""" # NLP LOGIC STARTS HERE projs = requests.get('http://localhost:8000/api/project/') projs = projs.json() projs = pd.DataFrame.from_records(projs) user = requests.get("http://localhost:...
08a29d95b2fa3958dbc4eb596d307b5058ed9495
65,279
def _add_to_grid(x, y, marker, color): """It adds data to the plot grid.""" h.xplot=[] h.yplot=[] for i in range(len(x)): c=int((x[i] - h.xmin)/h.dx) r=int((y[i] - h.ymin)/h.dy) if 0<=r<h.rows and 0<=c<h.cols: h.xplot.append(c) h.yplot.append(r) ...
6e8faa25d818c382680bbb98c9e007ff9be043ea
65,280
import re def remplace_accents(text: str) -> str: """Remplace spanish accents vocab lower case: Unicode code point literal to str""" text = re.sub(r"á", "a", text, flags=re.I) text = re.sub(r"é", "e", text, flags=re.I) text = re.sub(r"í", "i", text, flags=re.I) text = re.sub(r"ó", "o", text, flags...
d9967d401c637ae5674f88ce72cc86bf7143ba96
65,281
def encodeProductionCompany(df, filter, threshold): """ MultipleHotEncode column production_companies Json loads does not work here Regex to extract needed values Seperate them with | for MultipleHotEncoding :param df: DataFrame :param filter: boolean if set should be filtered by threshold ...
89d97f6a6c4e2d48e2c7823cebc58e6c47ff14ec
65,282
def mock_get_fire_centre_station_codes(__): """ Returns mocked WFWXWeatherStations codes. """ return all_station_codes
dcaf4c80720427aad43c162368a44fa72ffd4ca7
65,283
def b(n): """ Simple function to approximate b(n) when evaluating a Sersic profile following Capaccioli (1989). Valid for 0.5 < n < 10 Parameters ---------- n: float or array Sersic index Returns ------- b(n): float or array Approximation to Gamma(2n) = 2 gamma(2n,b(n))...
c0a236c1394cdac31559c2d376b0d62d023e5709
65,284
from typing import Optional from datetime import datetime from typing import Any async def get_next_task( *, now: Optional[datetime] = None ) -> tuple[int, str, dict[str, Any], datetime, Optional[int]] | None: """ Get and lock the next pending task. Must be called from within a transaction. """ ...
34784db0a60b43d7a93e4f247f1c53e0d99a8c7e
65,285
from typing import List def compute_sigma_for_given_alpha(bundles:List[float],alpha:float)->float: """ This is a helper function to compute_alpha5_using_binary_search. the function computes one side of the inequality . :param bundles: valuations of the bags from B1 to Bk, were k is number of agents ...
08ae1c84f13de03b5404158de146b05b9efbfdce
65,286
def process_upstart_file(pim, filename): """Process the UPStart UPE file.""" try: with open(filename) as file_handle: _process_file(pim, file_handle) file_handle.close() return True except EnvironmentError as exc: LOG.error("Cannot open UPStart file: %s", exc)...
c9d42066965d42f8bb3875578857ae3d300d0355
65,287
def _make_line_map(target_filename, stream=None): """ >>> from StringIO import StringIO >>> _make_line_map('box', ... StringIO('''// ###sourceLocation(file: "foo.bar", line: 3) ... line 2 ... line 3 ... line 4 ... // ###sourceLocation(file: "baz.txt", line: 20) ... line 6 ... lin...
d8822c2e8ea026a40cc45c5758aa5feb3fbf5f00
65,288
from unittest.mock import Mock def test_app_context_thread(flask_app): """Test accessing flask.g from another thread.""" mock_action = Mock() @flask_app.route(TEST_URL) def test_handler(): g.test = TEST_G thread = AppContextThread(target=lambda: mock_action.action(g.test)) thr...
8c44ecf35cbe08dba54576ea964abcc99500a399
65,289
from desispec.qa import qalib import copy def qa_skysub(param, frame, skymodel, quick_look=False): """Calculate QA on SkySubtraction Note: Pixels rejected in generating the SkyModel (as above), are not rejected in the stats calculated here. Would need to carry along current_ivar to do so. Args:...
7c0874e607efe4fa7b5b3e3507aeb3868f07b5e0
65,290
def ind2(e,L): """returns the index of an element in a list""" def indHelp(e,L,c): if(c==len(L)): return c if(e==True): return c if(e == L[c]): return c return indHelp(e,L,c+1) return indHelp(e,L,0)
bab0ba443e3b5d9223b6af82763c92e03c91dcb9
65,291
async def member_novel( id: int, page: int = 1, size: int = 20, endpoint: PixivEndpoints = Depends(request_client), ): """ ## Name: `member_novel` > 通过用户ID获取用户小说列表 --- ### Required: - ***int*** **`id`** - Description: 用户ID --- ### Optional: - ***int*** `...
e4673442145d06d5fcf0e2783263e71d534bd877
65,292
def index(): """Show homepage""" # users = User.query.count() return render_template('site/index.html') # return render_template('site/index.html', users=users)
b7abdec6e0d2b922b83bb00cb9ab9255ea59467c
65,293
def opponent(team): """Given a team, return the opponent team. >>>opponent(TEAM_WHITES) -1 #=TEAM_BLACKS >>>opponent(TEAM_BLACKS) 1 #=TEAM_WHITES >>>opponent(0) 0 """ return -team
4363665bfd8b56c80292c8435b000b4a40fc1a46
65,294
import logging def get_query_limit(access_token: str) -> int: """ Get the current rate limit for the GitHub GraphQL API :param access_token: The access token to be used for the query :return: The current rate limit for the GitHub GraphQL API """ try: data = get_template( {"...
0bab08b65ed490ffc09f13c02e7b1e39bfc07ac5
65,295
def start_razorpay_txn(basket, amount, user=None, email=None): """ Record the start of a transaction and calculate costs etc. """ if basket.currency: currency = basket.currency else: currency = getattr(settings, 'RAZORPAY_CURRENCY', 'INR') transaction = Transaction( user=...
528ca71d2d222968b016e4787222643207e6a578
65,296
import random def create_aug_matrices(nb_matrices, img_width_px, img_height_px, scale_to_percent=1.0, scale_axis_equally=False, rotation_deg=0, shear_deg=0, translation_x_px=0, translation_y_px=0, seed=None): """Create...
3596be1913d7bbbe723b4e4688dbed1c36d8f00e
65,297
def get_users_composer(): """Montagem do caso de uso GetUsers""" user_repository = UserRepository() usecase = GetUsers(user_repository) controller = GetUsersController(usecase) return controller
6efe265c909c0139ab1268ab7e4d685901ccdd58
65,298
def get_pairs_over_threshold(m, labels, threshold): """ detect pairs over threhold in a similarity matrice """ m = np.triu(m) ind0, ind1 = np.nonzero(m>threshold) #remove diag keep = ind0!=ind1 ind0 = ind0[keep] ind1 = ind1[keep] pairs = list(zip(labels[ind0], labels[in...
76e9f471b088c62463d04d44a6f53fd10b4199b3
65,299