content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import io def process_image(base_image, mask_array, output_format="jpeg"): """ Create the final image including the aerial imagery background with the outside of the featured boundaries masked. :param base_image: A file-like object with the image :type base_image: File-like object :param mask...
73e45f5b2bd006e40be09696c5b8674d70d5a6ba
3,620,600
def get_scene(scene_id, client=default): """ Return scene corresponding to given scene ID. """ return raw.fetch_one("scenes", scene_id, client=client)
d1ae7409b3eec57a8b24d0522cae89ee45e9a87b
3,620,601
def build_uwp( package_family_name, target, location=None,logo44x44=None, lnk_name=None, ) -> Lnk: """ :param lnk_name: ex.: crafted_uwp.lnk :param package_family_name: ex.: Microsoft.WindowsCalculator_10.1910.0.0_x64__8wekyb3d8bbwe :param target: ex.: Microsoft.WindowsCalcul...
092a518e682b870353431efbdbdd3a341f360ca7
3,620,602
def elevation_nl(xarray=False): """ Fetch surface elevation dataset for the Netherlands. """ fname = REGISTRY.fetch("elevation_nl.nc") ds = xr.open_dataset(fname) if xarray: return ds else: grid = xugrid.Ugrid2d.from_dataset(ds) return xugrid.UgridDataArray(ds["elevat...
48d85e99911f3a6a5d9ec31a3f3d231b25129ac4
3,620,603
def parse_single_event(when, local_tz=None, now=None): """ This function parses a text string describing a single time range on a specified date, returning a tuple of start and end times (datetime.datetime). The year will be set to the current year, unless the optional argument now is provided, in w...
36f1e4eddfe37cea2ae28e942cbc1f0d54cffe37
3,620,604
def encode(state: "knx_stack.State", msg: "knx_stack.Msg") -> "knx_stack.Msg": """ >>> import knx_stack >>> address_table = knx_stack.AddressTable(0x1001, [], 255) >>> association_table = knx_stack.AssociationTable(address_table, []) >>> state = knx_stack.State(knx_stack.state.Medium.usb_hid,associa...
a44730583b3c9692a08be0ac084bd947b6d75cd1
3,620,605
def _antialias_filter_image(data, oldstep, newstep, oldfmax=None, window="blackman"): """Apply an anti-aliasing prefilter to an image to prepare it for subsampling. Parameters ---------- data : np.ndimage The 2D image to be filtered. oldstep: float or (float,...
f54a56ffd487bc1efa9e33d3de329c2c17d173cb
3,620,606
def post(name): """Prints a post.""" global config global dbh if name == "all": return index() elif name == "": return index(config.getint("blog", "default")) elif "\t" in name: (selector, term) = name.split("\t", 1) return search(term) c = dbh.cursor() c.execute("SELECT post_title, post_content FROM...
e97651ccda47ca638ee428553c6010f684d93c54
3,620,607
import pandas def read_csv(csv_path: PathLike) -> pandas.DataFrame: """ Read a csv file. Returns a DataFrame. """ csv_info = pandas.read_table( csv_path, sep=",", index_col=False, header=None, ).T csv_info.columns += 1 # Make the channel numbers correspond ...
0ca2d856efae3026998b461b0f7a0d6442bd3680
3,620,608
def c2t00a(tta, ttb, uta, utb, xp, yp): """ Form the celestial-to-terrestrial matrix given the date, the UT1 and the polar motion, using IAU 2000A nutation model. :param tta, ttb: TT as a two-part Julian date. :type tta, ttb: float :param uta, utb: UT1 as a two-part Julian date. :type uta, utb...
e174e6623eadb97d841d941b6efa97bd5ddc9f66
3,620,609
def center_of_mass(input, labels=None, index=None): """ Calculate the center of mass of the values of an array at labels. Args: input (cupy.ndarray): Data from which to calculate center-of-mass. The masses can either be positive or negative. labels (cupy.ndarray, optional): Labe...
2af2c745accf40e1c65909bdd88f983e4f8dd448
3,620,610
def encodewrap(s): """改行コードを\nに置換する。""" r = [] if not s: return u"" for c in s: if c == '\\': r.append("\\\\") elif c == '\n': r.append("\\n") elif c == '\r': pass else: r.append(c) return "".join(r)
a3486f3340d898751371fb4d4e29876120ec280b
3,620,611
def initialize_new_task_list(user_info, all_tasks): """ initializes new task and user from POST request """ new_user = User(**user_info) new_user.save() user_id = new_user.id for task in all_tasks.values(): task['user_id'] = user_id new_task = Task(**task) new_task.sa...
850c2c0fd0a540249566b554d262ac377d548341
3,620,612
def load_labels(label_path, label_interest): """ Loads the label table. Parameters ---------- label_path: string, path to label csv table label_interest: string, name of variable to predict. Has to be in the table loaded by the parameter label_path. Returns ----...
d70e024bd1671330944ddab982facc02fa0d7be6
3,620,613
from typing import Tuple from typing import Optional from typing import Sequence from typing import Union def clonotype_modularity( adata, ax=None, target_col="clonotype_modularity", jitter: float = 0.01, panel_size: Tuple[float, float] = (6, 4), base_size: float = 2, size_power: Optional[...
83ea2453bb0b773129858bbb48fc8a6545f4a09e
3,620,614
def gen_plot_4(fig, x_recon_l,x_recon_r,inputs_l,inputs_r ): """Create a pyplot plot and save to buffer.""" ax1 = get_ax(x_recon_l, fig, subplot='141', az=0) plot_skeleton_and_scatter(x_recon_l, ax1) ax2 = get_ax(inputs_l, fig, subplot='142', az=0) plot_skeleton_and_scatter(inputs_l, ax2) ax3 = ...
02ee41334db4142ed0144fa28dd711246234d289
3,620,615
def is_lone_coo(where): """Check if ``where`` has been specified as a single coordinate triplet. """ return (len(where) == 3) and (isinstance(where[0], Integral))
83e258e21fbac34010699f18ee2f510ba31e1f99
3,620,616
import time def get_tzoffset(): """ 取得時區差異秒數 (在臺灣會取得負值: -28800) """ global _tzoffset, _tzoffset_last_update current_time = time.time() if (current_time - _tzoffset_last_update) > 3600: _tzoffset_last_update = current_time _tzoffset = time.altzone if _tzoffset is None: _tzoffset = time.timezone if _t...
a8ed92007c400c6599ef863ad95594c0b7bd6247
3,620,617
def build_metrics(config): """pytorch_lightning metrics""" metrics = {} if config.trainer.metrics is not None: for name, cfg in config.trainer.metrics.items(): metrics[name] = build_from_config(cfg, METRICS) return edict(metrics)
1fef4f90a49194ad632607782aec68a59ab59dca
3,620,618
def kde_scipy(x, x_grid, bandwidth=0.2, **kwargs): #x_grid = np.linspace(-4.5, 3.5, 1000) """Kernel Density Estimation with Scipy""" # Note that scipy weights its bandwidth by the covariance of the # input data. To make the results comparable to the other methods, # we divide the bandwidth by the s...
aa8a1a5fc538f09668b69d35ebcde4d756bf79b6
3,620,619
def gini(x): """Calculate the Gini coefficient for series of observed values (x). where: * x is the array of observed values (and all x are positive, non-zero values) Note: x must be a numpy array or a pandas series See: https://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm ...
352c4fa44529a43bdd9862e7949b1103e7969f42
3,620,620
import requests def try_request(url, params=None, data=None, timeout=5, num_retries=1, method='post'): """ @params dict: 请求查询参数 @data dict: 提交表单数据 @timeout int: 超时时间,单位秒 @num_retries int: 超时重试次数 """ headers = {"User-Agent": "Mozilla/5.0 (X11; CentOS; Linux i686; rv:7.0.1406) Gecko/20100101...
508a9959cb05b50dd395f0a3d1050691b5479621
3,620,621
def qv_to_char(qv): """Convert a qv to a phred-encoded char.""" return chr(qv + CHAR_OFFSET)
83cc3c421ef3194b483e233b79e13607d622cf83
3,620,622
import urllib3 import json def get_public_urls(): """Get a list of available external tunnel URLs""" urls = [] try: http = urllib3.PoolManager() req = http.request('GET', 'http://localhost:4040/api/tunnels') data = str(req.data, 'utf-8') obj = json.loads(data) tunn...
d17e57cafe0833f35b4c5742a96901869dd8b7b1
3,620,623
def is_fragment(href): """Return True if href is a fragment else False""" is_fragment = False try: if href[0] == '#': is_fragment = True except IndexError: is_fragment = False return is_fragment
da1899ac1b59b8a6a42034a46194ff0d09a8799d
3,620,624
def adjacency_matrix(graph): """ :param graph: :return: dictionary Converts directed graph to an adjacency matrix. Note: The distance from a node to itself is 0 and distance from a node to an unconnected node is defined to be infinite. This does not mean that there is no path from a node to...
4e14880bdcec130a3cf4357f54609422142efa39
3,620,625
import os def query_shard(args): """Helper for request query from shard, same as shard[query]. Parameters --------- args : (list of (int, number), :class:`~gensim.interfaces.SimilarityABC`) Query and Shard instances Returns ------- :class:`numpy.ndarray` or :class:`scipy.sparse.c...
00e3233f7b2d204a93d45ebd26d22690e351b8e6
3,620,626
from typing import List def s_cat(inputfiles: List[str], outputfile: str, NumPort: int) -> str: """Concatenate 2 port s files into an n port s file Args: inputfiles (List[str]): List of files outputfile (str): Name of output file - optional NumPort (int): Number of ports - optional ...
9971afdde992c4b09dbda4185a2efd303e1802c0
3,620,627
import os def is_dir(path): """Is the path a directory""" return os.path.isdir(path)
3ea885ce332c37ba069a34a493d3fb07b4c6d976
3,620,628
def get_item_by_id(item_id): """ Return item by id :param item_id: :return object: """ return session.query(Catalog).filter_by(id=item_id).first()
ebdf9569414619d49d624652763df6d20a616dac
3,620,629
from typing import Callable def data_generator(X: np.ndarray, encoder_preprocessor: Callable, predictor: Callable, conditional_func: Callable, batch_size: int, shuffle: bool = True, **kwargs): """ ...
caf40a9358dc6dbb67389429081789a0aae1e06d
3,620,630
import re def generate_room_times(course_data: CourseData) -> dict: """ Generates data structure for getting the room availability. """ room_time = {} # iterate through all the courses for course in course_data.courses: # checks if room does not already have an entry if course....
ede287525b40dfc828494cb2375465177843f80d
3,620,631
def make_mlph_data(modified, h): """Creates features and target labels data with MLPH histogram computations. :param modified: Boolean value to indicate if modified MLPH is used :param h: Integer with window size for MLPH histogram computations :return: Training set features and target labels numpy mat...
69e76ca70f9fb4a044ff3ee3a1ea332acf6879be
3,620,632
from framework.auth import signals as auth_signals def add_poster_by_email(conference, message): """ :param Conference conference: :param ConferenceMessage message: """ # Fail if no attachments if not message.attachments: return send_mail( message.sender_email, ...
39f88e0126d174f237cb8620d86ea291113e2e14
3,620,633
def _remove_scheme(bucket_path): """Remove scheme from the bucket path.""" if '://' not in bucket_path: raise BuildManagerException('Invalid bucket path: ' + bucket_path) return bucket_path.split('://')[1]
7bc507acd8d0deccb95a705dc4863bb8bdedebae
3,620,634
import os def check_if_limits_executed(product, log_dir, quiet): """Function which checks if any of our two limit orders have executed since the last time this script was run. It checks by looking at the order ids in the file current_order_ids.txt, and comparing to the current active orders. If a...
ed9983bb6d8c39ef894a4b6097b009fa78b7ebdc
3,620,635
import os def gen_mask_array(icon_dir, dtype): """Generates a numpy array of an icon mask.""" icon = Image.open(os.path.join(icon_dir, 'icon.png')) mask = Image.new("RGBA", icon.size, (255, 255, 255, 255)) mask.paste(icon, icon) mask_array = np.array(mask, dtype=dtype) return mask_array
548a37a29435dbde527dbfbf8893b885f80230a4
3,620,636
import multiprocessing def run_sources_on_mesh(mesh, sources_list, processes=1): """ Run multiple sets of sources on the mesh, supports multiprocessing. :param mesh: Mesh to be used in calculations. :param sources_list: a LIST of LISTS of sources, like: [[mag1_1, mag1_2, mag1_3], [mag2_2, mag...
4a8cd6c4d776f611e4f84280dc00d35035d6ae11
3,620,637
def parse_xml_io(xml_io): """ Parses xml and get data for mapped_name key """ assert xml_io is not None port_names = [] for xml_cell in xml_io.findall("CELL"): mapped_name = xml_cell.get("mapped_name") # define properties for scalar pins scalar_mapped_pins = vec_to_scalar...
471aa357d8a9b791c0d053739df19c9b781a1f0f
3,620,638
def isposdef(A): """ Check if a matrix positive definite.""" if np.array_equal(A, A.T): try: np.linalg.cholesky(A) return True except np.linalg.LinAlgError: return False else: return False
270806133e06fbee16af3fdc689bedaf7f5e1af7
3,620,639
def read(stream): """Read a Scheme expression from a stream""" def read_ahead(token): if token == '(': expr = [] while True: token = stream.next_token() if token == ')': return expr else: expr...
ae1029023070f8e0b7d254b3b328cba4e54ecc74
3,620,640
def reset_initial_conditions(ClockStruct, InitCond, ParamStruct, weather): """ Function to reset initial model conditions for start of growing season (when running model over multiple seasons) *Arguments:*\n `ClockStruct` : `ClockStructClass` : model time paramaters `InitCond` : `InitCondCl...
3435c62de186f3c3564047089ffb5af942a976a0
3,620,641
import sys import os def _get_interpreters_relative(): """ Get interpreters relative to our prefix and the parent directory. This allows Pyzo to be shipped inside a pre-installed conda env. """ pythonname = "python" + ".exe" * sys.platform.startswith("win") exes = [] for d in [".", ".."]: ...
d7805900adce6dc092a921aef2b2912e4da896a8
3,620,642
def myocardialmass(myocardvol): """ Specific gravity of heart muscle (1.05 g/ml) """ return myocardvol*1.05
ca12a23a27a3dc2cb3df96abe4bfe94424125b14
3,620,643
def lineEdit(*args, editable:bool=True, transparentBackground:bool=True, borders=False, **kwargs): """ Generate a pre-customized QLineEdit Widget :param parent: Parent Index :param editable: Defines whether the line edit should be editable or not :param transparentBackground: Sets the style sheet to a ...
6332f303f57597c3124fc17c3549b9a7d9e90859
3,620,644
from re import T def sheva_nah_ending_tsere_hiriq_male(neg_idx, guess, guesses): """`sheva` before `tsere`, `hiriq-male` is `sheva-nah` This rule was emperically checked for the Pentateuch. """ pattern = [ {"vowel": T.NAME_SHEVA}, {"vowel": T.NAME_TSERE}, {"vowel": T.NAME_HIRI...
dd4c0a0b92da0afe0d9abb0d591409c715beb505
3,620,645
import time def train(gan, train_dataset, n_epochs, epochs_so_far=0, checkpoint_path=None): """Train the GAN model Args: gan (GAN): GAN model to train train_dataset (tf.data.Dataset): training dataset n_epochs (int): number of epochs to train epochs_so_far (int, optional): sta...
04c34d4d2b0a5c8473e680e03f1f1ba7101a20c0
3,620,646
def curvature(dem, res, kind, L=None): """ Calculate curvature for a digital terrain model. Parameters ---------- dem : ndarray Terrain elevation (m). res : float DEM resolution (m). kind : str Curvature calculation method. Allowed values are: - 'liston...
37e61a21831bc24dead3a16c50e1a56e3706523a
3,620,647
def parse_datasets(xml_str, tds_type): """ """ results = [] root = etree.fromstring(xml_str) ns_map = root.nsmap # check a ns_map for a key of None, i.e.default namespace and set to arbitray prefix so we can use xpath # Search for k of None, delete and set a random prefix to the original ns value for k...
4841393dce5e938e0f4a38723f7f385d7cc25966
3,620,648
async def challenge(websocket, user): """Challenges a user. """ return await websocket.send(f'|/challenge {user}, gen8metronomebattle')
bee53e79d085ebc7f8a48e0091adb2e6605a2ac6
3,620,649
def onset_to_hosp_or_asymp(clip_low=2, clip_high=21.1, mean=6.2, std=4.3): """ Returns the time for someone to either get removed or hospitalized in days within range(clip_low, clip_high), of a truncated_norm(mean, std). """ return sample_truncated_norm(clip_low, clip_high, mean, std)
7646651026363239a258c5ca88b5d261af1127a1
3,620,650
from .main.config import MachineType from .main.model import PicoFermSession, PicoBrewSession, iSpindelSession from .main.routes_frontend import initialize_data from .main.session_parser import restore_active_sessions, active_brew_sessions, active_ferm_sessions, active_iSpindel_sessions from .main import main as main_b...
7298622579c41b6b4e1b9941bdb4772c9e9e4d5c
3,620,651
def create_character_ngrams(text_list, length): """ Create character ngrams of the specified length from a string of text Args: text_list (list): Pre-tokenized text token to process. length (int): Length of ngrams to create. http://stackoverflow.com/questions/18658106/quick-implement...
5df4dda2fe83a921c3b949fa3e9e7e843c333530
3,620,652
def unscramble_wavefunction(wavefunction): """ the state ordering within the wavefunctions (complex numpy array) returned by cirq's simulate() function are not in standard sequential counting order (0, 1, 2), but are scrambled this function takes a wavefunction of arbitrary qubit legnth, an...
df797aa25ed1bb353cdf45627905b9b232870591
3,620,653
def fit_bonus_points( gameweek=NEXT_GAMEWEEK, season=CURRENT_SEASON, min_matches=10, dbsession=session ): """Calculate the average bonus points scored by each player for matches they play between 60 and 90 minutes, and matches they play between 30 and 59 minutes. Mean is calculated as sum of all bonus p...
a48cecb8eb0f77b474ac83523bb47d0921ab5e0b
3,620,654
import io def get_gt_SHT(gt_path, img_w, img_h, scaling=1., sigma=4): """ Retrieves and generates the GT density for the ShanghaiTech A/B dataset.""" mat = io.loadmat(gt_path) points = mat["image_info"][0, 0][0, 0][0] den = gen_scaled_den_from_points(img_w, img_h, points, scaling, sigma) return ...
7e0cf51572e3578520b7f1c5fac784bc751b11cb
3,620,655
from typing import Optional from typing import Tuple from typing import List def gen_output_mappings( outputs : int, inputs : int, active : int, rows : int = MAX_ROW_COUNT, columns : int = MAX_COLUMN_COUNT, base_off : int = 0, min_tgts : int = 1, max_tgts : int = 1, exclu...
bc4acfb296b78a1eb0a57751b4a42fe00d2bc7fe
3,620,656
def air2vacMortonIAU(wl_air): """Take an input air wavelength in Angstroms and return the vacuum wavelength. Formula taken from https://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion """ s = 1e4 / wl_air n = 1 + 0.00008336624212083 + (0.02408926869968 / (130.1065924522 - s**2))\ ...
66823170493c3b7d8f63bd7d2e32364aa5efa78e
3,620,657
import os def verify_path(file_name, folder): """Ensures folders for checkpoints and network parameters exists. :param file_name: Name of file. :param folder: Name of folder """ folder_path = os.path.join(os.getcwd(), folder) if not os.path.isdir(folder_path): os.makedirs(folder...
6f933651b25078873ac660cf655b113748bb418a
3,620,658
def get_vocabs(datasets): """Build vocabulary from an iterable of datasets objects Args: datasets: a list of dataset objects Returns: a set of all the words in the dataset """ print("Building vocab...") vocab_words = set() vocab_tags = set() for dataset in datasets: ...
05a11e1ed47887c05bdbbd1845074a5765d67701
3,620,659
def get_max_node(candidates, gr_values, column_prefix=""): """Given a set of candidate nodes, and return the one with the highest Gain Ratio. Args: candidates (list): List of candidate nodes. gr_values (dict): Dictionary with column names as keys and the corresponding Gain Rat...
5d64dad256784a932bcdc85265713d2b32c19c47
3,620,660
def tablefy(data, column=None, gutter=1, width=79): """ Convert a list of strings into being a table, displaying in a left-to-right and top-to-bottom pattern. This does not sort the values. :param data: list of strings :param column: width of column, if None, detected :param gutter: width of g...
d8aa63421578b9a0c4cb9c3fa106e7336de946d9
3,620,661
def stations_by_distance(stations, p): """This function uses haversine to calculate the distance between all the UK river monitoring stations and a given co-ordinate named in this function as p. We then return a list of the stations as instances of MonitoringStations and sort the list by the distances to th...
c6484e199333e1636f7ea4952d19a015e9e174d5
3,620,662
import functools def once(func): """ Decorate func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> func = once(lambda a: a+3) >>> func(3) 6 >>> func(9) ...
60e6c4a9e26b322c27da74ca98e119056247b900
3,620,663
import asyncio def pytest_pyfunc_call(pyfuncitem): """ Run asyncio marked test functions in an event loop instead of a normal function call. """ for marker_name, fixture_name in _markers_2_fixtures.items(): if marker_name in pyfuncitem.keywords: event_loop = pyfuncitem.funcargs...
b3d98cdd09abcd8e2325f972aa6e41d3279c942a
3,620,664
def contourAverage(inputC): """Function that approximate a contour by a line inside the contour. It realizes the mean of the lines of two points on a same column. If there is one point or strictly more than 2 points in a same column, the column is not considered and no mean is realized. ...
c6a27c39792bea00ae05978769f87d0d768421a2
3,620,665
def repeat(x, repeats, axis=None): """Repeat elements of an array. It returns an array which has the same shape as `x`, except along the given axis. The axis is used to speficy along which axis to repeat values. By default, use the flattened input array, and return a flat output array. The num...
094574bd3c01479cd2535e8d5990c9f2a7233287
3,620,666
import os def ptb_raw_data(data_path=None, vocab_path=None, args=None): """Load PTB raw data from data directory "data_path". Reads PTB text files, converts strings to integer ids, and performs mini-batching of the inputs. The PTB dataset comes from Tomas Mikolov's webpage: http://www.fit.vutbr.cz/~imi...
f3f0dc12a4b40007e5f08178256e2ee6358e184c
3,620,667
def format_search_filter(model_fields): """ Creates an LDAP search filter for the given set of model fields. """ ldap_fields = convert_model_fields_to_ldap_fields(model_fields) ldap_fields["objectClass"] = config.LDAP_AUTH_OBJECT_CLASS search_filters = import_func(config.LDAP_AUTH_FORMAT_SEA...
bceeefcd4dd00de5fcbd31b3bc72e7404f1b4ef9
3,620,668
def explore_match(win, img1, img2, kp_pairs, status = None, H = None, show=True): """ This function draws a set of keypoint pairs obtained on a match method of a descriptor on two images imgf and imgb :param win: window's name (str) :param img1: image1 (numpy array) :param img2: image2 (numpy ar...
85b77ec3aa325e1cb28cb6c33ec0ebb2457c99c7
3,620,669
def get_sorted_list_of_expr_not_in_use(path_to_db: str) -> list: """ Only expressions that are not in use can be deleted This list is used in the dropdown menu of expressions to be deleted Args: path_to_db: filename of the SQL database containing a JSON entry that returns a...
fb71b2fb69229f989e828e4cd8ed867ffaf81a38
3,620,670
def missing_query(*args, **kwags): """ A query returning something not in the local DB """ response = { 'responseHeader': {'params': {'rows': 1}}, 'response': { 'numFound': 1, 'docs': [{ 'id': 'abcde', 'chec...
c40ad0a6044bcaceee1b7431508a770f8fe21f61
3,620,671
def _element_basis(string: str): """ Parse element and basis from string Args: str Returns: element, basis """ cut_list = string.split(".") element = cut_list[0] basis = " ".join(cut_list[1:]) return element, basis
c6be1c2a05832bb3bbc4577015b541136c724a08
3,620,672
import json def loads(*args, **kwargs): # pragma: no cover (!CPython) # TODO """ Alias of :func:`json.loads`. """ return json.loads(*args, **kwargs)
0de0c84a7d6244058773d19a56d3ba7e64412f28
3,620,673
def calc_hist(img): """ To calculate histogram of an RGB image Parameters ---------- img : Array of uint8 Image whose histogram is to be calculated Returns ------- histogram : np.array The required histogram """ histogram = [0] * 3 for j in range(3): ...
084b3b7dc43caa06f400043d0116884abc6ad46c
3,620,674
def upper_bound(x): """Return the upper bound of interval x.""" "*** YOUR CODE HERE ***" return x[1]
e1e797d929c55ba18b098a22d242eb79a2db263f
3,620,675
def proportion_linear(time_right: float, time_between: float, time_step: float) -> tuple: """ :param time_right: right border in time :param time_between: time between borders :param time_step: step in time between borders :return: _Iterable_(alpha, beta) ...
a2841baf2b3022e2be7f47111e63f1f6eb9e76e2
3,620,676
import requests def getusercid(username): """ getusercid(string) -> string tries to retrieve the CID of an avatar for a name to cid lookup """ getuser = 'http://www.imvu.com/catalog/web_av_pic.php?av=%s' % (username) r = requests.get(getuser) link = r.url cid = link[link...
3f296e82191290646bef5e0c6e209f5d47b273f7
3,620,677
def channels(sound_object): """ DETERMINE IF A SOUND OBJECT IS MONO OR STEREO RETURN AN INTEGER REPRESENTING THE NUMBER OF CHANNELS (1, 2, 4, 6) CHANNEL 4 and 6 ARE NOT IMPLEMENTED YET (NEW FEATURE IN SDL 2.0) :param sound_object: numpy.ndarray; Sound samples into an array :return: int; return t...
b6b1635794fc9531e28c378cfdbb00b2c12d1561
3,620,678
def validate_request(): """ This method validates the Request payload. Args expected_args(tuple): where i = 0 is type and i > 0 is argument to be validated Returns f(*args, **kwargs) """ def real_validate_request(f): @wraps(f) def decorated(...
179c0c544982f899629c0cb46ff67f8ec7136086
3,620,679
def mr2rho(w,t,p): """rho = mr2rho(w,t,p) w in g/kg t in K p in mb This was provide by Holger Linne' from Max Planck Institute. Dave Turner Pacific Northwest National Laboratory Currently at the University of Wisconsin-Madison dave.turner@pnl.gov """ rho = w * (p * 0.3477) / t return rho
595cbb884a6824c7ec5fd28a1110a4dff1016417
3,620,680
def dir_to_cart(v, lattice): """ Convert direct coordinates to cartesian. Parameters ---------- v : ndarray | Dimension: (3) The direct vector to be converted. lattice : ndarray | Dimension: (3,3) The crystal lattice, where the first lattice vector is [...
c18094ff761fbdf3936fa4b1310aabfde19e579f
3,620,681
def parse_conf(stream, profile=PARSECONF_MID, encoding=None): """ Parse a .conf file. This is a wrapper around :func:`parse_conf_stream` that allows filenames or stream to be passed in. :param stream: the path to a configuration file or open file-like object to be parsed :type stream: str, file ...
959a25fe3cb3d9eb7ec22d226dfaa560e37f2945
3,620,682
def alpine2(x): """Alpine 2's function. It can be used with 'n' variables and has minimum at -2.808^n. Also, it is expected to be within [0, 10] bounds. Args: x (np.array): An n-dimensional input array. Returns: y = -prod(sqrt(x) * sin(x)) """ # Declaring Alpine 2's func...
49739cbe22a7c171cc5435cb0cd6a7027f6de850
3,620,683
def enum(*sequential, **named): """ Create enumeration-like classes, see: http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python A possibly better (yet heavier) recipe is here: http://code.activestate.com/recipes/67107/ """ enums = dict(zip(sequential, range(len(sequential)...
3c461298d05373f760186f507cf52223a6d4c60c
3,620,684
def get_block_time(): """ Returns block time Currently hardcoded """ return 0.25
80b0a035403384c7dbf17b7ee5971fe83cbe96cf
3,620,685
def ur5(): """Return a UR5 created programatically instead of from a file.""" return Robot('ur5', joints=[ Joint('shoulder_pan_joint', 'revolute', 'base_link', 'shoulder_link'), Joint('shoulder_lift_joint', 'revolute', 'shoulder_link', 'upper_arm_link')...
f47af1cec1b5aac9c8b3dda0c19a3622441f3c0e
3,620,686
import os import subprocess def get_rpm_packager(rpm_file_path): """ returns the rpm package PACKAGER tag """ fnull = open(os.devnull, 'w') return subprocess.Popen('rpm -qp --queryformat "%{PACKAGER}" ' + rpm_file_path, stdout=subprocess.PIPE, ...
08021fe2a525940b0af0eba7fa109d6e986a6d3e
3,620,687
def wav_format_code(encoding=None): """Calculate the format code for 'pcm16' encoded 'wav' files.""" if not encoding: encoding = 'pcm16' return construct_format('wav', encoding)
012b42e0f11ab139df713c968fd26443089c0d78
3,620,688
def detect_supported_hardware(): """Determine if UART for this Raspbery Pi is supported""" with open("/proc/device-tree/model", encoding="ascii") as file: model_string = file.readline().rstrip() for model in SUPPORTED_MODELS: if model in model_string: LOGGER.info("Detected suppo...
da55fc48cc60fd07e5bdb91b605f965ef1ca41a9
3,620,689
import torch def get_model_device(model: nn.Module) -> torch.device: """ The device the `model` is on (assuming that all the model parameters are on the same device). """ return get_next_parameter(model).device
7a72c79f593cb433d371acad5a358beff330de12
3,620,690
from pathlib import Path def write_file( mt_object, fn, file_type=None, longitude_format="lon", latlon_format="dms", overwrite=False, ): """ write a file based on extension or file type :param fn: DESCRIPTION :type fn: TYPE :param file_type: DESCRIPTION, defaults to None ...
a225d4d0b666f780a511403bf70abf6fe9ad3e20
3,620,691
def _create_asset_group_operation( client, customer_id, final_url, headline_asset_resource_names, description_asset_resource_names, ): """Creates a list of MutateOperations that create a new asset_group. A temporary ID will be assigned to this asset group so that it can be referenced by...
da09006e84aea150dbc0cbc6ee84f66d7a21f0bb
3,620,692
import random def test(links, walf): """test sample graph, take graph, return true/false """ node1 = random.choice(walf) node2 = random.choice(walf) print ("looking for path from", node1, "to node", node2) links = relink(links, walf) # find way using depth first search res1,...
6eded2e967370069d1adb5d62aafa93e9e969005
3,620,693
def reno(ghi, ghi_clearsky): """Identify times when GHI is consistent with clearsky conditions. Uses the function :py:func:`pvlib.clearsky.detect_clearsky`. .. note:: Must be given GHI data with regular (constant) time intervals of 15 minutes or less. Parameters ---------- ghi ...
04aa9c3f55c414dca35c12439b07df1ab13c1703
3,620,694
from cpyamf import amf0 from pyamf import amf0 from cpyamf import amf3 from pyamf import amf3 def get_decoder(encoding, *args, **kwargs): """ Returns a L{codec.Decoder} capable of decoding AMF[C{encoding}] streams. @raise ValueError: Unknown C{encoding}. """ def _get_decoder_class(): if e...
1737f660c68d41b7c5310fa2a4ccb409d8b7f318
3,620,695
def add(inputs_list): """ Add input tensors list Parameters ---------- inputs_list: Input tensors list """ return Add()(inputs_list)
6bf3b5a3416847e7dab084e7069974abf81b7236
3,620,696
def jars_from_output(output): """Collect jars for intellij-resolve-files from Java output.""" if output == None: return [] return [jar for jar in [output.class_jar, output.ijar, output.source_jar] if jar != None and not jar.is_source]
420736b5dfbec338c3323f39afc3088edf1833a9
3,620,697
from typing import Union def hz_warping( frequency: Union[float, np.ndarray], warp_factor: Union[float, np.ndarray], boundary_frequency_ratio: Union[float, np.ndarray], highest_frequency: float ): """Performs piece wise linear warping of frequencies in Hz. http://www.cs.toronto...
5f5b576845e202568f9ccb8a9d1d655847460e56
3,620,698
from unittest.mock import call def lint(): """get that linty fresh feeling""" return max( map( call, [ ["isort", "-rc", *ALL_PY], ["black", *ALL_PY], ["flake8", *ALL_PY], # ["pylint", *ALL_PY], ["m...
a1b0cd74d6ba8c167494e0ae85d9c9936e664a4f
3,620,699