content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def uncapitalize(string: str): """De-capitalize first character of string E.g. 'How is Michael doing?' -> 'how is Michael doing?' """ if len(string): return string[0].lower() + string[1:] return ""
1a294f171d16d7a4c41fb0546feca3c03b7ae37a
7,300
import sqlite3 import os def connect_db(): """Connects to the specific database.""" rv = sqlite3.connect(os.path.join(config['database'])) rv.row_factory = sqlite3.Row return rv
1a3f3e6385500758b9b0cef8af2b15210697e3b5
7,301
def _sc_weights_trad(M, M_c, V, N, N0, custom_donor_pool, best_w_pen, verbose=0): """ Traditional matrix solving. Requires making NxN0 matrices. """ #Potentially could be decomposed to not build NxN0 matrix, but the RidgeSolution works fine for that. sc_weights = np.full((N,N0), 0.) weight_log_inc =...
00b9ae93b52453281693660fa6de685cd784127e
7,302
import os import argparse def getargs(): """Parse command line arguments""" desc = ( "Analyze and query strace log given the strace log in CSV format " "(STRACE_CSV). See 'strace2csv.py' for converting strace " "log to the csv format expected by this tool." ) epil = "Example: ....
3d5b3132434ad0d74a633ee8bc5e231674571d7f
7,303
from typing import Callable from typing import Awaitable def generate_on_message( test_client: "DiscordTestClient", broker_id: int ) -> Callable[[discord.Message], Awaitable[None]]: """ Whenever a message comes in, we want our test client to: 1. Filter the message so we are only getting the ones ...
2de510a3195f60056ad13c8fb1b9c71fe480b5ab
7,304
import unittest def test_suite(): """ Construct a TestSuite instance for all test cases. """ suite = unittest.TestSuite() for dt, format, expectation in TEST_CASES: suite.addTest(create_testcase(dt, format, expectation)) return suite
791e6942d213c53a44f433495e13a76abfc1f936
7,305
def calcScipionScore(modes): """Calculate the score from hybrid electron microscopy normal mode analysis (HEMNMA) [CS14]_ as implemented in the Scipion continuousflex plugin [MH20]_. This score prioritises modes as a function of mode number and collectivity order. .. [CS14] Sorzano COS, de la Rosa-Tr...
e1c786bb90d6a7bc0367338f5e5bd6d10ec35366
7,306
def google_base(request): """ view for Google Base Product feed template; returns XML response """ products = Product.active.all() template = get_template("marketing/google_base.xml") xml = template.render(Context(locals())) return HttpResponse(xml, mimetype="text/xml")
a850e4c16f55486c872d0d581a25802d7de3c56e
7,307
def get_agivenn_df(run_list, run_list_sep, **kwargs): """DF of mean amplitudes conditiontioned on differnet n values.""" n_simulate = kwargs.pop('n_simulate') adfam_t = kwargs.pop('adfam_t', None) adaptive = kwargs.pop('adaptive') n_list = kwargs.pop('n_list', [1, 2, 3]) comb_vals, comb_val_res...
fe8fa42a3bc2e78ec1d5c5a7d47151d56789f5a5
7,308
def friendship_request_list_rejected(request, template_name='friendship/friend/requests_list.html'): """ View rejected friendship requests """ # friendship_requests = Friend.objects.rejected_requests(request.user) friendship_requests = FriendshipRequest.objects.filter(rejected__isnull=True) return rend...
2457de6e01bd4fee96d499a481a3c5a2cd0d1782
7,309
def cycle_ctgo(object_type, related_type, related_ids): """ indirect relationships between Cycles and Objects mapped to CycleTask """ if object_type == "Cycle": join_by_source_id = db.session.query(CycleTask.cycle_id) \ .join(Relationship, CycleTask.id == Relationship.source_id) \ .filter( ...
25de449672ef9ced358a53762156f3cbeaabd432
7,310
def Min(axis=-1, keepdims=False): """Returns a layer that applies min along one tensor axis. Args: axis: Axis along which values are grouped for computing minimum. keepdims: If `True`, keep the resulting size 1 axis as a separate tensor axis; else, remove that axis. """ return Fn('Min', lambda ...
09c83217b48f16782530c1954f3e4f0127c06e69
7,311
def sampling(args): """Reparameterization trick by sampling fr an isotropic unit Gaussian. # Arguments args (tensor): mean and log of variance of Q(z|X) # Returns z (tensor): sampled latent vector """ z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_me...
06e8ca16f1139e12242ee043aa680d5ce7c43c10
7,312
def get_expression_arg_names(expression, strip_dots=True): """ Parse expression and return set of all argument names. For arguments with attribute-like syntax (e.g. materials), if `strip_dots` is True, only base argument names are returned. """ args = ','.join(aux.args for aux in parse_definitio...
6f96395af45b008e5e8b0336c320813a760add49
7,313
from pathlib import Path def ORDER_CTIME(path: Path) -> int: """パスのソート用関数です。作成日時でソートを行います。 """ return path.stat().st_ctime_ns
435571222b26e0c83904305784d6c8868b5bf497
7,314
def format_location(data, year): """ Format any spatial data. Does nothing yet. Parameters ---------- data : pd.DataFrame Data before location formatting. Returns ------- data : pd.DataFrame Data with location formatting. """ # No spatial data yet so does nothing. ...
11d5d7b88f3143b38dc57248937b5e19e22e44c8
7,315
from typing import Union from typing import List def deploy_ingestion_service( featureset: Union[FeatureSet, str], source: DataSource = None, targets: List[DataTargetBase] = None, name: str = None, run_config: RunConfig = None, ): """Start real-time ingestion service using nuclio function ...
b1fb46c3900d70bf300a8acdf8045cf308be37ad
7,316
def create_app(service: Service): """Start a small webserver with the Service.""" app = FastAPI() @app.post("/query") def query(params: Params): """The main query endpoint.""" return service.query(**params.query, n_neighbors=params.n_neighbors) return app
3d2f01960d3def11f45bbbbf653511d6f5362881
7,317
def establecer_dominio(func_dist: Expr) -> dict: """Establece el dominio a partir de una FD. Parameters ---------- func_dist Distribución de probabilidad Returns ------- dict Dominio """ equations = func_dist.atoms(Eq) orders = func_dist.atoms(Rel) - equations ...
8ab1b4bc6518cb8baa300bd9f1d38ffff3dfbcf7
7,318
def random_init(n, max_norm): """Computes a random initial configuration of n 2D-vectors such that they all are inside of a circle of radius max_norm Parameters ---------- n : int Number of vectors max_norm : float or int Radius of the circle or maximum possible distance from the ...
5533e43572c47d8c8cd2d6765bb383382987015b
7,319
from typing import Dict from typing import Tuple def calc_cells(serial: int) -> Dict[Tuple[int, int], int]: """Calculate the power for all cells and store them in a dict to retrieve them faster later """ r = {} for i in range(300): for j in range(300): r.update({(i, j): calc_po...
70684827b5c3ef1ec31d419f3012356a9bde1e6c
7,320
import os def check_img(img, input_dir): """ Checks whether the img complies with API`s restrictions. Parameters ---------- img : str Image name. input_dir : str Path to the dir with the image to check. Returns ------- Error message if image does not comply with A...
1052554ac784c52c88830f07ba738c2feb6a79c1
7,321
from typing import Union import pathlib from typing import List import glob from pathlib import Path def child_files_recursive(root: Union[str, pathlib.Path], ext: str) -> List[str]: """ Get all files with a specific extension nested under a root directory. Parameters ---------- root : pathlib.Pa...
c16288b417d36d6d414c799c78fd59df976ca400
7,322
def ensure_dict(value): """Convert None to empty dict.""" if value is None: return {} return value
191b1a469e66750171648e715501690b2814b8b2
7,323
import random def mutSet(individual): """Mutation that pops or add an element.""" if random.random() < 0.5: if len(individual) > 0: # We cannot pop from an empty set individual.remove(random.choice(sorted(tuple(individual)))) else: individual.add(random.randrange(param.NBR_ITE...
f9919da7f6612e3f317dbe854eda05a71d106632
7,324
def validate_tweet(tweet: str) -> bool: """It validates a tweet. Args: tweet (str): The text to tweet. Raises: ValueError: Raises if tweet length is more than 280 unicode characters. Returns: bool: True if validation holds. """ str_len = ((tweet).join(tweet)).count(twe...
41c7ef1967cba5bb75ea8bce7ffa9b7d636ef80e
7,325
def train_and_eval(model, model_dir, train_input_fn, eval_input_fn, steps_per_epoch, epochs, eval_steps): """Train and evaluate.""" train_dataset = train_input_fn() eval_dataset = eval_input_fn() callbacks = get_callbacks(model, model_dir) history = model.fit( x=train_dataset, ...
54a30f82ab3da4b60534a2775c2217de057ba93c
7,326
import requests import html def open_website(url): """ Open website and return a class ready to work on """ headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' } page = req...
081ed99692ff9763cb19208fdc7f3e7e08e03e8d
7,327
import sys def train(): """Trains the model""" if not request.is_json: return jsonify(error='Request must be json'), 400 try: frame = data_uri_to_cv2_img(request.json['frame']) except: # pylint: disable=bare-except e_type, value, _ = sys.exc_info() print(e_type) ...
ce42f5751623dbf2da9544eab7ad98ea3cc67d51
7,328
def euclidean3d(v1, v2): """Faster implementation of euclidean distance for the 3D case.""" if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
89facc15567a7ed0138dee09ef1824ba40bb58a8
7,329
def blast_seqs(seqs, blast_constructor, blast_db=None, blast_mat_root=None, params={}, add_seq_names=True, out_filename=None, WorkingDir=None, SuppressStderr=None, Sup...
ce22f90fe3092a2c792478d7a4818d67fd13a753
7,330
def merge_dicts(dicts, handle_duplicate=None): """Merge a list of dictionaries. Invoke handle_duplicate(key, val1, val2) when two dicts maps the same key to different values val1 and val2, maybe logging the duplication. """ if not dicts: return {} if len(dicts) == 1: retur...
44c06ab30bb76920ff08b5978a6aa271abd3e449
7,331
from datetime import datetime def _timestamp(line: str) -> Timestamp: """Returns the report timestamp from the first line""" start = line.find("GUIDANCE") + 11 text = line[start : start + 16].strip() timestamp = datetime.strptime(text, r"%m/%d/%Y %H%M") return Timestamp(text, timestamp.replace(tz...
7e3083c6dec766fe681e82555daa59ba7f5166b5
7,332
def start_qpsworkers(languages, worker_hosts): """Starts QPS workers as background jobs.""" if not worker_hosts: # run two workers locally (for each language) workers=[(None, 10000), (None, 10010)] elif len(worker_hosts) == 1: # run two workers on the remote host (for each language) workers=[(work...
3b53693a292027fd82d808b6d609fb3276f1bc2a
7,333
import os def is_source_ext(filename): """ Tells if filename (filepath) is a source file. For our purposes "sources" are any files that can #include and can be included. """ _, ext = os.path.splitext(filename) return ext in [".h", ".hh", ".hpp", ".inc", ".c", ".cc", ".cxx", ".cpp", ".f", ".F"]
b388768191e3efbfe2ddf3925a3ebf9f3a6693ac
7,334
def MCE(conf, pred, true, bin_size = 0.1): """ Maximal Calibration Error Args: conf (numpy.ndarray): list of confidences pred (numpy.ndarray): list of predictions true (numpy.ndarray): list of true labels bin_size: (float): size of one bin (0,1) # TODO should convert t...
fb2390daeb8aed2f700994723884971198b613e8
7,335
def validate_frame_range(shots, start_time, end_time, sequence_time=False): """ Verify if the given frame range is overlapping existing shots timeline range. If it is overlapping any shot tail, it redefine the start frame at the end of it. If it is overlapping any shot head, it will push back all sh...
d287ad393c80b899cfba3bac92ea9717918aed4a
7,336
def sparse_add(sv1, sv2): """dict, dict -> dict Returns a new dictionary that is the sum of the other two. >>>sparse_add(sv1, sv2) {0: 5, 1: 6, 2: 9} """ newdict = {} keys = set(sv1.keys()) | set(sv2.keys()) for key in keys: x = sv1.get(key, 0) + sv2.get(key, 0) newdict...
ced3420a585084a246ad25f7686fb388f2c05542
7,337
def return_flagger(video_ID): """ In GET request - Returns the username of the user that flagged the video with the corresponding video ID from the FLAGS table. """ if request.method == 'GET': return str(db.get_flagger(video_ID))
c8ca346b60ffa322847b5444c39dcbc43c66701a
7,338
def get_all_hits(): """Retrieves all hits. """ hits = [ i for i in get_connection().get_all_hits()] pn = 1 total_pages = 1 while pn < total_pages: pn = pn + 1 print "Request hits page %i" % pn temp_hits = get_connection().get_all_hits(page_number=pn) hits.extend(temp_hits) return hits
23f4da652d9e89dd0401ac4d8ccf2aa4f2660a5e
7,339
import socket def create_socket( host: str = "", port: int = 14443, anidb_server: str = "", anidb_port: int = 0 ) -> socket.socket: """Create a socket to be use to communicate with the server. This function is called internally, so you only have to call it if you want to change the default parameters. ...
6b8cc3aa19af4582dbdf96d781d8ae64399165cf
7,340
def aten_eq(mapper, graph, node): """ 构造判断数值是否相等的PaddleLayer。 TorchScript示例: %125 : bool = aten::eq(%124, %123) 参数含义: %125 (bool): 对比后结果。 %124 (-): 需对比的输入1。 %123 (-): 需对比的输入2。 """ scope_name = mapper.normalize_scope_name(node) output_name = mapper._get_output...
c08fc3120130e949cbba4e147888fabca38c89e3
7,341
from typing import Tuple def _create_simple_tf1_conv_model( use_variable_for_filter=False) -> Tuple[core.Tensor, core.Tensor]: """Creates a basic convolution model. This is intended to be used for TF1 (graph mode) tests. Args: use_variable_for_filter: Setting this to `True` makes the filter for the ...
21deebe2de004554a5bdc6559ecf6319947f8109
7,342
def plot_diversity_bootstrapped(diversity_df): """Plots the result of bootstrapped diversity""" div_lines = ( alt.Chart() .mark_line() .encode( x="year:O", y=alt.Y("mean(score)", scale=alt.Scale(zero=False)), color="parametre_set", ) ) ...
8b91d1d6d1f7384dcbea6c398a9bde8dfb4aae39
7,343
def escape(s): """ Returns the given string with ampersands, quotes and carets encoded. >>> escape('<b>oh hai</b>') '&lt;b&gt;oh hai&lt;/b&gt;' >>> escape("Quote's Test") 'Quote&#39;s Test' """ mapping = ( ('&', '&amp;'), ('<', '&lt;'), ('>', '&gt;'), (...
2b4971c4e87e613cad457dde6d62806d299cdbcd
7,344
def _get_db_columns_for_model(model): """ Return list of columns names for passed model. """ return [field.column for field in model._meta._fields()]
181999f28ca659bf296bcb4dda7ac29ddfe61071
7,345
def get_UV(filename): """ Input: filename (including path) Output: (wave_leftedges, wav_rightedges, surface radiance) in units of (nm, nm, photons/cm2/sec/nm) """ wav_leftedges, wav_rightedges, wav, toa_intensity, surface_flux, SS,surface_intensity, surface_intensity_diffuse, surface_intensity_direct=np.genfromtx...
cd514ee29ba3ac17cdfcb95c53d4b5df4f4cad80
7,346
import json def load_chunks(chunk_file_location, chunk_ids): """Load patch paths from specified chunks in chunk file Parameters ---------- chunks : list of int The IDs of chunks to retrieve patch paths from Returns ------- list of str Patch paths from the chunks """ ...
c01ec6076141356ae6f3a1dc40add28638739359
7,347
import argparse def set_arguments() -> argparse.Namespace: """Setting the arguments to run from CMD :return: arguments """ # Adding main description parser = argparse.ArgumentParser( description=f'{m.__description__}', epilog=f'{m.__copyright__}\n | Versioon: {m.__version__}') ...
26d0d8efdb4bc13874c6ba8bb0cb7976ad000002
7,348
def get_model_input(batch, input_id=None): """ Get model input from batch batch: batch of model input samples """ if isinstance(batch, dict) or isinstance(batch, list): assert input_id is not None return batch[input_id] else: return batch
1b12ee86257bfbd5ab23404251bed39c0021f461
7,349
def issym(b3): """test if a list has equal number of positive and negative values; zeros belong to both. """ npos = 0; nneg = 0 for item in b3: if (item >= 0): npos +=1 if (item <= 0): nneg +=1 if (npos==nneg): return True else: return False
e8cc57eec5bc9ef7f552ad32bd6518daa2882a3e
7,350
def predictOneVsAll(all_theta, X): """will return a vector of predictions for each example in the matrix X. Note that X contains the examples in rows. all_theta is a matrix where the i-th row is a trained logistic regression theta vector for the i-th class. You should set p to a vector of values fro...
32bf9d386ef84debe75781a52335588da360b269
7,351
from typing import Tuple from typing import List def lecture_produit(ligne : str) -> Tuple[str, int, float]: """Précondition : la ligne de texte décrit une commande de produit. Renvoie la commande produit (nom, quantité, prix unitaire). """ lmots : List[str] = decoupage_mots(ligne) nom_produit : s...
355721522b9711f9bc206f4ab63af6121ef9b3d0
7,352
def affinity_matrix(test_specs): """Generate a random user/item affinity matrix. By increasing the likehood of 0 elements we simulate a typical recommending situation where the input matrix is highly sparse. Args: users (int): number of users (rows). items (int): number of items (columns). ...
8e033d230cbc8c21d6058bcada14aca9fb1d7e68
7,353
def get_wm_desktop(window): """ Get the desktop index of the window. :param window: A window identifier. :return: The window's virtual desktop index. :rtype: util.PropertyCookieSingle (CARDINAL/32) """ return util.PropertyCookieSingle(util.get_property(window, ...
050fe4a97a69317ba875aa59b3bf4144b9e2f83c
7,354
def get_parents(tech_id, model_config): """ Returns the full inheritance tree from which ``tech`` descends, ending with its base technology group. To get the base technology group, use ``get_parents(...)[-1]``. Parameters ---------- tech : str model_config : AttrDict """ ...
7220a57b770232e335001a0dab74ca2d8197ddfa
7,355
from chaoslib.activity import run_activity def load_dynamic_configuration( config: Configuration, secrets: Secrets = None ) -> Configuration: """ This is for loading a dynamic configuration if exists. The dynamic config is a regular activity (probe) in the configuration section. If there's a use-c...
aaeac23c0700c00c5b7946e010299fe5b2e74d82
7,356
import sys import copy import io def main(argv=None): """Main function: Parse, process, print""" if argv is None: argv = sys.argv args = parse_args(argv) if not args: exit(1) original_tags = copy.deepcopy(tags.load(args["config"])) with io.open(args["src"], "r", encoding="utf-8...
0aae5e3ab5d92de2b2fd2306645696733e81de38
7,357
import hashlib import urllib def profile_avatar(user, size=200): """Return a URL to the user's avatar.""" try: # This is mostly for tests. profile = user.profile except (Profile.DoesNotExist, AttributeError): avatar = settings.STATIC_URL + settings.DEFAULT_AVATAR profile = None ...
a810af7f7abb4a5436a2deed8c4e1069aa5d504c
7,358
import sys def szz_reverse_blame(ss_path, sha_to_blame_on, buggy_line_num, buggy_file_path_in_ss, buggy_SHA): """Reverse-blames `buggy_line_num` (added in `buggy_SHA`) onto `sha_to_blame_on`.""" ss_repo = Repo(ss_path) ss_name = pathLeaf(ss_path) try: # If buggy_SHA equals sha_to_blame_on, th...
abfefc8b3a02b4d3e63d151ab7213321b8b43d62
7,359
import tqdm def union(graphs, use_tqdm: bool = False): """Take the union over a collection of graphs into a new graph. Assumes iterator is longer than 2, but not infinite. :param iter[BELGraph] graphs: An iterator over BEL graphs. Can't be infinite. :param use_tqdm: Should a progress bar be displaye...
8ea9bae0386c497a5fe31c8bd44099ee450b2b2a
7,360
def get_month_n_days_from_cumulative(monthly_cumulative_days): """ Transform consecutive number of days in monthly data to actual number of days. EnergyPlus monthly results report a total consecutive number of days for each day. Raw data reports table as 31, 59..., this function calculates and returns ...
5ede033023d357a60ba5eb7e9926325d24b986e8
7,361
def get_text(name): """Returns some text""" return "Hello " + name
bff30de2184c84f6ed1c4c1831ed9fd782f479c9
7,362
import re def apply_template(assets): """ Processes the template. Used for overwrite ``docutils.writers._html_base.Writer.apply_template`` method. ``apply_template(<assets>)`` ``assets`` (dictionary) Assets to add at the template, see ``ntdocutils.writer.Writer.assets``. returns ...
51042e25f701935d668d91a923155813ce60b381
7,363
def harvest(post): """ Filter the post data for just the funding allocation formset data. """ data = {k: post[k] for k in post if k.startswith("fundingallocation")} return data
67f400caf87f2accab30cb3c519e7014792c84d7
7,364
import os from sys import flags def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ hom...
b786fef63c51380b543f04aa6c7fd91b3ede03d3
7,365
def model2(x, input_size, output_size): """! Fully connected model [InSize]x800x[OutSize] Implementation of a [InSize]x800x[OutSize] fully connected model. Parameters ---------- @param x : placeholder for input data @param input_size : size of input data @param output_size : size of output data Returns...
74a7f9129865e1d2b6cbfe767c7f218d53ee50e1
7,366
def cut_bin_depths( dataset: xr.Dataset, depth_range: tp.Union[int, float, list] = None ) -> xr.Dataset: """ Return dataset with cut bin depths if the depth_range are not outside the depth span. Parameters ---------- dataset : depth_range : min or (min, max) to be include...
ab4561711d118dc620100bec5e159dc4b7a29f92
7,367
def create_edgelist(file, df): """ creates an edgelist based on genre info """ # load edges from the (sub)genres themselves df1 = (pd .read_csv(file, dtype='str')) # get edges from the book descriptions df df2 = (df[['title', 'subclass']] ...
9cfba48eca977e8b2e3217078bd6d112c465ea23
7,368
def CodeRange(code1, code2): """ CodeRange(code1, code2) is an RE which matches any character with a code |c| in the range |code1| <= |c| < |code2|. """ if code1 <= nl_code < code2: return Alt(RawCodeRange(code1, nl_code), RawNewline, ...
c63213c63d96361451e441cf6923015238dae8f8
7,369
def sort_by_date(data): """ The sort_by_date function sorts the lists by their datetime object :param data: the list of lists containing parsed UA data :return: the sorted date list of lists """ # Supply the reverse option to sort by descending order return [x[0:6:4] for x in sorted(data, k...
f8d18b80404edcf141a56f47938ea09531d30df7
7,370
def get_menu_option(): """ Function to display menu options and asking the user to choose one. """ print("1. View their next 5 fixtures...") print("2. View their last 5 fixtures...") print("3. View their entire current season...") print("4. View their position in the table...") print("...
69e71555d9896d0c462b2e7b542ec87aea9213eb
7,371
def pdf(mu_no): """ the probability distribution function which the number of fibers per MU should follow """ return pdf_unscaled(mu_no) / scaling_factor_pdf
2d6fd461d12da6b00bbf20de7a7be7d61112014c
7,372
import requests def get_weather_by_key(key): """ Returns weather information for a given database key Args: key (string) -- database key for weather information Returns: None or Dict """ url = "%s/weather/%s.json" % (settings.FIREBASE_URL, key) r = requests.get(url) if r.sta...
8ab3bfa6b5924b726fef9a9c0b8bd9d47cf9dfc8
7,373
import warnings def source_receiver_midpoints(survey, **kwargs): """ Calculate source receiver midpoints. Input: :param SimPEG.electromagnetics.static.resistivity.Survey survey: DC survey object Output: :return numpy.ndarray midx: midpoints x location :return nump...
adec937949a4293d35c7a57aad7125f2e1113794
7,374
import copy def fix_source_scale( transformer, output_std: float = 1, n_samples: int = 1000, use_copy: bool = True, ) -> float: """ Adjust the scale for a data source to fix the output variance of a transformer. The transformer's data source must have a `scale` parameter. Parameters --------...
bf2dc0690732ce7677a484afee75fa7701b3d0e8
7,375
def samplePinDuringCapture(f, pin, clock): """\ Configure Arduino to enable sampling of a particular light sensor or audio signal input pin. Only enabled pins are read when capture() is subsequently called. :param f: file handle for the serial connection to the Arduino Due :param pin: The pin to en...
246dc76eb07b9240439befdffdc3f31376647a64
7,376
def year_filter(year = None): """ Determine whether the input year is single value or not Parameters ---------- year : The input year Returns ------- boolean whether the inputed year is a single value - True """ if year[0] == year[1]: single_year ...
35868a72196015c20517179dc89cd65b5601e969
7,377
def distance(p1, p2): """ Return the Euclidean distance between two QPointF objects. Euclidean distance function in 2D using Pythagoras Theorem and linear algebra objects. QPointF and QVector2D member functions. """ if not (isinstance(p1, QPointF) and isinstance(p2, QPointF)): ...
2e8b2d8fcbb05b24798c8507bef8a32b8b9468f3
7,378
import math import numpy def make_primarybeammap(gps, delays, frequency, model, extension='png', plottype='beamsky', figsize=14, directory=None, resolution=1000, zenithnorm=True, b_add_sources=False): """ """ print("Output beam file resolution = %d , output ...
371a29412b52b27c69193bed1e945eeed6a988d7
7,379
import json def view_page(request, content_id=None): """Displays the content in a more detailed way""" if request.method == "GET": if content_id: if content_id.isdigit(): try: # Get the contents details content_data = Content.objects.get(pk=int(content_id)) content_data.fire = int(conte...
11908d7d0f75377485022ab87a93e7f27b2b626d
7,380
def run_feat_model(fsf_file): """ runs FSL's feat_model which uses the fsf file to generate files necessary to run film_gls to fit design matrix to timeseries""" clean_fsf = fsf_file.strip('.fsf') cmd = 'feat_model %s'%(clean_fsf) out = CommandLine(cmd).run() if not out.runtime.returncode == 0: ...
4b033ff1aceb60cdf0c39ebfbefc0841dc4df507
7,381
def exportDSV(input, delimiter = ',', textQualifier = '"', quoteall = 0, newline = '\n'): """ PROTOTYPE: exportDSV(input, delimiter = ',', textQualifier = '\"', quoteall = 0) DESCRIPTION: Exports to DSV (delimiter-separated values) format. ARGUMENTS: - input is list of lists of data (a...
28075667459e872ec0713efb834a9c3aa1dc620e
7,382
def DatasetSplit(X, y): #Creating the test set and validation set. # separating the target """ To create the validation set, we need to make sure that the distribution of each class is similar in both training and validation sets. stratify = y (which is the class or tags of each frame) keeps ...
15c9d6acf51f6535bbd4396be83752b98c6a1fa0
7,383
def parse_children(root): """ :param root: root tags of .xml file """ attrib_list = set() for child in root: text = child.text if text: text = text.strip(' \n\t\r') attrib_list = attrib_list | get_words_with_point(text) attrib_list = attrib_list | pars...
5062b39775bdb1b788fa7b324de108367421f743
7,384
def load_data(ETF): """ Function to load the ETF data from a file, remove NaN values and set the Date column as index. ... Attributes ---------- ETF : filepath """ data = pd.read_csv(ETF, usecols=[0,4], parse_dates=[0], header=0) data.dropna(subset = ['Close', 'Date'...
84b4c20c7d74c7e028e62b0147662e9a54311148
7,385
def preprocess_LLIL_GOTO(bv, llil_instruction): """ Replaces integer addresses of llil instructions with hex addresses of assembly """ func = get_function_at(bv, llil_instruction.address) # We have to use the lifted IL since the LLIL ignores comparisons and tests lifted_instruction = list( [k fo...
656b6088816779395a84d32fe77e28866618b9ff
7,386
import json async def get_limited_f_result(request, task_id): """ This endpoint accepts the task_id and returns the result if ready. """ task_result = AsyncResult(task_id) result = { "task_id": task_id, "task_status": task_result.status, "task_result": task_result.result ...
e459d1963e2de829802927e3265b41bbe4da6bfe
7,387
def process_addr(): """Process the bridge IP address/hostname.""" server_addr = request.form.get('server_addr') session['server_addr'] = server_addr try: leap_response = get_ca_cert(server_addr) session['leap_version'] = leap_response['Body'] \ ['PingRe...
109d3e0652caa5e06fe00702f43640304c30323d
7,388
import requests import json from datetime import datetime import time def get_bkk_list(request): """板块课(通识选修课)""" myconfig = Config.objects.all().first() year = (myconfig.nChoose)[0:4] term = (myconfig.nChoose)[4:] if term == "1": term = "3" elif term == "2": term = "12" if...
03010646ce1e83f644f9bf44b8dcb4e5b8355e52
7,389
import calendar def mkmonth(year, month, dates, groups): """Make an array of data for the year and month given. """ cal = calendar.monthcalendar(int(year), month) for row in cal: for index in range(len(row)): day = row[index] if day == 0: row[index] = N...
71298d60e852e6045b4ab5c45c2f371ae7049808
7,390
def is_extension(step_str): """Return true if step_str is an extension or Any. Args: step_str: the string to evaluate Returns: True if step_str is an extension Raises: ValueError: if step_str is not a valid step. """ if not is_valid_step(step_str): raise ValueError('Not a valid step in a p...
a3b30e238b3b8c42b645d18ae370dea501d1f389
7,391
def diff_list(first, second): """ Get difference of lists. """ second = set(second) return [item for item in first if item not in second]
19975990b5a05433266b3258cd541cca54ab83ac
7,392
from typing import Optional def validate_dissolution_statement_type(filing_json, legal_type) -> Optional[list]: """Validate dissolution statement type of the filing.""" msg = [] dissolution_stmt_type_path = '/filing/dissolution/dissolutionStatementType' dissolution_stmt_type = get_str(filing_json, dis...
868c9f0d6b229c303462a4dee7df16f27cd58898
7,393
import argparse def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser( usage='%(prog)s [options] <target path> <image> [image] ...') parser.add_argument( '-c', '--captions', dest='captions', action='store_true', default=False, ...
87b2d65edb10647eb2b292819cc411f2d82cd2a0
7,394
from typing import List def weave(left: List[int], right: List[int]) -> List[List[int]]: """ Gives all possible combinations of left and right keeping the original order on left and right """ if not left or not right: return [left] if left else [right] left_result: List[List[int]] = weave_helper(left, right) ...
9a9717e43337802e6cef87a37b7d8d01493ebc8a
7,395
import torch def compute_rel_attn_value(p_attn, rel_mat, emb, ignore_zero=True): """ Compute a part of *attention weight application* and *query-value product* in generalized RPE. (See eq. (10) - (11) in the MuseBERT paper.) Specifically, - We use distributive law on eq. (11). The function com...
a39ca9d5933bc334648994fc5211355a496f8126
7,396
import sys import os def check_input(args): """Checks whether to read from stdin/file and validates user input/options. """ # Defaults option = None fh = sys.stdin # file handle if not len(args): # Reading from pipe with default option if sys.stdin.isatty(): sys....
23d2ca78c7bad056c686ac9d82c5800220a3f351
7,397
def mock_real_galaxy(): """Mock real galaxy.""" dm = np.loadtxt(TEST_DATA_REAL_PATH / "dark.dat") s = np.loadtxt(TEST_DATA_REAL_PATH / "star.dat") g = np.loadtxt(TEST_DATA_REAL_PATH / "gas_.dat") gal = core.Galaxy( m_s=s[:, 0] * 1e10 * u.M_sun, x_s=s[:, 1] * u.kpc, y_s=s[:, 2...
7dda66bccb5fcecbe55bd0f3ecb64171748947a6
7,398
def lend(request): """ Lend view. It receives the data from the lend form, process and validates it, and reloads the page if everything is OK Args: - request (HttpRequest): the request Returns: """ logged_user = get_logged_user(request) if logged_user is not None and logged_user.user_r...
59fdf04eafc1772b8ef880a1340af57739a71d25
7,399