content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _aggregate(df, variable, components=None, method=np.sum): """Internal implementation of the `aggregate` function""" # list of variables require default components (no manual list) if islistable(variable) and components is not None: raise ValueError( "Aggregating by list of variables...
25c36e6180aa5509ced7513c841eb9cc4450b41b
17,325
import inspect def get_attributes(klass): """Get all class attributes. """ attributes = list() for attr, value in inspect.\ getmembers(klass, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") and attr.endswith("__")): attributes.append(attr) return ...
6a72db39a9982b6a4ad5462ff9a4695f9cca6ce0
17,326
import io def render(html): """Convert HTML to a PDF""" output = io.BytesIO() surface = cairo.PDFSurface(output, 595, 842) ctx = cairo.Context(surface) cffictx = cairocffi.Context._from_pointer(cairocffi.ffi.cast('cairo_t **', id(ctx) + object.__basicsize__)[0], incref=True) html = etree.par...
9b0d4c252b7b7bf8dcdcab32e13cf183cef0312d
17,327
def computeFlowImage(u,v,logscale=True,scaledown=6,output=False): """ topleft is zero, u is horiz, v is vertical red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12 """ colorwheel = makecolorwheel() ncols = colorwheel.shape[0] radius = np.sqrt(u**2 + v**2) if output: ...
87690e34ae1509a63df982b68e35346be8b5d8dd
17,328
def day_display(year, month, all_month_events, day): """ Returns the events that occur on the given day. Works by getting all occurrences for the month, then drilling down to only those occurring on the given day. """ # Get a dict with all of the events for the month count = CountHandler(yea...
e17df37bb8908a557b9cf1175c3567b460a35385
17,329
import math def decimal_to_octal(num): """Convert a Decimal Number to an Octal Number.""" octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.pow(10, counter)) counter += 1 num = math.floor(num / 8) # basically /= 8 without remain...
e6bbc23a2235812c1e2298e8a0be8396c06b1c1f
17,330
def get_formatted_dates(date_ranges): """Returns list of dates specified by date_ranges, formtted for Swiftly API use. date_ranges is a list of dict, with each dict specifying a range of dates in string format. sample dict for Tue/Wed/Thu in Sep/Oct: { "start_date": "09-01-2019", "end_d...
db20459ffacb8cb621acdf40b0bdcbc203787680
17,331
def read_img(img: str, no_data: float, mask: str = None, classif: str = None, segm: str = None) ->\ xr.Dataset: """ Read image and mask, and return the corresponding xarray.DataSet :param img: Path to the image :type img: string :type no_data: no_data value in the image :type no_data: f...
2074269e47092313f1cb01dc81004b7ce9c8f411
17,333
def any_user(password=None, permissions=[], groups=[], **kwargs): """ Shortcut for creating Users Permissions could be a list of permission names If not specified, creates active, non superuser and non staff user """ is_active = kwargs.pop('is_active', True) is_superuser = kwargs.pop...
914bbb58b68aad9b19a77f2dec7ea1f0e91508bd
17,334
def devices_to_use(): """Returns the device objects for the accel. we are the most likely to use. Returns: List of logical devices of the accelerators we will use. """ if tf.config.list_logical_devices("TPU"): devices = tf.config.list_logical_devices("TPU") elif tf.config.list_logical_devices("GPU"):...
aca8cbd28ff46e79655b47e34334c12406cc94e8
17,335
def barcode_density(bars, length): """ calculates the barcode density (normalized average cycle lifetime) of a barcode """ densities = np.zeros(len(bars)) nums = np.array([len(bars[i][1]) for i in range(len(bars))]) num_infs = np.zeros(len(bars)) for i in range(len(bars)): tot = ...
4b585338cef3fd8b8ca91f89a1ae0532450b6209
17,336
def genRankSurvey(readername, candidates, binsize, shareWith=None): """ readername (str) candidates (iterable) binsize (int) shareWith (str) optional """ # connect and craete survey c = cornellQualtrics() surveyname = "Ranking Survey for {}".format(readername) surveyId = c.create...
e94f782389de86a8cbfb9c77aa078f004ac061c9
17,338
def _get_badge_status( self_compat_res: dict, google_compat_res: dict, dependency_res: dict) -> BadgeStatus: """Get the badge status. The badge status will determine the right hand text and the color of the badge. Args: self_compat_res: a dict containing a package's sel...
f367f75321c62a7c86b4ef26be446072e5eaca7c
17,339
import yaml def _get_yaml_as_string_from_mark(marker): """Gets yaml and converts to text""" testids_mark_arg_no = len(marker.args) if testids_mark_arg_no > 1: raise TypeError( 'Incorrect number of arguments passed to' ' @pytest.mark.test_yaml, expected 1 and ' '...
034dab9c5380035d2303df7ea7243b84baff47a0
17,340
def combine_dicts(w_dict1, w_dict2, params, model): """ Combine two dictionaries: """ w_dict = w_dict1 + w_dict2 eps = params[0] params[0] = 0 P_w = [] w_dict = md.remove_duplicates_w_dict(P_w,w_dict,params,model) return w_dict
21c2de003cca0165b5404431178450bf6e6c549c
17,341
def geocode_mapping(row, aian_ranges, aian_areas, redefine_counties, strong_mcd_states): """ Maps an RDD row to a tuple with format (state, AIAN_bool, AIANNHCE, county, place/MCD, tract, block), where place/MCD is the five digit MCD in MCD-strong states and 5 digit place otherwise AIAN_bool is '1' if th...
6d2dcd7aa5acb5bff71120d957f520d0eec79790
17,342
from typing import Dict def get_stan_input( scores: pd.DataFrame, priors: Dict, likelihood: bool, ) -> Dict: """Get an input to cmdstanpy.CmdStanModel.sample. :param measurements: a pandas DataFrame whose rows represent measurements :param model_config: a dictionary with keys "priors", "like...
d8e11401c1c86bb3306652f6f3b1aaebe47ef2d8
17,343
def get_mph(velocity): """ Returns ------- convert m/s to miles per hour [mph]. """ velocity = velocity * 3600 /1852 return velocity
f4a1922712ef2d8cfeba5650f410405956a39c31
17,344
import json def _load_jsonl(input_path) -> list: """ Read list of objects from a JSON lines file. """ data = [] with open(input_path, 'r', encoding='utf-8') as f: for line in f: data.append(json.loads(line.rstrip('\n|\r'))) print('[LoadJsonl] Loaded {} records from {}'.form...
2cd35ff8afa7c325688046165517746e2b120b77
17,345
import types import importlib def reload(name: str) -> types.ModuleType: """ Finalize and reload a plugin and any plugins that (transitively) depend on it. We try to run all finalizers in dependency order, and only load plugins that were successfully unloaded, and whose dependencies have been successf...
ea00d2139b51e80239960f61c0dc91dfe45de7d9
17,346
import json def load_from_config(config_path, **kwargs): """Load from a config file. Config options can still be overwritten with kwargs""" with open(config_path, "r") as config_file: config = json.load(config_file) config.update(kwargs) return TokenizationConfig(**config)
66ea64a334b265ae216413a043044767da0fd61c
17,347
import collections def get_tecogan_monitors(monitor): """ Create monitors for displaying and storing TECOGAN losses. """ monitor_vgg_loss = MonitorSeries( 'vgg loss', monitor, interval=20) monitor_pp_loss = MonitorSeries( 'ping pong', monitor, interval=20) monitor_sum_layer_los...
472605e4ff7a0e487fd868a573fbecf5acd977ba
17,348
def user_based_filtering_recommend(new_user,user_movies_ids,movies_num,n_neighbor,movies_ratings): """ This function return number of recommended movies based on user based filtering using cosine similarity to find the most similar users to the new user it returns movies_num of movies from the top ranked ...
4fa86b9966024e0d89969566d85ccf0b0a44bfcc
17,349
def query_ps_from_wcs(w): """Query PanStarrs for a wcs. """ nra,ndec = w.array_shape[1:] dra,ddec = w.wcs.cdelt[:2] c = wcs.utils.pixel_to_skycoord(nra/2.,ndec/2.,w) ddeg = np.linalg.norm([dra*nra/2,ddec*ndec/2]) pd_table = query(c.ra.value,c.dec.value,ddeg) # Crop sources to those in t...
806baf87722213ab021e1e3889322539069a3b55
17,350
import torch def permute(x, in_shape='BCD', out_shape='BCD', **kw): """ Permute the dimensions of a tensor.\n - `x: Tensor`; The nd-tensor to be permuted. - `in_shape: str`; The dimension shape of `x`. Can only have characters `'B'` or `'C'` or `'D'`, which stand for Batch, Channel, or extra Dim...
e74594df581c12891963e931999563374cd89c7d
17,351
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Parameters ---------- data A 2D numpy array of shape (N, M). row_labels A list or array of length N with the label...
51c60139f9f2668f8ba31859c036f48a3e8faf63
17,352
import zlib import struct def assert_is_normal_rpyc(f): """ Analyze the structure of a single rpyc file object for correctness. Does not actually say anything about the _contents_ of that section, just that we were able to slice it out of there. If succesful, returns the uncompressed contents of ...
f7db901dd99b0ac9036d6569093068e8f6b3e675
17,353
def substract_li(cfg, data, lats, lons, future_exp): """Difference between historical and future fields.""" pathlist = data.get_path_list(short_name='pr', exp='historical') ar_diff_rain = np.zeros((len(lats), len(lons), len(pathlist))) mism_diff_rain = np.zeros(len(pathlist)) mwp_hist_rain = np.zer...
40506221fbdf5a9b0e2174e0fe144958dd57c93b
17,355
def identify_jobs_to_update(file_path, jobs): """identify jobs to update.""" name_map = {} for job in jobs: cluster = get_desired_cluster(file_path, job) if cluster != job.get("cluster", ""): name_map[job["name"]] = cluster return name_map
be9b8bd38ed90c96ac185195a79a43ffbec5e7d5
17,356
def bootstrap_storage_bucket(project_id, bucket_name, google_credentials): """ Bootstrap the bucket used to store Terraform state for projects. Args: project_id: The ID of the project to create the bucket in. bucket_name: The name of the bucket to create. goo...
acdd72fbcb160d5c6347f1f41b6661fcf28ebdc2
17,357
def ValidateBucketForCertificateAuthority(bucket_name): """Validates that a user-specified bucket can be used with a Private CA. Args: bucket_name: The name of the GCS bucket to validate. Returns: A BucketReference wrapping the given bucket name. Raises: InvalidArgumentException: when the given b...
b28e501b7747f8a4d417b156c2e627d8ca524aee
17,358
def load_train_val(seq_len, batch_size, dataset="hollywood2"): """ This returns two dataloaders correponding to the train and validation sets. Each iterator yields tensors of shape (N, 3, L, H, W) where N is the batch size, L is the sequence length, and H and W are the height and width of the frame. ...
628a2c0db01b30c4736e482dbc81789afcbdc92a
17,359
import json import yaml def read_params_file(config_path: str) -> json: """Read the and open the params.yaml file Args: config_path (str): yaml config file Returns: yaml: yaml file """ with open(config_path) as yaml_file: config = yaml.safe_load(yaml_file) return con...
b8a4bf0f70d1b4e2096ebd6d96568fc7ee757e16
17,361
import re def fullmatch(regex, string, flags=0): """Emulate python-3.4 re.fullmatch().""" matched = re.match(regex, string, flags=flags) if matched and matched.span()[1] == len(string): return matched return None
72de0abe5c15dd17879b439562747c9093d517c5
17,362
from typing import Any from typing import Type import inspect def _is_class(module: Any, member: Type, clazz: Type) -> bool: """ Validates if a module member is a class and an instance of a CoreService. :param module: module to validate for service :param member: member to validate for service :p...
5792fadcc93068fa8d7050de7d84ee2bbe1fb0f1
17,364
def word_boundary(queries, count, degree, parallel=True, **kwargs): """ run augmentation on list of sentences :param queries: sentences to augment :type queries: list :param count: number of output for each query :type count: int :param degree: degree of augmentation, takes value between 0 a...
7ca4172d2900c773322d54380bde6780f2580597
17,365
def myFunction(objectIn): """What you are supposed to test.""" return objectIn.aMethodToMock() + 2
1907db338a05f2d798ccde63366d052404324e6f
17,366
def read_config(filename, section): """ Reads a section from a .ini file and returns a dict object """ parser = ConfigParser() parser.read(filename) dic = {} if parser.has_section(section): items = parser.items(section) for item in items: dic[item[0]] = item[1] ...
3eb84afc13b0ad40bcaf434d4a38712cedb4502a
17,367
def get_training_set_count(disc): """Returns the total number of training sets of a discipline and all its child elements. :param disc: Discipline instance :type disc: models.Discipline :return: sum of training sets :rtype: int """ training_set_counter = 0 for child in disc.get_desc...
9b28a9e51e04b559f05f1cc0255a6c65ca4a0980
17,368
def lazy_import(module_name, callback=None): """Returns a proxy module object that will lazily import the given module the first time it is used. Example usage:: # Lazy version of `import tensorflow as tf` tf = lazy_import("tensorflow") # Other commands # Now the module i...
bc94a18b4a8a2714d2cffd743de2a202ecb5af78
17,370
def _top_k(array, k): """Returns top k values and their indices along the last axis of the array. This function serves the same purpose as jax.lax.top_k, but in a more XLA friendly manner for TPUs: (1) On TPUs, we use one-hot matrix multiplications to select the top k values. This convoluted way of obtai...
74c7c705b6b972d227c10146f0b5209f62c1d59f
17,371
def time_to_accuracy(raw_metrics, tag, threshold): """Calculate the amount of time for accuracy to cross a given threshold. Args: raw_metrics: dict mapping TensorBoard tags to list of MetricPoint. tag: string name of accuracy metric. threshold: the desired model accuracy. Returns: float, amoun...
5ce2727a538a25f195c0d9ab3de2c2dcdbb56f88
17,372
def create_stencil(image_shape, smooth): """The stencil is a mask that will enable a smooth transition between blocks. blocks will be multiplied by the stencil so that when they are blitted to the image, transition between them are smoothed out. image 1: 1 1 1 1 1 1 1 , image 2: 2 2 2 2 2 2 2, stencil: .25 ...
49aca2fb63ea6bef134c0872520fd203ce21bfef
17,373
def a_m_to_P(a, m): """Compute the orbital period given the semi-major axis and total mass. Parameters ---------- {a} {m} """ return 2*np.pi * np.sqrt(a**3 / (G * m))
734332ff83c06830388ceeecd64315ee738756f1
17,374
def _async_attr_mapper(attr_name, val): """The `async` attribute works slightly different than the other bool attributes. It can be set explicitly to `false` with no surrounding quotes according to the spec.""" if val in [False, 'False']: return ' {}=false'.format(attr_name) elif val: ...
79e72067b244d705df9aa09a78db656f0847938c
17,375
from typing import Any from typing import Type def wrap(val: Any) -> Value: """Wraps the given native `val` as Protobuf `Value` message. Supports converting collection/array of primitives types to `Value` message: * numpy array of primitives. * list of primitives. * generator of finite no. of pri...
9208a2afd7b256ec791044531b13fe8c8b9fa2c8
17,376
def to_transform_msg(transform): """Convert a `Transform` object to a Transform message.""" msg = geometry_msgs.msg.Transform() msg.translation = to_vector3_msg(transform.translation) msg.rotation = to_quat_msg(transform.rotation) return msg
c471ec8dfed03caa9f7096ab3294589477cf6d39
17,377
def print_pos_neg(num): """Print if positive or negative in polarity level >>> print_pos_neg(0.8) 'positive' >>> print_pos_neg(-0.5) 'negative' """ if num > 0: return "positive" elif num == 0: return "neutral" else: return "negative"
414aa98f54a2f01af24d591ae47ec4f394adf682
17,378
def delete_volume_op(name: str, namespace: str): """ Creates a kfp.dsl.ContainerOp that deletes a volume (Kubernetes Resource). Parameters ---------- name : str namespace : str Returns ------- kfp.dsl.ContainerOp """ kind = "PersistentVolumeClaim" return kubernetes_resour...
d947905e01de29061895512fbfd1fbefb024110d
17,379
def distal(combo): """ Returns the distal subspecies from a combo :param combo: int representation of origin combination :return: int representation of the distal origin >>> distal(combine(CAS, DOM)) == DOM True """ return combo & _DISTAL_MASK
163875c1b4b081027344a3bc1f05bd0cb60a58d8
17,380
def get_eval_dataset(files, ftDict, axes = [2], splits = None, one_hot = None, moments = None, **kwargs): """ Get the preprocessed evaluation dataset Args: files (list): list of tfrecords to be used for evaluation Returns: A tf.data.Dataset of evaluation data. """ dataset = get_dataset...
73476bf1273923e77bf5f4e6d415191cf83023cc
17,381
def getTopApSignals(slot_to_io): """ HLS simulator requires that there is an ap_done at the top level """ # find which slot has the s_axi_control for slot, io_list in slot_to_io.items(): if any('s_axi' in io[-1] for io in io_list): # note the naming convention ap_done_source = [f'{io[-1]}_in' fo...
e40a8fb7797653ee7414c0120ceb29e49e9dfd84
17,382
def get_line_style(image: Image = None) -> int: """ Get line style of the specified image. The line style will be used when drawing lines or shape outlines. :param image: the target image whose line style is to be gotten. None means it is the target image (see set_target() and get_target()) ...
cc1b9285fbd3b168f40e66969e0a4b1ae9ee234a
17,383
def make_polygon_for_earth(lat_bottom_left, lon_bottom_left, lat_top_right, lon_top_right): """ Divides the region into two separate regions (if needed) so as to handle the cases where the regions cross the international date :param lat_bottom_left: float (-90 to 90) :param lon_bottom_left: float (...
6f73cc35c11cd16eea0c80aa7921ff1680ee75b6
17,384
def first_nonzero_coordinate(data, start_point, end_point): """Coordinate of the first nonzero element between start and end points. Parameters ---------- data : nD array, shape (N1, N2, ..., ND) A data volume. start_point : array, shape (D,) The start coordinate to check. end_p...
5db67cf49c3638a80695fd76a1a16eeec992d725
17,386
def l1_distance(prediction, ground_truth): """L1 distance difference between two vectors.""" if prediction.shape != ground_truth.shape: prediction, ground_truth = np.squeeze(prediction), np.squeeze(ground_truth) min_length = min(prediction.size, ground_truth.size) return np.abs(prediction[:min_length] - gro...
aaf79b386efa5f1b8726adda8d8e7dc66a502e87
17,387
from typing import Match import base64 def decode(match_id: str) -> Match: """Decode a match ID and return a Match. >>> decode("QYkqASAAIAAA") Match(cube_value=2, cube_holder=<Player.ZERO: 0>, player=<Player.ONE: 1>, crawford=False, game_state=<GameState.PLAYING: 1>, turn=<Player.ONE: 1>, double=False, r...
a48fae652650d03259fd003af16add381f2729f3
17,388
def _valid_proto_paths(transitive_proto_path): """Build a list of valid paths to build the --proto_path arguments for the ScalaPB protobuf compiler In particular, the '.' path needs to be stripped out. This mirrors a fix in the java proto rules: https://github.com/bazelbuild/bazel/commit/af3605862047f7b553b...
cb834a58fa091249f16d5cdfccf536229dacd3d0
17,389
def update_stats_objecness(obj_stats, gt_bboxes, gt_labels, pred_bboxes, pred_labels, pred_scores, mask_eval=False, affordance_stats=None, gt_masks=None, pred_masks=None, img_height=None, img_width=None, iou_thres=0.3): """ Updates statistics for object classification and affordance detecti...
c07d57921a6f3f3d2d97c9d84afb5dcbcb885ea6
17,390
from typing import Dict from pathlib import Path import inspect import json def load_schema(rel_path: str) -> Dict: """ Loads a schema from a relative path of the caller of this function. :param rel_path: Relative path from the caller. e.g. ../schemas/schema.json :return: Loaded schema as a `dict`. ...
297e0e01dd2f4af071ab99ebaf203ddb64525c89
17,391
def bquantize(x, nsd=3, abstol=eps, reltol=10 * eps): """Bidirectionally quantize a 1D vector ``x`` to ``nsd`` signed digits. This method will terminate early if the error is less than the specified tolerances. The quantizer details are repeated here for the user's convenience: The quantizer ...
2a2e5fb71f3198099a07d84e9ad83ba6849b38d0
17,392
def seg_to_bdry(seg, connectivity=1): """Given a borderless segmentation, return the boundary map.""" strel = generate_binary_structure(seg.ndim, connectivity) return maximum_filter(seg, footprint=strel) != \ minimum_filter(seg, footprint=strel)
dc4e66a7e6f86d2984a23a2e7a7297403502b51d
17,394
def depthwise_conv2d(x, filters, strides, padding, data_format="NHWC", dilations=1): """Computes a 2-D depthwise convolution given 4-D input x and filters arrays. Parameters ---------- x Input image *[batch_size,h,w,d]*. filters Convolution filters *[fh,fw,d]*. strides T...
cc09b910d06b8fd9d1b5b00a80c6d376cf7f6005
17,395
def OUTA(): """ The OUTA Operation """ control_signal = gen_control_signal_dict() opcode_addr = gen_opcode_addr_component_dict() mc_step_addr = gen_microcode_step_addr_component_dict() input_sig_addr = gen_input_signal_addr_component_dict() templates = [] # Step 2 - A -> OUT a...
3ebd5e74005316d3925eaa553c112df8a61eaf90
17,396
def incidence_matrices(G, V, E, faces, edge_to_idx): """ Returns incidence matrices B1 and B2 :param G: NetworkX DiGraph :param V: list of nodes :param E: list of edges :param faces: list of faces in G Returns B1 (|V| x |E|) and B2 (|E| x |faces|) B1[i][j]: -1 if node i is tail of edge...
90a82132100bb6d2e867ee7460ad55c6891b9082
17,397
def get_hosts_ram_total(nova, hosts): """Get total RAM (free+used) of hosts. :param nova: A Nova client :type nova: * :param hosts: A set of hosts :type hosts: list(str) :return: A dictionary of (host, total_ram) :rtype: dict(str: *) """ hosts_ram_total = dict() #dict of (host...
b913f9274339ab3ab976a17a8d07e5fe130b447d
17,398
import re import unicodedata def slugify(value): """ Normalizes string, converts to lowercase, removes non-ascii characters, and converts spaces to hyphens. For use in urls and filenames From Django's "django/template/defaultfilters.py". """ _slugify_strip_re = re.compile(r'[^\w\s-]') _s...
471a3205c84baa55573b780375999a7658031b89
17,399
def wpr(c_close, c_high, c_low, period): """ William %R :type c_close: np.ndarray :type c_high: np.ndarray :type c_low: np.ndarray :type period: int :rtype: (np.ndarray, np.ndarray) """ size = len(c_close) out = np.array([np.nan] * size) for i in range(period - 1, size): ...
0f1d8d46464be81daa6308df97a7a8d12a90274b
17,400
def delete_action_log(request, log_id): """ View for delete the action log. This view can only access by superuser and staff. """ action = get_object_or_404(ActionLog, id=log_id) if action.status == 0 or action.status == 1: messages.error(request, "Cannot delete the Action log that is r...
8560e5280a57ddc8158b811fac29763bbaa8ef37
17,401
def hsla_to_rgba(h, s, l, a): """ 0 <= H < 360, 0 <= s,l,a < 1 """ h = h % 360 s = max(0, min(1, s)) l = max(0, min(1, l)) a = max(0, min(1, a)) c = (1 - abs(2*l - 1)) * s x = c * (1 - abs(h/60%2 - 1)) m = l - c/2 if h<60: r, g, b = c, x, 0 elif h<120: r, g,...
55e546756d4dd2a49581a5f950beb286dd73f3f9
17,402
from typing import Dict from pathlib import Path from typing import Optional def prioritize(paths: Dict[int, Path], purpose: str) -> Optional[Path]: """Returns highest-priority and existing filepath from ``paths``. Finds existing configuration or data file in ``paths`` with highest priority and returns i...
2c00d0bfe696040c2c19dc1d8b3393b7be124e11
17,403
def traverse(d, path): """Return the value at the given path from the given nested dict/list""" for k in path.split('.'): if k.isdigit(): k = int(k) d = d[k] return d
ba832a008073da5d97ba0a237a8e0ded17e4694e
17,404
def _bundle_name_with_extension(ctx): """Returns the name of the bundle with its extension. Args: ctx: The Skylark context. Returns: The bundle name with its extension. """ return _bundle_name(ctx) + _bundle_extension(ctx)
51f9c84fa2dd0ef9c5736a59ca2cd3c2d76aa108
17,405
def cvt_axisang_t_o2i(axisang, trans): """-correction: t_r, R_rt_r. outer to inner""" trans -= get_offset(axisang) return axisang, trans
ef263052e91ecc2fb8e668bca89a9d5622b75ff2
17,407
import pytz import numpy import dateutil def processData(dict, valuename, timename='Aika', multiplier=1.0): """Process "raw" OData dict and strip only the time and value. Also convert time to UTC and hydrodynamics model (COHERENS) format. Parameters ---------- dict: dictionary Data dictionary a...
df452a703a3afface12dc76abb647a5e38b808c3
17,408
from datetime import datetime def get_current_year(): """Returns current year """ return str(datetime.date.today().year)
f019e7f2462a4d8db0db294fade6ca737e87a24c
17,409
def parse_ans(text): """ Parses the given text as an answer set, i.e., a sequence of predicate statements. Returns a (possibly empty) tuple of Predicate objects. """ return parser.parse_completely( text, parser.Rep(PredicateStatement), devour=devour_asp )
44479668629b142115c27476242cbdf23b6657cc
17,410
def get_xyz(data): """ :param data: 3D data :return: 3D data coordinates 第1,2,3维数字依次递增 """ nim = data.ndim if nim == 3: size_x, size_y, size_z = data.shape x_arange = np.arange(1, size_x+1) y_arange = np.arange(1, size_y+1) z_arange = np.arange(1, size_z+1) ...
b1bd78fee6ca4a8fc2a33430c4ea5e922d696381
17,411
def wc_proximal_gradient(L, mu, gamma, n, verbose=1): """ Consider the composite convex minimization problem .. math:: F_\\star \\triangleq \\min_x \\{F(x) \\equiv f_1(x) + f_2(x)\\}, where :math:`f_1` is :math:`L`-smooth and :math:`\\mu`-strongly convex, and where :math:`f_2` is closed convex and...
ff8b67b963a2301e9b49870ffa9b6736a23420a4
17,412
def all_asset_types_for_shot(shot, client=default): """ Args: shot (str / dict): The shot dict or the shot ID. Returns: list: Asset types from assets casted in given shot. """ path = "shots/%s/asset-types" % shot["id"] return sort_by_name(raw.fetch_all(path, client=client))
a7d06e49d564dbd294636e29f488703f5027026e
17,414
from typing import Iterable def train(x_mat: ndarray, k: int, *, max_iters: int = 10, initial_centroids: Iterable = None, history: bool = False): """ 进行k均值训练 :param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数 :param k: 聚类数目 :param max_iters: 最大迭代次数 :param initial_centroids: 初始聚类中心,不提供别的话将随机挑选聚类中心 ...
3a27cb709d6b267c8da19312f634f6003e2ba9a3
17,415
def download4(url, user_agent='wswp', num_retries=2): """Download function that includes user agent support""" # wswp: web scraping with python print 'Downloading:', url headers = {'User-agent': user_agent} request = urllib2.Request(url, headers=headers) try: html = urllib2.urlopen(reque...
1381e64e93b373e68a1a07eaab1688462f905374
17,416
import unittest def testv1(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('./tests/api/v1', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
519835d59ce7d370e8099e94a48b1e7309274d99
17,417
def get_third_order_displacements(cell, symmetry, is_plusminus='auto', is_diagonal=False): """Create dispalcement dataset Note ---- Atoms 1, 2, and 3 are defined as follows: Atom 1: The first disp...
6ae03dbd10ffec75bc274b4a4115b81d28cefc40
17,418
def get_result_type(action): """Gets the corresponding ROS action result type. Args: action: ROS action name. Returns: Result message type. None if not found. """ msg_type = rostopic.get_topic_type("{}/result".format(action))[0] # Replace 'ActionResult' with 'Result'. retu...
f5612ac116357000106f7ff24f0d2bebb6789547
17,419
import statistics import math def get_turbulence(sequence): """ Computes turbulence for a given sequence, based on `Elzinga & Liefbroer's 2007 definition <https://www.researchgate.net/publication/225402919_De-standardization_of_Family-Life_Trajectories_of_Young_Adults_A_Cross-National_Comparison_Using_Sequence_An...
9900d377240b609de1cb7a5284752457947ef6c3
17,420
def reflect(array, holder=1): """ Reflects a np array across the y-axis Args: array: array to be reflected holder: a holder variable so the function can be used in optimization algorithms. If <0.5, does not reflect. Returns: Reflected array """ c = array.copy() if ...
c39cbf0bb3a949254e4f0c35b20bdf84766d2084
17,421
def absolute_name_scope(scope, reuse=tf.AUTO_REUSE): """Builds an absolute tf.name_scope relative to the current_scope. This is helpful to reuse nested name scopes. E.g. The following will happen when using regular tf.name_scope: with tf.name_scope('outer'): with tf.name_scope('inner'): prin...
b9bd9e801603472c3e7e1db7a8768387b9942f3c
17,425
def regina_edge_orientation_agrees(tet, vert_pair): """ Given tet and an ordered pair of (regina) vert nums of that tet, does this ordering agree with regina's ordering of the verts of that edge of the triangulation """ edge_num = vert_pair_to_edge_num[tuple(vert_pair)] mapping = tet.faceMapping...
a70f08f56754eee24b9c4c71d5b6b537388a4ca4
17,426
from typing import Optional from datetime import datetime async def populate_challenge( challenge_status: str = "process", is_public: bool = True, user_id: Optional[UUID] = USER_UUID, challenge_id: UUID = POPULATE_CHALLENGE_ID, ) -> Challenge: """Populate challenge for routes testi...
fa47e65c7615af8dfebed4dd66fd92141d50e130
17,427
from typing import List def is_common_prefix(words: List[str], length: int) -> bool: """Binary Search""" word: str = words[0][:length] for next_word in words[1:]: if not next_word.startswith(word): return False return True
f57c7309f725baba0b65c92181a6f1ab2827558a
17,428
def freq_upsample(s, upsample): """ padding in frequency domain, should be used with ifft so that signal is upsampled in time-domain. Args: s : frequency domain signal upsample : an integer indicating factor of upsampling. Returns: padded signal """ if upsample =...
78377f6c552fe4f6d764a33b3e6ee555b4aabe71
17,429
def streaming_parsing_covering(groundtruth_categories, groundtruth_instances, predicted_categories, predicted_instances, num_classes, max_instances_per_category, ...
7c41f5b0c1111287759cc03cdc2a0c8a932aba11
17,430
from typing import Union def get_rxn_lookup(medObj:Union[m.Medication, m.LocalMed, m.NDC]): """ DEPRECATED Lookup RxCUI for codes from a different source :param medObj: :return: """ if isinstance(medObj, m.RxCUI): smores_error('TBD') return 0, [] success_count, errors ...
bba03aa380666b13db89497c720a62570a2918d0
17,431
def identity(dims): """ Create an identity linear operator :param dims: array of dimensions """ dims = expand_dims(dims) return identity_create(dims)
4d57c5a0da628c8f24de4f621728176714a4ab54
17,432
def _gen_samples_2d(enn_sampler: testbed_base.EpistemicSampler, x: chex.Array, num_samples: int, categorical: bool = False) -> pd.DataFrame: """Generate posterior samples at x (not implemented for all posterior).""" # Generate the samples data = [] rng...
19fc06700ae42b015694fc9389c05ad0caebf54d
17,433
def rules(r_index, c_index, lives, some_board, duplicate_board): """Apply Conway's Rules to a board Args: r_index (int): Current row index c_index (int): Current column index lives (int): Number of ALIVE cells around current position some_board (List of lists of strings): Board ...
f654a134be3eccad122720cd58f577a2d7e580d8
17,434
def get_describe_tasks(cluster_name, tasks_arns): """Get information about a list of tasks.""" return ( ecs_client() .describe_tasks(cluster=cluster_name, tasks=tasks_arns) .get("tasks", []) )
663cc2d2241aa3d75c8f2de35780ebe9a5d4ae31
17,435
def make_bcc110(latconst=1.0): """ Make a cell of bcc structure with z along [110]. """ s= NAPSystem(specorder=_default_specorder) #...lattice a1= np.array([ 1.0, 0.0, 0.0 ]) a2= np.array([ 0.0, 1.414, 0.0 ]) a3= np.array([ 0.0, 0.0, 1.41...
187556e30b4e89718d4c8d1179579ba498062d26
17,436
def mode_mods_to_int(mode: str) -> int: """Converts mode_mods (str) to mode_mods (int).""" # NOTE: This is a temporary function to convert the leaderboard mode to an int. # It will be removed when the site is fully converted to use the new # stats table. for mode_num, mode_str in enumerate(( ...
0bfaa8cf04bcee9395dff719067be9753be075c4
17,437