content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse def parameter_parser(): """ A method to parse up command line parameters. By default it trains on the Cora dataset. The default hyperparameters give a good quality representation without grid search. """ parser = argparse.ArgumentParser(description = "Run MixHop/N-GCN.") pars...
9a336b041e86de7ba182c2ef9b1a977b53ce1e0c
51,700
def loadCompareDirs(directories, runparamname='runparams.json'): """ Loads final results and run parameters of two comparison directories """ runPars = loadRunPars(directories, runparamname) paramnames = [p.get('paramname', None) for p in runPars] fs = loadResults(directories, paramnames...
60b5a3969eb56b8888fafae668a8b2710517cbf6
51,701
def sort(_list, base=10): """ Radix Sort :param _list: array to sort :param base: base radix number :return: sorted list """ # TODO: comment this result_list = [] power = 0 while _list: bs = [[] for _ in range(base)] for x in _list: bs[x // base ...
38c739fa46230fe37b16e1c4fe65ba7ed882f8aa
51,702
import requests def get_info(mid): """ 获取粉丝数量 :param mid: 用户ID :return: 返回关注数量和粉丝数量 """ headers = { 'Connection': 'keep-alive', 'Cookie': COOKIE, 'Host': 'api.bilibili.com', 'Referer': 'https://space.bilibili.com/' + str(mid), 'User-Agent': 'Mozilla/5.0 ...
147ed6362676af1caa3ac5e0fa587ec5b965348f
51,703
def _advapi32_encrypt(cipher, key, data, iv, padding): """ Encrypts plaintext via CryptoAPI :param cipher: A unicode string of "aes", "des", "tripledes_2key", "tripledes_3key", "rc2", "rc4" :param key: The encryption key - a byte string 5-16 bytes long :param data: ...
2399ffa6da771552a96538e646a1320d4eb5eedf
51,704
def process(request): """processes the input url and sends the date to web page for rendering """ try: url = request.POST['url'].strip() title, data = process_utility.get_data(url) return render(request,constants.FEEDS_TEMPLATE, {"title":title,"data":data}) except Exception...
bbeccd2d666b14f6c53da6de4ad6f8e44bdaadba
51,705
def rotscan(proj, N_steps, slice_mode = False): """ The function combines rotaxis_rough() and rotaxis_precise() It does three iterations to find the best match for the rotation axis It also finds the inclination of the rotation axis Parameters __________ projections: 3D array 0 d...
ed4aa524fbff1d9c86258eb5f1e062c4ab49fe81
51,706
import json def init_synsets(scene_graph, synset_file): """ Convert synsets in a scene graph from strings to Synset objects. """ syn_data = json.load(open(synset_file, 'r')) syn_class = {s['synset_name']: Synset( s['synset_name'], s['synset_definition']) for s in syn_data} for obj in ...
6e7f630bb1acc8bdc1670a1540027516cbb5d4a5
51,707
from datetime import datetime def bundle_config(tmp_path): """Provide a config class with an extra set method for the test to change it.""" class TestConfig(config_module.Config, frozen=False): """The Config, but with a method to set test values.""" def set(self, prime=None, **kwargs): ...
26cac266e2860db56cf72d96d5a677238ef18d35
51,708
def apex_settings(key=None, default=None): """ Gets an apex setting if the key is set. If no key it set, returns all the apex settings. Some settings have issue with a Nonetype value error, you can set the default to fix this issue. """ settings = get_current_registry().settings ...
2d2d9dec52c9b17cb7fb3981873bd2bd7cbc5555
51,709
def linear_curve(t, a, b): """ fit data to linear model """ return a*t + b
da224450cffde96780268ad8d4abe4c754d55b46
51,710
def _get_channel_setting() -> dict: """Default config format for each channel :return dict channel_setting : Default config format for each channel """ channel_setting = { "block_versions": { "0.1a": 0 }, "hash_versions": { "genesis": 1, "0x2"...
94f19f0647b08db188aefc5e4899fc6d329f0e42
51,711
import sys def main(argv=None): """The entry point of the application.""" if argv is None: argv = sys.argv[1:] usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:]) version = 'Nosey ' + __version__ # Parse options args = docopt(usage, argv=argv, version=version) # Execute return...
c591401f5a3d076c432b05a1f963a0d1956758d7
51,712
def serialize(iterable, encoding=None): """Serializes an iterable of key value pairs into a stream of string chunks. If an encoding is provided, it will be encoded into that. This is primarily used by the editor to write back data to a source file. """ def _produce(item, escape=False): if ...
b30f60c7173c666eb4d1d796093ee205bccb4521
51,713
def test_pre_rescaling_integration(is_invertible, model): """Test the pre-scaling feature""" def forward(x): return np.log(x), -np.log(x) def inv(x): return np.exp(x), x.copy() reparam = RescaleToBounds( parameters='x', prior_bounds={'x': [1.0, np.e]}, pre_resc...
0a55f7ec19bd882edaa94b90a8d0c4ea843ad02d
51,714
def DLSI_updateD(D, E, F, A, lambda1, iterations=100): """ def DLSI_updateD(D, E, F, A, lambda1, verbose = False, iterations = 100): problem: `D = argmin_D -2trace(ED') + trace(FD'*D) + lambda *||A*D||F^2,` subject to: `||d_i||_2^2 <= 1` where F is a positive semidefinite matrix ========= aproac...
9acbb70da112a266da041abeb6d827df43da35a1
51,715
from typing import Union from typing import Iterable from typing import Optional from typing import Any from typing import Callable def dispatch_requests( requests: Union[Request, Iterable[Request]], methods: Methods, *, extra: Optional[Any] = None, serialize: Callable = default_serialize, ) -> Re...
69fce0d55a0213a7a31fe597fd11979b25e7f0ea
51,716
def quicksort(data, leftmark, rightmark): """Quicksort implementation. QUICKSORT(A, p, r) if p<r q = PARTITION(A, p, r) QUICKSORT(A, p, q-1) QUICKSORT(A, q+1, r) Args: data (list): array to be sorted leftmark (int): starting index rightmark (int): ending...
74d211efecfb8128c3b321c2b236243b62a3aa44
51,717
def to_geopotential_height(z: pint.Quantity) -> pint.Quantity: """Convert altitude to geopotential height. Parameters ---------- z: quantity Altitude. Returns ------- quantity Geopotential height. """ return R0 * z / (R0 + z)
08493526ff930d834c6750da5881db7c13e2359c
51,718
def parse_kind(key): """Extract kind from colorbrewer.json .. note:: This can be None if key is not seq, div or qual """ if key == "seq": return Kind.SEQUENTIAL elif key == "div": return Kind.DIVERGING elif key == "qual": return Kind.QUALITATIVE
35a71ba3c89abe200e46e48654b5b74855f0ddf4
51,719
def is_bad(text): """ Returns true iff the given text looks like it contains mojibake. This can be faster than `badness`, because it returns when the first match is found to a regex instead of counting matches. Note that as strings get longer, they have a higher chance of returning True for `is_bad...
f422df400118d5ff053003715e42cffced4a9684
51,720
import ast import operator import copy import math def math_eval(expression, variables=None, functions=None): """Evaluate a mathematical expression with variables. All the functions in the standard module math are available together with - step(x) : Heaviside step function (1.0 for x=0) - step_hm(x) ...
a373754c3d9d536af2396d2b8a4aba77c16512ad
51,721
def DBPossibleAddressWrites(reg, cst, constraint, assertion, n=1): """ Return the list of [addr_reg, addr_cst] such than mem(addr_reg, addr_cst) <- reg+cst """ return db.possibleAddressWrites(reg, cst, constraint, assertion, n)
86ac19b0a617b90f45eaebb5ce45c78bf9c46cf1
51,722
def _decline(di, t, qoi, b): """Arp's equation for general decline in a well - qoi: initial rate of production - di: initial decline rate - b: curvature (b=0 exponential) """ return qoi / ((1 + b * di * t) ** (1 / b))
86368cef4d7d24bff738d5fe4acde2a1a9fb8922
51,723
def su_calculation(f1, f2): """ This function calculates the symmetrical uncertainty, where su(f1,f2) = 2*IG(f1,f2)/(H(f1)+H(f2)) Input ----- f1: {numpy array}, shape (n_samples,) f2: {numpy array}, shape (n_samples,) Output ------ su: {float} su is the symmetrical uncertai...
a7a1a11b3701d1d4511f1dc17465c9ddd51d2b5e
51,724
def _close_xml_tags(xml): """ Automagically takes an input xml string and returns that string with all of the xml tags properly closed. It can even handle when the open tag is in the middle of the string and not the end. """ output = [] stack = [] xml_chars = deque(list(xml)) c = Non...
c0eb655a08e53e97d8e8cacc970e391f67e18e3d
51,725
from jpickle import NetObj def NetPDF(addr): """ Retrieves a PDF from a remote address. :param addr: URI. PDF must be stored in JSON format :returns: A PDF object :Example: >>> u = NetPDF('http://foo.com/myproject/parameters/density') """ p = NetObj(addr) if not isinstance(p, PD...
2ef28c6f08aef3d73b3603ecc74f422d4450da02
51,726
import hashlib def gen_robohash(s, size=200): """Return URL for robohash pic for sha1 hash of string ``s``""" h = hashlib.sha1(s).hexdigest() return ('http://robohash.org/{0}.png?size={1}x{1}&bgset=bg2&set=set1' .format(h, size))
f4ac71b54801a3b86e3ec4e0cf60f25a9cae5990
51,727
def quarks_pairwise_same_flavor(unbarred,barred): """Check if a list of quarks and list of anti-quarks have same flavor order :param unbarred: list of quarks. :param barred: list of anti-quarks. :return: True if flavors match in order, false otherwise. """ if(len(unbarred)!=len(barred)): ...
034400a15a19dda9f7c410cfc16570bded61ff45
51,728
import argparse import sys def prepare_cmd_args(parser= None): """ parse the command line arguments """ if parser is None: parser = argparse.ArgumentParser(prog=sys.argv[0], description='Train the models over a distributed cluster.') #parser.add_argument('--chief_host', type=str, default="localhost:222...
a7b5100f3325b0375b0d6f7db895dc8ace06f3e8
51,729
import os def upload_folder_to_obj(directory, resource_obj, resource_label, remove=False, removeall=False, extract=True): """ Upload all of the files in a folder based on the pyxnat EObject passed :param directory: Full path of the directory to upload :param resource_obj: pyx...
8179f87123622e24dbb32fd9783bcd793f78374e
51,730
import collections def infer_type_names(model: SystemModel, ul: UserLevel) -> TypeNameMap: """Generates a list of unique type names for all typedefs depending on the user levels. Args: model (SystemModel): A DeCoP system model. ul (UserLevel): The highest user level for which code will be gen...
b0203a2e65ec0b7dac810e35af829b394561f1da
51,731
import io def detect_text(img): """Detects text in the file.""" with io.open(img, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.text_detection(image=image) # returns TextAnnotation df = pd.DataFrame(columns=['descripti...
a70dc2739e904fba7ff0526dc0622cf06ac7594e
51,732
def preproccess_image(image): """ this function applies some basic image processings to the original images :param image: original image :return: processed image """ # covert BGR image to RGB space image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # print(image.shape) # covert RGB ima...
6dc886fa4a79527040cc7de0a6d532755acd61a2
51,733
def setup_fig(title, x_label, y_label): """ set-up the figure for the the plots pre-conditions: title: <string> the title of the plot x_label: <string> x axis label y_label: <string> y axis label post-conditions: returns the figure and the axes """ fig, axes...
8202ec86559623330fa977de38fbd1d2ccb4bbb5
51,734
from sys import version def version_is_greater(current, minimum): """Compare two 'vv.nn.pp' versions. Return True is the current version string is greater or equal to the minimum string. Assumes that each string is of type vv.nn.pp, with vv, nn and pp being integers.""" return version.parse(current) >= ...
096fcabdfc7ff1930c6308d1a61c4a2de98c6608
51,735
import os from functools import reduce from dateutil import tz def _combine_sample_regions_batch(batch, items): """Combine sample regions within a group of batched samples. """ config = items[0]["config"] work_dir = utils.safe_makedir(os.path.join(items[0]["dirs"]["work"], "regions")) analysis_fil...
089028f8ec256b7d40bdfb0ecfbc3bf4979718dd
51,736
def logq(x, q=1): """ Calculates the `q`-logarithm of x. Parameters ---------- x : float, array Real number or array containing real numbers. q : float Tsallis's `q` parameter (default: 1). Returns ------- : float or array Value or array of values containing...
9ddaaeb27be316a556cab92d8b2d4408149b8a71
51,737
def wrap_deepmind(env_id, episode_life=True, clip_rewards=True, frame_stack=4, scale=False, warp_frame=True): """Configure environment for DeepMind-style Atari. The observation is channel-first: (c, h, w) instead of (h, w, c). :param str env_id: the atari environment id. :param bool e...
1758a46bad172d70bd08e7e95c80e6fdf05e6a43
51,738
def batch_intersection_union(output, target, nclass): """mIoU""" # inputs are numpy array, output 4D, target 3D mini = 1 maxi = nclass nbins = nclass predict = np.argmax(output.astype(np.float32), 1) + 1 target = target.astype(np.float32) + 1 predict = predict.astype(np.float32) * (targ...
355d060a5135663742826bb73745b2c2551ec5eb
51,739
from typing import Callable from typing import Any async def _async_get_ws_formatted_events( hass: HomeAssistant, msg_id: int, start_time: dt, end_time: dt, formatter: Callable[[int, Any], dict[str, Any]], event_processor: EventProcessor, ) -> tuple[str, dt | None]: """Async wrapper around...
eb6850210d773fba91a2abc26c25a35398080525
51,740
def laplace_ptr(boundary, trace, nb, matrix=False): """ μ, c, θ = laplace_ptr(boundary, trace, nb, matrix=False) The PTR method for the Laplace problem. Parameters ---------- boundary : Boundary Boundary object trace : function the function θ ↦ f(θ) the source term of the B...
08e7ebd443036f0c981094dd0389eb6a85c90e46
51,741
def _popen(cmd, data_in, data_out=PIPE): """ Helper function subprocess.popen replaces os.system - gives better input/output process control usage: pass <data_in> to process <cmd> and return results based on rgbeimage.py (Thomas Bleicher 2010) """ cmd = str(cmd) # gets rid of unicode odditie...
5b3fc74f87a7e58ad85ba25ac282738b05430a27
51,742
def reduce_min(attrs, inputs, proto_obj): """Reduce the array along a given axis by mean value""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes':'axis'}) return 'min', new_attrs, inputs
61d06d1a1c3fe8b86e0ba974802f2b49dc37c323
51,743
def fake_get_value(name, default=None): """ Method for getting configuration override values for a fake site. """ return FAKE_SITE.get(name, default)
7124758583e55a65cfc261667b49b5431f9bca1e
51,744
def check_statement(statement): """Given a single line of code expected to be a valid 'statement', that is a line which could be part of a larger source of code and contains no unmatched brackets and would not end with the continuation character, it is potentially modified to include some required '...
538c20d471c646eaa16bebe9353e69fef047f601
51,745
import math def hinter_sampling(min_n_pts, radius=1.0): """Samples 3D points on a sphere surface by refining an icosahedron, as in: Hinterstoisser et al., Simultaneous Recognition and Homography Extraction of Local Patches with a Simple Linear Classifier, BMVC 2008. :param min_n_pts: The minimum numb...
82b620159ca5c5d6eb98f24c7962ecd91afda7b2
51,746
def _load_md(rec,keys): """ Helper for load ensemble. Extracts metadata defined by keys list and posts to a Metadata container that is returned. """ # do this stupid for now without error handlers md=Metadata() for k in keys: x=rec[k] md.put(k,x) return md
3791e31f26129e14ea28b31d84e12ae88876caf7
51,747
import re def start(): """\\A: Match the start of the text.""" regex = re.compile(r'\Aa', flags=re.MULTILINE) match_start = regex.search("album") match_starting_newline = regex.search("\nart") return match_start and not match_starting_newline and match_start.string
9aa89978b122cd5dc3d3c00d3217e731636c2f71
51,748
def variance(y): """ Return the sample variance of y. >>> y = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> variance(y) 1.3720238095238095 """ av = mean(y) ss = sum((x-av)**2 for x in y) return ss/(len(y)-1)
6ca4e59ddd6725b31cf5dbd20adb85f1e0ed27f8
51,749
from typing import Callable def get_text_preprocessor(func: str) -> Callable[[str], str]: """ Given a string descriptor of the function, return the requested preprocessing function. Args: func: Function name. Returns: Text preprocessing function. """ if func == TextPreprocess...
9eb36d6b3017ec3394d47fd26908b6791dccf4e8
51,750
import numpy def BM_spectrum(E, I, B, ph_energy, hor_acc_mrad=1.0): """ Calculates the emitted spectrum of a Bending Magnet (vertically integrated) whithin a horizontal acceptance\n Units: [ph/s/0.1%bw]\n :E: Storage Ring energy [GeV] :I: Storage Ring current [A] :B: Magnetic Field value [T] ...
fd87dae1dc35bcb4a2ab87cb8c881875caa6ebd0
51,751
def finite_zeroth_d(grid): """ Gives the zeroth derivative operator on the function f(grid), so simply returns the identity matrix... XD """ return identity(len(grid))
95284bf0f16acc11b8d45396a2892865836d1813
51,752
def set_gdx_path(path): """Set file path of active GDX file.""" global ACTIVE_GDX ACTIVE_GDX = Gdx(path) logger.info(f"ACTIVE_GDX set to {ACTIVE_GDX.abs_path}") return f"Active gdx set to {ACTIVE_GDX.abs_path}"
7b196128cb77a10ffaab0d82da72ede7f6a86298
51,753
def process_reqs(reqs): """ Add all egg-containing links to list #1 and egg information plus package names to list #2. Note: we rely on dependency links, support for which will be removed in future versions of pip. TODO: migrate to custom pip repo. """ pkg_reqs = [] dep_links = [] f...
1d9ae56fecf1dbec21ea01daa1c2e1f7e34bcbe4
51,754
from datetime import datetime import json def Tweet(tw, config): """Create Tweet object """ logme.debug(__name__+':Tweet') t = tweet() t.id = int(tw["data-item-id"]) t.id_str = tw["data-item-id"] t.conversation_id = tw["data-conversation-id"] t.datetime = int(tw.find("span", "_timestam...
f118280f700c0238d09f3e5acb6dce74c32dc4b7
51,755
def bfs(problem, stype): """ Breadth-first search :param problem: problem :param stype: type of search: graph or tree (graph_search or tree_search) :return: (path, stats): solution as a path and stats The stats are a tuple of (time, expc, maxstates): elapsed time, number of expansions, max state...
f7f6c28e025e05d5acced7c1cf5702715903768d
51,756
def stock_valuation_n_period(discount_rate ,LT_growth_rate, dividends): """ Summary: Given an array of dividends, estimate the stock price using an n-period model. PARA discount_rate: The discount rate used to calculate the NPV & PV calcs. PARA type: float PARA LT_growth_rate: The long-ter...
7e0670fea9b963aa92cc093e7e1d7751fe8af17d
51,757
import os def calculate_wer_per_cat(df,category='category', id='', kind=False): """ Calculates the WER for every unique value for a certain column Args: df: the pandas dataframe category: name of a column in the pandas data frame, for each unique in this column value we return the wer. ...
fc4c3cddb3f3db80eb0a9021105f03f0fa248dc3
51,758
def two_versions(app, identity_simple, input_data, service): """Create 2 versions.""" # NOTE: We use app fixture to create/teardown the index only once for # this module. record = _create_and_publish(service, input_data, identity_simple) recid = record.id draft = service.new_version(recid,...
e9f72d6e74afbfca983ea427beabe4b9b5beeacd
51,759
def prepare_simulation(a,b,c, n): """ prepare simulation :return: :rtype: """ f_f = ForceField(linear=True, amplitude=20) f_f.origin = b print(f_f) # cell = CubicCell(a, b, c) cell = ForceCubicCell(a,b,c, f_f) print(cell) print(cell.get_center()) print("the force o...
0c4df93096752868ad5d30f2f338307c0988530b
51,760
from itertools import chain def flatten_list(lst): """ :param lst: original list :return: flattened list """ return list(chain(*lst))
5f0f796a543f0364cdb238ede40b6f021e698ba6
51,761
def checkwait(space, w_sock, writing): """If the socket has a timeout, do a select()/poll() on the socket. The argument writing indicates the direction. Returns one of the possibilities in the timeout_state enum (above).""" w_timeout = space.call_method(w_sock, "gettimeout") if space.is_w(w_timeout...
67123e1a5bb8803d3892387e067119bb69d4b1df
51,762
def sample_user( username='tesuser', email='test@test.com', password='Testpassword_123' ): """Create a sample user""" return get_user_model().objects.create_user(username, email, password,)
049453cd3bb9821b4bcd8a1081bf6c8d8f3a66d3
51,763
def min_date_nan(dates): """Find the earliest date from a series that may contain NaNs. Find the earliest date from a pandas series of datetime.dates that may contain NaNs. NaN dates are considered earlier than all others. """ if dates.isna().any(): return np.NaN else: return...
5684fa178d723dc61e5faddb74ff2e359e98a29f
51,764
from datetime import datetime def to_utctimestamp(a_datetime): """ Calculate number of seconds from UTC 1970-01-01 00:00:00. When: - dt doesn't have tzinfo: assume it's a utc time. - dt has tzinfo: use tzinfo. WARNING, if your datetime object doens't have ``tzinfo``, make sure it's a UT...
96502d9d0c2eef4bd2ba52fe7a73c647502bf81b
51,765
def function_with_cpp_args_kwargs(a, b, c=None, d=3, e=(None, "test")): """this is a doctring """ __cpp__ = """ return Py_BuildValue("(O,O,O,O,O)", a, b, c, d, e); """ return None
caf7622a4031bfee704f4ed3d0bcaa2a0591b52d
51,766
from typing import Any import attr def validated() -> Any: """Decorate an entity to handle validation. This will let ``attrs`` manage the class, using slots for fields, and forcing attributes to be passed as named arguments (this allows to not have to defined all required fields first, then optional ...
6903d654e74b6bd6fc2d062755823043125c922a
51,767
import uuid import requests import json def create_vendor(config): """ POST request to create a Vendor in QBO Refer here for other Vendor fields: https://developer.intuit.com/docs/api/accounting/vendor """ url = config['qbo_base_url'] + '/v3/company/' + config['realm_id'] + '/vendor?minorv...
c41a2bb5d589a5fa31eed3dda8506d49bcf42c57
51,768
def mean_match_accuracy(predicted, target): """Computes mean of number of matches between some target and some predicted values. Both 'predicted' and 'target' can be either scalars or sequences, but have to be of the same length. """ return np.mean(prediction_target_matches(predicted, target))
432a263b10eadecec9b1342f7d1b150504d4ae82
51,769
from absa_api import export_data import json def download_data_and_compare_same(hostname=["http://192.168.50.139:8081/api/","http://192.168.50.139:8080/api/"], dirpath="/opt/lavector/absa/", jsonfile=["192.168.50.139_500_8081_0129.json","192.168.50.139_500_8080_0129.json"], isabsa=True): """ 对比相同的hostname的数据 ...
c8089ea765a36c95384980c34db9390da2c2a1d8
51,770
def getDecoderClass(typ): """ Return Decoder class for the PK type. """ for cls in (CentralDirEntry, LocalFileHeader, EndOfCentralDir, DataDescriptor, Zip64EndOfDir, Zip64EndOfDirLocator, ArchiveExtraDataEntry, ArchiveSignature, ): if cls.MagicNumber == typ: return cls
5071ed571f78af7b57edf451e4f3dab9fd570682
51,771
def connex(vertices: np.ndarray) -> list: """Connection array to build vertex edges for vispy LineVisual. Notes ----- See http://api.vispy.org/en/latest/visuals.html#vispy.visuals.LineVisual """ return [True] * (vertices.shape[0] - 1) + [False]
b743f317a142da55ffd09409e16542d0263601db
51,772
def __parse_options(config_file, section, options): """ Parse the section options :type config_file: ConfigParser object :param config_file: The config file object to use :type section: str :param section: Which section to read in the configuration file :type options: list of dicts :param o...
c555855b56e35b53e14d664b99104e094d02a6a1
51,773
def visualize_cut_plane( cut_plane, ax=None, minSpeed=None, maxSpeed=None, cmap="coolwarm", levels=None, title = None ): """ Generate pseudocolor mesh plot of the cut_plane. Args: cut_plane (:py:class:`~.tools.cut_plane.CutPlane`): 2D plane through wind plant. ax (:py:class:...
1333b98664e1ed80c2dc18b3d3ce5d8438fa30fd
51,774
from typing import Dict from typing import Any import copy import functools from datetime import datetime def train(train_job_params: Dict[str, Any], output_dir: str, return_dict: Dict[str, float] = None, progress_dict: Dict[str, float] = None, env_tag: str = None): """Train....
07528c0d3e7e9236c7ef4c7465a882f4d656e278
51,775
import math def get_multistage_merge_pipeline( alias, vcf_files, processing_dir, chunk_size, bcftools_binary, process_name, process_command, stage=0, prev_stage_processes=None, pipeline=None ): """ Generate Nextflow pipeline for m...
7bda413b88f2eaad2e3cb2ecc9f15645b102a782
51,776
def tide_after_href(path): """Wrap href paths with 'app:/' and 'index.html' so all links point to static files to make them work in the TideSDK app when we run python application.py -f. This way paths like '/view-location/123/' turn into 'app://view-location/123/index.html' """ if app.confi...
9f9b068ed0cee6fdf10b11a270d7b55ac3f9f580
51,777
def guess_game_name_from_clone_arg(clone_arg: str) -> str: """Guess the name of the game from the --clone argument. :arg clone_arg: The str given by the user for the clone argument. Usually a git link as `https://github.com/ScienceGamez/world-3.git`.. """ if "/" in clone_arg: # If u...
6a1203f966beb566195ae51960d727376b099cc1
51,778
def midpoint_point_point_xy_numba(u, v): """ Compute the midpoint of two points lying in the XY-plane. Parameters ---------- u : array XY(Z) coordinates of the first point in the XY plane. v : array XY(Z) coordinates of the second point in the XY plane. Returns ------- ...
f78a21117f105322101569f1384d695fc49939a8
51,779
def extract_training_glucose(data): """ Extract the input variables (x), the time (t), and the objective (y) from the data samples. WARNING : need to be modified to include additional data, or override the function within the models :param data: :return: """ ...
144afb9cab81d67e9c2f966f0a80501697a820f4
51,780
def get_currencies(codes): """ Returns a list of (code, translation) tuples for codes """ currencies = [(code, get_display(code)) for code in codes] return currencies
3249c374a21160f2d15b8b72dcb63768270419e5
51,781
import importlib import pkgutil def load_from_module(extension_point, module_name, extension_function_name='__extend__', propagate_exceptions=False): """Load an ExtensionPoint from a Python module. This imports a module and scans it for immediate sub-modules, i.e. those modules nested directly under the firs...
7c505caef775eed86d23a013676e3965e94a7eec
51,782
import logging def is_hsts_preloaded(domain): """ Whether a domain is contained in Chrome's HSTS preload list. If preload_list is None, the caches have not been initialized, so do that. """ if preload_list is None: logging.error('`preload_list` has not yet been initialized!') rais...
1ec508cc4b5096a7980ba0de0e8e6e210e958c08
51,783
def FOEEWMO(t, **kwargs): """from IFS Documentation Cycle 31, Teten's formula for water only after Tiedtke 1993 (cloud and large-scale precipitation scheme) Uses the Tetens's formula Based on Buck 1981 & Alduchov and Eskridge 1996 Args: t: air temperature K Returns: es : sa...
5c8471fcee1fd7b22ce34691dbd938352fd5a16f
51,784
import os import glob def HeadPoseImage(path: str) -> Dataset: """`Head Pose Image <http://crowley-coutaz.fr\ /Head%20Pose%20Image%20Database.html>`_ dataset. The file structure should be like:: <path> Person01/ person01100-90+0.jpg person01100-90+0.tx...
fd5a64a329022eca964b886dcb943ecb1ab4606e
51,785
def partition(arr: list, start: int, end: int) -> int: """ Choosing last element as pivot """ i, j = start - 1, start while j < end: if arr[j] < arr[end]: i += 1 arr[i], arr[j] = arr[j], arr[i] j += 1 i += 1 arr[i], arr[end] = arr[end], arr[i] re...
766c8596aa434ede7ee269e75530859b06e1b59f
51,786
def generate_csv(fname, fields, trait_list): """ Generate CSV called fname with fields and trait_list """ csv = open(fname, 'w') csv.write(','.join(map(str, fields)) + '\n') csv.write(','.join(map(str, trait_list)) + '\n') csv.close() return fname
027da4c8022f8d3600f24da759d2776e48f748fb
51,787
def check_gae(): """Checks if Google App Engine is present on system""" return bool(find_gae_path()), 'Google App Engine SDK'
3033ec22d779b008d9715daf0434f8b33f7f5546
51,788
def default() -> dict: """The default hyperparameters. It will have a version key and a list of candidate models. Each model has its own search space inside. """ ret = { 'version': 1, 'models': { 'BertForTextPredictionBasic': { 'search_space': { ...
4ec6a4b13b756c378bf5c48752a2395f7ae4f47b
51,789
import os def load_dataset(key): """ Function to load datasets included in the chainladder package. Arguments: key: str The name of the dataset, e.g. RAA, ABC, UKMotor, GenIns, etc. Returns: pandas.DataFrame of the loaded dataset. """ path = os.path.dirname(os.path.a...
5b21830906df73cd8e00cae375f6b126820602b3
51,790
import glob def get_port_options(system): """Lists serial ports :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of available serial ports """ sys_platform = system.get_sys_platform() # For Windows Platform if sys_platform == 'windows': ...
f9cf1feebfc086fee7e20a33d2b793a451167bde
51,791
def fit_phase(w, si=1, fmin=0, fmax=None, axis=-1): """ Performs a linear regression on the unwrapped phase of a wavelet to obtain a time-delay :param w: wavelet (usually a cross-correlation) :param si: sampling interval :param fmin: sampling interval :param fnax: sampling interval :param ax...
74f41b6b0404c42a8a97570613f5295b35fec55b
51,792
def count_threshold(x, threshold=10e-6): """ count the number of above-threshold elements in an array """ return np.sum(x > threshold)
36952fb8dee56f19a3a48779b2bc472f81c10fe2
51,793
import scipy.sparse as sp from time import time def fit_lmk3d( lmk_3d, # input landmark 3d model, # model lmk_face_idx, lmk_b_coords, # landmark embedding weights, # weights for the objectives s...
3f03208ff2c73585faf2a4ae8b83d4b93d25a111
51,794
import socket import json def is_alive(): """ Checks if engine is running. Returns: bool: True if the engine is running and accepting commands, False otherwise """ ## --------------------------------------------------------------- cmd = dict() cmd["type_"] = "is_alive" ...
be9ceaa348a985b375f1bb75908bd26451f63f5e
51,795
def read_xml_no_ns(filename): """ read in the file or data, populating a lxml._elementTree object stripping out namespaces :param filename: filename representing a xml file or a string of xml data :return: lxml._elementTree object or None """ parsed_xml = read_xml(filename) if parsed_xm...
b44606e6c736d041496d78d52d6f048d4613bdfa
51,796
def keep_type(value): """ Keep hook returned value type :param value: Value to be returned :return: Any """ return value
f5048e2863aca6eced8c3be76a3623fd5f3a808e
51,797
def r2_score(y_true: np.array, y_score: np.array) -> float: """ Calculate the coefficient of determination (R^2) for a ground-truth prediction vector pair. Args: y_true (array-like): An N x 1 array of ground truth values. y_score (array-like): An N x 1 array of predicted values. Return...
6d29873e0fabd1f8a1d6b99f1c6c5aced822cc08
51,798
def varType(row): """Variants should be decomposed, and normalized using vt before applying this function""" c1 = len(row['REF']) == len(row['ALT']) c2 = ',' in row['REF'] c3 = ',' in row['ALT'] if c2 or c3: return 'other' if c1: return 'snp' else: return 'indel'
5870eb1c1fb13beb7e8e9756fa99de19df1f93ee
51,799