content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def available_mem(cores, mem, fmtstring=True): """Calculate available memory for a process Params: cores (int): number of cores mem (str): set memory as string with conversion (M, G, g) fmtstring (bool): return memory as formatted string """ prefix = "G" m = re.match("[0...
241ad5133917d84b78bc0670fc974184b88e3978
3,640,411
def normalize_v(v): """ Normalize velocity to [-1, 1]. Ref: https://github.com/microsoft/AirSim-Drone-Racing-VAE-Imitation/blob/e651be52ff8274c9f595e88b13fe42d51302403d/racing_utils/dataset_utils.py#L20 """ # normalization of velocities from whatever to [-1, 1] range v_x_range = [-1, 7] v_y_ran...
cd47c8d3498e677a1f566b64199224f23a4b5896
3,640,412
def allele_counts_dataframe(read_evidence_generator): """ Creates a DataFrame containing number of reads supporting the ref vs. alt alleles for each variant. """ return dataframe_from_generator( element_class=ReadEvidence, variant_and_elements_generator=read_evidence_generator, ...
dd76b3b168977eb185ba1205a75ba4642becc913
3,640,413
def validate_rule_paths(sched: schedule.Schedule) -> schedule.Schedule: """A validator to be run after schedule creation to ensure each path contains at least one rule with an expression or value. A ValueError is raised when this check fails.""" for path in sched.unfold(): if path.is_final and ...
2ddfd6f9607687f6a3e3c955ed3470913fdf14bd
3,640,414
def spiralcontrolpointsvert( x: int, y: int, step: int, growthfactor: float, turns: int): """Returns a list[(int, int)] of 2D vertices along a path defined by a square spiral Args: x, y: int centerpoint coordinates step: int step...
de9f577ed826b227d44b69e638dd33e08ea9c430
3,640,415
def validate_dependencies(): """Validate external dependencies. This function does NOT have to exist. If it does exist the runtime will call and execute it during api initialization. The purpose of this function is to verify that external dependencies required to auto-generate a problem are properly in...
0bea4c7bbf6198bf18514233c902f5bfa62dc8f8
3,640,417
def find_closest_vertex(desired_hop, available_vertices): """ Find the closest downstream (greater than or equal) vertex in availbale vertices. If nothing exists, then return -1. Keyword arguments: desired_hop -- float representing the desired hop location available_location -- np array of avai...
c0aa85238faf58ff30cc937bf73b53ce2cc0ee48
3,640,418
def second_smallest(numbers): """Find second smallest element of numbers.""" m1, m2 = float('inf'), float('inf') for x in numbers: if x <= m1: m1, m2 = x, m1 elif x < m2: m2 = x return m2
0ca7b297da68651e4a8b56377e08f09d4d82cfb7
3,640,419
import numpy def calc_sft_ccs_by_dictionary(dict_crystal, dict_in_out, flag_use_precalculated_data: bool = False): """Calculate structure factor tensor in CCS (X||a*, Z||c) based on the information given in dictionary. Output information is written in the same dictionary. """ dict_crystal_keys = dict...
6905b0c1b4d4b3b65099600822ca0f6077fe1393
3,640,420
def normalize_mesh(mesh, in_place=True): """Rescales vertex positions to lie inside unit cube.""" scale = 1.0 / np.max(mesh.bounds[1, :] - mesh.bounds[0, :]) centroid = mesh.centroid scaled_vertices = (mesh.vertices - centroid) * scale if in_place: scaled_mesh = mesh scaled_mesh.vertices = scaled_vert...
e70ff4dea9173a541267c2a5bd040f12de4499c8
3,640,421
from datetime import datetime import socket def get_run_name(): """ A unique name for each run """ return datetime.now().strftime( '%b%d-%H-%M-%S') + '_' + socket.gethostname()
26f57e72912e896fe192de61b6477ef65051fccd
3,640,422
import traceback def process_request(identifier, browser, document_type='Annual Return', num_doc=1, status_df=None): """ Search ICRIS for the passed identifier, analyze the returned documents, and cart the documents depending on whether we purchased the document before. Parameters ---------...
7a6071488aba447959264d80d5bb201deb9a2339
3,640,423
def create_blackboard(): """ Create a blackboard with a few variables. Fill with as many different types as we need to get full coverage on pretty printing blackboard tests. """ Blackboard.clear() blackboard = Client(name="Tester") for key in {"foo", "some_tuple", "nested", "nothing"}: ...
776129ba57a545ef3bcfca75c99816fd198bfc3d
3,640,424
def adminRoomDelete(*args, **kwargs): """ 删除房间 """ params = kwargs['params'] filters = { Room.room_uuid == params['room_uuid'] } Room().delete(filters) filters = { UserRoomRelation.room_uuid == params['room_uuid'] } UserRoomRelation().delete(filters) return BaseContro...
d8f9a29b46aac908eda9e5fedbc113ce93bc2bf4
3,640,425
def who_is_it(image_path, database, model): """ Arguments: image_path -- path to an image database -- database containing image encodings along with the name of the person on the image model -- your Inception model instance in Keras Returns: min_dist -- the minimum distance between image_pa...
e2301b2504cc7bbb4c362b98541cad325b4b8587
3,640,426
def compute_win_state_str_row(n_rows, n_cols, n_connects): """Each win state will be a string of 0s and 1s which can then converted into an integer in base 2. I assume that at the maximum n_rows = n_cols = 5, which means that a 31 bit integer (since in Python it's always signed) should be more th...
b0f0f2846de7506b4b69f90bb8a0b1641a421659
3,640,427
import hmac import hashlib def hmac_sha512(key: bytes, data: bytes) -> bytes: """ Return the SHA512 HMAC for the byte sequence ``data`` generated with the secret key ``key``. Corresponds directly to the "HMAC-SHA512(Key = ..., Data = ...)" function in BIP32 (https://github.com/bitcoin/bips/bl...
64850ea2d5e921138d8e0ebc2d021f8eaf5a7357
3,640,428
def __scheduler_trigger(cron_time_now, now_sec_tuple, crontask, deltasec=2): """ SchedulerCore logic actual time: cron_time_now format: (WD, H, M, S) actual time in sec: now_sec_tuple: (H sec, M sec, S) crontask: ("WD:H:M:S", "LM FUNC") deltasec: sample time window: +/- sec: -sec...
8c3cc2f23bf94bfe7f817db542f50345be8f1a20
3,640,429
def get13FAmendmentType(accNo, formType=None) : """ Gets the amendment type for a 13F-HR/A filing - may be RESTATEMENT or NEW HOLDINGS. This turned out to be unreliable (often missing or wrong), so I don't use it to get the combined holdings for an investor. Instead I just look at the number of holdings...
a8ff184b4d3eb43ea8da75a64e83cb136908364e
3,640,431
def tabs_to_cover_string(string): """ Get the number of tabs required to be at least the same length as a given string. :param string: The string :return: The number of tabs to cover it :rtype: int """ num_tabs = int(np.floor(len(string) / 8) + 1) return num_tabs
242496271bafc78a2180c8e8798b9ed4892afb29
3,640,432
def kl(p, q): """ Kullback-Leibler divergence for discrete distributions Parameters ---------- p: ndarray probability mass function q: ndarray probability mass function Returns -------- float : D(P || Q) = sum(p(i) * log(p(i)/q(i)) Discrete probability distribut...
905903324958414972329e32becf9c8848f54029
3,640,433
def map_uris(uris): """Map URIs from external URI to HDFS :return: """ pkgs_path = __pillar__['hdfs']['pkgs_path'] ns = nameservice_names() return map(lambda x: 'hdfs://{0}{1}/{2}'.format(ns[0], pkgs_path, __salt__['system.basename'](x)), uris)
8dd682e932c2ac4dd495cfd11e88abdf58e78800
3,640,434
def get_body(name): """Retrieve the Body structure of a JPL .bsp file object Args: name (str) Return: :py:class:`~beyond.constants.Body` """ return Pck()[name]
d9949d9638c27b77f0bff203d2015aeb7af8c389
3,640,436
def is_available(): """ Convenience function to check if the current platform is supported by this module. """ return ProcessMemoryInfo().update()
d7d1d842009b39f79c650d54f776db664b30ea14
3,640,437
def render_path_spiral(c2w, up, rads, focal, zrate, rots, N): """ enumerate list of poses around a spiral used for test set visualization """ render_poses = [] rads = np.array(list(rads) + [1.]) for theta in np.linspace(0., 2. * np.pi * rots, N+1)[:-1]: c = np.dot(c2w[:3,:4], np.arra...
0eb608be5f29425cca62b15ce48db02e2297be17
3,640,438
from typing import Dict from typing import List from typing import Any def placeAnchorSourceToLagunaTX( common_anchor_connections: Dict[str, List[Dict[str, Any]]] ) -> List[str]: """ The anchors are placed on the Laguna RX registers We move the source cell of the anchor onto the corresponding TX registers "...
d30cef6a42b846a3d82467eabebce1275a3d81ed
3,640,439
def post_example_form(): """Example of a post form.""" return render_template("post-form.html")
e5e934dfe0d2b81081cda5deeca483f46fae89fe
3,640,440
def validate(data): """Validates incoming data Args: data(dict): the incoming data Returns: True if the data is valid Raises: ValueError: the data is not valid """ if not isinstance(data, dict): raise ValueError("data should be dict") if "text" not in data ...
ae8b7e74bd7607a7c8f5079014a0f5e3af5bc011
3,640,441
def stripExtra(name): """This function removes paranthesis from a string *Can later be implemented for other uses like removing other characters from string Args: name (string): character's name Returns: string: character's name without paranthesis """ startIndexPer=name.find('(') start...
fd9b8c2d6f513f06d8b1df067520c7f05cff023d
3,640,442
def google_maps(maiden: str) -> str: """ generate Google Maps URL from Maidenhead grid Parameters ---------- maiden : str Maidenhead grid Results ------- url : str Google Maps URL """ latlon = toLoc(maiden) url = "https://www.google.com/maps/@?api=1&map_...
04c2a6d730831746dc63ce6c733b16322d0696da
3,640,443
def format_signed(feature, # type: Dict[str, Any] formatter=None, # type: Callable[..., str] **kwargs ): # type: (...) -> str """ Format unhashed feature with sign. >>> format_signed({'name': 'foo', 'sign': 1}) 'foo' >>> format_signed({'na...
4adeecb92b0d102ae512c2c8acf89d38454b4e4e
3,640,444
def load_ligand(sdf): """Loads a ligand from an sdf file and fragments it. Args: sdf: Path to sdf file containing a ligand. """ lig = next(Chem.SDMolSupplier(sdf, sanitize=False)) frags = generate_fragments(lig) return lig, frags
984ba4bf61af6f8197f96a80f0f493b7dae84f08
3,640,445
def CMDpending(parser, args): """Lists pending jobs.""" parser.add_option('-b', '--builder', dest='builders', action='append', default=[], help='Builders to filter on') options, args, buildbot = parser.parse_args(a...
a9d56333fa84f2c92a969135c0dcc02bf94b972f
3,640,446
def numpy_translation(xyz): """Returns the dual quaternion for a pure translation. """ res = np.zeros(8) res[3] = 1.0 res[4] = xyz[0]/2.0 res[5] = xyz[1]/2.0 res[6] = xyz[2]/2.0 return res
8180449ec6128237f63b4519117553e85a2d1369
3,640,447
def sort_car_models(car_db): """return a copy of the cars dict with the car models (values) sorted alphabetically""" sorted_db = {} for model in car_db: sorted_db[model] = sorted(car_db[model]) return sorted_db
a478f16ece83058ba411480b91584e4c61026141
3,640,448
import requests def test_module(params) -> str: """Tests API connectivity and authentication'" Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :return: 'ok' if test passed, anything else...
64d45742c82854a9eb3d4e04aadbe05d458f9aca
3,640,449
from typing import Tuple from typing import Container import asyncio def create(auto_remove: bool = False) -> Tuple[str, str]: """ Creates a database inside a docker container :return: container name, database name :rtype: Tuple[str, str] """ piccolo_docker_repository = PiccoloDockerRepository...
c875b034b564d85e104655086b7faa1ed7a2df2c
3,640,450
import re def load_expected_results(file, pattern): """Reads the file, named file, which contains test results separated by the regular expression pattern. The test results are returned as a dictionary. """ expected = {} compiled_pattern = re.compile(pattern) with open(file) as f: ...
05e20e2e6932c2a4db634f48046ea3e3f6e5dedc
3,640,454
def following(request): """View all posts from followed users""" if request.method == "GET": user = User.objects.get(pk=request.user.id) following = user.follow_list.following.all() # Post pagination: https://docs.djangoproject.com/en/3.1/topics/pagination/ posts = Post.objects....
1b350c835d6bbf6d51c1a99d56d405a989f681a2
3,640,455
def create_random_polygon(min_x, min_y, max_x, max_y, vertex_num): """Create a random polygon with the passed x and y bounds and the passed number of vertices; code adapted from: https://stackoverflow.com/a/45841790""" # generate the point coordinates within the bounds x = np.random.uniform(min_x, max_x, ...
ad04591daf524bd0c97890a36722233cd08c4e5e
3,640,456
def document_hidden(session): """Polls for the document to become hidden.""" def hidden(session): return session.execute_script("return document.hidden") return Poll(session, timeout=3, raises=None).until(hidden)
21376291398aea859ed0f4d080a7bf617d93521f
3,640,457
def create_blueprint(): """Creates a Blueprint""" blueprint = Blueprint('Tasks Blueprint', __name__, url_prefix='/tasks') blueprint.route('/', methods=['POST'])(tasks.create) blueprint.route('/', methods=['PATCH'])(tasks.patch) blueprint.route('/', methods=['GET'])(tasks.list) return blueprint
c0e0412e599e4f4378efa2e2749f957a8b58043b
3,640,458
import gzip def estimate_null_variance_gs(gs_lists, statslist, Wsq, single_gs_hpo=False, n_or_bins=1): """ Estimates null variance from the average of a list of known causal windows """ statspaths = {h : p for h, p in [x.rstrip().split('\t')[:2] \ for...
755f35c108b9045d237a6cbfa442e7b6b0c24829
3,640,459
import torch def create_model(config): """Create the score model.""" model_name = config.model.name score_model = get_model(model_name)(config) score_model = score_model.to(config.device) score_model = torch.nn.DataParallel(score_model) return score_model
ca0b9fa1c68d83c1697d82273fc740ba35826c87
3,640,460
import gc def at(addr): """Look up an object by its id.""" for o in gc.get_objects(): if id(o) == addr: return o return None
f408b9a63afad1638f156163c6249e0e8095bff4
3,640,461
import warnings def money_flow_index(close_data, high_data, low_data, volume, period): """ Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF)) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) catch_errors.check_for_period_erro...
7c122ae10ef406fabf56f63ac80a35557999c2ee
3,640,462
def Get_Weights(dict_rank): """Converts rankings into weights.""" Weights = adapt.create_Weightings(dict_rank) return Weights
d50b9dcad7803a34c969f357cd4659ffe49ab740
3,640,463
def psisloo(log_likelihood): """ Summarize the model fit using Pareto-smoothed importance sampling (PSIS) and approximate Leave-One-Out cross-validation (LOO). Takes as input an ndarray of posterior log likelihood terms [ p( y_i | theta^s ) ] per observation unit. e.x. if using py...
5500ebd85eb9ac796b0410756e4b51f674890ca6
3,640,465
from typing import Tuple from typing import Optional from typing import Pattern def rxdelim(content: str) -> Tuple[Optional[Pattern], Optional[Pattern]]: """ Return suitable begin and end delimiters for the content `content`. If no matching delimiters are found, return `None, None`. """ tp = magic...
884efcd13846da9938b6f120cb3d8963addd0b42
3,640,466
def GenKeyOrderAttrs(soappy_service, ns, type_name): """Generates the order and attributes of keys in a complex type. Args: soappy_service: SOAPpy.WSDL.Proxy The SOAPpy service object encapsulating the information stored in the WSDL. ns: string The namespace the given WSDL-defined type ...
794f74502b5db305f51bd560b388c64d305cd4e2
3,640,467
def read_binary_stl(filename): """Reads a 3D triangular mesh from an STL file (binary format). :param filename: path of the stl file :type filename: str :return: The vertices, normals and index array of the mesh :rtype: Mesh :raises: ValueError """ with open(filename, 'rb') as stl_file:...
53ae2a1806413280719286813e091392d965ce76
3,640,468
def monotonise_tree(tree, n_feats, incr_feats, decr_feats): """Helper to turn a tree into as set of rules """ PLUS = 0 MINUS = 1 mt_feats = np.asarray(list(incr_feats) + list(decr_feats)) def traverse_nodes(node_id=0, operator=None, threshold=None, ...
78405b1d2bf5c2617b248210058caca0b062b668
3,640,469
import pickle def pythonify_and_pickle(file, out_filename): """Convert all the data in the XML file and save as pickled files for nodes, ways, relations and tags separately. :param file: Filename (the file will be opened 4 times, so passing a file object will not work). Can be anything which :...
4140c9e66b9a43b6880b152c50facf89ba723339
3,640,470
def compute_inverse_volatility_weights(df: pd.DataFrame) -> pd.Series: """ Calculate inverse volatility relative weights. :param df: cols contain log returns :return: series of weights """ dbg.dassert_isinstance(df, pd.DataFrame) dbg.dassert(not df.columns.has_duplicates) # Compute inve...
347343729dc271dd161f419a394151b99f1ce876
3,640,471
def resattnet164(**kwargs): """ ResAttNet-164 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/model...
35023591d70a577526280489c19f47fffb0800a2
3,640,472
def stype(obj): """ Return string shape representation of structured objects. >>> import numpy as np >>> a = np.zeros((3,4), dtype='uint8') >>> b = np.zeros((1,2), dtype='float32') >>> stype(a) '<ndarray> 3x4:uint8' >>> stype(b) '<ndarray> 1x2:float32' >>> stype([a, (b, b)]) ...
76b805684361a13f03955692dacd02c045c43bd9
3,640,473
def board2key(Z): """ Turn a "Game of Life" board into a key. """ return(bin2hex(array2string(Z[1:-1, 1:-1].reshape((1, 512 * 512 * 4))[0])))
101b4ecdf03e9a9a832434d59e2eaa9a6bed2ef5
3,640,474
def CipherArray(Array = [[" "]," "], Random = 1): """ Array - array to coding Key - Key number to coding It's а function that encodes elements Returns an array consisting of coded elements """ if (type(Array) != list): raise TypeError("Неправильний формат масиву") if (type(Random...
a2d472cd49a803a4a08f0fba5362b54cce24c37a
3,640,475
def voltage(raw_value, v_min=0, v_max=10, res=32760, gain=1): """Converts a raw value to a voltage measurement. ``V = raw_value / res * (v_max - v_min) * gain`` """ return (float(raw_value) / res * (v_max - v_min) * gain, "V")
b4ea7d2521e1fa856a21b98ace2a9490f8a3b043
3,640,476
def extract_characteristics_from_string(species_string): """ Species are named for the SBML as species_name_dot_characteristic1_dot_characteristic2 So this transforms them into a set Parameters: species_string (str) = species string in MobsPy for SBML format (with _dot_ instead ...
abfcc0d3e425e8f43d776a02254a04b0e85dc6d1
3,640,477
def _get_bzr_version(): """Looks up bzr version by calling bzr --version. :raises: VcsError if bzr is not installed""" try: value, output, _ = run_shell_command('bzr --version', shell=True, us_env=True) ...
fb0171fe286e6251b25536dd40323c4af73a1255
3,640,478
def C(source): """Compile at runtime and run code in-line""" return _embed_or_inline_c(source, True)
d1bd11370a1df3c93209b8d60046c077ac872d3e
3,640,479
def normalize(x): """Standardize the original data set.""" max_x = np.max(x, axis=0) min_x = np.min(x, axis=0) x = (x-min_x) / (max_x-min_x) return x
eba8ff32dca072b134c689d727e0246d7563a95d
3,640,480
def _diff_bearings(bearings, bearing_thresh=40): """ Identify kinked nodes (nodes that change direction of an edge) by diffing Args: bearings (list(tuple)): containing (start_node, end_node, bearing) bearing_thresh (int): threshold for identifying kinked nodes (range 0, 360) Returns: ...
a29c3cdd009065d7a73dd993ae66f81853d5e2bc
3,640,481
from typing import Any import json import aiohttp import re async def request(method: str, url: str, params: dict = None, data: Any = None, credential: Credential = None, no_csrf: bool = False, json_body: bool ...
68b68df293f474ecfff5fdd7ae93f0431d700d50
3,640,482
def InflRate(): """Inflation rate""" return asmp.InflRate()
33fcaa24cc00875e059850574469a95bcab3b469
3,640,483
def author_single_view(request, slug): """ Render Single User :param request: :param slug: :return: """ author = get_object_or_404(Profile, slug=slug) author_forum_list = Forum.objects.filter(forum_author=author.id).order_by("-is_created")[:10] author_comments = Comment.objects.filte...
506ec5f980d5ee59809358ac2add7cfcd0327a60
3,640,484
def get_predefined(schedule): """ Predefined learn rate changes at specified epochs :param schedule: dictionary that maps epochs to to learn rate values. """ def update(lr, epoch): if epoch in schedule: return floatX(schedule[epoch]) else: return floatX(lr) ...
5cb9fab3bb3b4b4d868504953d78e3f93f5a7198
3,640,485
def launch_ec2_instances(config, nb=1): """ Launch new ec2 instance(s) """ conf = config[AWS_CONFIG_SECTION] ami_image_id = conf.get(AMI_IMAGE_ID_FIELD) ami_name = conf.get(AMI_IMAGE_NAME_FIELD) if ami_image_id and ami_name: raise ValueError('The fields ami_image_id and ami_image_nam...
27b3aa745021f3a1516b09746db1c8111b8905d2
3,640,486
def residual_error(X_train,X_test,y_train,y_test, reg="linear"): """ Plot the residual error of the Regresssion model for the input data, and return the fitted Regression model. ------------------------------------------------------------------- # Parameters # X_train,X_test,y_train,y_test (np.arrays): G...
38513473122ff1430f6f6cf44eb984086bcdda72
3,640,487
def centerSquare(pil_img: Image.Image): """Adds padding on both sides to make an image square. (Centered)""" pil_img = pil_img.convert('RGBA') # ensure transparency background_color = (0, 0, 0, 0) width, height = pil_img.size if width == height: return pil_img elif width > height: ...
a991fa4a7a877334bba9e93126e4c8561c27e6f7
3,640,488
def _convert_steplist_to_string(step_data): """Converts list of step data into a single string. Parameters ---------- step_data : list List of step data Returns ------- str A space delimited string where every 6th value is followed by a newline. """ text = '' for i, datum in enumerate(step_data): ...
112495edbafc3db39946d7abeefff6466e2dff94
3,640,489
from typing import Optional def get_global_public_delegated_prefix(project: Optional[str] = None, public_delegated_prefix: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGlobalPublicDelegatedPrefixResult: ...
7c48f4ccce1fb1640d3e3851d9e5481a9dd6a281
3,640,490
def has_conformer(molecule, check_two_dimension=False): """ Check if conformer exists for molecule. Return True or False Parameters ---------- molecule check_two_dimension: bool, optional. Default False If True, will also check if conformation is a 2D conformation (all z coordinates are ...
fd0501a70f3ad002612be7d0625678ccc9f24dc9
3,640,491
def pad_sequence(yseqs, batch_first=False, padding_value=0): """Numpy implementation of torch.pad_sequence Args: yseqs (np.ndarray): List of array. (B, *) batch_first (bool): padding_value (int, optional): Padding value. Defaults to 0. Returns: np.ndarray Examples: ...
42fe65a15b39227a31b6022f8dae84cabd1888fb
3,640,492
import re def parse_transceiver_dom_sensor(output_lines): """ @summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content @param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command @return: Return parsed transceivers in a list """ result = [...
367d6a744add04e7649c971ef8fec3788ed8db88
3,640,495
import math def superimposition_matrix( v0: np.ndarray, v1: np.ndarray, scaling: bool = False, usesvd: bool = True ) -> np.ndarray: """ Return matrix to transform given vector set into second vector set. Args: ---- v0: shape (3, *) or (4, *) arrays of at least 3 vectors. ...
a83fb9532a59cffdd986c364825c32fa682a45dc
3,640,496
def get_graph_metadata(graph_id: int): """Returns the metadata for a single graph. This is automatically generated by the datasource classes. Parameters ---------- graph_id : int Graph ID. Returns 404 if the graph ID is not found Returns ------- Dict A dictionary r...
a3eb61fcaf901d8caa47da345a8279e4e7058a84
3,640,497
def username_exists(username, original=""): """Returns true if the given username exists.""" return username != original and User.objects.filter(username=username).count() > 0
16f9a53922d0141459327e79aba5678af9446536
3,640,498
def set_n_jobs(n_jobs: int, x_df: pd.DataFrame) -> int: """ Sets the number of n_jobs, processes to run in parallel. If n_jobs is not specified, the max number of CPUs is used. If n_jobs is set to a higher amount than the number of observations in x_df, n_jobs is rebalanced to match the length of x_df. ...
e081f0f2ee6ceeac7587cb362c62ffef0a114a56
3,640,499
def group_node_intro_times(filt, groups, n_sents): """ Returns lists of addition times of nodes into particular groups """ devs = [[] for _ in range(len(set(groups)))] for i in range(len(groups)): intro = int(filt[i, i]) devs[groups[i]].append(intro/n_sents) # still normalize additi...
b5da0e97c76683201a9b81fce1b1f1c7f25e4d6d
3,640,500
def svn_client_version(): """svn_client_version() -> svn_version_t const *""" return _client.svn_client_version()
2ffab063bce4e32010eb1f3aa57306e60a0f2417
3,640,501
def getportnum(port): """ Accepts a port name or number and returns the port number as an int. Returns -1 in case of invalid port name. """ try: portnum = int(port) if portnum < 0 or portnum > 65535: logger.error("invalid port number: %s" % port) portnum = -1...
7a5e287a0014afc1fa2933fcaae389a3c8aa50e8
3,640,504
def getParafromMinibatchModel(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True): """ Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of s...
2716d4a02b0ce5a0a7a640f80a51f180d280eb0d
3,640,505
def add_land( ax=None, scale="10m", edgecolor=None, facecolor=None, linewidth=None, **kwargs ): """Add land to an existing map Parameters ---------- ax : matplotlib axes object, optional scale : str, optional Resolution of NaturalEarth data to use ('10m’, ‘50m’, or ‘110m'). edgecolo...
c2a5e97a7e6cb76ffe4a70b754fe86c59b71eb05
3,640,506
import CLSIDToClass def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on! """Given a COM prog_id, return an object that is using makepy support, building if necessary""" disp = win32com.client.Dispatch(prog_id) if not disp.__dict__.get("CLSID"): # Eeek - no makepy suppo...
9f9ed2d87ab5c0329ce729a4fca3078daf6e8d17
3,640,507
def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes): """Private function used to compute log probabilities within a job.""" n_samples = X.shape[0] log_proba = np.empty((n_samples, n_classes)) log_proba.fill(-np.inf) all_classes = np.arange(n_classes, dtype=np.int) for...
a42510017d8b14ddf8f97de5902f6e1fb223da0d
3,640,508
def sort_coords(coords: np.ndarray) -> np.ndarray: """Sort coordinates based on the angle with first coord from the center. Args: coords (np.ndarray): Coordinates to be sorted. The format of coords is as follows. np.array([[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]] Returns: ...
a05390e56e57e66e6f288096fd4583bee26da88f
3,640,510
import warnings def to_fraction(value, den_limit=65536): """ Converts *value*, which can be any numeric type, an MMAL_RATIONAL_T, or a (numerator, denominator) tuple to a :class:`~fractions.Fraction` limiting the denominator to the range 0 < n <= *den_limit* (which defaults to 65536). """ ...
6ee8c13ab17e08480f13012a834d5d928a7d4f51
3,640,511
def find_closest(myList, myNumber): """ Returns closest value to myNumber. If two numbers are equally close, return the smallest number. # adapted from # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value """ sortList = sorted(myList) ...
0e4b6e2932aa4bb1886627e831d90d3a339b73b6
3,640,512
from pathlib import Path def remove_uuid_file(file_path, dry=False): """ Renames a file without the UUID and returns the new pathlib.Path object """ file_path = Path(file_path) name_parts = file_path.name.split('.') if not is_uuid_string(name_parts[-2]): return file_path name_part...
f2c8aa77595081ff968596340b45f61c490d16ec
3,640,513
def get_9x9x9_scramble(n=120): """ Gets a random scramble (SiGN notation) of length `n` for a 9x9x9 cube. """ return _MEGA_SCRAMBLER.call("megaScrambler.get999scramble", n)
7f5d11ad8cec05de5165fa0f90da40a7d9f17d97
3,640,514
import re def youku(link): """Find youku player URL.""" pattern = r'http:\/\/v\.youku\.com\/v_show/id_([\w]+)\.html' match = re.match(pattern, link) if not match: return None return 'http://player.youku.com/embed/%s' % match.group(1)
efcf1394cc02503a1ae18d91abee34777958e545
3,640,515
from typing import Optional def get_default_service_account(project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDefaultServiceAccountResult: """ Use this data source to retrieve default service account for this project :param str pro...
0d0c859771a11fe9a0772b9dd4aa2597a9081bd3
3,640,516
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result = [] candidates = sorted(candidates) def dfs(remain, stack): if remain == 0: result.append(stack) return for item in candidates: if item > remain: break if stack...
e8739c196c84aa7d15712ba1007e602a330fd625
3,640,517
import re def get_Xy(sentence): """将 sentence 处理成 [word1, w2, ..wn], [tag1, t2, ...tn]""" words_tags = re.findall('(.)/(.)', sentence) if words_tags: words_tags = np.asarray(words_tags) words = words_tags[:, 0] tags = words_tags[:, 1] return words, tags # 所有的字和tag分别存为 data...
9d850f74af6417c0172cb944b0e1ce4e3d931a96
3,640,519
def create_gap_token(rowidx=None): """returns a gap Token Parameters ---------- rowidx: int (Optional) row id Returns ------- Token """ return TT.Token(token_type=SupportedDataTypes.GAP, value='', rowidx=rowidx)
08f18bfcbf54e8861c684943111e22c33af2c69f
3,640,520
def get_local_bricks(volume: str) -> Result: """ Return all bricks that are being served locally in the volume volume: Name of the volume to get local bricks for """ vol_info = volume_info(volume) if vol_info.is_err(): return Err(vol_info.value) local_ip = get_local_ip() ...
d49db6aac12d976a1cfbd72540862be6406f85c9
3,640,521
def unionWCT(m=6, n=6): """ @ worst-case family union where @m>=2 and n>=2 and k=3 :arg m: number of states :arg n: number of states :type m: integer :type n: integer :returns: two dfas :rtype: (DFA,DFA)""" if n < 2 or m < 2: raise TestsError("number of states must both gr...
2b93c22e380c0ed52db2c9dfb9042785541b5885
3,640,522
def week_changes (after, before, str_dates, offset = 0, limit = 3) : """Yield all elements of `str_dates` closest to week changes.""" return unit_changes (after, before, str_dates, "week", offset, limit)
0b744db3f2cc581ea1fd2c59bbdc569339b88737
3,640,523