content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def shimenreservoir_operation_rule_lower_limit(): """ Real Name: ShiMenReservoir Operation Rule Lower Limit Original Eqn: WITH LOOKUP ( Date, ([(1,190)-(366,250)],(1,240),(32,240),(152,220),(182,220),(244,225),(335,240),(365,\ 240) )) Units: m Limits: (None, None) Type: component """ r...
72830cd13bb411afe67398750f33c75a3a5bfba3
3,652,000
def pre_process(dd, df, dataset_len, batch_size): """Partition one dataframe to multiple small dataframes based on a given batch size.""" df = dd.str2ascii(df, dataset_len) prev_chunk_offset = 0 partitioned_dfs = [] while prev_chunk_offset < dataset_len: curr_chunk_offset = prev_chunk_offset...
a0a19916d60476430bdaf27f85f31620f2b5ae2a
3,652,001
from datetime import datetime import re def fromisoformat(s): """ Hacky way to recover a datetime from an isoformat() string Python 3.7 implements datetime.fromisoformat() which is the proper way There are many other 3rd party modules out there, but should be good enough for testing """ return...
7db362222f9da28f43eab5363336e0ca09b65960
3,652,002
def non_repeat(a, decimals=12): """ Функция возвращает матрицу А с различными строками. """ a = np.ascontiguousarray(a) a = np.around(a, decimals = int(decimals)) _, index = np.unique(a.view([('', a.dtype)]*a.shape[1]), return_index=True) index = sorted(index) return a[index]
312ce49fe275649c745ee22c79a08c0a2c1b798b
3,652,003
def softmax_with_cross_entropy(predictions, target_index): """ Computes softmax and cross-entropy loss for model predictions, including the gradient Arguments: predictions, np array, shape is either (N) or (batch_size, N) - classifier output target_index: np array of int, shape is (1...
9683da852dae92a5dec1f4353f4d93b2243fd30d
3,652,004
import re def scraper_main_olx(url): """ Reads pages with offers from OLX and provides URLS to said offers. """ def __create_url_olx(offs_ids, prefix="https://www.olx.pl"): """ Method creates an olx offer link from parts read from a main page. """ return [ "/".join([ ...
4f209dd800124c3b59db31029141e4d37f98e7d8
3,652,005
import sys def process_sha1(dataset_infos): """Computes the SHA-1 hash of the datasets. Removes the datasets for which the SHA-1 hash is already in the database. N.B.: a dataset for which the SHA-1 hash is not in the database represents a new dataset version. :param datasets_infos: A list of DatasetInfos ...
159d5b9b9a43c42b2b5c3fb5af2caa42728a6659
3,652,006
import torch from typing import Tuple from typing import List def accuracy( output: torch.Tensor, target: torch.tensor, topk: Tuple[int] = ( 1, )) -> List[float]: """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad...
73dd8a03e729fa89cea7abf535779dd45897113d
3,652,007
def _make_unique(key, val): """ Make a tuple of key, value that is guaranteed hashable and should be unique per value :param key: Key of tuple :param val: Value of tuple :return: Unique key tuple """ if type(val).__hash__ is None: val = str(val) return key, val
65d746276f635c129aa0a5aeb9b9f467453c0b2a
3,652,008
def replace_caps(x): """Replace all Capitalized tokens in `x` by their lower version and add `TK_MAJ` before.""" res = [] for t in x: if t == '': continue if t[0].isupper(): if len(t) == 1 and t[0] == 'I': res.append(TK_MAJ) if len(t) > 1 and (t[1:].is...
72519c264a97b60b05d430fc86dce1069e3718a7
3,652,009
def computes_ts_coverage(k, outputs, two_symbols): """ Computes the input coverage by Two Symbol schematas. Args: k (int): the number of inputs. outpus (list): the list of transition outputs. two_symbols (list): The final list of Two Symbol permutable schematas. This is returned by `fin...
741718bb78ffc6840bb004eb80f096dc30d4df79
3,652,010
def create_measurements(nh, nv, offset, measurement_type): """Creates necessary measurement details for a given type on a given lattice. Given the lattice size, whether odd or even pairs are being measured, and the measurement type, this function returns a namedtuple with the pairs of qubits to be meas...
ff4dbe1ee49a0db41c30fc9ba8fc6ab94c314c48
3,652,011
def headline( in_string, surround = False, width = 72, nr_spaces = 2, spacesym = ' ', char = '=', border = None, uppercase = True, ): """return in_string capitalized, spaced and sandwiched: ============================== T E S T...
1848d91bbf6c9d2216338f35433a26bcd3854664
3,652,012
import itertools import unicodedata def rainbow_cmd(bot, trigger): """Make text colored. Options are "rainbow", "usa", "commie", and "spooky".""" text = clean(trigger.group(2) or '') scheme = trigger.group(1).lower() if not text: try: msg = SCHEME_ERRORS[scheme] except Key...
292e55511b40c3c265e7ba87164cf179e54c16a6
3,652,013
def url_decode(s, charset='utf-8', decode_keys=False, include_empty=True, errors='ignore', separator='&', cls=None): """Parse a querystring and return it as :class:`MultiDict`. Per default only values are decoded into unicode strings. If `decode_keys` is set to `True` the same will happen f...
2b5b9598639ef600900dd1cb50c8ec6de892feff
3,652,014
from typing import Type def special_loader(as_type: type) -> Type[FullLoader]: """Construct new loader class supporting current class structure""" class TypedLoader(FullLoader): # pylint: disable=too-many-ancestors """Custom loader with typed resolver""" ... _add_path_resolvers(as_type,...
e60c96284334fc57cc32af557a86433bb5302526
3,652,015
def try_(func, *args, **kwargs): """Try to call a function and return `_default` if it fails Note: be careful that in order to have a fallback, you can supply the keyword argument `_default`. If you supply anything other than a keyword arg, it will result in it being passed to the wrapped function a...
206b25bd2e345d9cd6423e2cbc2706c274f36c89
3,652,016
def _create_course_and_cohort_with_user_role(course_is_cohorted, user, role_name): """ Creates a course with the value of `course_is_cohorted`, plus `always_cohort_inline_discussions` set to True (which is no longer the default value). Then 1) enrolls the user in that course, 2) creates a cohort that th...
6f55d10d4b1dfa27c067298862e89a558c5618a1
3,652,017
def relative_vorticity( u, v, wrap=None, one_sided_at_boundary=False, radius=6371229.0, cyclic=None ): """Calculate the relative vorticity using centred finite differences. The relative vorticity of wind defined on a Cartesian domain (such as a plane projection) is defined as ζcartesian = δv...
6134a44594cd84174f44f00a57df2f7284c4a7e5
3,652,018
import torch_geometric import torch def coalesce( edge_index: torch.Tensor, edge_attr: _typing.Union[ torch.Tensor, _typing.Iterable[torch.Tensor], None ] = None, num_nodes: _typing.Optional[int] = ..., is_sorted: bool = False, sort_by_row: bool = True ) -> ...
00006971c06fc599edb6b3ff12b2e0a7700dd136
3,652,019
def get_label_names(l_json): """ Get names of all the labels in given json :param l_json: list of labels jsons :type l_json: list :returns: list of labels names :rtype: list """ llist = [] for j in l_json: llist.append(j['name']) return llist
bab12bedc8b5001b94d6c5f02264b1ebf4ab0e99
3,652,020
from ...niworkflows.engine.workflows import LiterateWorkflow as Workflow from ...niworkflows.interfaces.utility import KeySelect from ...smriprep.workflows.outputs import _bids_relative from ...niworkflows.interfaces.space import SpaceDataSource def init_asl_derivatives_wf( bids_root, metadata, output_dir...
c5a5425dd38fd1b451b41a687a44c8edbb3d24b0
3,652,021
def makehash(w=dict): """autovivification like hash in perl http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python use call it on hash like h = makehash() then directly h[1][2]= 3 useful ONLY for a 2 level hash """ # return defaultdict(m...
5c772c07de9231c40053b29c545e25b611dd3b6e
3,652,022
def sample_parameters(kmodel, tmodel, individual, param_sampler, scaling_parameters, only_stable=True, ): """ Run sampling on first order model """ solution_raw = individu...
cc48f170c58c090844dbbf0e72aa2bc9f2a1598b
3,652,023
import yaml def load_yaml(fpath): """ load settings from a yaml file and return them as a dictionary """ with open(fpath, 'r') as f: settings = yaml.load(f) return settings
bd9c19407c39e190f2d7fd734d118dbb4e9378ab
3,652,024
import statistics def recommendation(agent, other_agent, resource_id, scale, logger, discovery, recency_limit): """ Get recommendations on other agent of third agents and average them to one recommendation value. :param agent: The agent which calculates the popularity. :type agent: str :param oth...
0670ec3d388dc008f2c5315907fac11f80aa7ebe
3,652,025
import time import numpy import pandas import numpy.testing import mhctools def do_predictions_mhctools(work_item_dicts, constant_data=None): """ Each tuple of work items consists of: (work_item_num, peptides, alleles) """ # This may run on the cluster in a way that misses all top level imports...
c42270f3b31b984973e9e668902ac2018f38b25f
3,652,026
def inceptionresnetv2(**kwargs): """ InceptionResNetV2 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for mod...
7c11c147d01b6551fa1b65cb5d24497efc2a3d3b
3,652,027
import sys def convertStringToSysEncoding(strng): """ Convert a string to the current platform file system encoding. Returns the new encoded string. :Args: strng: string String to convert. """ if type(strng) not in [bytes_t, unicode_t]: strng = strng.decode("utf...
e7287b32577bdb0f832352e073982d1b074f1b07
3,652,028
def _n_pow_i(a, b, n): """ return (1+i)**k """ x = a y = b for i in range(1, n): x1 = (x*a) - (y*b) y1 = (y*a) + (x*b) x = x1 y = y1 return x, y
35b00c7bc76aaf19a5acdf012e63c9c0c50e5d1d
3,652,029
def IsNameBased(link): """Finds whether the link is name based or not :param str link: :return: True if link is name-based; otherwise, False. :rtype: boolean """ if not link: return False # trimming the leading "/" if link.startswith("/") and len(link) > 1: lin...
e887fd6cd02c7ef71cbafa825014e1fca2c9d4d1
3,652,030
def register_submit(class_name, fire) -> None: """ Register on a form a handler :param class_name: class name of the form :param fire: function that will be fire on form submit :return: None """ def submit_handler(event) -> None: """ Handle form submit and fire handler ...
f2f8b2b067a282b073d6cc13825aedc3509c8077
3,652,031
from typing import Any def compile(obj: Any) -> Definition: """Extract a definition from a JSON-like object representation.""" return ConcreteValue(obj)
5e82471be599e77739e485468571bee296bfca71
3,652,032
def policy_network(vocab_embed_variable, document_placeholder, label_placeholder): """Build the policy core network. Args: vocab_embed_variable: [vocab_size, FLAGS.wordembed_size], embeddings without PAD and UNK document_placeholder: [None,(FLAGS.max_doc_length + FLAGS.max_title_length + FLAGS.max_image...
d59cf6d1d99fca7c654087d8fc720b64e419bced
3,652,033
def get_feature(file_path: str): """ Read and parse given feature file""" print('Reading feature file ', file_path) file_obj = open(file_path, "r") steam = file_obj.read() parser = Parser() return parser.parse(TokenScanner(steam))
e30e78afdb205aa2c26e3831ca7b0091579866a3
3,652,034
def hough_lines_draw(img, outfile, peaks, rhos, thetas): """ Returns the image with hough lines drawn. Args - img: Image on which lines will be drawn - outfile: The output file. The file will be saved. - peaks: peaks returned by hough_peaks - rhos: array of rhos used in Hough Sp...
f1731adb7d90a69dc50721c03f9e2ab01b7e2078
3,652,035
def cg_file_h(tmpdir): """Get render config.""" return { 'cg_file': str(tmpdir.join('muti_layer_test.hip')) }
caedb2324953e4ca90ebffdf80be60fed1b8026d
3,652,036
from ._groupbyuntil import group_by_until_ from typing import Optional from typing import Callable from typing import Any def group_by_until( key_mapper: Mapper[_T, _TKey], element_mapper: Optional[Mapper[_T, _TValue]], duration_mapper: Callable[[GroupedObservable[_TKey, _TValue]], Observable[Any]], s...
c4f54140dadbd0d043400a35f9be9f978460ae3c
3,652,037
def GetFilesystemSize(options, image_type, layout_filename, num): """Returns the filesystem size of a given partition for a given layout type. If no filesystem size is specified, returns the partition size. Args: options: Flags passed to the script image_type: Type of image eg base/test/dev/factory_inst...
1ea542366a11f9a00b648b5158282a4b5e39f633
3,652,038
def match_pairs(obj_match, params): """ Matches objects into pairs given a disparity matrix and removes bad matches. Bad matches have a disparity greater than the maximum threshold. """ # Create a list of sets, where the i-th set will store the objects # from image1 that have merged with objects in...
42939faca3cc2a61e8dde1b00818da593aa89c7a
3,652,039
def spike_train_convolution(spike_times, interval, dt, sigma): """ Needed for Schreiber reliability measure """ N = int(np.floor((interval[1]-interval[0])/dt)+1) x = np.linspace(interval[0], interval[1], N) s = np.zeros(N) for spike in spike_times: s = s + gaussian(x, spike, sigma) ...
0dbd2ac6a3cc016ecb0ab7209256d1544b6acfd1
3,652,040
import os def touch(file): """ update a file's access/modifications times Attempts to update the access/modifications times on a file. If the file does not exist, it will be created. This utility call operates in the same fashion as the ``touch`` system command. An example when using in the ...
0e37f6e1924dc06a05ad54b9412ef6210a4f7feb
3,652,041
def interpolate_peak(spectrum: list, peak: int) -> float: """ Uses quadratic interpolation of spectral peaks to get a better estimate of the peak. Args: - spectrum: the frequency bin to analyze. - peak: the location of the estimated peak in the spectrum list. Based off: htt...
0e74057908e7839438325da9adafdf385012ce17
3,652,042
def _check_trunk_switchport( dut, check, expd_status: SwitchportTrunkExpectation, msrd_status: dict ) -> tr.CheckResultsCollection: """ This function validates a trunk switchport against the expected values. These checks include matching on the native-vlan and trunk-allowed-vlans. """ results =...
a739ae5897c4627ea78d27a07f831e528318f052
3,652,043
def is_valid_compressed(file): """Check tar gz or zip is valid.""" try: archive = ZipFile(file, 'r') try: corrupt = archive.testzip() except zlib_error: corrupt = True archive.close() except BadZipfile: corrupt = True return not corrupt
261a4fcdfa1117aa749b00805e323f21a04d0f57
3,652,044
def Krsol_SP_pt(SP,pt): """ Krsol_SP_pt solubility of Kr in seawater ========================================================================== USAGE: Krsol = sol.Krsol_SP_pt(SP,pt) DESCRIPTION: Calculates the krypton, Kr, concentration expected at equil...
3402fdf5756ca9a54938211e67a57de1326bcc7f
3,652,045
def get_node_element(tree_element, tag, key=None): """ FIXME: This is an ugly function that should be refactored. It wqs written to create the same function for getting either an attribute or a subelement for an element. :param tree_element: Element object from the ElementTree package :param tag:...
2fdd641575a9928aa53389a9bf644698b97cbee8
3,652,046
def find_title(item): """Title of the video""" title = item['snippet']['title'] return title
9c6f64e02d959d46cfd1e4536f5faf7ec0c281bd
3,652,047
import hashlib def calc_fingerprint(text): """Return a hex string that fingerprints `text`.""" return hashlib.sha1(text).hexdigest()
8be154e4e32ae9412a73e73397f0e0198ae9c862
3,652,048
from typing import List from typing import Any from typing import Tuple import torch def yolo_collate_fn( batch: List[Any], ) -> Tuple[Tensor, Tuple[Tensor, Tensor, List[Tuple[Tensor, Tensor]]]]: """ Collate function to be used for creating a DataLoader with values for Yolo model input. :param ba...
599d4e9bbb91cf6d79225024cbcd9690cb55f8e6
3,652,049
def delete_category(category_id): """Delete a category.""" category = session.query(Category).filter_by(id=category_id).first() if 'username' not in login_session: flash("Please log in to continue.") return redirect(url_for('login')) if not exists_category(category_id): flash(...
979aabe5b6d7730c9f75a714266d6aad61e1cd41
3,652,050
from typing import List def get_all_users_of(fx_module: GraphModule, index: int) -> List[int]: """Given the graph(fx_module) and an index, return a list of all node indexes that use this node""" graph = fx_module.graph current_node = graph.nodes[index] user_indexes: List[int] = [] """if the node A...
e3fc32aa7baf549bbfe4a2fb7558aa7bfb3d84b0
3,652,051
from operator import and_ def insert_from( table_name, into_table_name, column_names=None, join_columns=None, create_if_not_exists=False, engine=None ): """ Inserts records from one table into another :param table_name: the name of the table from which to insert records :param into_table_name: th...
8c013bdaeb1c16e1a487c4a90c0554e9b673f4d9
3,652,052
def format(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: _fo...
bd526cab85bd8909904af0c6e32b22d29c1de561
3,652,053
def array_to_mincvolume(filename, array, like, volumeType=None, dtype=None, labels=None, write=True, close=False): """ Create a mincVolume from a data array. Create a mincVolume from a data array, using coordinate system information from another volume. ...
16074668c1143091322969a501b23203378ca169
3,652,054
import random def getRandomPipe(): """returns a randomly generated pipe""" # y of gap between upper and lower pipe gapY = random.randrange(0, int(BASEY * 0.6 - PIPEGAPSIZE)) gapY += int(BASEY * 0.2) pipeHeight = IMAGES['pipe'][0].get_height() pipeX = SCREENWIDTH + 10 return [ {'x'...
a5789a090ff7ab88b5cf6cbf4ad8e0943ea9ccdf
3,652,055
from typing import Optional def get_spot_market_price(facility: Optional[str] = None, plan: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetSpotMarketPriceResult: """ Use this data source to get Packet Spot Market Price. ...
912f07ced8a12ba4df7992c8cbba2576673a893f
3,652,056
def _get_cluster_id(emr: boto3.client("emr"), clusterName: str) -> str: """ Returns the id of a running cluster with given cluster name. """ clusters = emr.list_clusters()["Clusters"] # choose the correct cluster clusters = [c for c in clusters if c["Name"] == clusterName and c["Status"]["State...
9fba31d05157411d8fddde7502e174433859898f
3,652,057
def seed_student(request, i): """Returns the properties for a new student entity. """ gsoc2009 = Program.get_by_key_name('google/gsoc2009') user = User.get_by_key_name('user_%d' % i) if not gsoc2009: raise Error('Run seed_db first') if not user: raise Error('Run seed_many for at least %d ...
01f1923b4d1e5af74c6bbad2649f04be62f29c6f
3,652,058
from typing import List def apply(effect: List[float], signal: List[float]): """Given effect interpolated to length of given signal. Args: effect: effect to interpolate to signal length. signal: length of which effect is interpolated to. """ max_len = max(len(effect), len(signal)) ...
11bd4938c997cbef445493274fa3ee7447f1821e
3,652,059
def cli_cosmosdb_sql_trigger_update(client, resource_group_name, account_name, database_name, container_name, trigger_name, ...
bee6e060aecde084c9690eaeb316bdac7ae12b31
3,652,060
from typing import List def evaluate_features(features: np.ndarray, labels: np.ndarray, train_frac: float = 0.8) -> List[int]: """ Evaluates the marginal impact of each feature in the given array (by retraining). Args: features: A [N, T, D] array of input features for each sequence element ...
88b9d7cab4723934f16ab59c43e41d5a4140daa5
3,652,061
import six def pad_for_tpu(shapes_dict, hparams, max_length): """Pads unknown features' dimensions for TPU.""" padded_shapes = {} def get_filler(specified_max_length): if not specified_max_length: return max_length return min(specified_max_length, max_length) inputs_none_filler = get_filler(hp...
b72e1463fad9740c8a265b795c4b3c5a45e42a9a
3,652,062
from typing import Union from typing import Tuple from typing import List def _get_child_query_node_and_out_name( ast: Union[FieldNode, InlineFragmentNode], child_type_name: str, child_field_name: str, name_assigner: IntermediateOutNameAssigner, ) -> Tuple[SubQueryNode, str]: """Create a query nod...
c99e2a1aa7ea56600203e1550dca6a0a59eed094
3,652,063
def has_balanced_parens(exp: str) -> bool: """ Checks if the parentheses in the given expression `exp` are balanced, that is, if each opening parenthesis is matched by a corresponding closing parenthesis. **Example:** :: >>> has_balanced_parens("(((a * b) + c)") False :par...
f76c7cafcf6aadd0c2cb947f0c49d23835a9f6e4
3,652,064
def _is_binary(c): """Ensures character is a binary digit.""" return c in '01'
b763a5a8ba591b100fea64a589dcb0aea9fbcf53
3,652,065
import os import re def get_interface_ib_name(hosts, interface, verbose=True): """Get the InfiniBand name of this network interface on each host. Args: hosts (NodeSet): hosts on which to detect the InfiniBand name interface (str): interface for which to obtain the InfiniBand name verb...
41aa431fda790ddfe427363163107f50d60f20e0
3,652,066
import os import sys def _get_script(args_file): """compiled contents of script or error out""" DEFAULT_SCRIPT = 'build.jfdi' script_path = None if args_file != None: script_path = args_file elif os.path.exists(DEFAULT_SCRIPT): script_path = DEFAULT_SCRIPT script_path...
26defa7db2166cb379575463e8e1e2dddae8b6b1
3,652,067
from ml import cv import logging from pathlib import Path import sys def render(img, result, classes=None, score_thr=None, show=True, wait_time=0, path=None): """Visualize the detection on the image and optionally save to a file. Args: ...
4c8cbc005cca4e41bd74eb13cc973fe40186e83e
3,652,068
import logging import pkgutil def check_python_import(package_or_module): """ Checks if a python package or module is importable. Arguments: package_or_module -- the package or module name to check Returns: True or False """ logger = logging.getLogger(__name__) logger.deb...
e6371d3bcb08efed2dfbdbfc1b4d30409e0f10ba
3,652,069
def read_frame_positions(lmp_trj): """ Read stream positions in trajectory file corresponding to time-step and atom-data. """ ts_pos, data_pos = [], [] with open(lmp_trj, 'r') as fid: while True: line = fid.readline() if not line: break ...
c168f08577e38758bf3d9d42bae8379125d7fc33
3,652,070
async def async_setup_entry(hass, config_entry): """Set up Enedis as config entry.""" hass.data.setdefault(DOMAIN, {}) pdl = config_entry.data.get(CONF_PDL) token = config_entry.data.get(CONF_TOKEN) session = async_create_clientsession(hass) enedis = EnedisGateway(pdl=pdl, token=token, session=...
93ee0360c509088b75935f6b94bf7d918658e86b
3,652,071
import requests def get_file_list(prefix): """ Get file list from http prefix """ print("Fetching file list from", prefix) k = requests.get(prefix) if not k.ok: raise Exception("Unable to get http directory listing") parser = HRefParser() parser.feed(k.content.decode()) k.clos...
ca559a20e6f35f31a07e25f7f2a9dbc5db450cc0
3,652,072
def train_model(model: nn.Module, trainDataLoader: DataLoader, testDataLoader: DataLoader, epochs: int, optimizer, lossFuction, metric, device) -> dict: """ Training model function: it will train the model for a number of epochs, with the corresponding optimizer. It will return the corresponding losses an...
bd971d4d5063ad83188e3093f46a6dba86ac995b
3,652,073
import builtins def _has_profile(): """Check whether we have kernprof & kernprof has given us global 'profile' object.""" return kernprof is not None and hasattr(builtins, 'profile')
3cbb4a0539efbadcea22e2d39ee520e14d7c6da3
3,652,074
import requests import re def get_video_info(url): """ adapted from https://www.thepythoncode.com/article/get-youtube-data-python Function takes a YouTube URL and extracts the different parts of the video: title, view number, description, date-published, likes, dislikes, channel name, cha...
40e11098b49d676e6b17ca0cc0a6770ab83a996f
3,652,075
from typing import OrderedDict def routing_tree_to_tables(routes, net_keys): """Convert a set of :py:class:`~rig.place_and_route.routing_tree.RoutingTree` s into a per-chip set of routing tables. .. warning:: A :py:exc:`rig.routing_table.MultisourceRouteError` will be raised if entrie...
50384fa0f834f6311cea3b2901b6723ca3fab3c7
3,652,076
def extract_response_objects(image_file, mask_file, stim_file, input_dict): """inputs are file names for aligned images, binary mask, and unprocessed stimulus file outputs a list of response objects""" # read files I = read_tifs(image_file) mask = read_tifs(mask_file) labels = segment_ROIs(mask) ...
95b7a5e831d9ab0703c51d41966b36babf52b24d
3,652,077
import torch def get_top_diff_loc(imgs, ref_imgs, crop_size, grid_size, device, topk=10): """Randomly get a crop bounding box.""" assert imgs.shape == ref_imgs.shape batches = imgs.size(0) img_size = imgs.shape[2:] crop_size = _pair(crop_size) grid_size = _pair(grid_size) stride_h = (img_s...
2e35cc56a484432dd1c1ef05f38e01079414eecb
3,652,078
import json def decode(file): """ This function creates a dictionnary out of a given file thanks to pre-existing json functions. :param file: The file to decode. :return: The corresponding Python dictionnary or None if something went wrong (i.e: the given file \ is invalid). """ # J...
bfd0671f9e6bb06faa02a3179c1a5e18a607882c
3,652,079
def kron_compact(x): """Calculate the unique terms of the Kronecker product x ⊗ x. Parameters ---------- x : (n,) or (n,k) ndarray If two-dimensional, the product is computed column-wise (Khatri-Rao). Returns ------- x ⊗ x : (n(n+1)/2,) or (n(n+1)/2,k) ndarray The "compact"...
55c2c89fa7eb9f7c2c1a3a296798b022c158c399
3,652,080
def record_speech_sequentially(min_sound_lvl=0.01, speech_timeout_secs=1.): """Records audio in sequential audio files. Args: min_sound_lvl: The minimum sound level as measured by root mean square speech_timeout_secs: Timeout of audio after that duration of silence as measured by min_sound_lvl ...
f726f90575cf49a7de0608473f16a12f2a80d3cf
3,652,081
def home(): """ Display Hello World in a local-host website """ return 'Hello World'
f65a035d679878cfd897c9ea9c79fc41cf76db95
3,652,082
def build_cinder(args): """Build the cinder client object.""" (os_username, os_password, os_user_domain_name, os_auth_url, os_auth_type, os_region_name, os_project_name, os_project_id, os_project_domain_name, os_project_domain_id, os_region_name, os_user_domain_...
ca5ec1cc864524f39d2913b8f9b4c7c8bb0e8306
3,652,083
def selecaoEscalar(Mcorr, criterios, N=0, a1=0.5, a2=0.5): """ Performs a scalar feature selection which orders all features individually, from the best to the worst to separate the classes. INPUTS - Mcorr: Correlation matrix of all features. - criterios: - N: Number of best features to be returned. - a1: Weig...
713a7c8543cefdef8f4a35dd970d326fb49229a1
3,652,084
def sum_by_letter(list_of_dicts, letter): """ :param list_of_dicts: A list of dictionaries. :param letter: A value of the letter keyed by 'letter'. """ total = 0 for d in list_of_dicts: if d['letter'] == letter: total += d['number'] return total
bffc5990eaa9e352d60d86d40b8a8b7070fd00c0
3,652,085
def gate_settle(gate): """ Return gate settle times """ return 0
f452a343550c4f7be2133119c89dc386665921c4
3,652,086
import psutil import subprocess def parse_csr_domains(csr_pem=None, csr_pem_filepath=None, submitted_domain_names=None): """ checks found names against `submitted_domain_names` This routine will use crypto/certbot if available. If not, openssl is used via subprocesses `submitted_domain_names` sh...
b09fcc35d70c0f08641dceda4a0201fa8c94c7d8
3,652,087
def fov_gc(lons, lats): """Field of view great circle. Properties ---------- lons: [float] Field of view longitudes (degE). lats: [float] Field of view latitudes (degN). Return ------ geojson.Feature GeoJSON field of view polygon. """ return geo_polygon...
3013648c04e5626c51995288afd6e441d3afef30
3,652,088
import logging def return_covid_data() -> tuple[dict, dict]: """A function that acts as a getter method, allowing for functions in main to get the national and local COVID data and then display the values on the dashboard. Returns: tuple: (england_data, local_data). A tuple of two values (Eng...
723e93d4a878d5a9d8a28dd90cefe83bc2f00be4
3,652,089
import ietf.sync.rfceditor from ietf.doc.templatetags.mail_filters import std_level_prompt def request_publication(request, name): """Request publication by RFC Editor for a document which hasn't been through the IESG ballot process.""" class PublicationForm(forms.Form): subject = forms.CharField...
d6377b08c5eae6740e98a154d991ba268ed37815
3,652,090
def strip_trailing_characters(unstripped_string, tail): """ Strip the tail from a string. :param unstripped_string: The string to strip. Ex: "leading" :param tail: The trail to remove. Ex: "ing" :return: The stripped string. Ex: "lead" """ if unstripped_string.endswith(str(tail)): ...
dbd09fe9a58b0fb3072a680a9c7ac701257ebfcd
3,652,091
def is_prime(x): """ Prove if number is prime """ if x == 0 or x == 1: return 0 for i in range(2, x//2 +1): if x % i == 0: return 0 return 1
63980c49b9ea05458ecafe874073805df50ce1d0
3,652,092
import pickle def obj_to_str(obj, encoding='utf8') -> str: """ Examples: >>> d = dict(a=1, b=2) >>> assert isinstance(obj_to_str(d), str) """ b = pickle.dumps(obj) return bytes_to_str(b, encoding=encoding)
76c87052596aefcbd15a5135379ff2a3512bed77
3,652,093
from pathlib import Path from sys import path def deploy_sqlfiles(engine: Engine, directory: str, message: str, display_output: bool = False, scripting_variables: dict = None) -> bool: """Run every SQL script file found in given directory and print the executed file names. If any file in directory cannot be ...
e26fa2f77069b4bbd5415c7e6c6c2aa5f002839a
3,652,094
def sample_ellipsoid(p0, covmat, size=1): """ Produce an ellipsoid of walkers around an initial parameter value, according to a covariance matrix. :param p0: The initial parameter value. :param covmat: The covariance matrix. Must be symmetric-positive definite or it will raise the ...
a09448f29920a7758a549ede80608c8c4dd9892a
3,652,095
def avg_pool_2d(x, size=(2, 2), stride=(2, 2), name='avg_pooling', padding='VALID'): """ Average pooling 2D Wrapper :param x: (tf.tensor) The input to the layer (N,H,W,C). :param size: (tuple) This specifies the size of the filter as well as the stride. :param name: (string) Scope na...
b39dfed959f43346c48d13b7e41601999c1b7f8b
3,652,096
import logging def patch_base_handler(BaseHandler, log=None): """Patch HubAuthenticated into a base handler class so anything inheriting from BaseHandler uses Hub authentication. This works *even after* subclasses have imported and inherited from BaseHandler. .. versionadded: 1.5 Made availa...
132cc3151793e0c033cdf0506fe45b33ddcf2ad6
3,652,097
from django.contrib.auth import get_user_model def get_username_field() -> str: """Get custom username field. Returns: str: username field. """ user_model = get_user_model() return getattr(user_model, "USERNAME_FIELD", "username")
45dfe6888d8c69e012b98a0edd1b639b7bf56af7
3,652,098
def get_edited_file_name(): """ Gets the current open file in xcode """ script = ''' tell application "Xcode" set last_word_in_main_window to (word -1 of (get name of window 1)) set current_document to document 1 whose name ends with last_word_in_main_window set current_d...
f919f8475dd553a6b907df1d42f2c48b9d91b81d
3,652,099