content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime def get_formatted_date(date: datetime.datetime) -> str: """ Formatted date """ return date.isoformat()[:10]
10704d33e1ae10de6829e4de1e29e2e260b9bd57
3,609,600
def get_submission_max_ram(session, submission_id): """Get the max amount RAM used by a submission during processing. Parameters ---------- session : :class:`sqlalchemy.orm.Session` The session to directly perform the operation on the database. submission_id : int The id of the subm...
56aee778f366e8007292512b2efbade4b161472a
3,609,601
import os def is_dir(path: str, basedir): """Takes a dot separated directory path""" maybe_path = _parse_path(path, basedir) return os.path.isdir(maybe_path)
909334eeb56d71cb2bf4f3725d3c633744eb235c
3,609,602
def uuid_to_cbuuid(uuid): """Convert native Python UUID type to Objective-C CBUUID type.""" return CBUUID.UUIDWithString_(str(uuid))
e9e91aca658291adc4f1bbdfae9839e98b5c1709
3,609,603
import re def is_valid_hostname(hostname): """ Check that hostname passed in is valid. Pretty much a copy paste of this https://stackoverflow.com/questions/2532053/validate-a-hostname-string """ if len(hostname) > 255: return False if hostname[-1] == ".": hostname = hostnam...
aacf57c7ef740c4cebfe008c67867921d4b8a958
3,609,604
import glob import os def concat_data(years): """ Convert to long format, add 'Year' and concatenate into one DataFrame """ data = [] for year in years: for file in glob.glob(os.path.join("CSV", str(year), "*.csv")): csv_data = pd.read_csv(file) csv_data = pd.melt(c...
c0cfadea0d30208f1cd771048946ec4449ecbb71
3,609,605
def delta_soga_from_masso(m_orig, m_new, s_orig): """Infer a change in global average salinity from mass""" delta_s = s_orig * ((m_orig / m_new) - 1) return delta_s
a0ffb18378c3d997ea8ab88286a11e34b9abbb71
3,609,606
from typing import Union from pathlib import Path from typing import Dict from typing import List from typing import OrderedDict def find_packages_source_files( packages_path: Union[str, Path] ) -> Dict[str, List[Path]]: """ List packages source files. Args: packages_path: Path to the package...
d210f00e5311fa609fd3841afeecf636649289f4
3,609,607
from pathlib import Path import hashlib import base64 def calc_sha(obj): """Calculates the base64-encoded SHA hash of a file.""" try: pathfile = Path(obj) except UnicodeDecodeError: pathfile = None sha = hashlib.sha256() try: if pathfile and pathfile.exists(): ...
2669046e0053f0f73471e9fbadc95a287ed5d9a4
3,609,608
def L_model_backward(AL, Y, caches): """ Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group Arguments: AL -- probability vector, output of the forward propagation (L_model_forward()) Y -- true "label" vector (containing 0 if non-cat, 1 if cat) caches --...
1e1cb08914c43b7d017df6735c06f87102e459a6
3,609,609
from graph_tool.all import load_graph def load_gt_graph(graph_path): """Load a graph in graphml or gt format.""" logger.info(f"loading the generated graph file from {graph_path}") g = load_graph(graph_path) return g
ddcc5cb56be87412764ec1d499333b132eee0d87
3,609,610
def generate_key(name: str) -> str: """ Given a display name, generate a global unique value suitable for use as a step key in Buildkite. """ norm = name.lower() for regex in (RE_NONID, RE_MULTI_US): norm = regex.sub('_', norm) if norm not in KEY_COUNT: KEY_COUNT[norm] = 1 ...
d3de408564ac34bec8cac53a0621eb51cc99c8cd
3,609,611
def get_session(): """ Set tf backend to allow memory to grow, instead of claiming everything """ config = tf.ConfigProto() config.gpu_options.allow_growth = True return tf.Session(config=config)
3dc72968da1da0df3e0a1cc641b3833afa225da0
3,609,612
import os import csv def read_pcd_to_exchange_lut(): """ Produces all unique postcode-to-exchange combinations from available data, including: 'January 2013 PCP to Postcode File Part One.csv' 'January 2013 PCP to Postcode File Part Two.csv' 'pcp.to.pcd.dec.11.one.csv' 'pcp.to.pcd.dec.11.two.c...
3d4bfa11405ab5c3f27c1f3ef8cd3101316b3abf
3,609,613
def get_axis_lims_con(epoch): """ Generates an invisible mne.viz.plot_topomap plot and gets the ylim from its matplotlib.axes._subplots.AxesSubplot. Helper function for plot_connectivity. Parameters: epoch: mne.epochs.Epochs MNE epochs object containing the timestamps. ...
b127bd10c1b6d84ff8ba9f452be84d036d0d50ec
3,609,614
import re from bs4 import BeautifulSoup import requests import urllib def osdn(url: str) -> str: """ OSDN direct links generator """ osdn_link = 'https://osdn.net' try: link = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0] except IndexError: reply = "`No OSDN links found`\n" ...
579cc6f14b878a45a764f9584d7cae7be2356245
3,609,615
def abox2bbox(aboxes): """covnert affine boxes to bounding point box reference: https://www.iquilezles.org/www/articles/ellipses/ellipses.htm Args: aboxes ([np.ndarray]): affine boxes shape with [*, 3, 3] """ c = aboxes[..., :2, 2] e = np.linalg.norm(aboxes[..., :2, :2], ord=2, axis=-...
4c43138f232a7e704a2a2a534c146f795e639908
3,609,616
def nrrd_2_numpy(input_nrrd, return_all=False): """ Loads nrrd data and optionally return a nrrd header in pynrrd's format. If array is 4D, swaps axes so that time dimension is last to match nifti standard. """ nrrd_data, nrrd_options = nrrd.read(input_nrrd) if nrrd_data.ndim == 4...
250b01136810a42eef71c939759109ca8486ee70
3,609,617
import os import sys def get_evergreen_api() -> EvergreenApi: """Return evergreen API.""" # Pickup the first config file found in common locations. for file in EVERGREEN_CONFIG_LOCATIONS: if os.path.isfile(file): evg_api = RetryingEvergreenApi.get_api(config_file=file) retu...
db21974eec8849389189babe4c0d3745282e91c7
3,609,618
from typing import Callable def make_schedule(schedule: config_pb2.Schedule) -> Callable[int, float]: """Creates a schedule.""" if schedule.HasField('inverse_time_decay'): base_schedule = optimizers.inverse_time_decay( step_size=schedule.inverse_time_decay.base, decay_steps=sc...
b41caac8fc4a6da91523c263b366222365b40764
3,609,619
def procstringT0(candidate): """ ProcessingString validation function for T0 specs """ if isinstance(candidate, dict): for candi in viewvalues(candidate): check(r'^$|[a-zA-Z0-9_]{1,100}$', candi) return True else: return check(r'^$|[a-zA-Z0-9_]{1,100}$', candidate...
67ad6554dbf452d9607439e76bcf31e8c96e00fe
3,609,620
def index(): """Return an index page.""" return render_template('index.html')
2220eb1ea5fd14cbb7d8afa17a6e318874986355
3,609,621
import re import logging import urllib import io def download_file(location, wv_user=None, wv_password=None, wv_host_name=None): """ Download a file from the specified URL location. It recognizes MAGIC's Nextcloud (WebDAV) instance AND Google Drive URL's Of course, it should work with Zenodo. Goo...
83793df6c2faff0bf65a5fd92eea8143e505b094
3,609,622
def rreplace(s, old, new, occurrence = 1): """ Replaces the last occurence(s) of an expression in a string. """ return new.join(s.rsplit(old, occurrence))
92a3fdb0e5a2014debd6e3530c7c6c754ed45953
3,609,623
def get_cal_params(power_data_dict,particle_data,config_header,config_transducer): """ Get calibration params from the unpacked file Parameters come from config_header and config_transducer (both from header), as well as particle_data (from .RAW file) """ cal_pa...
081e3cf5d48d14056948617bc01d65205ed242aa
3,609,624
def get_decompounder(): """ Restarts the JVM with the decompounder. It is necessary once in a while. """ javabridge.start_vm(class_path=["tf/jwordsplitter/target/jwordsplitter-4.2-SNAPSHOT.jar"]) java_instance = javabridge.make_instance("de/danielnaber/jwordsplitter/GermanWordSplitter", "(Z)V", Fals...
3a6196a119c6bbbb8793f038abbbd548637f881c
3,609,625
def get_instance(): """Return a DB API instance.""" return IMPL
3bbd1f160adde70ac700e4c5d6fb59e315a1d43c
3,609,626
def loadfile(filename): """ Helper function to load content given the filename @param filename: target file's name @type filename: C{string} """ try: f = open(filename , "r") except IOError , e: print >> sys.stderr, "Fail to load file %s: %s" % (filename, e) return []...
8315a80cf7f6e4a2c9fb6f08bd4a0ce04540576c
3,609,627
import traceback import sys def save_images_to_excel(file_name, sheet_name, image_names): """ # 保存图形文件到excel :param file_name: excel文件名 :param sheet_name: workSheet :param image_names: 图像文件名列表 :return: """ if file_name is None or len(sheet_name) == 0 or len(image_names) == 0: r...
27261fbdc62b1fba6084673aa4a115601d0221ad
3,609,628
import re def num_groups(aregex): """ Counts groups in regexp """ return re.compile(aregex).groups
3ce4dc9f08ec5ae2e0edfeac889c213569a3053e
3,609,629
def check_internet(url=None): """Check if internet is available""" url = "https://github.com" if url is None else url try: urlopen(url) except URLError as err: return False return True
f9f2b4aede5340725ea28d73997ad635e3d6bc19
3,609,630
import math def progress_bar_str(char_limit, max_value, current_value): """ Returns a pretty progress bar string, complete with colorization. :param int char_limit: How wide the progress bar (in characters) should be. This includes the bar and its brackets. Must be at least 6. :param int max_...
ec1fde450161645559aa6317015c353e641788cb
3,609,631
def post_profession_evidence(profession_id, body): """post_profession_evidence Post profession evidence # noqa: E501 :rtype: Response """ if connexion.request.is_json: if type(body) is not Evidence: body = Evidence.from_dict(connexion.request.get_json()) evidence = DB...
06fd3731d6cdf31a6ff4e15c00fd439a87cff043
3,609,632
def histogram_metric(p_data, p_metric): """ Histograma y estadistidicas descriptivas Parameters --------- p_data: DataFrame : datos de pymes con columna de metrica p_metric: str : nombre de la metrica Returns --------- fig : plotly figure : mapa de la zmg de jalisco Debuggin ...
e676b344391a7cfb071c4a7045437379c58235e1
3,609,633
from typing import Dict def type_updater_columns(graph: Graph, updaters: Updaters) -> Dict: """Determines the types of graph columns used by Tally updaters.""" column_dependencies = tally_columns(updaters) column_types = { col: type_graph_column(graph, col) for col in column_dependencies.v...
c0dd3db96945226e733e540515724a37103fd127
3,609,634
import os def normpath(path): """Return a normalized path in canonical form.""" return os.path.normpath(path).replace(os.sep, '/')
90980985fe8ce8e4fbca517c8663c04ac7e518d3
3,609,635
def manhattan_distance(problem_: rules.EightPuzzle) -> int: """:returns: Sum of Manhattan distances for each misplaced tile.""" rv = 0 for k, v in problem_.state.items(): if v is None: v = (problem_.height - 1, problem_.width - 1) rv += _manhattan_distance(k, v) return rv
2055e8077f516e06edcf49e3a590a5e0603d5c8d
3,609,636
def geo_x(arg: ir.GeoSpatialValue) -> ir.FloatingValue: """Return the X coordinate of `arg`, or NULL if not available. Input must be a point. Parameters ---------- arg Geometry expression Returns ------- FloatingValue X coordinate of `arg` """ op = ops.GeoX(arg...
f1b0ecdc7d90feb6328870a8ca98c649109bf98d
3,609,637
def extract_tags(signature_def, graph): """.""" output = dict() for key in signature_def: output[key] = dict() output[key]['inputs'] = extract_tensors(signature_def[key].inputs, graph) output[key]['outputs'] = extract_tensors(signature_def[key].outputs, graph) return output
0129f84d6229cf6a3d3ddd2e6a5652c87279a529
3,609,638
def otsu(gray_image): """ h:图像的宽度 w:图像的高度 (h*w 得到图像的像素数量) threshold_t :灰度阈值(我们要求的值,大于这个值的像素我们将它的灰度设置为255,小于的设置为0) n0:小于阈值的像素数量,前景 n1:大于等于阈值的像素数量,背景 n0 + n1 == h * w w0:前景像素数量占总像素数量的比例 w0 = n0 / (h * w) w1:背景像素数量占总像素数量的比例 w1 = n1...
0217bddfb58bdef9b7474379fdb09f526a88d132
3,609,639
import glob import os def get_modules(path): """ Get a dictionary containing metadata about all the Python modules found in the referenced path. :param str path: The directory in which to find modules. :return: A dictionary containing metadata about the found modules. """ result = {} ...
eca51bb9a93cb89ccf8b6b6cec9b341588b99b98
3,609,640
def load_report(report): """Splits the report from a string into a list of list of "bits" """ return [list(c for c in code) for code in report.split("\n") if len(code)]
18de97d81b174e03a760b1a051433bb23dd0fe7f
3,609,641
import math def standardized_euclidean_distance_0(x_list, data_list): """ :param x_list: [(x0, y0), (x1, y1), (x2, y2), ..., (xn-2, yn-2), (xn-1, yn-1)] data_list: [x_list_0 (same data structure as x_list), x_list_1, x_list_2, ..., x_list_n-2, x_list_n-1] :return: ...
40b71d342d4dbedd6fba2a7764555eccca0b18ea
3,609,642
import re def get_airport_details(airport_name: str = Query(..., min_length=1, description="Name of the airport you are trying to " + "find, can be its full name or just a phrase", example="Heathrow")): """ Find ...
06d302d044b3d90270139a85822f424fbb5d6435
3,609,643
def attr_visitor_name(attr_name: str) -> str: """ Returns the visitor_method name for `attr_name`, e.g.:: >>> attr_visitor_name('class') 'attr_class' """ # assert re.match(r'\w+$', node_name) return 'attr_' + attr_name
5fb31f9ea9d563ba05b4a80046c0b48ace35e9b5
3,609,644
def permutation_test_cv(X, y, n_permutations=1000, C=None, Cs=np.logspace(-7, 1, 9), seed=0, n_jobs=1, verbose=1): """Cross-validated permutation test shuffling the target Parameters ----------- X : ndarray, shape (n_samples, n_features) Data. ...
4d92095914ccdbfd765309484795f2830634fe69
3,609,645
def compile_akg_kernel_parallel(json_infos, process, waitime): """ compile kernel use multi processes Parameters: json_infos: list. list contain kernel info(task id and json str) process: int. processes num waittime: int. max time the function blocked Returns: True for ...
2d62da437ccd74d9eb9c059fdecb52729afe5a84
3,609,646
from typing import List def mk_string(strings: List[str], separator: str) -> str: """ Creates a string from a list of strings, with a separator in between elements. :param strings: the list of strings. :param separator: the separator. :return: the string of elements separated by the separator. ...
0230022eb3168c3dae92b6edb1cc0cdf252158d6
3,609,647
import json def radtherm_set_float(what, value, trace): """Set the value of a piece of floating point data from the thermostat""" try: if what != "t_heat": wg_error_print("radtherm_set_float", " Invalid 'what' argument " + what) return RADTHERM_FLOAT_ERROR pman = PoolMa...
c1a6825fb71fc8cad9975a808d7d2674809392dd
3,609,648
def subsets(x, L): """Return all subsets of length 1, 2, ..., min(l, len(x)) from x""" return chain.from_iterable([x[s:s+l+1] for s in range(len(x)-l)] for l in range(min(len(x),L)))
b0562cd3470bea94a329cf96448270785ed7a09e
3,609,649
def pic_in_db(hash_val): """ Args: hash_val(bytes obj): Hash value of uploaded pic Returns: Boolean true if pic in db, o.w. false """ if imagePost.query.filter_by(hash_val=hash_val).count() > 1: return True return False
205972218a7bceabf1577c7dc6f10e17950efe3e
3,609,650
def get_dev_risk(weight, error): """ :param weight: shape [N, 1], the importance weight for N source samples in the validation set :param error: shape [N, 1], the error value for each source sample in the validation set (typically 0 for correct classification and 1 for wrong classification) """ ...
1bb7bef768bb1e0012f8f61be3a1f7a92f5d1d00
3,609,651
import pathlib import os import sys def _parse_args(template_dir, all_services, sets, pick, dst_project, env_files): """Parses args common to 'process' and 'deploy'.""" if not template_dir: path = appdirs_path / "templates" template_dir = path if path.exists() else pathlib.Path(pathlib.os.getc...
fa6b5b5082b693c8b44c9cdaa3470d5f213bdedf
3,609,652
def unflatten_list(flat_dict, separator='_'): """ Unflattens a dictionary, first assuming no lists exist and then tries to identify lists and replaces them This is probably not very efficient and has not been tested extensively Feel free to add test cases or rewrite the logic Issues that stand o...
bbf8eb33ce47a75ab84eb1667a4e9d7dcc95ce28
3,609,653
def notes(filters=None): """Retrieve all Note objects. Args: filters (list, optional): A list of additional filters to apply to the query. """ filter_list = FilterSet(filters) filter_list.add(Filter('type', '=', 'note')) return query(filter_list)
91e663afef3fd74fe56ae1d55879a0eab81a0209
3,609,654
def Normalize(df): """ This function takes a pandas dataframe and normalize it Arguments ---------- - df: pandas dataframe Return ---------- - df: pandas dataframe The initial dataframe normalized """ df = (df - df.min())/(df.max() - df.min()) return df
b16a196ea14c93d2100d8030ef1417a7112560c7
3,609,655
import os def emp_img_exists(filepath): """ # For use if hosting static content in a remote location try: urllib.request.urlopen(STATIC_URL+filepath) return filepath except: index = filepath.rfind('/') new_filepath = filepath[:index] + '/default.jpg' return new_fil...
c72748b82d21f74864478e0b84cb6d437ec11ac0
3,609,656
def _filter_featured_downloads(lst): """Filter out the list keeping only Featured files.""" ret = [] for item in lst: if 'Featured' in item['labels']: ret.append(item) return ret
d722fdd01966f1650575912715f8a6f07d793dda
3,609,657
def shifted_conv2d(input, out_channels, kernel_size, spatial_shift, strides=(1, 1), channels_last=True, conv_fn=conv2d, name=None, scope=None, **kwar...
bfc6063b338a17202e939aca0cfff7c29b22cf5b
3,609,658
def alphabet_index(text: str) -> str: """Replaces each letter with its appropriate position in the alphabet.""" return " ".join([str(ord(x.lower())-96) for x in text if ord(x.lower())-96 >= 1 and ord(x.lower())-96 < 27])
1221477a924121f50abc79c6afc55fc09ebc88b9
3,609,659
def AddJetID(proc, jetName="", jetSrc="", jetTableName="", jetSequenceName=""): """ Setup modules to calculate PF jet ID """ isPUPPIJet = True if "Puppi" in jetName else False looseJetId = "looseJetId{}".format(jetName) setattr(proc, looseJetId, proc.looseJetId.clone( src = jetSrc, filterPa...
f19a56e3eedaa37479644b7005dca5078bb25029
3,609,660
def hds_builder( project_id, table_id, dataset_id, landing_zone_dataset, landing_zone_table_name_override, column_mapping, column_casting, new_column_udfs, surrogate_keys, ingestion_type, hds_table_config, partition_expiration, location, dag, cluster_fields=No...
53c1fc8535b151e24b6c09d18076c39b2c26a09a
3,609,661
from typing import Optional def _should_use_gp(search_space: SearchSpace, num_trials: Optional[int] = None) -> bool: """We should use only Sobol and not GPEI if: 1. there are less continuous parameters in the search space than the sum of options for the choice parameters, 2. the number of total iterat...
8c0fed84876673a0aafa3461584f57b1ab74d05f
3,609,662
def k_means_extraction(arr, height, width, palette_size): """ Extracts a color palette using KMeans. :param arr: pixel array (height, width, 3) :param height: height :param width: width :param palette_size: number of colors :return: a palette of colors sorted by frequency """ arr = n...
49e3f8c665d9806680f02b998ed711efa6bdc6d2
3,609,663
def check(rule, target, creds, *args, **kwargs): """A shortcut for policy.Enforcer.enforce() Checks authorization of a rule against the target and credentials and returns True or False. """ enforcer = get_enforcer() return enforcer.enforce(rule, target, creds, *args, **kwargs)
201d598fa46bbb16cfecce84f084b8e3ab9339c2
3,609,664
import json import sys def organize_content_by_type(archive_content): """Organize JSON content by resourceType. """ content_by_type = { } for item in archive_content: if PACKAGE_REGEX.match(item['name']): # parse JSON to get resourceType parsed_json = json.loads(item['...
2dfdd43a2776dcae5e091495cb9944fa5e1fa22a
3,609,665
def logout(): """ Logout current user from session """ # remove user from session session.pop("user_id", None) flash("Logged Out", "success") return redirect(url_for("index"))
777d16b9f1e049d896950dd0703268df4f2ab1f0
3,609,666
import os def find_ammr_path(folder=None): """Return the root AMMR path if possible . The function will walk up a directory tree looking for a ammr_verion.any file to parse. """ folder = folder or os.getcwd() version_files = ("AMMR.version.any", "AMMR.version.xml") for basedir, _, files i...
da72eb4f6c33d8e9e52977cd0cd9c128dcc1ea73
3,609,667
def print_snd(expr): """ Arguments: - `expr`: """ return color.cyan + "snd" + color.reset + "({0!s})".format(expr.expr)
e0de5ce197848087d5e64e169d766f949868140f
3,609,668
def metadef_namespace_get_by_id(context, namespace_id): """Get a namespace object""" try: namespace = next(namespace for namespace in DATA['metadef_namespaces'] if namespace['id'] == namespace_id) except StopIteration: msg = (_("Metadata definition namespace not foun...
a101c9c1cc1fcb766263eff12bde8fbae2817837
3,609,669
def detect_edge(image_array, sigma=1.0, low_threshold=None, high_threshold=None): """ Detect the edges in an image using the Canny filter Parameters ---------- image_array Returns ------- array with edges identified Side Effects ------------ None """ ...
8b488bb768e4a081d9dcf64df7f3e31beb702ad3
3,609,670
def remove_duplicate(id_list, class_target_id, return_type, check): """ Check duplication in class member and return a new user id list that is not duplicate in class. This function mainly use in add_member_to_class function. :param id_list: A user id list as a string. :type id_list: str :para...
2c420d705ecb52fa0e89f0fc6820069b5d9773cd
3,609,671
from typing import Optional def wait_selector( gen: PQGen[RV], fileno: int, timeout: Optional[float] = None ) -> RV: """ Wait for a generator using the best strategy available. :param gen: a generator performing database operations and yielding `Ready` values when it would block. :param f...
71d43e4a16f23b9538d2d89840c5bc12a3d387cc
3,609,672
def field_has_type(needle: BaseType, field: BaseType) -> bool: # pylint: disable=too-many-return-statements, too-many-branches """ Return True if field haystack contains a field of type needle. :param needle: A schematics field class to search for. :param haystack: An instance of a schematics field wi...
fca952bf63f4b42b8ee8f823afbf248b8098845c
3,609,673
def get_max_batch_size(model, tile_size, device, classes): """get max possible batch_size based on GPU memory This function calculates the maximum possible batch size based on the available GPU memory. Args: model (pytorch model): model to train tile_size (int): size of the input image...
a5b76b9dc180223d8c4248c1bec35d30b85da9f3
3,609,674
import os def abspath(path): """convert relative path to absolute path""" try: path=pathexists(path) curpath = os.getcwd() changedir(path) path = os.getcwd() + '/' changedir(curpath) except: raise SaltIOError('Could not determine absolute path to '+path) ...
f0c72806bd708ba3f98943b2faf9b734cf2dd71a
3,609,675
def authorize(func): """ User needs to be logged in """ @wraps(func) def wrapper(*args, **kwargs): if app.current_user is not None: return func(*args, **kwargs) app.flash('Login to view this page') redirect('/login?back=' + request.path) return wrapper
500787de037775de68f042c777cdd33375335a47
3,609,676
def handle_no_range(node): """Returns stl_node with range set to [0,0] if not previously set""" if node.range_start==None or node.range_end==None: node.range_start = 0 node.range_end = 0 return node
1baad2869cf769d6caac73e52d2799d04b1fc16d
3,609,677
def PageRankResponseStartValuesVector(builder, numElems): """This method is deprecated. Please switch to Start.""" return StartValuesVector(builder, numElems)
b54e7659266c9c3802e9f3621758e1099aa19c92
3,609,678
def normdiff(p, q) -> float: """ Alias to the 2-norm of a difference between two vectors Parameters ---------- p : iterable q : iterable Returns ------- float Norm discrepancy. """ return np.linalg.norm(p - q)
de279fd51528781d7cf0fe339e87b9594626defb
3,609,679
def build_frequency_case(mt): """ Bin frequencies. Output refers to bin floor :param MatrixTable mt: Input MatrixTable with .freq annotation :return: Binned frequencies :rtype: FloatExpression """ return (hl.case() .when(mt.freq[0].AF >= 0.2, 0.2) .when(mt.freq[0].AF...
cd07427c4cadceb2d7a959b7e47ffd4724d59a0a
3,609,680
import logging def transform_architecture(model, pretrained_model_file=None): """Transform architecture.""" if not hasattr(model, "_arch_params") or not model._arch_params or \ PipeStepConfig.pipe_step.get("type") == "TrainPipeStep": return model model._apply_names() logging.info("...
997020421fca590db8cfee9cc9844104f203cfd7
3,609,681
def merge_kwargs(kwargs, defaults): """Helper function to merge ``kwargs`` into ``defaults``. Args: kwargs: Keyword arguments. defaults: Default keyword arguments. Returns: Merged keyword arguments (``kwargs`` overrides ``defaults``). """ if defaults is not None: kw...
09a887bbcefdd2e0795fee043354d4bdf8e806a8
3,609,682
def f84a(): """Return a unit-distance embedding of the F84A graph - not degenerate despite its looks. The graph is notable in having the simple PSL(2,8) as its automorphism group.""" t0 = findroot(lambda *t: f84a_vertices(*t)[1], (-0.46, -1.44, 0.25, 0.75)) return all_unit_distances(f84a_vertices(*t...
1799a079dbc403ec076665658904b0a9c3c7fd07
3,609,683
def plot_metrics(couplings, cost_func, cost_func_name, epsilons, log = False, points=False, scale=1.0, label_font_size=18, tick_font_size=12): """ Plots cost_func evaluated as a function of epsilon """ zero_offset = epsilons[0]/2 all_ys = [] if "lineageOT" in couplings.keys(): ys = np.ar...
50acb7a5faf58b37a0a45d553a4be9cce5852996
3,609,684
import functools def translateUpdate(q, base=None, initNs=None): """ Returns a list of SPARQL Update Algebra expressions """ res = [] prologue = None if not q.request: return res for p, u in zip(q.prologue, q.request): prologue = translatePrologue(p, base, initNs, prologue...
313acac54ea8409656282a0be97436a2e4daa8b8
3,609,685
def format_decimal(value): """Format value to 2 decimal places""" formatter = "{0:.2f}" return float(formatter.format(value))
694efd34d7e36d493a66ef25ab5a552f93eac087
3,609,686
import os def substitute(s, mapping): """Substitute values from *mapping* into *s*. *mapping* can be a :class:`dict` or any type that supports the ``get()`` method of the mapping protocol. Replacement values are copied into the result without further interpretation. Raises :exc:`~.SubstitutionSyn...
ec47b4102e5374b79f284a2b2f3e5c93c30132da
3,609,687
import re def rename_pretrained(name: str): """ Matches the name of a variable saved in the pre-trained MobileNet networks with the name of the corresponding variable in this network. https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet_v1.md Parameters ---------- na...
6913159aef0d9b4019af34dcd72984d3dd6870e9
3,609,688
def do_ldap_search(conn, query): """ Search Yale LDAP for a particular netid. On the command line this would be something like the following: ldapsearch \ -H ldaps://ad.its.yale.edu:3269 \ -D cn=s_klj39,OU=Non-Netids,OU=Users-OU,dc=yu,dc=yale,dc=edu \ -w $LDAP_PAS...
183d126b3dda117a42d1a8a93a5a90fbd752eb92
3,609,689
def BrokerFeaturesAddEventHistory(builder, eventHistory): """This method is deprecated. Please switch to AddEventHistory.""" return AddEventHistory(builder, eventHistory)
57e3729762f079af9c32dd28f71bee455cf9bce0
3,609,690
def _forwarder(func): """Returns a function that applies func to all given images.""" def fwd(*images): _apply_images(func, images) fwd.__doc__ = "Forward to Canvas." + func.__doc__ return fwd
7e24c394ce273f38a2e6175bc24f8702b17df3eb
3,609,691
import copy def clip_norm(g, c, n): """Clip the gradient `g` if the L2 norm `n` exceeds `c`. # Arguments g: Tensor, the gradient tensor c: float >= 0. Gradients will be clipped when their L2 norm exceeds this value. n: Tensor, actual norm of `g`. # Returns Ten...
05204e2a06f18da71be44aa15ddabeafed794e9a
3,609,692
def update_action(body): """ Updates an action :param body: Updated action instance :type body: list | bytes :rtype: None """ if connexion.request.is_json: body = [Action.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!'
c73cac1bcc973ceaf9555e7ddf87acca19225ad9
3,609,693
def anagram(word1, word2): """Determines if two words are anagram of each other NOTE: This solutoin does not work for all test cases. """ # if the strings are not equal length they can't be anagram if len(word1) != len(word2): return False s1 = 0 s2 = 0 # add up the ascii valu...
d90d58723986da8fdab4c01433d074cb2f0151b2
3,609,694
def build_table_def(table_name, keys, additional_attributes=None, global_secondary_indices=None): """ Creates a minimal dynamodb definition suitable for use with localstack. Args: table_name: The full name of the test table keys: The key definitions to use - a list of 4-tuples (<name>, <key...
84b124ac0a084f05685ed4e636fb8eda78317c07
3,609,695
import logging async def delete_config(key: str, type: str, response: Response, id: str = ""): """Delete a config from the database Attributes: key (str): key to be deleted type (str): global/package/node id (str): package or node id as per type response (Response): Starlette...
8c04f65d3fa39a88d3487242ac09ba95bbb018c1
3,609,696
import fsspec def scan_grib(url, common_vars, storage_options, inline_threashold=100, skip=0, filter={}): """ Generate references for a GRIB2 file Parameters ---------- url: str File location common_vars: list[str] Names of variables that are common to multiple measurable (i....
839d7fe3ba3fb36872f530408d4eef0d5f173230
3,609,697
def reauth(): """ Reauthenticates a user """ if not login_fresh(): form = ReauthForm(request.form) if form.validate_on_submit(): confirm_login() flash(("Reauthenticated"), "success") return redirect(request.args.get("next") or ...
7fdf19ddb0e9c076f3c7fa82dae400defd5e6c0a
3,609,698
def execution_has_failures(playbook_results): """Return value 2 means failure in ansible-playbook""" if type(playbook_results) != list: playbook_results = [playbook_results] return 2 in playbook_results
1c8ea2767a78ca72147f65f3ca5fa90018f8c141
3,609,699