content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def integrate(n=1.0): """ integrate the Lane Emden equations, and return the solution as a dictionary """ if n > 4.99: raise SystemExit('Error: integrate: choose n < 4.99.') list_xi = [] list_theta = [] list_d_theta = [] # Initial Conditions xi = 1e-6 theta = 1.0 d...
1fd8349ccc3a758dd2d107e939207dfb2d9ea424
47,715
def purge_all_unused(): """Remove all unused data blocks.""" counter = 0 # keep this order. # as the lower things are contained in the higher ones.. counter += purge_block(bpy.data.objects) counter += purge_block(bpy.data.meshes) counter += purge_block(bpy.data.materials) counter += purg...
8f77142f5d89a3a934dec3d01423ac942b62c914
47,716
from openmmtools.multistate import MultiStateReporter, MultiStateSamplerAnalyzer from perses.analysis.utils import open_netcdf def analyze_repex(nc_file_path): """ Analyze RepEx simulation and return the free energy over time and the final free energy. """ reporter = MultiStateReporter(nc_file_path) nc_f...
28ada066c51498297d1d48cdf6b3ff649ecec7f5
47,717
import urllib def get_url_params(url, encoding="utf-8"): """ get the main_part and query_part from a url """ frags = urllib.parse.urlparse(url, allow_fragments=True) components = (frags.scheme, frags.netloc, frags.path, frags.params, "", "") return urllib.parse.urlunparse(components), urllib.p...
0a4bf8848e7ec2588070477c81e8a1b8c7ad695e
47,718
def get_direction_values() -> []: """ Returns all payment directions as enum """ return [DIRECTION_IN, DIRECTION_OUT, DIRECTION_TRANSFER]
89be5df7089b32936442c19062923b318c9e956d
47,719
from typing import Tuple import torch import multiprocessing def run_simulations_on_all_cores( agent: agent_base.Agent, env_name: str, batch_size: int ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ Run multiple simulations using the same agent on multiple cores to obtaine actions, observati...
7ae6e587843b2fe707c28967a0531638dfaf2b61
47,720
def expected_svg(image: str) -> str: """Calculate expected SVG.""" return Scour().scour_string(image)
bf8355a8e65c8dbc60279c745135d2156ac15f40
47,721
def get_valid_ip_address(ls): """ Question 7.10: Compute all valid IP addresses from decimal string, given that """ ips = [] # loop over first ip packet first_idx = 1 while first_idx < 4 and first_idx < len(ls): second_idx = 1 while second_idx < 4 and \ fi...
eb8b8fc574f489ab260c1a854c4fb1302ca170f8
47,723
def lemma_details_internal(request): """ Render word-detail.html for a lemma. `index` view function renders a whole page that contains word-detail.html too. This function, however, is used by javascript to dynamically replace the paradigm with the ones of different sizes. `lemma-id` and `paradigm-size`...
72b925e3814c69573d83cf597c634b27ab3f4309
47,724
from typing import Dict from typing import Tuple from typing import Any def _pack_single_bin( rect_dict: Dict[int, Tuple[Number, Number]], aspect_ratio: Tuple[Number, Number], max_size: Tuple[float, float], sort_by_area: bool, density: float, precision: float, ) -> Tuple[Dict[int, Tuple[Number...
024709ebebc4e5d13ce6d26c8a80dbc6e96d0d59
47,725
def device_list(): """Return a list of devices.""" return IMPL.device_list()
f6f461ee4c8897bad46099903ec0aa7973fc3996
47,726
from io import StringIO def analyze(source_code): """ Trace the source code for display in the browser. :param source_code: Source code to trace. :return: (tracing_report, output) """ tracer = TraceRunner() tracer.standard_files.old_files['stderr'] = StringIO() tracer.max_width = 200000 ...
c2d0e61bf5403d9fefccedd05a5c4e505375404b
47,728
def _padding_for_dimension(data, axis, pad_value): """Tile `pad_value` so it can be used to pad `data` at the given axis. Returns a tensor `result` that has the same shape as `data` up to dimension `axis`, but where each value `data[i0...iaxis]` is replaced by `pad_value`. I.e., returns `result[i0...iaxis, j0....
d99c7afb4218bf7e78bef9d3adc2b62dfb5d6790
47,729
def is_error_status(status): """Function that determines whether the RPC status is an error. Args: status: Initialized RpcStatus message to check for errors. """ status.check_initialized() return RpcError.from_state(status.state) is not None
4b2f427eaea201e5abe4239d246b16632b932a12
47,730
import typing def getOption(key: str) -> typing.Union[str, bool, None]: """Get the value of a CLI solution option. If not defined, will return `None`.""" return _solutionOptions.get(key, None)
3debc54bb57f11d465cfbedf0df711724ef25f48
47,731
def primes(upto): """ Prime sieve below an <upto> value. Copied from http://rebrained.com/?p=458 Parameters ---------- upto : int Find all primes leq this limit. """ primes = np.arange(3, upto+1, 2) isprime = np.ones((upto-1)/2, dtype=bool) for factor in primes[:int(np...
bf20e031af9d087614391a4de101bea466d4fb0d
47,732
import copy def _filter_heads(heads, heads_height, radius, polygon): """Filter the head candidates following Kienholz et al. (2014), Ch. 4.1.2 Parameters ---------- heads : list of shapely.geometry.Point instances The heads to filter out (in raster coordinates). heads_height : list ...
41b310f521b08d6b882d8906dc75a3460f266946
47,733
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
ee8757a69d7240316265475f98a3137eea872ec2
47,734
def program_name(output_str): """ Reads the program name from the output file string. :param output_str: string of the program's output file :type output_str: str :rtype: str """ prog_string = _get_prog_string(output_str) prog_name = prog_string.split(':')[1].strip() prog_n...
281714b432f2579697b22dd0116f75bbc59cc457
47,735
def delistify(a, b=None): """ If a single element list, extract the element as an object, otherwise leave as it is. Examples -------- >>> delistify('string') 'string' >>> delistify(['string']) 'string' >>> delistify(['string', 'other']) ['string', 'other'] >>> delisti...
61053bd9b37aff70d0e1892a6051c68a53f67d97
47,736
def upload_parts( mcg_obj, awscli_pod, bucketname, object_key, body_path, upload_id, uploaded_parts ): """ Uploads individual parts to a bucket Args: mcg_obj (obj): An MCG object containing the MCG S3 connection credentials awscli_pod (pod): A pod running the AWSCLI tools bucket...
5b3bc840fea74506afe5849bdf2d1a081adcbdc4
47,737
from typing import List def get_available_datasets(m1: str, m2: str) -> List[str]: """Calculate what datasets are available between m1 and m2 Args: m1 (str): Name (or path) to pretrained HF model 1 m2 (str): Name (or path) to pretrained HF model 2 Returns: List[str]: List of all ...
f52df0aeffaf3c7691b9e0ed62ae604347ced3aa
47,738
import torch def histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor: """Helper function to make torch.histc work with other than fp32/64. The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What this function does, is cast inpu...
086081405a9a60322d09cb737d9827c3eb720de0
47,740
def getkwpars(camera,parname): """Extract the correct row of the parameter file based on the value of CAMERA. Parameters are returned as a keyword:value dictionary.""" d={} f=pyfits.open(parname) t=f[1].data cols=f[1].columns # Pick out the matching row of the "camera" column. cams ...
994e992e1afaf178cd8aa80cf6d5e9a2e01bb21c
47,741
def get_routes(): """ Get a list of routes for this agency. NOT USED. RESERVE. :return: """ # First get the list of routes route_list_xml = get_nextbus_request(command='routeList', a=NEXTBUS_AGENCY) route_list_dom = parseString(route_list_xml) routes = [] # Collect here the routes ...
bf4cf8eb50011b8ae452f86017261d6e04d7b54e
47,742
import requests from bs4 import BeautifulSoup def get_new_drugs(month=7,year=2017): """Returns a list of all new drug ids or urls.""" drugs = [] query_url=FDA_URL+FDA_QRY_URL+FDA_MONTH+str(month)+FDA_YEAR+str(year) req = requests.get(query_url) print( req.status_code) soup = BeautifulSoup(req....
775690adadfaa5ffc5141f6e29e506e632743805
47,743
from re import T import re def jwt_token(value: str) -> T.Union[T.Match[str], None]: """ JWT Token Validator Detail: https://en.wikipedia.org/wiki/JSON_Web_Token """ _jwt_pat = r'^[\w\d\-\_\=]+\.[\w\d\-\_\=]+\.?[\w\d\-\_\.\+\/\=]*$' return re.fullmatch(_jwt_pat, value)
60158b572cedf8c3dcf4da4f3cac27b156a89015
47,745
def paginate(parser, token, paginator_class=None): """Paginate objects. Usage: .. code-block:: html+django {% paginate entries %} After this call, the *entries* variable in the template context is replaced by only the entries of the current page. You can also keep your *entries* ori...
f511dc445a41146425fa49ef4495162167466a4a
47,746
def autocorrelation(x, lag): """Credit goes to https://github.com/blue-yonder/tsfresh""" if type(x) is pd.Series: x = x.values if len(x) < lag: return np.nan # Slice the relevant subseries based on the lag y1 = x[:(len(x) - lag)] y2 = x[lag:] # Subtract the mean of the wh...
f69ab3685d57e105313054e33ed8c5c67560c3fc
47,747
from fsleyes.views.lightboxpanel import LightBoxPanel def run_with_lightboxpanel(func, *args, **kwargs): """Create a ``FSLeyesFrame`` with a ``LightBoxPanel`` and run the given function. """ return run_with_viewpanel(func, LightBoxPanel, *args, **kwargs)
704b94f3a61237eb356e39ca858e47cabc07b907
47,748
import requests def auth_callback(): """ Callback route for after authorization. parameters: - name: code in: args type: string required: true description: Authorization code sent by OAuth Server - name: state in: args type: string r...
9748f6a87fa0522a781c551cb5d39f0c356938ae
47,749
def convert_specification_to_graph(formula): """Converts a specification formula to a specification graph.""" given_clause, when_clause, then_clause = get_fundamental_clauses(formula) when_property = convert_clause_to_graph(when_clause) then_property = convert_clause_to_graph(then_clause) final_pr...
5b3f5ba4a8dc7cf90e7438213223ea888820b4c1
47,750
def get_sens_spec(y_true, y_pred): """ Args: y_true: list of binary ground-truth labels y_pred: list of binary predictions Returns: sensitivity: True Positive Rate = Sensitivity specificity: True Negative Rate = Specificity (TNR = 1-FPR) """ stat_table = sensitivity_s...
3279caecfeb2a795719b0fabd0f465d2efe16967
47,751
def shape(context): """Returns a new, independent geometry with coordinates *copied* from the context. """ if hasattr(context, "__geo_interface__"): ob = context.__geo_interface__ else: ob = context geom_type = ob.get("type").lower() if 'coordinates' in ob and _is_coordinates...
d120ca2455ab19cbd426407255da7182dd420d43
47,752
import csv def process_csv(csv_path, image='image_id_', stage='image_stage_', fake='image_fake_', answer='image_answer_'): """ Process a csv file to a list of Result objects :param csv_path: :param image: :param stage: :param fake: :param answer: :return: """ results = [] w...
f363521cac13e80d92b9398e284ed6c9b7cf3e54
47,753
from typing import OrderedDict import itertools def extract_colorpalette(palette_name: str, n: int=None, mode: str='hex'): """ Convert color palette to color ramp list. palette_name {str} name of color palette n {int} size of color ramp. If None, automatically return the maximum number of colors in t...
c0365ee4f20cdd7c0498317b9d54469f5c655248
47,754
def max_wave_speed(u): """Returns the maximum wave speed for the Euler system""" # Primitive variables rho = u[0, 0::3] v = u[0, 1::3] / rho E = u[0, 2::3] p = (constants.gamma - 1) * (E - 0.5 * rho * v * v) # Get the wave speed wave_speed = np.fabs(v) + np.sqrt(constants.gamma * p / r...
4026af0bf620941cffd51e16773656f6469674b2
47,755
def detect_face(frame): """ detect human faces in image using haar-cascade Args: frame: Returns: coordinates of detected faces """ faces = face_cascade.detectMultiScale(frame, 1.1, 2, 0, (20, 20)) return faces
3b4162491580013d94d826583d138175cbfb14dc
47,756
def read_aq(filename, UTC=False): """read in a corrected record that has been exported from Aquarius springboard""" #filename = r'NO3+NO2,water,insitu_as_N.mg_l.(purged,_ex_situ_SUNA2)@364200119420001.EntireRecord (1).csv' #skiprows=15 #UTC=False meta_data = read_aq_metadata(filename) skipro...
8fe6acdc2d83c8adb2c569e29fa7a0831b5f018d
47,757
def create_plan( self, plan_name: str, plan_trial_days: int, plan_length: int, plan_type: str, main_currency_code: str = 'USD', initial_price_usd: float = None, initial_price_gbp: float = None, initial_price_eur: float = None, recurring_price_usd: float = None, recurring_pric...
555a1e2e6d0cd4baa61d4b97aa66c814e2df6d2a
47,758
from typing import Optional def make(target: str = "all", rules: dict = rules) -> Optional[File]: """ Make a target (file) using a series of rules. """ rule = rules.get(target) if not rule: # No rule. See if target already exists. file = File(target) if not file.exists(): ...
e6bd9927c469d1717a331daebf0d2103309b8509
47,759
def _make_datasets(tfds_datasetname: str, vocab: seqio.vocabularies.Vocabulary, batch_size: int, sequence_length: int, has_test: bool = True) -> base.Datasets: """Make Datasets object from tokenized tfds dataset.""" if has_test: splits ...
500276122c913d98daf7483f1d5c2255bc050b95
47,760
def fftconvolve2d(inData, inKernel): """ Parameters ---------- inData: array_like Image to be convolved. inKernel: array_like Convolution kernel. Odd size preferred. Returns ------- outData: array_like Convolved image. """ # Input sizes y1, x1 = inD...
84b2c4320fb99783bbbf309626ab1a5bed6747d4
47,761
def unsorted_segment_sum(tensor, segment_ids, num_segments): """Custom PyTorch op to replicate TensorFlow's `unsorted_segment_sum`.""" result_shape = (num_segments, tensor.size(1)) result = tensor.new_full(result_shape, 0) # Init empty result tensor. segment_ids = segment_ids.unsqueeze(-1).expand(-1, t...
44740eeb5cc202646c28c39cd65ce727f10bb2da
47,763
def predict_dataframe(df, model_class, hyperspectral_pool, site_label_dict, domain_label_dict, HSI_size=20, k_neighbors=5): """Iterate through a geopandas dataframe and get neighbors for each tree. Args: df: a geopandas dataframe model_class: A deeptreeattention model class to extract layer features ...
eb9bf4dbc841c3263b9c509eee71391aebd61257
47,764
def extract_trades_of_period(dataframe: pd.DataFrame, trades: pd.DataFrame, date_index=False) -> pd.DataFrame: """ Compare trades and backtested pair DataFrames to get trades performed on backtested period :return: the DataFrame of a trades of period """ if date_index: ...
63726301b2f53a46167976c8656ecd6024ad61e7
47,765
import io import PIL def chunks(png): """Yield ``(chunk_type, chunk_raw_data)`` from ``png``. .. note:: ``chunk_raw_data`` includes chunk length, type, and CRC. :arg png: If ``png`` is a :any:`path-like object` or :any:`file-like object` object, read the content into bytes. :type png: path-like, file-li...
cb79306217663a1908d6dce0bc3591b38676c071
47,766
def get_device_tracking_counters_vlan_message_type(device, vlanid, message_type="received"): """ Get device_tracking vlan count message type Args: device ('obj'): device object vlanid ('str'): vlan message_type ('str', optional): message type. Defaults to "received" ...
3de23dbb76cefd84cdb71f9e62934a3dcc452d9c
47,767
import fnmatch def match(name: str, expression: str) -> bool: """Test whether NAME matches EXPRESSION. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char ...
62a56bbb33f73519c80b9319211f8f55543aef85
47,768
from typing import Dict from pathlib import Path import shutil import re def fixup_attachment_references(tree: Node, attachments: Dict[Path, AttachmentInfo], source_root_dir: Path, target_root_dir: Path): """ The export from Confluence results in attachments identified by page_...
2c208edef86d5a301bfa20aa7889107dd97c5e3a
47,769
def before_request(): """ CORS preflight, required for off-server access """ def _build_cors_prelight_response(): response = make_response() response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "*") response.headers.add("A...
4a08fba97383b800d0ec303fb4abd97d21e1e2ed
47,770
import scipy def waa_leijnse_2008_from_A_obs( A_obs, f_Hz, L_km, T_K=293.0, gamma=2.06e-5, delta=0.24, n_antenna=np.complex(1.73, 0.014), l_antenna=0.001, ): """Calculate wet antenna attenuation according to Leijnse et al. 2008 Calculate the wet antenna attenuation from observ...
23f4c902a424c309ffc3fd41365a20cdaadffce2
47,771
def find_brackets(text: str) -> tuple: """ Find position of angled brackets in a string and return as a tuple (start, end) ISSUES: - Will return a value for "<adjective noun>" which isn't what we want (Maybe can resolve this by checking returned str matches certain values - done...
8f61563118fb5f205d0e77ffb38f11e2703be6bf
47,772
import torch import datasets def fake(): """ Fake Dataset by torchvision Returns: ImageDataset """ target_transform = transforms.Compose([ transforms.Lambda(lambda x: torch.LongTensor([x])), transforms.Lambda(lambda x: F.one_hot(x, num_classes=10).float()), ]) tr...
53525a2e2155671ec4fd3d5ff82817cd785b449e
47,773
def find_e0(energy, mu=None, group=None, _larch=None): """calculate E0 given mu(energy) This finds the point with maximum derivative with some checks to avoid spurious glitches. Arguments ---------- energy: array of x-ray energies, in eV or group mu: array of mu(E) group: outpu...
c905a4f3da8f697d09c21f7934b23ae7179a94e7
47,774
def move_odict_item(odict, key, newpos): """ References: http://stackoverflow.com/questions/22663966/changing-order-of-ordered-dictionary-in-python CommandLine: python -m utool.util_dict --exec-move_odict_item Example: >>> # ENABLE_DOCTEST >>> from utool.util_dict impor...
2bf86d8a5da8b474b8d487a0247424cb360c0d35
47,775
def document_search_keys(): """A list of Regulations.gov document search keys.""" return ['documents', 'totalNumRecords']
c0969bde192a249c087590332d5deeff19ee06eb
47,776
from datetime import datetime def sleep_timer(enable=None, period=1800, **kwargs): """ Setup sleep timer to schedule power off upon inactivity. NOTE: Do not access pillar data in this function as they will not be available when called from engines (separate processes). Optional arguments: - en...
48f366b7217e156a222770702e38a23b2058de46
47,777
def eqn23_rule(model,g,tm): """ Ensures that once you begin to use H2, you cannot transition backwards to old technologies. """ if tm > 1: return model.hydrogen_use[g,tm] >= model.hydrogen_use[g,tm-1] else: return Constraint.NoConstraint
da4b9ecd3afced23ea3c29372d96d457d5881b5e
47,779
import re def readjMRUItxt(filename): """ Read .txt format file Parameters ---------- filename : string Name of jmrui .txt file Returns ------- array-like Complex data dict Header information """ signalRe = re.compile(r'Signal (\d{1,}) out of (\d{1...
0c6fc4123d81b4116aa90e6f65f0c7d91454b2f9
47,782
def call_hooks(event, entry): """ Rerun pre or post hooks """ hook = event + "-command" if entry.config["holland:backup"][hook] is not None: cmd = entry.config["holland:backup"][hook] try: cmd = Template(cmd).safe_substitute( hook=hook, backupset=entry.ba...
095d5ab2f676d68e3ed7818ae2c54e5c9bae3c40
47,783
def make_envs(env_id, log_dir, gamma, max_train_ep_length, max_eval_ep_length, seed): """Make training and evaluation environments (vectorized envs).""" # Training env train_env = gym.make(env_id) train_env.seed(seed) # Set random seed train_env = TimeLimitW...
7c0b7347ee64ec2712a0d72110190f2aab20a31b
47,784
def list_or_caseless_string(value): """ Converts the value into a list of ``caseless_string``'s. If the value is not iterable a one-element list with stringified value will be returned. """ if isinstance(value, basestring): return [caseless_string(value)] else: try: ...
2052e551a07aae23948ab1286a153d863fcdb9a5
47,785
from operator import xor def keyinplaintext(ciphertext, keylen, keyindex, seed, seedindex, decfunc=xor, keyfunc=None): """Solves the case when the key used to encrypt is embedded in the plaintext itself. This function assumes a polyalphabetic substition cipher is used. Arguments: ciphertext -- t...
4a9aaac70c297fae4105106b379085c4cb49fd96
47,787
def LBGI_HBGI(df): """ Connecter function to calculate rh and rl, used for ADRR function Args: (pd.DataFrame): dataframe of data with DateTime, Time and Glucose columns Returns: LBGI (float): Low blood glucose index HBGI (float): High blood glucose index ...
361b9a33286c9beb1b72024ee459fdc01f007a4f
47,788
import pandas as pd def describe(col, data): """ return basic statistical descriptions """ d = {} # number of observations d['Nobs'] = [data[col].count()] # mean d['Mean'] = [data[col].mean()] # std d['Std.'] = [data[col].std()] # mad d['Mad'] = [data[col].mad()] # ...
300310365fe67a5b76747474c77d0a674299fe49
47,790
import nose def nose_command(verbose=True, detailed=True, cover=None): """Returns the NoseTest TestCommand runner. You can use this directly if you want, or pass any of these kwargs to test_command instead, while also passing nose=True. KWArgs: verbose: print verbose test output deta...
1b3885b427d593217c12a83694fdff0221ffd104
47,791
def dealt_damage( attacker: Pokemon, defender: Pokemon, attack_type: str, attack_power: float, attack_modifier: float = 1, defense_modifier: float = 1, global_modifier: float = 1, ) -> float: """ Calculates the damage dealt by a pokemon to another one. Args: attacker (Po...
dd91b9e1b1a7b1ba4b2f9e28785ab0b8fea24cdb
47,792
def last_breakout_failed(mode, historical_data, num_days_entry=55, num_days_exit=20): """ Returns a Boolean result indicating whether the last breakout cycle before the specified date, if acted upon, would have led to a loss. Ar...
8075fb9457d63f33845973a38de249b326622d05
47,793
import yaml def timing_report(file_path): """Check whether `file_path` is a valid YAML timing report file @param file_path @return ``True`` if valid, ``False`` otherwise @throw IOError if `file_path` cannot be opened for reading @throw YAMLError if `file_path` cannot be parsed as a YAML file ...
b0a4641581dc1f68ef5264bddd29ace167c39042
47,794
def _resample(resampling_way, ts_list, resampling_period, adding_method=AddingMethod.LINEAR_INTERPOLATION, timestamp_position=TimestampPosition.BEG, aggregation_method=AggregationMethod.AVG, nb_points_by_chunk=50000, gener...
5bbeb832401977e7310f94a7462fefdf700cff92
47,795
def send_roll(team, roll, args): """Post the roll to Slack.""" chat = Chat(team.get_bot_token()) try: # Attempt to post message chat.post_message( args['channel_id'], roll, username='Roll Bot', icon_emoji=':game_die:' ) except Err...
3d7b41eb9056d68f10b9bf342ea31634f71cea5d
47,796
def get_intervals(x): """ From an unsorted and possibly sparse collection of 1D coordinates, compute the number of bins and the distance between bin centres. Default is nearest-metre precision, which should be fine for most seismic surveys. """ # Preliminaries. x = np.asanyarray...
5de65241c0a2a1d0e508927c3dc3cacceef243a9
47,797
def cmt_final_digest(parent_digest: str, spec_digest: str, refs_digest: str) -> str: """Determine digest of commit based on digests of its parent, specs, and refs. Parameters ---------- parent_digest : str digest of the parent value spec_digest : str digest of the user spec value ...
a77a3cfcc85d9798720af1cda79b06ca2185e1f2
47,798
def get_mouse_loc(): """ Get the x,y location of the mouse """ pos = pygame.mouse.get_pos() return pos[0], pos[1]
c427ba118a31461b3b70a628698837505d899359
47,799
def b85encode(octet_string): """Encode a octet_string using 85 characters. Compliant with RFC1924 Intended originally for only 128 bit IPv6 addresses Longer or shorter strings will work. """ return base_N_encode(octet_string, _b85chars )
17533ca3c91b26c8521a8fb4194b3048d4c93bfc
47,800
def computeIoUs(preds, truths): """ Compute intersection over union for the predicted masks vs ground-truth masks. @preds and @truths must have the same length and both are iterables of numpy matrices of same dimensions. """ # List to collect IoU for each pair IoUs = [] # Iterate over the collections and comput...
208606710c07878bccf8cae0f3b95ce65cb4180a
47,801
def gamma_prior(mode,std): """ In general you should prefer the log_normal prior. """ a = std/mode#sqrt(k)/(k-1) shape = (2* a**2 + np.sqrt((4 * a**2 + 1)/a**4) * a**2 + 1)/(2 *a**2) scale = std/np.sqrt(shape) return gp.priors.Gamma(shape,scale)
6aaac79facbd5da60349c44b65d42df724c3bdd9
47,802
def test_no_global_imports_of_banned_package(): """This test ensures that neither of the banned packages are imported module wise in any of our code files. If one of the dependencies is needed, they should be imported within a function.""" banned_packages = ["spacy", "mitie", "sklearn", "duckling"] ...
154870ebaff7df266d65d1be805929627c3d675c
47,803
def remove_host(mac, *args, **kwargs): """ Delete a host from the system Variables: mac => MAC Address of the host to be deleted Arguments: None Data Block: None Result example: {"success": True} """ STORAGE.delete_node(mac) return make_api_...
2308b7bc3496eee7cfda31c6e468fd33af60bff6
47,806
def get_ordered_tests(tests_setup, test_type): """Determines the order of tests to be run, filtered to only return the specified type. Args: tests_setup (dict): Map of test name to its configuration (see: res/test/translator.json). test_type (str): Which apps are to be tested. Must be one of "c...
fa5f04ea46d1385ac3f174c2f9733d68b7d97ecf
47,807
import re import random def flip(message, txt): """ <text> -- Flips <text> over. :param message: Slackbot message object :param txt: Text to flip :return: Message to slack channel """ global table_status chan = message._body['channel'] text = txt.strip() if re.match(re_table, ...
39c2ea731a74b64e5a08870ba73d7b16f0c33801
47,808
def ilr(X: np.ndarray): """ Isometric Log Ratio transformation. Parameters --------------- X : :class:`numpy.ndarray` Array on which to perform the transformation, of shape :code:`(N, D)`. Returns -------- :class:`numpy.ndarray` ILR-transformed array, of shape :code:`(N...
988e1591ff996e12067d188ebe2c137c45238535
47,810
def _stub_create_regularizer(op_slice, model_stub): """Create a StubOpRegularizer for a given OpSlice. Args: op_slice: A op_regularizer_manager.OpSlice. model_stub: Module name where REG_STUB and ALIVE_STUB will be found. Returns: StubOpRegularizer with stubbed regularization and alive vectors. ""...
34db10bbf19cafcd0f052391dadd71b450215ba5
47,811
def standard_method(row, iters): """ Given a tape represented as a row of Booleans, compute (in-place) the next row according to the Rule 110 ruleset. Assume that the tape wraps around to form a cylinder, i.e. for a tape of length `n`, column 0 is adjacent to column 1 and column n-1. Inputs: ...
015aef5bc6b1c757163917a43669d57067e97d6a
47,812
def compute_mi(dataset, target_name, vocab, level=None): """ compute the mutual information for each token in a lexicon """ if not level: # bucket based on bottom/top 30% response = dataset.datafile_to_np( datafile=dataset.whole_data_files[target_name]) response = respons...
2be687af778a9772d89453a9ce0ba907d90ab77e
47,813
def split_code_to_cells(code): """converts code to a list of AbstractCell :param code: string representing the code :return: list of AbstractCell """ raw_cells = _split_to_raw_cells(code) return _raw_cells_to_cells(raw_cells)
26c8451cbc7adec12948d23d379ff6937cf051a3
47,814
def present(name, service_name, auth=None, **kwargs): """ Ensure an endpoint exists and is up-to-date name Interface name url URL of the endpoint service_name Service name or ID region The region name to assign the endpoint enabled Boolean to cont...
1c042ac2ad30bb92d231d9747be5b7f564f1ecff
47,815
def registration(request): """Render the registration page""" #redirect to the index page if user is authenticated if request.user.is_authenticated: return redirect(reverse('index')) if request.method == "POST": # create an instance of the reg form using values within the pos request # ...
9e2ff50b7b329ceb75fd0e83ca3a90897f9f2894
47,816
import posixpath from urllib.parse import unquote from urllib import unquote def url_collapse_path(uripath): """Mimic standard lib's _url_collapse_path() but return a tuple That is, a tuple of path, trailing slash, everything else (query and fragment). The only other difference is that the path comp...
f0f562f5df4436f920a18ea7977c783426aa0dd3
47,817
from datetime import datetime import traceback def compute_use_days(personnel): """计算已用天数 1/如果”改善状态”字段是“改善“,则等于改善日期-问题日期 2/如果"改善状态”字段是“持续“,则等于当前日期-问题日期 :param personnel:个人操作质量单条数据对象 :return:天数 """ use_day = 0 try: now_date = datetime.date.today() # 现在日期 improve_status = personnel.improve_status.name # 改...
aeb67af3865221855409840a1b4a8d5b7376cb8c
47,818
import inspect def layer_test(test_case, layer_cls, kwargs={}, input_shape=None, input_dtype=None, input_data=None, expected_output=None, expected_output_dtype=None, fixed_batch_size=False): """ Test routine for a layer with a single input tensor and single output tensor. ...
3e4f35ca2048b07e0ba0f5252e4f0bad75d1f465
47,819
import re def remove_special_char(in_seq): """ Function is responsible for normalize strings to defined format (UPPERCASE with '_' replacing any special character) :param in_seq: list of strings :return: list of strings """ _sub = re.sub(" {1,5}", "_", in_seq.strip()).lower() _chars = ['*', '\\', '&', '/', '+'...
425f8a7fcd6a2df7db667063564f419536ae68d9
47,820
import numpy def position_from_msg(tf_msg, fmt='xyz'): """Extract position from geomety_msg/TransformStamed message.""" return numpy.array([getattr(tf_msg.transform.translation, d) for d in fmt])
f74b5aa4fe9e9e462e6eedc4dafa22c7ba2be1e8
47,821
import json def format_navigation_links(additional_languages, default_lang, messages, strip_indexes=False): """Return the string to configure NAVIGATION_LINKS.""" f = u"""\ {0}: ( ("{1}/archive.html", "{2[Archive]}"), ("{1}/categories/{3}", "{2[Tags]}"), ("{1}/rss.xml", "{2[RSS fee...
81882137af3e80ba24a3de797ebb9f30e6d5a877
47,822
def fixture_spring_metadata( first_read, second_read, spring_tmp_path, checksum_first_read, checksum_second_read ): """Return metada information""" metadata = [ { "path": str(first_read.absolute()), "file": "first_read", "checksum": checksum_first_read, ...
f6e9964b811fd1ce4e873f7a5f57d392ebb3fe98
47,823
def get_clocks(work, start_date = None, end_date = None, errant_clocks = None, case_sensitive = False, adjust_clocks = True): """Filter work by messages conataining the word 'clock' """ if errant_clocks is not None: work = work[~work.hash.isi...
2df5ce8379e7155b594f3459b90acd603643fcad
47,824
def loss_K(loss_mat, Segmentation = False): """ TF function to calculate loss from the loss matrix: Inputs: y_true: true values (N,D) y_pred: predicted values (N,D) loss_mat: matrix of loss values for selecting outputs (D,D) """ loss_mat = tf.constant(loss_mat,dtype=tf.float32) if Segmentation: def lo...
1a09e5f4101fdcf972c0ef24450daadacb2651ad
47,825
def ActionClear( request, id, command ): """ Clear trash or cache folders and than redirect back """ if request.user.is_anonymous( ) and not settings.LIMITED_ANONYMOUS: return HttpResponseRedirect( '%s?next=%s' % (settings.LOGIN_URL, request.path) ) lib_id = int( id ) home = get_ho...
7648c4c472e2f1bb4679ea1bdf1b37574315a7ec
47,826
def ConvertArgsToSingleString(*args): """ :param *args: """ max_line_total, width_used, total_lines, = 0, 0, 0 single_line_message = '' # loop through args and built a SINGLE string from them for message in args: # fancy code to check if string and convert if not is not need. Just ...
0051b46460790f2ef92c7cf636b196356d1f7ca8
47,827