content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def _parse_mqtt_message(topic, payload): """ Parsitaan viestistä virheilmoitus """ match = re.match(MQTT_REGEX, topic) if match: sijainti = match.group(1) laite = match.group(2) return SensorData(sijainti, laite, payload) else: return None
7d382c1b53dbb9483db129eebbe38dc68198bdcd
56,509
import codecs import re def get_bookmarks_tree(bookmarks_filename): """Get bookmarks tree from TEXT-format file Bookmarks tree structure: >>> get_bookmarks_tree('sample_bookmarks.txt') [(u'Foreword', 0, []), (u'Chapter 1: Introduction', 1, [(u'1.1 Python', 1, [(u'1.1.1 Basic syntax', 1, []),...
a1cd349be3570900ae48ffc5e6ae217c8655cc42
56,510
def single_npjpe_not_mean(gt_cam0_pose, pred_cam0_pose, allow_mirror = True): """Normalized PJPE optionally resolving "mirrored" solutions. Arguments: gt_cam0_pose: GT 3D pose in the zero's camera frame pred_cam0_pose: predicted 3D pose in the zero's came...
e14e174c5c246d20c9455ef24b252ddfa9656412
56,511
def head(repo, subset, x): """Changeset is a named branch head. """ # i18n: "head" is a keyword getargs(x, 0, 0, _("head takes no arguments")) hs = set() cl = repo.changelog for ls in repo.branchmap().itervalues(): hs.update(cl.rev(h) for h in ls) return subset & baseset(hs)
047b1e9601751f5cfca215c095c53fb453880533
56,512
import jinja2 def render_template(authors, configuration): """ Renders a template in `adoc`, `html`, `md`, `rst`, or `txt` format. Parameters ---------- authors : list The authors to include in the rendered template. configuration : dict Configuration settings rel...
879693831529fb1786a04df3df1173601adebd63
56,513
def is_running(): """Make sure the controller is running Returns: object: will only reply if the controller is alive """ # This endpoint needed without authentication return HTTPResponse( j.data.serializers.json.dumps({"running": True}), status=200, headers={"Content-Type": "applica...
7f15538f37c05ae8ef9d0fe1ad02e8f1142b0afd
56,514
import re def ranks_unclassified(desc): """ Returns number of unclassified ranks in description :param desc: :return: """ regex = re.compile(".+(_[X]+)$") return sum( [1 if x else 0 for x in [regex.match(s) for s in desc.split(";")]])
3a016315019b03e0456e7315afd5b3fa303e265a
56,517
def expand_output(out): """Plotly callback outputs for `update_simulator` function""" return [ *out["alert"], *out["mrsim"], *out["children"], *out["mrsim_config"], *out["processor"], ]
b1d1135c8fb16d2245f882a29c622e1da42f501a
56,518
def _load_strategies(): """Load all strategy modules.""" modules = {} namespace = "glance.common.image_location_strategy.modules" ex = stevedore.extension.ExtensionManager(namespace) for module_name in ex.names(): try: mgr = stevedore.driver.DriverManager( namespa...
cf705509f3535c824c3c4a84f9d950a7532cd670
56,519
def drop_table_if_exists(): """ Removes all tables on app start so as to start working with no data """ drop_users = """ DROP TABLE IF EXISTS users """ drop_meetups = """ DROP TABLE IF EXISTS meetups """ drop_questions = """ DROP TABLE IF EXISTS questions """ drop_comments = """ DROP TABLE IF EXISTS...
d3e79992c88becd5f398162938bd22990e238803
56,520
def autocorr_periodic_arrivals(t, gamma, A_mean, A_rms, norm=True): """Calculates the closed expression of the autocorrelation function of a process of periodic Lorentzian pulses with duration time td = 1 Args: time: array[floats], time array gamma: float, intermittency parameters A...
dfcacba81c1e15abdadf66a29f01b97b11be53c1
56,521
def get_the_data(): """ Function to hold data getting stuff. """ dic_dates = {'2014-03-29': ('2014-03-29 00:00:00', '2014-03-30 00:00:00'), '2012-07-06': ('2012-07-06 00:00:00', '2012-07-07 00:00:00'), '2017-09-06': ('2017-09-06 00:00:00', '2017-09-07 00:00:00'), '...
4b0edf1df22538e31b55ac233dfdab1fce2c9615
56,522
from typing import Optional def get_available_regions(opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAvailableRegionsResult: """ Retrieve a list of available cloud regions in Astra ## Example Usage ```python import pulumi import pulumi_astra as astra regions = astra.get_ava...
962d20c86dc62f36b676c7e359b7403c4514db88
56,523
def pause(name): """ Pauses a container name Container name or ID **RETURN DATA** A dictionary will be returned, containing the following keys: - ``status`` - A dictionary showing the prior state of the container as well as the new state - ``result`` - A boolean noting whe...
825073c51afc48e488faa884f0cf696d83fcecec
56,524
import json def fablabNowFlask(): """! @brief URL pro získání aktuálního stavu strojů ve Fsblabu. @return JSON s aktuálním stavem strojů ve Fsblabu """ # return request_error("Neni implementovano :-(") try: fablab = Fablab() machinesStat = fablab.getMachinesStatus() json...
abd33f697fd3615ac64d4f1dd0a1343f7d7e8526
56,525
def find_by_email(email, session): """ Fetches a single user by email :param session: :param email: :return: a single user if found else None """ users = session.query(User).filter(User.email == email).all() return users[0] if len(users) > 0 else None
88c24fb15ee394b7a353aa54eb1a6f9c274749f9
56,526
def admin_author(): """Updates author info""" obj = models.getAuthor(int(current_user.rowid)) # Hold on to this until we validate the fields from the form password = models.getAuthor(int(current_user.rowid)).password form = AuthorForm(obj=obj) # populate the form with our blog data if requ...
18115aa97809f7b1f1e55923f45bf1d8092ce35e
56,527
def _diff(rankx, ranky): """ Return the valuation difference from int64 rankx to int64 ranky """ shift = int64(32) mask = int64((1 << 32) - 1) scale = float64(mask + 1) hi = ranky >> shift hi -= rankx >> shift lo = ranky & mask lo -= rankx & mask out = scale * hi out += lo re...
964f49ac3a89759ede85f109e81b9ab114c5db58
56,529
def get_body_part_colour(shot): """ Decide the colour of a plot element based on the shooter's body part. """ body_part = shot['shot']['body_part']['name'] if body_part == 'Right Foot': return 'orange' if body_part == 'Left Foot': return 'red' if body_part == 'Head': ...
89a6187840ee2f830f2c07579a555fc1944ea086
56,530
from datetime import datetime def login_resolver(obj, info, username, password): """ Login user :param obj: :param info: :param username: email user :param password: password user :return: token """ try: if username is not None and password is not None: reposit...
1f328942741ad9f91204598828ab6d401fc8796c
56,531
def plot_f1_per_phylum(test_phyla, figsize): """ Create barplot showing median F1 score per phylum in the test set Arguments: test_phyla (dict of lists) -- for each phylum in the test set (keys), list of F1 scores (float) for all genome vectors in that phylum figsize (tuple) -- figure size in (inches, inches) ...
5b0bcae91bd9421c111c9312cc30194d40f713bf
56,532
import scipy def load_npz(file): """Load a sparse matrix from a file using ``.npz`` format. Parameters ---------- file : str or file-like object Either the file name (string) or an open file (file-like object) where the data will be loaded. Returns ------- result : csc_matr...
8508a01c3c1fe7c7666b2857b19a06600415e967
56,534
def clear_submissions(uid=None, tid=None, pid=None): """ Clear submissions for a given team, user, or problems. Args: uid: the user's uid to clear from. tid: the team's tid to clear from. pid: the pid to clear from. """ db = api.common.get_conn() match = {} if pi...
92255c6b83e6bc5a0b7df2569f504b5f705e5c0f
56,535
import crypt def login(request, access_token): """ Validate a google access token and retrieve user's email. Returns ------- user : str User email. permissions : list List of permissions that the user has. """ try: idinfo = client.verify_id_token(access_token,...
bc9f8c6c18c96669e92bc3fca64b3a8e6a079af7
56,536
import random def generate_key(num_digit): """Generate key using user email and random str""" min_val = 10 ** (num_digit - 1) max_val = (10 ** num_digit) - 1 otp = random.randint(min_val, max_val) return otp
132716dd643af309a8e7e90a72fbed60e47bd255
56,538
from datetime import datetime def to_date(value: str, format="%Y-%m-%d") -> date: """Convert value to a date""" return datetime.strptime(str(value), format=format).date()
68febd40f5a3d4d49a47d64755addd8956a0a690
56,541
def visualize_featuregroup_clusters(featuregroup_name, featurestore=None, featuregroup_version=1, figsize=(16,12), plot=True): """ Visualizes the feature clusters (if they have been computed) for a featuregroup in the featurestore Example usage: >>> featurestore.vis...
516b0e6c207996b97e360a3efdbfc45e47c61fb7
56,542
def memoized(old_f): """Decorator that memoizes calls to old_f into a single instance-specific _memoized_data hash""" def new_f(self, *args, **kw): """Function to wrap the decorated method""" if not self._memoized_data: self._memoized_data = {} #generate a hash using the prov...
2e7133e88d1dd684d3a7338debb06036cedd09e1
56,543
def intensityPSF_Blues(N=1000): """Return ColorBrewer 2.0 9-class Blues based matplotlib colormap optimized for showing intensity PSF This colormap is a sequential colormap, however it has more color distribution near zero. Parameters ---------- N : integer Length of the colormap ...
a56fac9dceba1a70c8ab420e9b46da5dc422c580
56,544
def split(allFpdsDict): """ Splits an allFpdsDict (eg for bestOutOfSampleCorrs with returnErrors=True) """ N = scipy.shape(allFpdsDict.values()[0][0])[-1] allFpdsDictList = [] for i in range(N): d = {} for key in allFpdsDict.keys(): itemList = [] for item ...
54543352ea4fd2383220979e1d00dd0725eb8a1a
56,545
import re def parse_rst_index(rstpth): """ Parse the top-level RST index file, at `rstpth`, for the example python scripts. Returns a list of subdirectories in order of appearance in the index file, and a dict mapping subdirectory name to a description. """ pthidx = {} pthlst = [] wit...
0e57abb09c85b0023926eed29c1eedc11ea6d018
56,546
def get_stats(summoner_id, season=None): """ https://developer.riotgames.com/api/methods#!/1018/3453 Args: summoner_id (int): the summoner to get ranked stats for season (str): the season to get ranked stats for ("SEASON2015", "SEASON2014", "SEASON3") (default None) Returns: Pl...
61abc3cb3ad9234bd7cbae4418b6efa7a867b707
56,547
from datetime import datetime import pathlib import copy def start_transfer_from_file_list(src_endpoint, dst_endpoint, dst_base_path, file_list, src_base_path=None): """ Start a new transfer task for a list of files. Parameters ---------- src_endpoint : `str` ...
8c5c92b066a6089d81fa7131f052e25e10081e00
56,548
def harmonic_bond(conf, params, box, lamb, bond_idxs): """ Compute the harmonic bond energy given a collection of molecules. This implements a harmonic bond potential: V(conf) = \sum_bond kbs[bond] * (distance[bond] - r0s[bond])^2 Parameters: ----------- conf: shape [num_atoms, 3] np.a...
c6450ba9af0ba66bb29e8ac3fdb99089940ebb64
56,549
from typing import Optional from typing import Dict from typing import Any from typing import List import requests def metadata(api_url : str, network_id : NetworkIdentifier, options : Optional[Dict[str, Any]] = None, public_keys : Optional[List[PublicKey]] = None, session : Optional[requests.Session] =...
6be91260e2752e77363b1306cbd302e301248b86
56,550
import json def extract_json(fname: str) -> Export: """Extract JSON from supplied Day One journal export. Parameters ---------- fname: `str` path to file Returns ------- `Export` Nested dictionary object with Day One JSON properties """ with open(fname, "r") as f...
1aff9227237f1bea77d35d1c76e772b3d4d53323
56,552
def serialize_mc(analysis, type): """serialised function for the Monte Carlo Analysis""" return { 'id': None, 'type': type, 'attributes': { 'window': analysis.get('window', None), 'mc_number': analysis.get('mc_number', None), 'bin_number': analysis.get...
f5c7b890312997bd7c5f712e52d63ff066c358c7
56,553
def check_3(sigs): """ Repository managed by both SIG and Private. """ print("Repository managed by both SIG and Private.") supervisors = {} for sig in sigs: for repo in sig["repositories"]: # Gitee requries strict case senstive naming for direct access # repo =...
908737c960ce54bb8c724a792977e23b36775174
56,554
import http def server_handshake_headers(client_key, protocol=None, extensions=None): """ The server response is a valid HTTP 101 response. Returns an instance of http.Headers """ h = http.Headers( connection="upgrade", upgrade="websocket", sec_websocket_accept=create_serv...
878c880556c91424ce544a8632ed775077cbb5e2
56,555
def removeLines(s): """ Replace \\r and \\n with a space. """ return removeR(removeN(s))
3cc6e6886db11e8cbb36fc8d581eef6a9e1c68a0
56,556
def init_dashboard(server): """ Initialize the dashboard. --- Args: server: the main Flask app Returns: a hug ༼ つ ◕_◕ ༽つ """ # Initialize the Dash app dash_app = Dash( __name__, title="Dashmap", server=server, url_base_pathname='/helsinki/' )...
86191c9205ac8d58f81c19b3e69d195ce70aebb0
56,557
def _HasOption(_, option): """Validate the option exists in the config file. Args: option: string, the config option to check. Returns: bool, True if test is not in the option name. """ return 'test' not in option
5c8304b8e4abe91ec8e3e55f14201a1a3d7f5c57
56,558
def final_time(): """ Real Name: FINAL TIME Original Eqn: 1 Units: Month Limits: (None, None) Type: constant Subs: None The final time for the simulation. """ return 1
48e128bab98fb7d8f11bc8607e65cf4759e68481
56,559
def bronchus_data(): """Gets the data needed for the bronchus tests Returns: dict -- Data for broncus test """ return fetch_data("LCTSC", patient_ids=["LCTSC-Train-S1-001"])
d47bd84b33bd160e441c095fa8b5475e09a7b4e0
56,560
def hashtag_counts_in(collection, geometry, skip_users=None): """ Returns hashtag counts for all tweets in a geometry. Parameters ---------- collection : MongoDB collection The collection of tweets. geometry : GeoJSON-like geometry or list The GeoJSON-like object representing th...
d97239c1a323603a96a690594b41aa2f60a284ad
56,561
def hist_last_time(check_type, check_action): """ Get the last time the type + action occurred Primarily used to get the last time a song was added / updated in history. If this time is greater than time top directory was last changed then refresh not required. """ global HISTORY_ID...
b72c927de8310b15130052e8196d8454c4abfae8
56,562
from ipywidgets import HTML def fingerprint_table(fingerprint_df, as_widget=True, structure=None): """ Create HTML and CSS table layout for the calculated fingerprint. Parameters ---------- fingerprint_df : pd.DataFrame Fingerpint in dataframe form as_widget: bool Whether to b...
cb7788152cd4d0f62ae51535d43bdea472036cba
56,563
def change_partition_by_name(in_partition, in_partition_type: str, out_partition_type: str): """Switch between partition types. Only for 1-D partition tensors. Uses RaggedTensor partition scheme naming. Not all partition schemes are fully complete or can be converted into each other. Args: in_parti...
5b055a6a8cde3a096837fcf8934338fd458b4566
56,564
def donation_payment(request, account, project=None, campaign=None): """Collect donor contact information. Expects a GET param, payment_amount, in dollars.""" form = DonationAmountForm(data=request.GET, account=account) if not form.is_valid(): if project: url = reverse('donate projec...
f05991043c39daf675daa6956e448cd9c1c028b8
56,565
import pdb def putInBed(conscensus, value, window=10, mergetype='mean', columns=['foldchange']): """ given a conscensus bed-like dataframe and another one, will merge the second one into the first Args: ----- conscensus df[start,end,chrom] the conscensus (first one) value df[start, end, chrom]+columns the v...
a2816aa037f5ce86563c6d4240064c221e0e7040
56,566
def _segment(binary): """ Parses a chunk of text provided in a boolean numpy array. Returns: a tuple with a list of unique tags for each each individual 'letter' a numpy array with these tags inserted where the 'letters' are. The skimage.measure.label() function segments an arra...
214dbc094755c6b2d00040559570278329413db0
56,567
def get_parameters_nodes(input_nodes): """Find operations containing the parameters of the model. Args: input_nodes (:obj:`list` of :obj:`Node`): the input operations of the model. Returns: parameters (:obj:`list` of :obj:`Node`): the operations containing the par...
a4185512a577521f0ed3d7cc9b098800fda58974
56,568
def get_method(interface, method): """ Get a specific method Parameters: ---------- interface : interface of CST Studio method : string Specific method that you want Returns: ---------- instance : function Instance of the method """ return getattr(interface,...
bd0a8322e2a47f8c0b760894617c9ed2429fcb02
56,570
def read_file_header( filename ): """ A header is: 1. Any number of blank lines before the header 2. Any number of KEY=value pairs (anything else is ignored) 3. One or more blank lines stops the header Returns a tuple (format type, version integer, header dict, hdr lines), where the ...
54bec5d22db1d04ba081786b287abe678c71e487
56,571
def create_norm_pipelines(features): """ create_norm_pipelines() returns a dict of normalization pipeline instances of four subsets of the dataset taking as parameter features (pandas.DataFrame). """ # break into subset (timbral_rhythmic_predictors, predictors_with_pos_corr, wavel...
e219356deb351de453cfd3c46d6a9352205ad7d8
56,572
def tutorial(): """Render the tutorial page""" return render_template('meta/help.html')
5c89bf30e03ff520c4b2aa5f4e72722260929059
56,573
def is_valid(token_line, token_type=cluster_tokens_file): """ Check whether a token is valid :param token: token to be checked :param token_type: the type of token (bootstrap or signature) :returns: True for a valid token, False otherwise """ token = token_line.strip() # Ensure token is...
f22f8e92860648d2844c213129783eace4ba8e77
56,575
def create_24_hour_means(raw_data, value_column, date_column): """Takes raw sensor data and produces 24 hour mean for each data point. :param raw_data: The raw sensor data to aggregate :type raw_data: DataFrame :param value_column: Name of the column with values to aggregate :type value_column: str...
2247279a878d2973e8ef7c6bb0c5412fc49d494f
56,577
def decode_values(mfg_data: bytes, device_type_id: int) -> dict: """Decode values""" pack_params = SENSORPUSH_PACK_PARAMS.get(device_type_id, None) if pack_params is None: _LOGGER.error("SensorPush device type id %s unknown", device_type_id) return {} values = {} packed_values = 0 ...
0351e9db8468238b799f3d04e2dcbe2915f87877
56,578
import re def short_page_img_url(book_page): """Return a short url for the book page image. Args: book_page: BookPage instance Returns: string, url, eg http://101.zco.mx/My_Book/001.jpg """ book_page_url = short_page_url(book_page) if not book_page_url: return m ...
81b244bc881778c20db419125549a4cd93d1e878
56,579
def dot2svg(dot): """ Render Graphviz data to SVG """ svg = graphviz.Source(dot).pipe(format='svg').decode('utf8') # strip doctype and xml declaration svg = svg[svg.index('<svg'):] return svg
1ff440d8e55fa9d68208d9cc914465c0c8595c29
56,580
def load_mash(dist_file, simplify_names=True): """Loads fastANI output calculates overlap. Outputs a table with ['Genome1','Genome2','Distance','Pvalue','Fraction','Identity'] in header""" F = load_ani_table_( dist_file, ["Distance", "Pvalue", "Fraction"], simplify_names=simplify_names ) F[...
b17a3839c163a840cfbae3f196adc433b64d6732
56,581
def get_pip_command_packages(command): """Return packages included in a pip command.""" return command.split()[2:]
63757643862b590f27eed927b2037ad45eaf4792
56,582
def t_rel_len2048_h384_att512_fs1024_n8_dropout10(): """Hparams for LM with relative attention.""" hparams = transformer.transformer_base() update_transformer_hparams_for_music(hparams) update_truncate_length(hparams, 2048) update_small(hparams) hparams.self_attention_type = "dot_product_relativ...
490371f12e2b668f1252b1e644feb4c086dd2289
56,583
def get_file(request, file_hash) -> JsonResponse: """ Получает информацию о файле вместе с прямыми ссылками на эскиз и контент. :param request: Запрос. :param file_hash: SHA512 хэш файла. :raise Http404: Если файл не найден. """ file = get_object_or_404(File, hash=file_hash) serializer ...
bb3b35e3ef3ca0a56546365658c7fdd8d8a534df
56,584
def median(x): """ Get column median Parameters ---------- x : Expr, Series Column to operate on Examples -------- >>> df.summarize(median_x = tp.median('x')) >>> df.summarize(median_x = tp.median(col('x'))) """ x = _col_expr(x) return x.median()
cbaf11f14e3069a259876171d8a312b4297b6bb2
56,586
def decode(expr, *argv): """ --------------------------------------------------------------------------- Compares expression to each search value one by one. Parameters ---------- expr: object Expression. argv: object Infinite Number of Expressions. The expression generated will look like: even: CA...
4bdd6f02dd94622ad6fc3e62258ee9d69dd3b374
56,587
import json def elvanto(end_point, **kwargs): """Shortcut to create Elvanto API instance.""" base_url = "https://api.elvanto.com/v1/" e_url = "{0}{1}.json".format(base_url, end_point) resp = retry_request(e_url, "post", json=kwargs, auth=(settings.ELVANTO_KEY, "_")) data = json.loads(resp.text) ...
27a0327457447dc8eb9682da842ec1d3bd7a3000
56,588
def fuzzy_match(keys, fuzzy_key): """Match a fuzzy key against sequence of canonical key names. :param keys: Sequence of canonical key names. :param str fuzzy_key: Fuzzy key to match against canonical keys. :returns: Canonical matching key name. :raises KeyError: If fuzzy key does not match. "...
0739a57a82979d6e184f1a5021173c2433f6bd08
56,589
def random_walker(data, labels, beta=130, mode='cg_mg', tol=1.e-3, copy=True): """ Segmentation with random walker algorithm by Leo Grady, given some data and an array of labels (the more labeled pixels, the less unknowns and the faster the resolution) Parameters ---------...
62aa341bfd7379bc28c1feeec623d7a5c240441a
56,590
def utctime(nist_lookup=0, time=time.time, DateTimeDeltaFromSeconds=DateTime.DateTimeDeltaFromSeconds, utctime=DateTime.utctime,_diffs=_diffs): """ Returns the current UTC time as DateTime instance. Works must like the standard DateTime.now(), but tries to use ...
bea96ff02db1d20ea3827ee02c1a2acdc7d4127a
56,591
def gini(k_proportions): """ Gini impurity function. This is used to determine the impurity of a given set of data, given the proportions of the classes in the dataset. This is equivalent to: H = ∑ pk(1-pk) for all k classes. k_proportions, in this case, is an array of pk's :param k_propo...
db0e74b29166603ed2bda3aa5fa9614ba9206b67
56,592
from pathlib import Path def fixture_project_dir() -> Path: """Return path to the Python project directory. :return: a path """ return Path(__file__).parent.parent
08ef4059aa5fa4b125928e9843b83f2befff8576
56,593
def return_element_from_list(i, l): """ Returns an element from the list @param: i is an integer corresponding to the index of the element in the list @param: l is a list of elements return: element of the list if 0 <= i <= len(l) - 1 None otherwise """ if(i < 0 or i >= ...
7d57263d67fe85c13f34428c23cdaf9ae7671855
56,594
def integer_identical_to_index(nums): """ :param nums: array :return: the number equals its index """ left, right = 0, len(nums) - 1 while left <= right: mid = (left + right) >> 1 if nums[mid] < mid: left = mid + 1 elif nums[mid] > mid: right = mid...
8f289bdf268839659d68565a69e61eb36a717b40
56,595
def sprint_prefixes_db_full(prefix_db, loopback_only=False): """given serialized prefixes output an array of lines representing those prefixes. IPV6 prefixes come before IPV4 prefixes. :prefix_db openr_types.PrefixDatabase: prefix database :loopback_only : is only loopback address expected :re...
5a9b10647a30ea32a9e1664b57194cf802c4098f
56,596
def pidlist2indexlist(painting_df, painting_list): """From a list of painting ID, returns the indexes of the paintings Input: painting_df: dataframe of paintings painting_list: list of paintings ID (e.g ['000-02T4-0000', '000-03WC-0000...']) Output: index_list: list of th...
17435b9871878f5f7f0fd5a8b34bbaccc93d43f7
56,597
from typing import List def countOccupiedSeats(seats: List[str], rowBound, colBound) -> int: """ Counts number of occupied seats """ numSeats: int = 0 for i in range(0, rowBound): for j in range(0, colBound): if seats[i][j] == OCCUPIED: numSeats += 1 return numSeats
db990f1a5dda0e141c8282026e0e735823aa2abe
56,598
def maxcut_obj(x,w): """Compute -1 times the value of a cut. Args: x (numpy.ndarray): binary string as numpy array. w (numpy.ndarray): adjacency matrix. Returns: float: value of the cut. """ X = np.outer(x, (1 - x)) return -np.sum(w * X)
422a982252c4b6d718ff1a6f7421bdfce4a16277
56,599
from masci_tools.util.schema_dict_util import eval_simple_xpath from masci_tools.util.xml.converters import convert_to_xml import numpy as np from typing import Union from typing import Iterable from typing import Tuple def set_kpointlist_max4(xmltree: Union[etree._Element, etree._ElementTree], schema_dict: 'fleur_sc...
bba037a7db41eae8663a85b8a44cfecca3f8d300
56,601
from typing import Tuple async def infer_type_head(engine, tup): """Infer the return type of head.""" tup_t = await tup['type'] if not isinstance(tup_t, Tuple): raise MyiaTypeError('head of non-tuple') if not len(tup_t.elements) >= 1: raise MyiaTypeError('head on empty tuple') retu...
e3933541d3e36647affacb8510f5665a3518b49b
56,603
def has_large_adenoma_precise(pm: PathManager, cm: CspyManager, min_size=10): """ Adds option of 'maybe' WARNING: Logic will break down if >= 3 jars with the same location :param pm: :param cm: :param min_size: :return: 1=large adenoma, 0=no large adenoma, 9=maybe large adenoma """ ...
ea4f469ed42ce964690f6f13ea287b9602bf0873
56,604
def detail_url(recipe_id): """return detail url for a recipe""" return reverse('recipe:recipe-detail', args=[recipe_id])
3ba1a75fd93326a4d25cb28a1b0e9efb305446c0
56,606
from typing import Callable from typing import List def create_track(track_func: Callable, distance: int, frames: int = 100) -> List[int]: """創建軌跡 :param track_func: 所采用的轨迹函數 :param distance: 所要移動的距離 :param seconds: 操作執行時間 :param frames: 幀數 :param noice_func: 噪声函数, 计算的结果会叠加在轨迹...
94a2b68540d4fe28e53e89594b1be22dc0c2ad5d
56,607
def map_nested(f, itr): """apply a function to every element in a 2D nested array""" return [[f(pt) for pt in lst] for lst in itr]
6546781478ef0f1b53a257c3571a56dd77942014
56,608
def findmatch(x, y, xsearch, ysearch, dtol=4, silent=0, returndist=0, xsorted=0): """FINDS AN OBJECT GIVEN A LIST OF POSITIONS AND SEARCH COORDINATE RETURNS INDEX OF THE OBJECT OR n IF NOT FOUND""" n = len(x) ...
4833db9e7f54d5f009c24683f94e10ea3d3077dc
56,609
def resource_from_collection(collection, name, child_resource): """Return a child resource from a collection by name. If no item is found, return ErrorResource. """ item = collection.get_by_name(name) if item is None: return ErrorResource("Cannot find child '%s'" % name) return child_re...
b822afea4526e084149fb6cd826d08bdd23a0c67
56,610
import tqdm def get_positional_dataset_from_file(tokenizer, data): """ with open(file, 'rb') as f: data = pickle.load(f) """ truncated_sequences = 0 for inst in tqdm(data): tokenized_para = tokenizer.tokenize(inst['paragraph']) tokenized_question = tokenizer.tokenize(inst['...
c58cde79dbca2340c33d9263142b82b3c8ee4cf0
56,611
def inference(images_placeholder, keep_prob): """"AIの学習モデル部分(ニューラルネットワーク)を作成する.""" def weight_variable(shape): """重みを標準偏差0.1の正規分布で初期化する.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): """バイアスを標準偏差0.1の正規分布で初期化する.""" ...
220bd41ee60deb8b04a5f80cdaf89974c26396c5
56,615
def read_pickle(file_path: str, **kwargs): """ Returns functions to read any python object stored as a pickle file Args: file_path: file path to be loaded. **kwargs: any other argument given to pandas.read_pickle Returns: """ return lambda: pd.read_pickle(file_path, **kwargs)
5dd9f52d694173d5feec0cd019ae93fdc6fa8781
56,616
def test_metrics_node(dcos_api_session): """Test that the '/system/v1/metrics/v0/node' endpoint returns the expected metrics and metric metadata. """ def expected_datapoint_response(response): """Enure that the "node" endpoint returns a "datapoints" dict. """ assert 'datapoints' ...
9d53978eeb3df874181a6081b3456dc85f1ab014
56,617
def valid_privkey(privkey): """Is valid RSA private key? :param str privkey: Private key file contents in PEM :returns: Validity of private key. :rtype: bool """ try: return OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, privkey).check() except (TypeError...
f5214da44c645fc31b32784eef1f31df6bb25080
56,618
def generate_data_model(data_type, verbose=False): """Load data model and sample info data""" tcga_data = TCGADataModel(training_data=data_type, test=True, verbose=verbose) sample_info_df = du.load_sample_info(train_data_type=data_type, ...
34505a05b87145c2a9f07ea4e469659e2f2f15f1
56,619
def pollard_rho( num: int, seed: int = 2, step: int = 1, attempts: int = 3, ) -> int | None: """ Use Pollard's Rho algorithm to return a nontrivial factor of ``num``. The returned factor may be composite and require further factorization. If the algorithm will return None if it fails to ...
6089d12f22c4d5bfb4f306485d7dc028d7e1a2ff
56,620
def concat(old_data, add_data): """input: 2d ndarray or pandas dataframe newest first """ if not isinstance(old_data, pd.DataFrame): if old_data.size == 0: return add_data if add_data.size == 0: return old_data overlap = np.argwhere(old_data[:, 0] == add_d...
08107d49004370e0936f2250321df99f6ddb1305
56,621
def process_template_file(self, request, template_file, variable_encoding = None): """ Processes the given template file, using the given variable encoding. :type request: Request :param request: The request to be used in the template file processing. :type template_file: Template :para...
036f28e44008f97498cbd5dcc756ee795f1c6d30
56,622
import re def is_indvar(expr): """ An individual variable must be a single lowercase character other than 'e', 't', 'n', 's', followed by zero or more digits. @param expr: C{str} @return: C{boolean} True if expr is of the correct form """ assert isinstance(expr, str), "%s is not a st...
c00e62199263214596a0b9519868ffdeb86e9580
56,623
def sample_gp_function(kernel, bounds, num_samples, noise_var, interpolation='linear', mean_function=None): """ Sample a function from a gp with corresponding kernel within its bounds. Parameters ---------- kernel: instance of GPy.kern.* bounds: list of tuples [(x...
1466ed48105f6a3fe3622e912c230e7dd2e94614
56,624
def makeFileDataset(datasetType, dataId, filename): """ Make a new FileDataset. Args: datasetType (lsst.daf.butler.DatasetType): The DatasetType object. dataId (dict): The dataId. filename (str): The filename. Returns: lsst.daf.butler.FileDataset: The FileDataset object. ...
e470f319f6a310fba1128d9b4a544255cbfbc8dd
56,625
def bokeh_heatmap_cat(data, x_label, y_label, grid_column='zz'): """ Plot heatmap for categorical values (resolution defined by number of choices) Grid-values are the values being filled in the headt-map rectangles Parameters ---------- data: pandas.Dataframe dataframe x_label, y_la...
55d9a4a2466568d35964c97367db242c3f89d25a
56,626