content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def truth_seed_box(true_params, init_range, az_ind=4, zen_ind=5): """generate initial box limits from the true params Parameters ---------- true_params : np.ndarray init_range : np.ndarray Returns ------- np.ndarray shape is (n_params, 2); returned energy limits are in units of...
3c3087702be4b91589f7e75f5c7e2f18776a658a
3,489
def summary(task): """Given an ImportTask, produce a short string identifying the object. """ if task.is_album: return u'{0} - {1}'.format(task.cur_artist, task.cur_album) else: return u'{0} - {1}'.format(task.item.artist, task.item.title)
87387c47e90998c270f6f8f2f63ceacebd4cdc78
3,491
def ds_tc_resnet_model_params(use_tf_fft=False): """Generate parameters for ds_tc_resnet model.""" # model parameters model_name = 'ds_tc_resnet' params = model_params.HOTWORD_MODEL_PARAMS[model_name] params.causal_data_frame_padding = 1 # causal padding on DataFrame params.clip_duration_ms = 160 params...
b018fa56efd67d8378496d5b4b1975580fc92f89
3,492
def expected_calibration_error_evaluator(test_data: pd.DataFrame, prediction_column: str = "prediction", target_column: str = "target", eval_name: str = None, ...
0f34a5c0883325324b11fd9b97a8a55250574392
3,493
def format_bytes(size): """ Takes a byte size (int) and returns a formatted, human-interpretable string """ # 2**10 = 1024 power = 2 ** 10 n = 0 power_labels = {0: " bytes", 1: "KB", 2: "MB", 3: "GB", 4: "TB"} while size >= power: size /= power n += 1 return str(round...
332b9d43c044da92ef7a9b16e57cfa7d552de12f
3,494
def load_input_data(filenames, Ag_class): """ Load the files specified in filenames. Parameters --- filenames: a list of names that specify the files to be loaded. Ag_class: classification of sequences from MiXCR txt file (i.e., antigen binder = 1, non-binder = 0) ""...
9ae9cc814f150168ca1703b1a4af54bc440b4425
3,495
from typing import Optional def get_maximum_value( inclusive: Optional[Edge] = None, exclusive: Optional[Edge] = None, ignore_unlimited: bool = False, ) -> Result[Boundary, TestplatesError]: """ Gets maximum boundary. :param inclusive: inclusive boundary value or None :param exclusive: e...
3ef7557ed3f7f353e0765a92fb008449409039a8
3,496
from typing import List def build_graph(order: int, edges: List[List[int]]) -> List[List[int]]: """Builds an adjacency list from the edges of an undirected graph.""" adj = [[] for _ in range(order)] for u, v in edges: adj[u].append(v) adj[v].append(u) return adj
86bdd0d4314777ff59078b1c0f639e9439f0ac08
3,497
import torch import math def construct_scheduler( optimizer, cfg: OmegaConf, ): """ Creates a learning rate scheduler for a given model :param optimizer: the optimizer to be used :return: scheduler """ # Unpack values from cfg.train.scheduler_params scheduler_type = cfg.train.sche...
d0ed907aa3582978cb3adf5eada895366dc1282f
3,498
import numpy def GenerateSerialGraph(num_samples, block_size): """ Generates a (consistent) serial graph. """ N = num_samples num_blocks = N // block_size if N % block_size != 0: err = "num_samples(%d) must be a multiple of block_size (%d)" % (num_samples, block_size) raise Exception(...
7348c08051aa0b7ec51f79f1f6f2097ab5857ef8
3,499
def load_ref_system(): """ Returns alpha-d-rhamnopyranose as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C -0.8728 1.4263 -0.3270 O -1.5909 0.3677 0.2833 C -1.1433 -0.9...
ba8d952cb777fac9e9d445c0865027c2fe25fbe4
3,500
def find_python_root_dir(possibles): """Find a python root in a list of dirs If all dirs have the same name, and one of them has setup.py then it is probably common Python project tree, like /path/to/projects/cd /path/to/projects/cd/cd Or, if all dirs are the same, except that o...
849d9f967899f1cdba7f9579891afbb7fb0580dc
3,502
import time def findEndpoint(): """ scroll to bottom to get the last number """ print("Fetching school count") clickToOpen() # get scroller scrollbar = driver.find_elements_by_class_name("scrollbar-inner")[1] driver.execute_script("arguments[0].scrollBy(0,2);", scrollbar) inner ...
7f979df78ff7dbebc4819ee4f09c86d9d8c243c0
3,504
def _shake_shake_block(x, output_filters, stride, is_training): """Builds a full shake-shake sub layer.""" batch_size = tf.shape(x)[0] # Generate random numbers for scaling the branches rand_forward = [ tf.random_uniform( [batch_size, 1, 1, 1], minval=0, maxval=1, dtype=tf.float32) for _ ...
29170e867ab8a01277adbbd49f60960408ceb28b
3,505
def get_all_paged_events(decision, conn, domain, task_list, identity, maximum_page_size): """ Given a poll_for_decision_task response, check if there is a nextPageToken and if so, recursively poll for all workflow events, and assemble a final decision response to return """ # First check if the...
5125c5bbff547a02496443477aee88165ece9d80
3,506
def get_pools(): """ gets json of pools. schema follows #{ # "kind": "tm:ltm:pool:poolcollectionstate", # "selfLink": "https://localhost/mgmt/tm/ltm/pool?ver=11.5.3", # "items": [ # { # "kind": "tm:ltm:pool:poolstate", # "name": "mypoolname", # "partit...
36baa4d556a69a9498357b1a5534433fc8732683
3,507
def set_runner_properties(timestep, infguard=False, profile_nodenet=False, profile_world=False, log_levels={}, log_file=None): """Sets the speed of the nodenet calculation in ms. Argument: timestep: sets the calculation speed. """ if log_file: if not tools.is_file_writeable(log_file): ...
a2ddcd6b33304cef4c03a55a78a691fa9b5d1112
3,508
def chunk_sum(vec, chunksize): """Computes the sums of chunks of points in a vector. """ Nchunks = len(vec)//chunksize end = Nchunks*chunksize arr = np.reshape(vec[:end], [Nchunks, chunksize]) sums = np.sum(arr, 1) return sums
036bfe2d2277d90339c2bcacc1c0943a96a52ece
3,509
def get_feature_definitions(df, feature_group): """ Get datatypes from pandas DataFrame and map them to Feature Store datatypes. :param df: pandas.DataFrame :param feature_group: FeatureGroup :return: list """ # Dtype int_, int8, int16, int32, int64, uint8, uint16, uint32 # and uin...
75573b3e8ed1f666b68dde2067b5b14655c341de
3,511
def draw_2d_wp_basis(shape, keys, fmt='k', plot_kwargs={}, ax=None, label_levels=0): """Plot a 2D representation of a WaveletPacket2D basis.""" coords, centers = _2d_wp_basis_coords(shape, keys) if ax is None: fig, ax = plt.subplots(1, 1) else: fig = ax.get_figure() ...
5e731fa02c833f36c0cde833bfdb5d4b30706519
3,512
import numpy def build_normalizer(signal, sample_weight=None): """Prepares normalization function for some set of values transforms it to uniform distribution from [0, 1]. Example of usage: >>>normalizer = build_normalizer(signal) >>>pylab.hist(normalizer(background)) >>># this one should be unifo...
b4227364899468ca2017d9bedd87aff4bf35d9c6
3,513
from typing import Callable from typing import Tuple def get_phased_trajectory(init_state: np.ndarray, update_fn: Callable) -> Tuple[np.ndarray, HashableNdArray]: """ evolve an initial state until it reaches a limit cycle Parameters ---------- init_state update_fn ...
603aa9f3e626d51132b70b87321453cfacba579a
3,515
import logging import time def exponential_backoff(func): """ Retries a Boto3 call up to 5 times if request rate limits are hit. The time waited between retries increases exponentially. If rate limits are hit 5 times, exponential_backoff raises a :py:class:sceptre.exceptions.RetryLimitExceededExc...
63db7514b88eb64ca0ee5d626be5a59f7d40d7d6
3,516
def post_config_adobe_granite_saml_authentication_handler(key_store_password=None, key_store_password_type_hint=None, service_ranking=None, service_ranking_type_hint=None, idp_http_redirect=None, idp_http_redirect_type_hint=None, create_user=None, create_user_type_hint=None, default_redirect_url=None, default_redirect_...
b6b082929904123f96c044753995ff1d19cb9cbf
3,517
import json def _pcheck(block): """ Helper for multiprocesses: check a block of logs Args: block List[List[str], int]: lines, block_id Returns: [type]: [description] """ results = [] lines, block_id = block for li, line in enumerate(lines): json_line = json.load...
3a581e3440079d5f31b00c86d84abee3eca0a396
3,519
import sqlite3 def fetch_exon_locations(database): """ Queries the database to create a dictionary mapping exon IDs to the chromosome, start, end, and strand of the exon """ conn = sqlite3.connect(database) cursor = conn.cursor() query = """ SELECT e.edge_ID, loc1.chromosome, MIN(loc1.position,...
54cdd3ffa2ccd10bd777f9130caaae992ac3d451
3,520
import http def add(request): """Displays/processes a form to create a collection.""" data = {} if request.method == 'POST': form = forms.CollectionForm( request.POST, request.FILES, initial=initial_data_from_request(request)) aform = forms.AddonsForm(request.POST) ...
04491d0465e09057a2e6c3cc7b80f41ff84314ec
3,521
def get_camera_pose_cpp(): """ Returns camera pose """ rospy.wait_for_service('/asr_robot_model_services/GetCameraPose', timeout=5) pose = rospy.ServiceProxy('/asr_robot_model_services/GetCameraPose',GetPose) return pose().pose
b52be4a613d1de482387f6643ea12181f84f6cf4
3,522
import copy def _convert_model_from_bytearray_to_object(model_bytearray): """Converts a tflite model from a bytearray into a parsable object.""" model_object = schema_fb.Model.GetRootAsModel(model_bytearray, 0) model_object = schema_fb.ModelT.InitFromObj(model_object) model_object = copy.deepcopy(model_object...
9579b58438571b41e8451a13d5e292e142cd6b57
3,523
import requests def get_service_mapping(): """ Get mapping dict of service types Returns: A mapping dict which maps service types names to their ids """ # Get all Service types: all_service_type = requests.get(base_url + 'services/v2/service_types', headers=headers3).json() # Make...
8a8adb8fff086b323dd95012c1a901918afa2bc2
3,524
def get_recently_viewed(request): """ get settings.PRODUCTS_PER_ROW most recently viewed products for current customer """ t_id = tracking_id(request) views = ProductView.objects.filter(tracking_id=t_id).values( 'product_id').order_by('-date')[0:PRODUCTS_PER_ROW] product_ids = [v['product_id'] f...
048187566446294285c7c8fe48b3dafba5efdcc1
3,525
import re def chapter_by_url(url): """Helper function that iterates through the chapter scrapers defined in cu2.scrapers.__init__ and returns an initialized chapter object when it matches the URL regex. """ for Chapter in chapter_scrapers: if re.match(Chapter.url_re, url): retu...
83112ab2b68faf7d48a7a8fab3cd359ff442550d
3,526
def get_model_name(part_num): """ 根据型号获取设备名称 :param part_num: :return: """ models = current_config.MODELS for model_name, model_part_num in models.items(): if model_part_num == part_num: return model_name
843489174c844e05752f499f250a30b157ae386e
3,527
def run_get_pk(process, *args, **inputs): """Run the process with the supplied inputs in a local runner that will block until the process is completed. :param process: the process class or process function to run :param inputs: the inputs to be passed to the process :return: tuple of the outputs of the...
782c3b49b90347a48495f2b7b48e34c2418d31a1
3,528
def _random_mask(target_tokens, noise_probability=None, target_length=None): """ target_length其实是mask_length""" unk = 3 target_masks = get_base_mask(target_tokens) if target_length is None: target_length = target_masks.sum(1).float() if noise_probability is None: # sample ...
89e603c7a5bfd4fd6fa1d6a36cea3e429e7bd6b7
3,529
def calculate(cart): """Return the total shipping cost for the cart. """ total = 0 for line in cart.get_lines(): total += line.item.shipping_cost * line.quantity return total
4b6d9bd94ce3a5748f0d94ab4b23dab993b430e4
3,531
def arr_to_rgb(arr, rgb=(0, 0, 0), alpha=1, invert=False, ax=None): """ arr to be made a mask rgb:assumed using floats (0..1,0..1,0..1) or string """ # arr should be scaled to 1 img = np.asarray(arr, dtype=np.float64) img = img - np.nanmin(img) img = img / np.nanmax(img) im2 = np.ze...
73a19cfed712d93cbbaa69454ca2df780bc523fa
3,532
def parameters(number, size, v=3): """ sets item parameters of items and puts in list :param number: number of items :param size: characteristic size of the items :param v: velocity :return: list with items """ param = [] for i in range(number): angle = randint(0, int(2 * pi ...
1b2ad225359c53ce4dd3feb9d356b1637c76c79c
3,533
def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape, enforce_square=True): """Validate arguments and format inputs for toeplitz functions Parameters ---------- c_or_cr : array_like or tuple of (array_like, array_like) The vector ``c``, ...
977a40e279d3a0000cc03b181e65182e2fe325cc
3,534
def get_application_id(): """Returns the app id from the app_identity service.""" return app_identity.get_application_id()
f23f6ac7473f81af6c2b40807dd20f8f602bbd96
3,536
def prior(X, ls, kernel_func=rbf, ridge_factor=1e-3, name=None): """Defines Gaussian Process prior with kernel_func. Args: X: (np.ndarray of float32) input training features. with dimension (N, D). kernel_func: (function) kernel function for the gaussian process. D...
6ca9d150924473a0b78baa8da4e0734b7719e615
3,537
def multiclass_eval(y_hat: FloatTensor, y: IntTensor) -> int: """ Returns number correct: how often the rounded predicted value matches gold. Arguments: y_hat: 2d (N x C): guesses for each class y: 2d (N x C): onehot representation of class labels Returns: nubmer correct ""...
6385d1113a0c29191a8951a30d8219278511451d
3,539
def extract止めないでお姉さま(item): """ Parser for '止めないで、お姉さま…' """ badwords = [ 'subs', ] if any([bad in item['tags'] for bad in badwords]): return None vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'WA...
1ee52b649fbf24452285c44538b1bfc0fe3cb0c8
3,541
import urllib import json def GetExpID(startRow=0,numRows=2000,totalRows = -1): """ Queries the Allen Mouse Brain Institute website for all gene expression data available for download. Returns: -------- GeneNames: list[dict()] list of all genes where expression data is available for download. Dict contains ex...
f361e94b5d2c61bc80b182c2ee63a734d7e8dc4e
3,542
from typing import Counter def _add_biotype_attribute(gene_content): """ Add `biotype` attribute to all intervals in gene_content. Parameters ---------- gene_content_ : dict Intervals in gene separated by transcript id. Returns ------- dict Same gene_content_ object w...
21e09ebd4048acf4223855c23b819352aac013db
3,543
def random_solution(W, D, n): """ We generate a solution of size n """ sol = np.random.permutation(n) + 1 fitness_sol = fitness(W=W, D=D, sol=sol) return [fitness_sol, sol]
be95c1f08591e90e0e808ea7938763bb7fecd1da
3,544
def format_perm(model, action): """ Format a permission string "app.verb_model" for the model and the requested action (add, change, delete). """ return '{meta.app_label}.{action}_{meta.model_name}'.format( meta=model._meta, action=action)
12f532e28f685c2a38a638de63928f07039d44c8
3,545
def verify_password(plain_password: str, hashed_password: str) -> bool: """Verify plain password and hashed password. Args: plain_password (str): Plain text password. hashed_password (str): Hashed password. Returns: bool: Returns true if secret is verified against given hash. "...
adb7ac87516a02298468858216481d9ddad1ce13
3,546
from typing import List from typing import Dict def render_siecle2(tpl: str, parts: List[str], data: Dict[str, str]) -> str: """ >>> render_siecle2("siècle2", ["1"], defaultdict(str)) 'I<sup>er</sup>' >>> render_siecle2("siècle2", ["I"], defaultdict(str)) 'I<sup>er</sup>' >>> render_siecle2("s...
d0abd2703aebf3a05c0cc893c6678ed6683bb31a
3,547
def get_interactions(request): """Function to get the interactions for a molecule""" dist_dict = {"SingleAtomAcceptor_SingleAtomDonor": {"dist": 4.0}, # H-bonding "SingleAtomAcceptor_WeakDonor": {"dist": 3.0}, # Weak H-bond "Halogen_SingleAtomAcceptor": {"dist": 4.0}, # H...
86d4444b1c4a9251e8be91f453e1489234edf087
3,548
import json def sendmail_action(): """Send an email to the address entered in the sendmail form.""" if not MSGRAPHAPI.loggedin: redirect("/sendmail") email_body = json.dumps( { "Message": { "Subject": request.query.subject, "Body": {"ContentTyp...
ed4f31ee22005e9ea1b3e24ca92b33be3980ebe2
3,549
import math def normal_to_angle(x, y): """ Take two normal vectors and return the angle that they give. :type x: float :param x: x normal :type y: float :param y: y normal :rtype: float :return: angle created by the two normals """ return math.atan2(y, x) * 180 / math.pi
c6f5b5e2952858cd3592b4e0849806b0ccd5de78
3,551
def glDeleteFramebuffersEXT( baseOperation, n, framebuffers=None ): """glDeleteFramebuffersEXT( framebuffers ) -> None """ if framebuffers is None: framebuffers = arrays.GLuintArray.asArray( n ) n = arrays.GLuintArray.arraySize( framebuffers ) return baseOperation( n, framebuffers )
8c14fa4ce55c6fe995c01822776b17728e132987
3,552
def outline(image, mask, color): """ Give a color to the outline of the mask Args: image: an image mask: a label color: a RGB color for outline Return: image: the image which is drawn outline """ mask = np.round(mask) ...
dc66410053e2326965c591a9d3b566e477133295
3,554
import socket def is_open_port(port): """ Check if port is open :param port: port number to be checked :type port: int :return: is port open :rtype: bool """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.bind(("127.0.0.1", port)) except socket.error: ...
df81cc942f39d00bbdb8cb11628666a117c9788f
3,556
def stopping_fn_from_metric(metric_name: str): """ Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name. """ def stopping_fn(engine: Engine): return engine.state.metrics[metric_name] return stopping_fn
c6b47fd417134eb72c017a4cd55b8dfc995ea0c5
3,557
def build_attribute_set(items, attr_name): """Build a set off of a particular attribute of a list of objects. Adds 'None' to the set if one or more of the objects in items is missing the attribute specified by attr_name. """ attribute_set = set() for item in items: attribute_set.add(...
2cee5922463188a4a8d7db79d6be003e197b577f
3,559
def potential_fn(q): """ - log density for the normal distribution """ return 0.5 * np.sum(((q['z'] - true_mean) / true_std) ** 2)
f2b4ff07b7188494c9901c85f3b920e9d273a3f4
3,560
import yaml def patch_rbac(rbac_v1: RbacAuthorizationV1Api, yaml_manifest) -> RBACAuthorization: """ Patch a clusterrole and a binding. :param rbac_v1: RbacAuthorizationV1Api :param yaml_manifest: an absolute path to yaml manifest :return: RBACAuthorization """ with open(yaml_manifest) as...
1830cc26dc79674bfb628556e34572ddc6d6e89e
3,562
def _shp_to_boundary_gdf(shp_file_path): """.shpかshpが格納された.zipを指定してgdfを作成する Args: shp_file_path (Path): 変換対象のshpファイルを格納するディレクトリのパス文字列 Returns: gpd.GeoDataFrame: shpを変換したGeoDataFrame """ s2g = ShapeToGeoPandas(str(shp_file_path.resolve())) gdf = s2g.gdf necessary_columns =...
4e1aef42f6bb16f184f0669b37dc7720851bee14
3,563
import random def insert_site(site, seq, offset=None): """Inserts a sequence (represeting a site) into a larger sequence (which is a sequence object rather than a series of letters.""" # inputs: # site The site to be inserted # offsets the offset where the site is to be ...
88a4df8e2ab094337a27d0e2d84c2078dfed5cc4
3,564
def sex2bpzmags(f, ef, zp=0., sn_min=1., m_lim=None): """ This function converts a pair of flux, error flux measurements from SExtractor into a pair of magnitude, magnitude error which conform to BPZ input standards: - Nondetections are characterized as mag=99, errormag=m_1sigma - Objects with absur...
ec95566f680326cd550626495a6983d0221ae29b
3,565
def get_elk_command(line): """Return the 2 character command in the message.""" if len(line) < 4: return "" return line[2:4]
550eda4e04f57ae740bfd294f9ec3b243e17d279
3,566
def safe_div(a, b): """ Safe division operation. When b is equal to zero, this function returns 0. Otherwise it returns result of a divided by non-zero b. :param a: number a :param b: number b :return: a divided by b or zero """ if b == 0: return 0 return a / b
68e5bccbe812315b9a1d27a1fa06d26d5339d6fd
3,567
def decrypt_story(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Use the functions getStoryString and loadWords to get the raw data you need. returns: string - story in plain text """ story = CiphertextMessage(get_story...
af636efedf5e95847c4a7dd52031cfc3dfa094a0
3,568
def shouldAvoidDirectory(root, dirsToAvoid): """ Given a directory (root, of type string) and a set of directory paths to avoid (dirsToAvoid, of type set of strings), return a boolean value describing whether the file is in that directory to avoid. """ subPaths = root.split('/') for i, sub...
afc92111f57031eb1e2ba797d80ea4abc2a7ccd0
3,569
def atom_explicit_hydrogen_valences(xgr): """ explicit hydrogen valences, by atom """ return dict_.transform_values(atom_explicit_hydrogen_keys(xgr), len)
e409b82606f113373086ca52689baeb117d3a8ea
3,570
def change_account_type(user_id): """Change a user's account type.""" if current_user.id == user_id: flash('You cannot change the type of your own account. Please ask ' 'another administrator to do this.', 'error') return redirect(url_for('admin.user_info', user_id=user_id)) u...
3c13b4ea1d3b080a4c925d576eee29c61346363a
3,571
import re def test_runner(filtered_tests, args): """ Driver function for the unit tests. Prints information about the tests being run, executes the setup and teardown commands and the command under test itself. Also determines success/failure based on the information in the test case and generate...
39e1af33a563dd9915ec6f107c8dd1f199528cab
3,572
def get_all_infos_about_argument(db_argument: Argument, main_page, db_user, lang) -> dict: """ Returns bunch of information about the given argument :param db_argument: The argument :param main_page: url of the application :param db_user: User :param lang: Language :rtype: dict :return:...
56c03e8d11d23c3726b54b2d2be954ecefba786b
3,573
def average_proxy(ray, method, proxy_type): """ method to average proxy over the raypath. Simple method is direct average of the proxy: $\sum proxy(r) / \sum dr$. Other methods could be: $1/(\sum 1 / proxy)$ (better for computing \delta t) """ total_proxy = 0. try: methode.evaluation ...
912925339f6a2087020781e898de102c3ee4f0d6
3,574
import _datetime from datetime import datetime def after(base=_datetime, diff=None): """ count datetime after diff args :param base: str/datetime/date :param diff: str :return: datetime """ _base = parse(base) if isinstance(_base, datetime.date): _base = midnight(_base) res...
80f3ccb2d45f247a93a0d69bf0a55bc9264ee7de
3,575
import string def open_lib(ifile): """Opens lib with name ifile and returns stationmeta, arraydim, rlengths, heights, sectors, data.""" with open(ifile, 'rb') as f: lines = f.readlines() lines = [x.strip() for x in lines] data = {} lines = filter(lambda x: x.strip(), lines) ...
22fb842112f1558ab086058d997e08cb416e9a19
3,576
def convert_examples_to_features(examples, intent_label_list, slot_label_list, max_seq_length, tokenizer): """Convert a set of `InputExample`s to a list of `InputFeatures`.""" features = [] for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: tf.log...
078f6e23e3a2f42a12851763a3424d938569d25b
3,577
from bs4 import BeautifulSoup def get_blb_links(driver): """takes (driver) and returns list of links to scrape""" homepage = "https://www.bloomberg.com/europe" rootpage = "https://www.bloomberg.com" driver.get(homepage) ssm = driver.find_elements_by_class_name("single-story-module")[0].get_attribu...
f2ecf967aa6e755b51e43450239b5606013cb9bf
3,578
def randomProfile(freq,psd): """ Generate a random profile from an input PSD. freq should be in standard fft.fftfreq format psd should be symmetric as with a real signal sqrt(sum(psd)) will equal RMS of profile """ amp = np.sqrt(psd)*len(freq) ph = randomizePh(amp) f = amp*ph sig...
54477fc37bb81c24c0bde3637112a18613201565
3,579
def getP(W, diagRegularize = False): """ Turn a similarity matrix into a proability matrix, with each row sum normalized to 1 :param W: (MxM) Similarity matrix :param diagRegularize: Whether or not to regularize the diagonal of this matrix :returns P: (MxM) Probability matrix """ if ...
1c5c7da2e86b5c800660acaf825507914cd630ce
3,580
def get_structure_index(structure_pattern,stream_index): """ Translates the stream index into a sequence of structure indices identifying an item in a hierarchy whose structure is specified by the provided structure pattern. >>> get_structure_index('...',1) [1] >>> get_structure_index('.[.].',1) ...
8f1def101aa2ec63d1ea69382db9641bf0f51380
3,581
import random import torch def n_knapsack(n_knapsacks=5, n_items=100, # Should be divisible by n_knapsack n_weights_per_items=500, use_constraints=False, method='trust-constr', backend='tf' ): """ Here we solve a contin...
ed4068bad29aff385a86286eab224da3c1beefa5
3,582
def has_url(account: Accounts) -> bool: """Return True if the account's note or fields seem to contain a URL.""" if account.note and "http" in account.note.lower(): return True if "http" in str(account.fields).lower(): return True return False
d858ef1bedcac064bbc9a5c20de02b1438c5cdad
3,583
def conv2x2(in_planes, out_planes, stride=1, groups=1, dilation=1, padding=0): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=2, stride=stride, padding=padding, groups...
a96112cd56817940292f92b5417584f18b7d2fb7
3,584
def face_normals(P,T,normalize=True): """Computes normal vectors to triangles (faces). Args: P: n*3 float array T: m*3 int array normalize: Whether or not to normalize to unit vectors. If False, then the magnitude of each vector is twice the area of the corresponding tria...
379c82624aeb1a772befb91acee1b46a7ff7f937
3,585
import itertools def transform_pairwise(X, y): """Transforms data into pairs with balanced labels for ranking Transforms a n-class ranking problem into a two-class classification problem. Subclasses implementing particular strategies for choosing pairs should override this method. In this method, ...
d4c376fe1a594f6baecb78aeaa11e90bffcde8a5
3,586
def format_project_title(rank: int, project_id: str, status: str) -> str: """Formats a project title for display in Slack. Args: rank: The rank of in the list. Will be prepended to the title. project_id: The project ID. status: The status of the project. This is used to determine which ...
35a8b7dd2c3e8afd3975ddf97056a81d631e3576
3,587
def fake_3dimage_vis(): """ :return: a Nifti1Image (3D) in RAS+ space Following characteristics: - shape[LR] = 7 - shape[PA] = 8 - shape[IS] = 9 Visual thing using voxel art... """ shape = (7,8,9) data = np.zeros(shape, dtype=np.float32, order="F") # "L" indices =np...
65d766d04a6a85e5cafcdc0d7c62e2f3974caa5b
3,588
import atexit def watch_dependencies(dependency, func, time_execution=15000, registry=None, app=current_app): """ Register dependencies metrics up """ if not registry: registry = app.extensions.get("registry", CollectorRegistry()) app.extensions["registry"] = registry # pylint: d...
f502f3e1e6beba5169160459bc0887462ac6662c
3,589
def view_cache_key(func, args, kwargs, extra=None): """ Calculate cache key for view func. Use url instead of not properly serializable request argument. """ if hasattr(args[0], 'build_absolute_uri'): uri = args[0].build_absolute_uri() else: uri = args[0] return 'v:' + func_c...
85139dc6a77d3758b6e691b565361b390c643e91
3,590
def get_filter(sampling_freq, f_pass, f_stop, taps): """Get FIR filter coefficients using the Remez exchange algorithm. Args: f_pass (float): Passband edge. f_stop (float): Stopband edge. taps (int): Number of taps or coefficients in the resulting filter. Returns: (numpy.nd...
a0fb303ad74ee6e60dd0521af5e00b4b1d1d42e0
3,591
def errorcode_from_error(e): """ Get the error code from a particular error/exception caused by PostgreSQL. """ return e.orig.pgcode
981b447d540e949834c10f4a05fb21769091b104
3,592
def _comp_point_coordinate(self): """Compute the point coordinates needed to plot the Slot. Parameters ---------- self : SlotW28 A SlotW28 object Returns ------- point_dict: dict A dict of the slot point coordinates """ Rbo = self.get_Rbo() # alpha is the angle...
0938c9ecba5e9fc1ed76e804e8eab6f9bd97f253
3,593
from typing import IO def save_expected_plot(series: pd.Series, colour="C0") -> IO: """Return an image of the plot with the given `series` and `colour`.""" fig, ax = plt.subplots() ax.add_line(mpl_lines.Line2D(series.index, series.values, color=colour)) return _save_fig(fig, ax)
6c898a622f983cebd46fb368a40e2a492bddb37f
3,594
def GRU_architecture( GRU_layers, GRU_neurons, Dense_layers, Dense_neurons, add_Dropout, Dropout_rate, data_shape, ): """ Parameters ---------- GRU_layers : int Number of GRU layers. GRU_neurons : list List with the numbers of GRU cells in each GRU layer. ...
77c2aaed6a82f2f4aedade73649d843ff8afd2e2
3,595
def create_lock(name): """Creates a file in the /locks folder by the given name""" lock_path = get_lock_path(name) if not check_lock(lock_path): return touch_file(lock_path) else: return False
1f5e4d43a85a01aaba19295a72cdee20fd7adb1b
3,596
def gen_rigid_tform_rot(image, spacing, angle): """ generate a SimpleElastix transformation parameter Map to rotate image by angle Parameters ---------- image : sitk.Image SimpleITK image that will be rotated spacing : float Physical spacing of the SimpleITK image angle : flo...
5cadbd59340328d1af5e4ec2c5c0c47e69e19013
3,597
def get_param_response(param_name, dict_data, num=0, default=None): """ :param param_name: 从接口返回值中要提取的参数 :param dict_data: 接口返回值 :param num: 返回值中存在list时,取指定第几个 :param default: 函数异常返回 :return: 提取的参数值 """ if isinstance(dict_data, dict): for k, v in dict_data.items(): if...
b9ffa5dfe6e9707771a812dad1d8d9284acbc2e7
3,598
def _strict_conv1d(x, h): """Return x * h for rank 1 tensors x and h.""" with ops.name_scope('strict_conv1d', values=[x, h]): x = array_ops.reshape(x, (1, -1, 1, 1)) h = array_ops.reshape(h, (-1, 1, 1, 1)) result = nn_ops.conv2d(x, h, [1, 1, 1, 1], 'SAME') return array_ops.reshape(result, [-1])
dabe247f97c285ed5d250d7d8d99dae5795a8fec
3,599
def timed_zip_map_agent(func, in_streams, out_stream, call_streams=None, name=None): """ Parameters ---------- in_streams: list of Stream The list of input streams of the agent. Each input stream is timed, i.e. the elements are pairs (timestam...
0c23ff84ed72ee25b04bf118d57203c7831702e8
3,600
def get_repository_ids_requiring_prior_install( trans, tsr_ids, repository_dependencies ): """ Inspect the received repository_dependencies and determine if the encoded id of each required repository is in the received tsr_ids. If so, then determine whether that required repository should be installed prio...
035e7f358b8af7d4915b255b988f1fabc56605c1
3,601
from typing import Iterable from typing import Tuple from typing import List def get_words_and_spaces( words: Iterable[str], text: str ) -> Tuple[List[str], List[bool]]: """Given a list of words and a text, reconstruct the original tokens and return a list of words and spaces that can be used to create a ...
205c48435018a99433fce298a6035de902774810
3,602
from typing import List import ast def parse_names(source: str) -> List['Name']: """Parse names from source.""" tree = ast.parse(source) visitor = ImportTrackerVisitor() visitor.visit(tree) return sum([split_access(a) for a in visitor.accessed], [])
42f622052bc8acd5cdec187cd16695cec3b86154
3,603