content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def hasScript(s): """Dig out evil Java/VB script inside an HTML attribute. >>> hasScript('script:evil(1);') True >>> hasScript('expression:evil(1);') True >>> hasScript('http://foo.com/ExpressionOfInterest.doc') False """ s = decode_htmlentities(s) s = ''.join(s.split()).lower() for t ...
ed44770e256e01d26e6795e6bd7aaeb77f5270f9
39,572
from typing import Tuple def add_link_data( link_proto: core_pb2.Link, ) -> Tuple[InterfaceData, InterfaceData, LinkOptions, LinkTypes]: """ Convert link proto to link interfaces and options data. :param link_proto: link proto :return: link interfaces and options """ iface1_data = link_i...
fb692b81ad3504b6524791f04d4193c54923e570
39,573
def _create_sender(net_type, msg_queue_size=2*1024*1024*1024): """Create a Sender communicator via C api Parameters ---------- net_type : str 'socket' or 'mpi' msg_queue_size : int message queue size (2GB by default) """ assert net_type in ('socket', 'mpi'), 'Unknown network...
bdf22c799cb5348087897821c8805ab9bf996d37
39,574
def evaluate_predictions_per_char(predictions, original_sentences, answers): """Evaluates predictions per char, returning the accuracy and lists of correct and incorrect sentences.""" predicted_chars = [] sentences_with_preds = [] errors = set() correct_sentences = [] total = 0 correct = 0 ...
fb27ce85ad0843e474930802b06ab89849d87aba
39,575
def n2es(x): """None/Null to Empty String """ if not x: return "" return x
cf73dd72230040cfc1c71b248b4cdd490004a213
39,576
def eval_loss_and_grads(generated): """ Computes the loss and gradients :param generated: The generated image :return: The loss and the gradients """ generated = generated.reshape((1, img_height, img_width, 3)) outs = f_outputs([generated]) loss_value = outs[0] grad_values = outs[1]....
d0801878afe142b7e9b3d262449616f5fc630fc4
39,577
def rand_no_gen(seed, a, c, m, no_of_randnos): """ This function generates a numpy array of random numbers (positive integers) using Linear congruent method If r_i is initial random number, the next random number in the sequence is given by r_i+1 = (a*r_i + c) % m The random numbers generated will ...
a817d65825bff623f56706edd737f88cf07ec3ef
39,578
def get_genes(db, location=None, use_strand=False, overlap=True): """ Get Gene objects """ gene_ids = get_genes_ids(db, location, use_strand, overlap) genes = {} for i, gene_id in enumerate(gene_ids): genes_temp = get_gene(db, gene_id) if genes_temp: for ensembl_id, ...
29a225bdcee15fdf0a9ca36a7e40618924aa922f
39,579
def proc_frac(cases, lcl, frac=True): """fraction or sum of process occurrences per case""" cl_sum = cases.case.apply(lambda x: 0) for cl in lcl: cl_sum += cases.case.apply(lambda x: cl_frac_in_case(x, cl, frac=False)) if frac: sizes = cases.case.apply(lambda x: x.classes.size) r...
269259a34dc98625f8df3e0eb3a7448b756763a8
39,580
def get_source_version(service_name = None, default_version=None): """ Gets the source (from) version of a service participating in an upgrade. If there is no upgrade or the specific service is not participating, this will return None. :param service_name: the service name to check for, or None to extract it f...
86038eee166e48124c94d960b7ef76802e01165f
39,582
def strict_match_data(payload): """ Takes in explanation data, and a source of unlabeled data and will annotate the unlabeled data with the explanations provided. Converts explanations into binary labeling functions and if an explanation applies to a datapoint the label associated with the e...
53982cbc0f14b55e82d5c6a7bf48d14fba714754
39,583
def CollectProcesses_NoCache(): """Collect raw data here, which can be formatted in Parse(). Called from Parse()""" metrics = [] # Get our rolled-up parent processes for creating metrics for info in GetParentProcessItems(): is_system_process = False if not info['cmdline']: ...
fc36ec948fdbff889e4e747ba608a45f5b50f6ef
39,584
import time def stop_mdsd(): """ Stop mdsd process :return: None """ pids = get_lad_pids() if not pids: return 0, "Already stopped" kill_cmd = "kill " + " ".join(pids) hutil.log(kill_cmd) RunGetOutput(kill_cmd) terminated = False num_checked = 0 while not term...
d3e97ff8f799401d8c813fda51982dc0b664f9ff
39,585
def get_translation_matrix(translation_vector): """Convert a translation vector into a 4x4 transformation matrix """ T = mx.nd.zeros(translation_vector.shape[0], 4, 4).as_in_context( context=translation_vector.context) t = translation_vector.contiguous().view(-1, 3, 1) T[:, 0, 0] = 1 T...
5d029dbb8725714e6d6b359a7094fc47484a1c46
39,586
def task_install_node_certificates(ca_cert, node_cert, node_key): """ Install certificates and private key required by a node. :param FilePath ca_cert: Path to CA certificate on local machine. :param FilePath node_cert: Path to node certificate on local machine. :param FilePath node_key: Pa...
7fe5fa8cc21a47f1d362395bcd6dc3fced203275
39,587
def json_subscription_property(request, user_profile, subscription_data=REQ( validator=check_list( check_dict([["stream", check_string], ["property", check_string], ["value", check_variable_type( [check_string, check_bool])]...
0d8601e6ada68c7af9a5d80e66314507a0f0ad27
39,588
def _get_int_axis_extra_coords(cube_list, axis_coord_names, axis_coord_units, axis): """ Retrieve all extra coord names and units assigned to a data axis along a sequence of cubes. Parameters ---------- cube_list: `list` of `ndcube.NDCube` The sequence of cubes from which to extract the ...
c83e9f119fea87a55fea0cdd773d596e551fd459
39,589
def est_shape( bg, tracking_settings_frame=None ): """Estimate fly shape from a bunch of sample frames.""" interactive = params.feedback_enabled and tracking_settings_frame is not None if interactive: progressbar = \ wx.ProgressDialog('Computing Shape Model', ...
05cb1bd4bb3639acc312ef335fd982a60829c06b
39,590
from types import FunctionType def get_class_methods(class_item=None): """ Returns the class methods of agiven class object :param class_item: Class item to introspect :type class_item: object :returns: list -- Class methods """ _type = FunctionType return [x for x, y in iteritems(cla...
3b43e27264ac6d13698250c6ed43bc9cc38463c1
39,591
def get_default_benchmark_simulated_datasets(): """Default parameter sets to generate simulated data for benchmarking. The training periods and forecast horizon are chosen to complement default real datasets. Every tuple has the following structure: (data_name, frequency, training_periods, forecast_hori...
aa0d7017fc693e71c016d80f7e50cc1c9a6cdc24
39,592
def all_reduce_v2(t, group_size, group_key, instance_key, merge_op='Add', final_op='Id', communication_hint='auto', timeout=0): """Reduces tensors collectively, across devices. Args: t:...
b6bbe60f560f1c16266e13eea77d1f9eaecbcd98
39,594
def get_actions(chunkstart, chunkstop, grid): """Updates policy for a subsection of the grid with greedy actions. Input should be the first and last row of the subsection.""" actions = ['up', 'down', 'left', 'right'] new_actions = [] for i in range(chunkstart, chunkstop): ...
3a6a5c521404e6fc942e2860e1be74825e561d50
39,595
import math def deconv_size(input_height, input_width, stride=2): """ Compute the feature size (height and width) after filtering with a specific stride. Mostly used for setting the shape for deconvolution. Args: input_height (int): height of input feature input_width (int): width of ...
d7e3df3087142f6ccea3c6ed8ea3724b12b8ce89
39,598
def G(x, alpha, shift=0): """ Return Gaussian line shape at x with HWHM alpha """ return np.sqrt(np.log(2) / np.pi) / alpha\ * np.exp(-((x - shift) / alpha)**2 * np.log(2))
b89afb23564f15a2d798708977fb8c82890190c1
39,599
from typing import Optional from typing import Type def boolean_op_wrapper( _cls=None, *, and_: Optional[Type[BinaryOp]] = _And, or_: Optional[Type[BinaryOp]] = _Or, not_: Optional[Type[UnaryOp]] = _Not, ): """ Provide the atom class with __and__, __or__ and __not__ dunder methods. :p...
dc1fe474ab41982db9ac6118a8c5e4c856e74c5e
39,600
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Modem Caller ID from a config entry.""" device = entry.data[CONF_DEVICE] api = PhoneModem(device) try: await api.initialize(device) except EXCEPTIONS as ex: raise ConfigEntryNotReady(f"Unable to o...
ce5ad077056fea1f7ecaf492811d343548f48b1b
39,602
import array def _expect_array(obj): """Return an ndarray, or raise TypeError.""" if obj in (0, "0"): return array([ZERO]) if obj in (1, "1"): return array([ONE]) if obj in ("x", "X"): return array([LOGICAL]) if obj == "?": return array([ILLOGICAL]) if isinstanc...
caedb628f0812937199f63eaf67871b4e30d0bbb
39,603
from typing import Callable def internal_rescue( container: KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType], function: Callable[ [_SecondType], KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType], ], ) -> KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType]: "...
162b11fd5ba310dd7a993d2cae3c8a71aa369387
39,604
def connection_stats(): """ Get packet statistics. """ return qmilib.wds_get_packet_statistics()
07af477de5be24c5637f5479a793a1b256c3419b
39,606
def date_after(d): """ Input: an integer d Quickly find out the actual calendar date of some day in the EPIC dataset. Output: the date, d days after 2015-06-13 00:00:00.000 """ t_i = Time("2015-06-13", format='iso', scale='utc') # make a time object t_new_MJD = t_i.mjd + d #...
f2b5fb9a575c3d5311767e526e37c8be67be6542
39,607
import re def __remove_punctuation(string): """ Remove all the punctuation symbols and characters in a string. :param string: the string where the punctation characters must be removed. :return: a string without punctuation. """ return re.sub("[!@#£$.()/-]", "", string)
bb2015dc040fedb3656099b57b103f7fb9c416b9
39,609
def pad_chunk_columns(chunk): """Given a set of items to be inserted, make sure they all have the same columns by padding columns with None if they are missing.""" columns = set() for record in chunk: columns.update(record.keys()) for record in chunk: for column in columns: ...
2e5d91ad03ad613b55bcaea97fd8c0785eec977f
39,610
def username_check(username: str) -> str: """ Run a loop to check and determine if a username is valid. :param username: The username to check. """ running = True while running: flag1 = True flag2 = True if username_exists(username): print_error(f"'{username...
b717e0c2fcf90fd49aff6abe3fc203710627e260
39,611
def get_next_match( map ): """ This changes the inverse table by removing hits""" todelete = [] retval = None for px,s in map.iteritems(): if len(s) > 1: retval = s.pop(),s.pop() if retval[0][0] == retval[1][0]: s.add( retval[1] ) #print retval, s retval = None co...
a1154773fb466f976c8145787200c6489f800f5f
39,612
import math def coefficient(multiset): """ multinomial coefficient of the multiset """ S = multiset.size_as_nat() return math.factorial(S) / facto(multiset)
7cf88891adaa9b5844ae4f1b5605ebae1e1a5ffc
39,613
def join_contains(): """**Flask POST rule.** Spatial join on two spatial files drived by contains relationship. --- post: summary: Spatial join on two spatial files drived by contains relationship. description: Create a new spatial file on the condition that the geometry of the **other*...
edbd199403a07d33dd26fca12f477dfe3f47bf10
39,614
def parse_request_table(path: str) -> pd.DataFrame: """Return a dict of userid mapped to keywords. Capitalised columns are in the original file. Derived columns are all lower case. """ df = pd.read_excel(path).dropna() df["username"] = df["Link"].str.split("/").str[-1] return df
d8d041d3a60045125b13c909134f2ad61280ff7a
39,616
import joblib def load_model(model_path): """ Loads the model from the path specified. """ return joblib.load(model_path)
116546721d1de9f6a59dfbf8a1246b966dfb8074
39,617
import re def parse_system(system): """ Parse a system string into a pair of projectiles and a beam energy. """ match = re.fullmatch('([A-Z]?[a-z])([A-Z]?[a-z])([0-9]+)', system) return match.group(1, 2), int(match.group(3))
b0b578e48fbd366cd11cc385fa4c9b7a9b9a1b20
39,618
def is_negligible(in_text): """" Checks if text or tail of XML element is either empty string or None""" if in_text is None: return True elif type(in_text) is str: if in_text.strip(chr(160) + ' \t\n\r') == '': return True else: return False else: r...
3e9e5276e0b58518d942fc3e2a16f64223eb4e0d
39,619
from typing import Union def get_MD5(file: Union[BufferedReader, str]) -> str: """ Creates a MD5 hash of a file """ buffered_file: BufferedReader = None if isinstance(file, str): buffered_file = open(file, 'rb') else: buffered_file = file chunk_size = 8192 h = md5() ...
8da321f3cda89d282751637f16f3ab7139d19ce8
39,620
def jsd_distance_0(x_list, data_list): """ :param x: a list or an np.ndarray data: a list or an np.ndarray :return: jsd_list measure distance between numbers """ jsd_list = [] x_list = single_point_list_2_list(x_list) data_list = pa...
0ba7f1f1c46613ed2506133b401fdec0c5f29ae1
39,621
import numpy import math def quaternion_from_matrix(matrix, isprecise=False): """Return quaternion from rotation matrix. If isprecise is True, the input matrix is assumed to be a precise rotation matrix and a faster algorithm is used. """ M = numpy.array(matrix, dtype=numpy.float64, copy=False)[...
56e4c97d1808d79947f26703ae7f6141a3e78490
39,622
def apply_backoff(strategy = None, max_tries = None, max_delay = None, catch_exceptions = None, on_failure = None, on_success = None): """Decorator that applies a backoff strategy to a decorated function/method. :param st...
fe34a6cb760a3e630ca5a2db21bf5ecba99e9882
39,623
def make_a_tweet(Hash, Message, Reduced): """ Generate a valid tweet using the info passed in. """ tweet = Hash + ': ' + Message if Reduced: tweet += '…' return tweet
1d0c3246874f8a6c9b3cb1b1f7cf27040ff1bd1b
39,624
def ldns_pkt_edns_udp_size(*args): """LDNS buffer.""" return _ldns.ldns_pkt_edns_udp_size(*args)
83140c4dad1764a45385aa0850db23037ee6d0f5
39,625
from typing import Mapping def split_some_by_age( files_data: Mapping[str, np.ndarray], metadata ) -> Clients_X_y: """ Split the datum points (X,y) into three sets based on the age of the patients. Like `split_by_age`, except the first two sets are mixed. In effect, yes, this implies that ...
14d1eb283d968ab6b956ffa370d44b35a512d037
39,626
async def fetch_confirmed_proposals(request, next_id): """Get confirmed proposals for a user, by their next_id.""" log_request(request) head_block = await get_request_block(request) start, limit = get_request_paging_info(request) conn = await create_connection() proposals = await proposals_query...
6df321ab59783c37c868ec8d8b73f5997e1c7334
39,629
def get_first_transcript_name(fasta_file): """Return the first FASTA sequence from the given FASTA file. Keyword arguments: fasta_file -- FASTA format file of the transcriptome """ with open_pysam_file(fname=fasta_file, ftype='fasta') as f: transcript_name = f.references[0] return tran...
547bb3490c996229b6bae71215d5c72621143934
39,630
def export_account_json(request): """Export an account as JSON""" subdomains = [] for subdomain in Subdomain.objects.filter(user=request.user): subdomains.append({'name': subdomain.name, 'ip': subdomain.ip, 'ipv6': subdomain.ipv6, 'updated': subdomain.updated}) return ...
71bf569e97ecf58c92fa9dc5b14278905f18b99e
39,631
def calc_lat(hours_daylight, delta): """ Latitude is estimated from equation (1.6.11) in: Duffie, John A., and William A. Beckman. Solar engineering of thermal processes. New York: Wiley, 1991. :param hours_daylight: daylight hours as calculated by calculate_hours_daylight or calculate_hours_daylig...
cf5182f8a368fac80c456e3f207458e52e7c9698
39,632
def remainder(numbers): """Function for finding the remainder of 2 numbers divided. Parameters ---------- numbers : list List of numbers that the user inputs. Returns ------- result : int Integer that is the remainder of the numbers divided. """ ret...
4c17d717ef52a7958af235e06feff802ed9c3802
39,633
def branin(x): """ A standard 2-dimensional global optimization test function with a long, shallow valley. f(x) = (x2 - 4 * 5.1 (x1 / pi)^2 + 5 x1 / pi - 6)^2 + 10 (1 - (8 pi)^-1 ) cos (x1) + 10 (The general form doesn't specify coefficients.) There is a global minimum at [[-pi, 12.275], [pi, 2.275], [9.4247...
4d1490406311fae82c2f565ecb1ccc9161335f2f
39,635
def connect_to_cloud( account: str, password: str, appkey=DEFAULT_APPKEY, appid=DEFAULT_APP_ID, appname: str = None, hmackey=DEFAULT_HMACKEY, iotkey=DEFAULT_IOTKEY, api_url=DEFAULT_API_SERVER_URL, proxied=DEFAULT_PROXIED, sign_key=DEFAULT_SIGNKEY, ) -> MideaCloud: """Connects...
6a2e66b426e072f24318948b54094cf0995bc6ae
39,636
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_m...
330c284cf5c31819c1ae975c48b4b0ec743a543c
39,637
import requests def getItemSpecs(session_id, guid): """Get specs of a certain item :param session_id: token for current user session :param guid: unique id of an item :return: :class:'Response <Response>' object :rtype: requests.Response """ url = base_url + "/items/{guid}?includeEmp...
f94c125fb2074fb5704eea41319edfc68e090be6
39,638
def _calculate_noise_by_substitution(below_thresh_positions: pd.DataFrame, sample_id: str) -> pd.DataFrame: """ Use the below_threhold_positions data frame to calculate noise of each substitution type :param below_thresh_positions: pd.DataFrame :param sample_id: str - sample ID for first column :re...
393403b49de7cb0ce6fc5d1fdf0ae60afcb1a85a
39,639
def get_sorted_fields(doctype, custom_fields): """sort on basis of insert_after""" fields_dict = frappe.get_meta(doctype).get("fields") standard_fields_count = frappe.db.sql("""select count(name) from `tabDocField` where parent=%s""", doctype)[0][0] newlist = [] pending = [d.fieldname for d in fields_dict] m...
c4448af0f1ee3d7838e462777372b97a0d6e84fc
39,640
def staffing_agency_employee_factory(db): """ Fixture to get the factory used to create staffing agency employees. """ return StaffingAgencyEmployeeFactory
8060bde2937485db2e88f808747cedfcc03fb2bf
39,642
def parse_dburi(url:str, uppercase:bool=False) -> dict: """Parse a given URL or URI string and return the component parts relevant for database connectivity. These come in the general UNIX form: engine://[user:pass@]host[:port]/database[?options] """ uri = URI(url) parts = { 'engine': str(uri.scheme),...
e4dc8aa8bd6fb8827decdfa24fee5d4235c0e3b8
39,643
import posixpath def relativize(home_domain, web_root_path, html_file_path, link_attr_value): """ :param home_domain: Domain that originally hosted the file :param web_root_path: Path of the web root on the local filesystem :param html_file_path: Path of html file containing the links we are working on :param li...
750ccf7f3413a596067c591a6b502fa4cfb0efff
39,644
def train_classifier(input_raster, input_training_sample_json, classifier_parameters, segmented_raster=None, segment_attributes="COLOR;MEAN", *, gis=None, future=False, ...
100a0f73a1cd49376a8e9f2bd575af7356231277
39,645
def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False): """ Given some wanted signal names, and the signal names contained in a record, return the indices of the record channels that intersect. Parameters ---------- wanted_sig_names : list List of desired signal name st...
00812318105f92cc0552fcf58cbe4b0ec53547a2
39,646
def make_cmsweb_prod_request(query_url, data=None, timeout=90, keep_open=True): """ Make a request to https://cmsweb-prod.cern.ch """ return make_request('https://cmsweb-prod.cern.ch:8443', query_url, data, timeout, keep_open)
cda459d3f2b3d9e21b063a0ae0676786fda47802
39,648
def logpdf_multivariate_normal(x:np.ndarray, mean:np.ndarray, cov:np.ndarray): """ Calculate \log p(x|w) = \sum_{j=1}^M \log(\frac{\sqrt{s_j}}{2\pi} 1/cosh(\sqrt{s_j}/2(x_j - b_j))) Input: + x: n*M + mean: M + cov :M * M Output: + n*M """ return(multivariate_normal.logpdf(x, ...
f6133a9ff674aaf33a42ea4e7a05160b425d46ae
39,649
def get_thumbnail_options(file_, thumb_options=None): """ Get all options of thumbnail, including default ones. """ options = thumb_options.copy() if thumb_options else {} if settings.THUMBNAIL_PRESERVE_FORMAT: options.setdefault('format', sorl_backend._get_format(file_)) for key, valu...
551c0e800fec9edee982f1fb69b9f73bc5667e0d
39,650
def subset_sum(numbers: list, target: int, partial=[], results=[]) -> list: """ Determine all combinations of list items that add up to the target :param numbers: A list of values :type numbers: list :param target: The total that the values need to add up to :type target: int :param partial...
120a9604db4f503fe001732ca52059e86ff50a7e
39,651
import functools import logging def oneTimeJob(func): """ Decorator that causes the given scheduled function to run only once. As a bonus, it also logs the subsequent job to be ran. NOTE: This decorator suppresses any returned results by the given function. :param func: function, the function to...
14729dce9b47d957d9da825eabbd07262e2a4a25
39,653
def getTimezone(profile): """ Returns the pytz timezone for a given profile. Arguments: profile -- contains information related to the user (e.g., email address) """ try: return timezone(profile['timezone']) except: return None
f9abd83fc3065d9859d20b101e5eaedd0678d6f9
39,655
def ret_int(potential): """Utility function to check the input is an int, including negative.""" try: return int(potential) except: return None
682ab4987e94d7d758be5957b610dc1ee72156a1
39,656
def card_component( title, context, highlight_start, highlight_end, score, url, key=None): """Create a new instance of "my_component". Parameters ---------- title: ... context: ... highlight_start: ... highlight_end: ... score: ... url: ... key: str or None A...
46a2180f1f95fca7f0d507ee13775b3692b4e5c6
39,657
def read_file(file_name): """Read contents of file.""" with open(file_name, encoding='utf8') as file: return file.read().rstrip().lstrip()
cb8e85c076baa97d8f1a5361abe6ab4ee5b9f00c
39,658
def mean_squared(array): """Returns the mean squared value of an array """ # We need to handle both real and complex cases sqr = jnp.conj(array) * array mean_sqr = jnp.mean(sqr) # Make sure that we are down to float data type return jnp.abs(mean_sqr)
0a8eb7b6610a232222b58c59a4d59bbc1f48a10d
39,659
def create_plankton_dataset(start: int, end: int) -> dict: """Function to create dataset for plankton experiment. Uses data from experiments C1 to C4 from [1]. A series of ten chemostat experiments was performed, constituting a total of 1,948 measurement days (corresponding to 5.3 years of measurement) an...
e6e5f679a9bfd56fbe84be5379041a0a389e743f
39,660
def series_quatrot_inverse(x, y, z, q0, q1, q2, q3, rot_name=""): """Given pandas series x-z and quaternion q0-q4, compute reversed rotated vector x_r, y_r, z_r. Arguments: x,y,z -- vector to be rotated q0-q4 -- quaternion entries. The vector is being rotated with the inverse of that quaternion Ke...
326977d1e0612ab04f4278c72cfa11b5dc8dddd3
39,661
def frexp102str(x): """ Convert to mantesa exponent form in txt """ m, exp = frexp10(x) txt = r"%.2f$\times 10^{%d}$" % (m, exp) return txt
d62d0017061c79337a017c4e3da852d1032fd53d
39,662
def post_theme(config, storage_url, parameters, files): """ POST the theme zip file to the provided storage url :param config: context config :param storage_url: the storage url provided by import job response :param parameters: the parameters provided by the import job response :param files: th...
e3f691d0129a7f48765163c990a8089889eddce1
39,663
import pickle def get_data(sequence_length): """ Get all the notes and chords from the midi files in the ./midi_songs directory """ vocab = set() sequence_in = list() sequence_out = list() all_notes = list() for file1 in data_dir.glob("simpl*.txt"): notes = None with open(fil...
840752bce1c8e5274652f85d92f3b034d52f9cfc
39,664
def pipeline_lightcurve(d, l1=0, m1=0, segments=[], scan=-1): """ Makes lightcurve at given (l1, m1) l1, m1 define phase center. if not set, then image max is used. """ if scan == -1: scan = d['scan'] if segments == []: segments = range(d['nsegments']) d = set_pipeline(d['filename'], scan, fil...
eb2a757da802a2af2b4fcde6bbfd44d2ad50fe78
39,665
import numpy def registry_sources(sntype, subclassName=None): """ get a list of sources in the SNCosmo registry that are of the supernova type sntype, and also of the same subclass if subclassName is not None Parameters ---------- sntype: string, mandatory string used to denote a part...
c1ceaab0f597c2779053f695ee00d6c80bcd691e
39,666
import numpy as np from scipy.linalg import pinv def transform_mne_ica2data(sources, ica, idx_zero=None, idx_keep=None): """ performs back-transformation from ICA to Data space using rescaling as used as in MNE-Python sources: shape [n_chan, n_samples] ica: ICA object from MNE-Python ...
83de6a08e03a98894958ba381541706d54c327f1
39,667
def RGB2HEX(color): """In: RGB color array Out: HEX string""" return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
7283f0a8a72d83496c93084ab5c514a0184682c7
39,669
def updateBenchmarkInfo(AllInfo, CurInfo, nRepeat, **kwargs): """ Aggregate information about different experiments into one dict. """ for method in CurInfo: tvec = np.asarray([ CurInfo[method][r]['telapsed'] for r in range(nRepeat)]) key = 't_' + method loc = np.flatnonz...
f2a7d1a9f228e2491919abedbc50d4849dcc8701
39,670
from typing import Tuple async def infer_type_tail(engine, tup): """Infer the return type of tail.""" tup_t = await tup['type'] if not isinstance(tup_t, Tuple): raise MyiaTypeError('tail of non-tuple') if not len(tup_t.elements) >= 1: raise MyiaTypeError('tail on empty tuple') retu...
831731b8e8c08dfbe3d62b4a2a01803756cd40e3
39,671
def search() -> dict: """ Parses the user's search. Can be POST or GET method. """ form = forms.SearchForm() if form.validate_on_submit(): query = form.query.data elif flask.request.args.get("query", None) is not None: query = flask.request.args["query"] else: return {} r...
385e8b95bce91f720381c99dffa1368d2033207b
39,672
def getMetrics(predictions, ground): """Given predicted labels and the respective ground truth labels, display some metrics Input: shape [# of samples, NUM_CLASSES] predictions : Model output. Every row has 4 decimal values, with the highest belonging to the predicted class ground : Ground truth...
81e6684606e27397bb3f45e7e0092e09dabb9725
39,673
def tgos(location, **kwargs): """TGOS Provider :param location: Your search location you want geocoded. :param language: (default=taiwan) Use the following: > taiwan > english > chinese :param method: (default=geocode) Use the following: > geocode API Reference ...
a8b3edfcebc47dccb49c09d36c09a566e07aa551
39,674
def read(source_file, *args, **kwargs): """ Read an input file of various formats. Arguments: source_file: The first argument is a structure file of some format. The remaining args and kwargs are passed to the methods called to read the structure. If the structure name con...
e7ed71d5c065ef13fd09153311291982a03ac537
39,675
def snap_flow_mapper(product_set, snap_function, config, mount=None, rebuild=False): """Run a single set of products through the workflow. Inputs ------ product_set : list of N-tuple Something like... [(s1), (s1_2)...] [(s1, s2), (s1_2, s2_2)...] [(s1_old, s1...
b248c07022c30d116a96555ea5897d17f7157097
39,676
import six def _parse_selection(*selection): """ Parser for *selection* strings used in :py:func:`join_root_selection` and :py:func:`join_numexpr_selection`. """ _selection = [] for s in flatten(selection): if isinstance(s, (int, float)): # special case: skip ones ...
689fa575a0d57ca443c1d84c3b45db76da742cc4
39,677
def prompt_download(): """ Ask the user if they want to download the object """ while True: result = raw_input('Download? [y/n]') if result == 'y' or result == 'Y': return True elif result == 'n' or result == 'N': return False else: pri...
71265c22763b0c6efdf8f4c28a87433691bb73a9
39,678
import torch def blk_chol_mtimes(A, B, x, lower = True, transpose = False): """ Evaluate Cx = b, where C is assumed to be a block-bi-diagonal matrix ( where only the first (lower or upper) off-diagonal block is nonzero. Inputs: A - [T x n x n] tensor, where each A[i,:,:] is the ith block dia...
35584bbe7a1486f06980fb65aab4e3cd3cc7269c
39,679
def signed_area(contour): """Return the signed area of a contour. Parameters ---------- contour: sequence of x,y coordinates, required Returns ------- area: :class:`float` Signed area of the given closed contour. Positive if the contour coordinates are in counter-clockwise...
79a60d064fad70afb8902d6d66b980d778215de3
39,680
def payload_too_large(error) -> BaseErrorType: """Payload is too large.""" return BaseRequestException(413, error, request.path), 413
d792e25188f8d8dfd203a21b83ccbbce1a8857bb
39,681
def get_mean_centroids_coords_distances(df): """ Creates a features array. For each address (each row), calculate the \ mean distances between the corresponding centroid coords and the coords \ suggested from different services. Args: df (pandas.DataFrame): Contains data points for which th...
a5fa41fc08e2bad81f2ec9d6e1836a111ad5c91e
39,682
def rmsd(native, p, loops_as_strings, ca_only = False, all_atom=False): """ Prints + Returns RMSD for Full Protein, as well as any loops in loops_as_strings. """ rms = "" if ca_only: rms = CA_rmsd(native, p) print("C-Alpha:") print("%.3f RMSD"%rms) elif all_atom: ...
8627a5406a9271cf21692fa0b5126d7ff460a74d
39,683
def unlinked_objects(self: JSONClassObject) -> dict[str, list[JSONClassObject]]: """Unlinked objects of this jsonclass object. """ return self._unlinked_objects
72a54356829c24d797054aedf3b54210bbb5bcc4
39,685
def ChooseFunction(title): """ Ask the user to select a function Arguments: @param title: title of the dialog box @return: -1 - user refused to select a function otherwise returns the selected function start address """ f = idaapi.choose_func(title, idaapi.BADADDR) return...
301372b59463aa11c8f7944a05ac8352a9be82a8
39,686
def collect_nodes(trees): """ Collect node information(token, left child, right child, label) of trees by starting from lower part of trees and moving to the top Param: ------ trees: list of tree Return: ------ list of tuple, (token, left child token, right child token, label) ...
351b9e976379b4d81c88ff6d6735758ba80995d0
39,687
def conv2d( inputs, filters, training, batchnorm=constants.BN, activation=tf.nn.relu, padding=constants.SAME, data_format='channels_last', kernel_size=3, strides=1, kernel_initializer=None, name=None): """Buils a 2d convolutional layer with batch normalization. Args: ...
964694fc374be8777795119e16de33bd7e1faa2f
39,688