content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests import json def get_table_count(url, table_id): """ Count the number of rowns in a ActivityTable :param url: :param table_id: The ActivityTable ID to update count from and return :return: count : count of rows from ActivityTable """ token = ActivitySites.objects.get(site_id...
d7243c202317f0302fb2515f09aa096f0c275619
3,639,100
def get_audio_mfcc_features(txt_files, wav_files, n_input, n_context, word_num_map, txt_labels=None): """ 提取音频数据的MFCC特征 :param txt_files: :param wav_files: :param n_input: :param n_context: :param word_num_map: :param txt_labels: :return: """ audio_features = [] audio_fea...
bed03fb10944d00e27af400776a8efc894770e46
3,639,101
def getOffsetsFromPixelFractions(col, row): """ Determine just the fractional part (the intra-pixel part) of the col,row position. For example, if (col, row) = (123.4, 987.6), then (colFrac, rowFrac) = (.4, .6). Function then returns the offset necessary for addressing the interleaved PRF ar...
4f5945f4e3e6e2dd71056b615dc3571f6ece42c6
3,639,102
def all_index(request): """ Inventory Index View """ # build changelist item_changelist = HTSChangeList(request, Item, list_filter=[], search_fields=[], list_per_page=200, model_admin=ItemAdmin(Item, None) ) context_dict = { 'item_changelist': item_ch...
7fdd0b5f278b55767a7918e2977315312e823e93
3,639,103
def calcSeason(ra, time): """Calculate the 'season' in the survey for a series of ra/dec/time values of an observation. Based only on the RA of the point on the sky, it calculates the 'season' based on when this point would be overhead. To convert to an integer season label, take np.floor of the returned ...
1309a302fac9d01d7b5567d5722bf8f04dc9b88e
3,639,104
def set_node_event_info(info: NodeEventInfo) -> Item: """Encaches an item. :param info: Node event information. :returns: Item to be cached. """ if info.event_type in ( EventType.MONIT_CONSENSUS_FINALITY_SIGNATURE, EventType.MONIT_BLOCK_FINALIZED, EventType.MONIT_BLOCK...
9ee50e73b1c50172ada1b6040b675cbda5aede44
3,639,105
def check_hashtarget(bible_hash, target): """ tests if the biblepay hash is valid for the hashtarget, means that is it lower. True = is lower and all is fine """ rs = False try: rs = int(bible_hash, 16) < int(target, 16) except: pass return rs
a0041d8834b2a0af0a08c2562ffed599925ed5a8
3,639,106
def assert_and_infer_cfg_fl(cfg_fl, args, make_immutable=True, train_mode=True): """ Calls /semantic-segmentation/config.assert_and_infer_cfg and adds additional assertions """ if args.manual_client_setup: cfg_fl.CLIENT.MANUAL = args.manual_client_setup if cfg_fl.CLIENT.MANUAL: prin...
b779e0a5f06d06b9ebc542f3cd7c190efb70bca5
3,639,107
def replace_service(name, metadata, spec, source, template, old_service, saltenv, namespace="default", **kwargs): """ Replaces an existing service with ...
e363ed9d9233ff6455963edba5bfa8109f6c7260
3,639,108
from typing import Optional from typing import Dict from typing import Any from typing import List from datetime import datetime import logging def timesketch_add_manual_event( data: Text, timestamp: Optional[int] = 0, date_string: Optional[Text] = '', timestamp_desc: Optional[Text] = '', attributes: ...
c84f04bbd3a9344c5797e6d79be141b05f6edae0
3,639,109
def filter_vcf_by_sex(vcf_file, data): """Post-filter a single sample VCF, handling sex chromosomes. Handles sex chromosomes and mitochondrial. Does not try to resolve called hets into potential homozygotes when converting diploid to haploid. Skips filtering on pooled samples, we still need to impleme...
6eb6528ce4deb86b8c8ecd8746143cb0f6c82fde
3,639,110
def gen_spacer(spacer_char="-", nl=2): """ Returns a spacer string with 60 of designated character, "-" is default It will generate two lines of 60 characters """ spacer = "" for i in range(nl): spacer += spacer_char * 60 spacer += "\n" return spacer
7434f191dafdf500c2fc3e67373afc664e543ce0
3,639,111
def repo_config_factory(repo_type, repo_id, repo_label, **kwargs): """ Constructs a repository configuration in form of a TTL structure utilizing the TTL templates from ./repo_types_template. """ # Check if the repo_type is a known template if repo_type not in REPO_TYPES: raise Repos...
3840d698691f226d56d25233c3fc00db23abd5d9
3,639,112
def oil_isothermal_density(rho: NDArrayOrFloat, p: NDArrayOrFloat) -> NDArrayOrFloat: """Calculates the oil density for a given pressure at 15.6 degC B&W 1992 Equation 18 Args: rho: The oil reference density (g/cc) at 15.6 degC can be compensated for disovled gases by running `oil_rho_...
f8184f4820b5a19525b47f357b92ea7059e2bd74
3,639,113
def get_waveform_dataset(path): """Loads the waveform dataset from a given path. Args: path: The path to the .npz file containing the waveform data set. Returns: An array of waveform chunks loaded from the given path. """ dataset = np.load(path)['arr_0'] return dataset
3d8e13cddd7abdb3bc459b68761e4a6385208c77
3,639,114
import logging def logger(filename: str, name: str) -> logging.Logger: """configure task logger """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(filename) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s: %(message)s') f...
60200abbd7a97204bf143694058ba87ff1ea7a2a
3,639,115
def verify_signature(pubkey_path, message, signature): """ Use Crypto.Signature.PKCS1_v1_5 to verify the signature on a message. Returns True for valid signature. """ log.debug("salt.crypt.verify_signature: Loading public key") pubkey = get_rsa_pub_key(pubkey_path) log.debug("salt.crypt.veri...
c0f6d9b36fd00eb7a17c656546bd685ccee97609
3,639,116
def untranslate_module_name(module): """Rename module names mention in JSON to names that we can import This reverses the translation applied by translate_module_name() to a module name available to the current version of Python. """ if PY3: # remap `__builtin__` and `exceptions` to the `b...
fae87c9fb852ff1b6b82e4ebccf9c058fb4a313f
3,639,117
def RGBRamp(size=256, upperValue=.6666666666666667): """Generate an RGB color ramp, values range from 0.0 to 1.0""" assert size > 0 hsv = HSVRamp(size, upperValue) rgb = Numeric.zeros( (hsv.shape[0], 3), viewerConst.FPRECISION ) for i in xrange(hsv.shape[0]): rgb[i] = ToRGB(hsv[i]) retu...
10be72b654ac9e36610bc4c08fd05edbba45de8a
3,639,118
def find_poly_ras_intersect(shape, raster_dir, extension='.tif'): """ Finds all the tiles falling within raster object the get shape geometry should be seperated from the intesect check, currently causes a exit code 139 on unix box :param polygon: :param extension: :param raster_dir: """ ...
8f7ae23a2c442ff5b61bde46d8b42ac4c2c8eade
3,639,119
from typing import Iterable import requests def Session( retries: int = 10, backoff_factor: float = 0.3, allowed_methods: Iterable[str] = ('HEAD', 'TRACE', 'GET', 'POST', 'PUT', 'OPTIONS', 'DELETE'), status_forcelist: Iterable[int] = (408, 429, 500, 502, 503, 504), ) -> requests.Session: """Return...
ca7d5f4d3f34e24c67eae47c01a6bd63796b03be
3,639,120
def tp53(): """Create a TP53 gene fixture.""" params = { 'label': 'tumor protein p53', 'concept_id': 'hgnc:11998', 'symbol': 'TP53', 'location_annotations': [], 'strand': None, 'locations': [ { '_id': 'ga4gh:VCL._Cl_XG2bfBUVG6uwi-jHtCHa...
d1c41af9dce6b5eee3aa475c207a669529001b7d
3,639,121
def factorOrder(factors, varOrder): """Return an order of factors for sampling given a variable order for sampling""" pri = [0 for x in varOrder] for i,x in enumerate(varOrder): # first, find position of each var in sampling order pri[x]=i factorOrder = [ Factor() for x in varOrder ] # fill order ...
98ec337ab126d77b854be28f937eef392b9c8144
3,639,122
def boundary_nodes(graph, nodes): # TODO: move to utils #TODO: use networkx boundary nodes directly: does the same thing """ returns nodes at boundary of G based on edge_boundary from networkx """ graph = unwrap_graph(graph) nodes = list(nodes) nbunch = list(unwrap_nodes(nodes)) # find boundary ...
e498b74ce3d36c3fc7f4ef0913fa470e2cfa12bc
3,639,123
def home(request): """ rendering ui by template for homepage this view never cache for delivering correct translation inside template """ template = loader.get_template('weather/home.html') return HttpResponse(template.render({}, request))
b2fdf6facd633441da9d11a53a781e9e418b42de
3,639,124
def plot_histogram(df, path, col_x, ax=None, size=None, save=True, suffix=None, show=False, **kwargs): """Geneate a histogram plot. Args: df (:class:`pandas.DataFrame`): Data frame to plot. path (str): Path to data frame to use if ``df`` is None, also used as ...
ec97358a9b7f8c3d20dd7a15d77b588fc2bffbe0
3,639,125
def __check_interface_state(duthost, interface, state='up'): """ Check interface status Args: duthost: DUT host object interface: Interface of DUT state: state of DUT's interface Returns: Bool value which confirm port state """ ports_down = duthost.interface_fac...
bc17d489064e9a81ec77dad5ab3682c9a96fa88d
3,639,126
def find_dateTime_in_html(text): """ find dateTime in html """ r = findall('<time dateTime="(.*?)">', text) if r: return r return []
0ba36b69a52f421e303da4c10b70362d6d724c96
3,639,127
import torch def get_number_of_voxels_per_class(labels: torch.Tensor) -> torch.Tensor: """ Computes the number of voxels for each class in a one-hot label map. :param labels: one-hot label map in shape Batches x Classes x Z x Y x X or Classes x Z x Y x X :return: A tensor of shape [Batches x Classes] ...
568a91639a42cf3cd3debe365c5a963512d95dfc
3,639,128
def get_columns_width(user_width): """define width of the report columns""" default_width = [30, 7, 60] if not user_width: return default_width try: return [7 if user_width[i] < 7 else user_width[i] for i in range(3)] except (TypeError, IndexError): _LOGGER.error( ...
96901c79ac7ba2cf6d5dc56fe26d63e81a2437d4
3,639,129
def tx_failure(): """ Failed ```tx```. """ message = request.args.get('m') protocol = request.args.get('p') address = request.args.get('a') command = request.args.get('c') repeats = request.args.get('r') bits = request.args.get('b') response = make_response( render_...
f5938cf59207125030502113ce3b541301279b98
3,639,130
import pydoc def read_docstring(object_): """ Returns object docstring without the FILE information. """ fmt = "```\n{}\n```\n" docs = pydoc.plain(pydoc.render_doc(object_)).split("FILE")[0].rstrip() return fmt.format(docs)
5c21f6eadf400ac9316e3f44d98464536b9b7536
3,639,131
def _bernoulli_spiral(theta, theta_offset=0., *args, **kwargs): """Return Equiangular (Bernoulli's) spiral Args: theta: array-like, angles from polar coordinates to be converted theta_offset: float, angle offset in radians (2*pi = 0) Kwargs: exp_scale: growth rate of the exponential """ exp_scal...
3e889bc61ab8e93daefc2feeaad40ae86c167627
3,639,132
import httpx import copy def _redacted_to_curl(request: httpx.Request) -> str: """Pass through to curlify2.to_curl that redacts the authorization in the headers """ if (auth_header := request.headers.get('authorization')) is None: return curlify2.to_curl(request) req_copy = copy.copy(request)...
e3a713c3fcf6c875af4cae6ab4c5e696eb0bd432
3,639,133
def get_norm(norm): """ Args: norm (str or callable): Returns: nn.Module or None: the normalization layer """ support_norm_type = ['BN', 'SyncBN', 'FrozenBN', 'GN', 'nnSyncBN'] assert norm in support_norm_type, 'Unknown norm type {}, support norm types are {}'.format( ...
299525099ecb38b171a8bcddd2661f943a1514ec
3,639,134
def parse_scales_line(line): """ Args: - line: Returns: - scales_dict """ def advance_past_token(str, token): return str[str.find(token) + len(token):] scales_dict = {} line = advance_past_token(line, 'Scales:') pair_str = line.split(',') for pair_str in pair_str: dname, scale = pair_str.split(':')...
b16e1f431b878aa6418beaed3f141fe928a229e1
3,639,135
import collections def parse_remove_configuration(configuration): """ Turns the configuration line of splitting into a name and a set of params. """ if configuration is None: return "None", None print('conf', configuration) conf_dict = collections.OrderedDict(configuration) name ...
40bf749c2e142cef534f945179b987fd3c7ba6d8
3,639,136
def _calc_cost_grad_first(data_input, w, label, features): """Calculate the partial cost and gradient.""" train_data = read_stage_file(data_input, features + [label]) size_train = train_data.shape[0] labels = train_data[label].values train_data = train_data[features].values if size_train > 0: ...
d7b62ac39f824f7598cc83a078bc0f5e4e49c4ea
3,639,137
def subtract_dbm(dbm1: float, dbm2: float): """Adds two decibel values""" watt1 = dbm_to_watt(dbm1) watt2 = dbm_to_watt(dbm2) return watt_to_dbm(watt1 - watt2)
ea7c6f9372182a6a39d72265428e86b26b4da765
3,639,138
import os import subprocess def _validateConfigFile(configFilePath): """ Test a configuration file path to be sure it is usable in the plugin Uses a binary included in the project to test a given configuration file, and will raise an exception if something is not valid. The idea if to fail fast at...
bc79a36701a8b97f619245e06a2e190936e3ce64
3,639,139
def focused_evaluate(board): """ Given a board, return a numeric rating of how good that board is for the current player. A return value >= 1000 means that the current player has won; a return value <= -1000 means that the current player has lost """ score = board.longest_chain(board.ge...
b2cbb91cdb048ef41a13532e400173daa05af4b8
3,639,140
def tanh(x, name=None): """ sparse tanh activation, requiring x to be a sparse coo or sparse csr tensor. .. math:: out = tanh(x) Parameters: x (Tensor): The input Sparse Tensor with data type float32, float64. name (str, optional): Name for the operation (optional, default is ...
24bf0889c2e1ba642442e0d8f6b11eeeaf94bf6c
3,639,141
import os import errno import subprocess import sys import json from datetime import datetime def record(args, filename): """Record a snapshot in a json file, as specified by arguments in args. Return 0 on success, 1 on failure.""" LOGGER.debug('In subcommand record.') os.chdir(args.project) pro...
07393a4d7947914ed694b47badbf0aafc7348dc6
3,639,142
def collector(monkeypatch): """ Unit test: base case """ col = SunPowerPVSupervisorCollector(use_device_data_timestamp=False) attrs = [ 'connect', 'disconnect', 'info_metrics', ] mocked = MagicMock() mocked.connect.return_value = [] mocked.disconnect.return_...
f9e99071b2dde231b4a3fc7c89e00846d26efb12
3,639,143
def GetParents_old(con, cur, term): """ Get all the parents of the term in the ontology tree input: con,cur term : str The term for which to look for parents output: err : str Error message or empty string if ok parents : list of str the parents of term """ ...
7e3cfcd821d746fc10e68a9ca94ef6f19a3ba7e3
3,639,144
def uploadResourceFileUsingSession(url, session, resourceName, fileName, fullPath, scannerId): """ upload a file for the resource - e.g. a custom lineage csv file works with either csv for zip files (.csv|.zip) returns rc=200 (valid) & other rc's from the post """ print( "uploading fi...
8a4a8c21563f1467db284f2e98dd1b48dbb65a3c
3,639,145
from typing import Literal def read_inc_stmt(line: str) -> tuple[Literal["inc"], str] | None: """Attempt to read INCLUDE statement""" inc_match = FRegex.INCLUDE.match(line) if inc_match is None: return None inc_path: str = inc_match.group(1) return "inc", inc_path
64ac4b53363a4aa5b9e2c4cf91b27f169ad0465c
3,639,146
import platform import os def _clear_screen(): """ http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """ if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
2958ef538e95d717d60c577c631ddd91240c48f9
3,639,147
def sent2vec(s, model): """ Transform a sentence to a vector. Pre: No parameters may be None. Args: s: The sentence to transform. model: A word2vec model. Returns: A vector, representing the given sentence. """ words = word_tokenize(s.lower()) # Stopwords and numbers m...
1e61639cc27e3a430257ff3ac4b2a002a42cf177
3,639,148
def subnet_group_present( name, subnet_ids=None, subnet_names=None, description=None, tags=None, region=None, key=None, keyid=None, profile=None, ): """ Ensure ElastiCache subnet group exists. .. versionadded:: 2015.8.0 name The name for the ElastiCache subn...
d7d441dcfacd92f33b4172e33299df398cfa3ba2
3,639,149
def GetTensorFlowVersion(vm): """Returns the version of tensorflow installed on the vm. Args: vm: the target vm on which to check the tensorflow version Returns: installed python tensorflow version as a string """ stdout, _ = vm.RemoteCommand( ('echo -e "import tensorflow\nprint(tensorflow.__v...
4380ec75f2b5713ab0ead31189cdd7b3f81c6b9b
3,639,150
def process_step_collect_parse(project, step, process_result, format_args=None): """ Function will parse the file from an output :type step: structures.project_step.ProjectStep :type project: structures.project.Project :type process_result: proc.step.step_shell.ProcessStepResult ...
3f20af272635592bf682f38f29d48e227f631a24
3,639,151
import json from typing import OrderedDict def datetime_column_evrs(): """hand-crafted EVRS for datetime columns""" with open( file_relative_path(__file__, "../fixtures/datetime_column_evrs.json") ) as infile: return expectationSuiteValidationResultSchema.load( json.load(infile...
c229f08250c51a805a15db653e3e70513a6f6e9a
3,639,152
from typing import List from typing import Dict def chat_header_args(panel_vars: List[PanelVariable], parsed_args: Dict) -> List: """Creates a list of tuples containing the passed in arguments from the chat command. Args: panel_vars (list(nautobot_plugin_chatops_grafana.models.PanelVariable)): A list...
645a550d098d71dda9bf21d18b3e98bb5b8f9aa0
3,639,153
def pd_df_timeseries(): """Create a pandas dataframe for testing, with timeseries in one column""" return pd.DataFrame( { "time": pd.date_range(start="1/1/2018", periods=100), "A": np.random.randint(0, 100, size=100), } )
9b6b217e2a4bc80b5f54cecf56c55d5fb229d288
3,639,154
from typing import Union def n_tokens(doc: Union[Doc, Span]): """Return number of words in the document.""" return len(doc._._filtered_tokens)
4b1f1cbb9cb6baf5cb70d6bd38a88d3e0e54610a
3,639,155
def getJobs(numJobs=1): """ Return a list of dictionary data as provided to the plugin `submit` method """ job = {'allowOpportunistic': False, 'bulkid': None, 'cache_dir': TEST_DIR + '/JobCollection_1_0/job_1', 'estimatedDiskUsage': 5000000, 'estimatedJobTime'...
56543a5a6ef66ec7fdf9f3ef26594eafa3f7bb41
3,639,156
def create_test_user(): """Creates a new user with random username for testing If two randomly assigned usernames overlap, it will fail """ UserModel = get_user_model() username = '%s_%s' % ('test', uuid4().get_hex()[:10],) user = UserModel.objects.create(username=username) return user
d20ecbdb07db886a526402c09d7d14d768329c2b
3,639,157
def make_logical_or_tests(options): """Make a set of tests to do logical_or.""" return _make_logical_tests(tf.logical_or)(options, expected_tf_failures=1)
b4c7f5c0d89139938881f7301930651c9a3e7d0a
3,639,158
def guess(key, values): """ Returns guess values for the parameters of this function class based on the input. Used for fitting using this class. :param key: :param values: :return: """ return [min(values)-max(values), (max(key)-min(key))/3, min(values)]
908868b150340b02ba61fcc6ccf5937ba31bfe30
3,639,159
from datetime import datetime import time def add_metadata_values_to_record(record_message, schema_message): """Populate metadata _sdc columns from incoming record message The location of the required attributes are fixed in the stream """ extended_record = record_message['record'] extended_record...
e85e2620b816907204443af1c014ca4d927cb20c
3,639,160
from datetime import datetime def manipulate_reservation_action(request: HttpRequest, default_foreward_url: str): """ This function is used to alter the reservation beeing build inside a cookie. This function automatically crafts the required response. """ js_string: str = "" r: GroupReservati...
f93b8e2ed68daebdf04aa15898e52f41a5df1e49
3,639,161
def _dense_to_sparse(data): """Convert a numpy array to a tf.SparseTensor.""" indices = np.where(data) return tf.SparseTensor( np.stack(indices, axis=-1), data[indices], dense_shape=data.shape)
b1fe24dd82eff2aa31e40f6b86e75f655e7141c7
3,639,162
def getflookup(facetid): """ find out if a facet with this id has been saved to the facet_files table """ found = FacetLookup.objects.all().values_list('graphdb', flat=True).get(id=facetid) if found: return True else: return False
a1c6b0ec7e8ab96eef16574e64ac1948f0fa8419
3,639,163
def numeric_to_string(year): """ Convert numeric year to string """ if year < 0 : yearstring = "{}BC".format(year*-1) elif year >= 0: yearstring = "{}AD".format(year) else: raise return yearstring
3469e2dd5e05c49b4861782da2dd88bac781c61d
3,639,164
def _get_num_ve_sve_and_max_num_cells(cell_fracs): """ Calculate the num_ve, num_sve and max_num_cells Parameters ---------- cell_fracs : structured array, optional A sorted, one dimensional array, each entry containing the following fields: :idx: int Th...
c0d154898bbfeafd66d89a2741dda8c2aa885a9a
3,639,165
from datetime import datetime def is_void(at): """Returns True if the given object is an ``adatetime`` with all of its attributes equal to None. """ if isinstance(at, datetime): return False return all((getattr(at, attr) is None) for attr in adatetime.units)
49744c361177060b508d5537a1ace16da6aef37d
3,639,166
def _get_metric_fn(params): """Get the metrix fn used by model compile.""" batch_size = params["batch_size"] def metric_fn(y_true, y_pred): """Returns the in_top_k metric.""" softmax_logits = y_pred logits = tf.slice(softmax_logits, [0, 1], [batch_size, 1]) # The dup mask should be obtained from...
2793975542241f36850aaaaef4256aa59ea4873f
3,639,167
def check(): """Check if all required modules are present. Returns 0 on success, non-zero on error. """ flag = 0 for package in import_list: try: exec( "import " + package ) except Exception: log.error( "Missing module: %s", package ) flag = True ...
027ae4346a642740ca4b1ef4ebec5a831688f850
3,639,168
def flip_nums(text): """ flips numbers on string to the end (so 2019_est --> est_2019)""" if not text: return '' i = 0 s = text + '_' while text[i].isnumeric(): s += text[i] i += 1 if text[i] == '_': i += 1 return s[i:]
e0534e25e95b72e1d6516111413e32a6dae207ef
3,639,169
def nnls(A, b, k=None, maxiter=None): """ Compute the least-squares solution to the equation ``A @ x = b`` subject to the nonnegativity constraints ``x[:k] >= 0``. Parameters ---------- A : array_like, shape (m, n) Matrix `A` as shown above. b : array_like, shape (m,) Right-...
4d6c7e7d53e570222b752c4bf2013100c15b7297
3,639,170
import os def read_inputs(filename, height, padding, num_quant_levels, p_norm, predict_semantics): """Reads inputs for scan completion. Reads input_sdf, target_df/sem (if any), previous predicted df/sem (if any). Args: filename: TFRecord containing input_sdf. height: height in voxels to...
fac5ec6ae02bf930d881a75d483f4001aabbf9d4
3,639,171
def f_elas_linear_tsswlc(x, t3, t2, e_b, gam, e_par, e_perp, eta): """Compute spring forces and torques on each bead of dsswlc.""" N, _ = x.shape f = np.zeros(x.shape) t = np.zeros(x.shape) for i in range(0, N - 1): dx = x[i+1] - x[i] dx_par = dx @ t3[i] dx_perp = dx - dx_par...
b5a217521667e95b4ba7bafa74f2d1371e01dc34
3,639,172
def extent2(texture): """ Returns the extent of the image data (0.0-1.0, 0.0-1.0) inside its texture owner. Textures have a size power of 2 (512, 1024, ...), but the actual image can be smaller. For example: a 400x250 image will be loaded in a 512x256 texture. Its extent is (0.78, 0.98), the...
16c6d220ad48201fd133ed11c97452bf0831c0d8
3,639,173
def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # Store the total length of the hand hand_len = 0 # For every letter in the hand for key in hand.keys(): # Add the number of...
297f8af5943bf87bb7999a1212d54430857de12b
3,639,174
def add_fieldmap(fieldmap: BIDSFile, layout: BIDSLayout) -> dict: """ Locates fieldmap-related json file and adds them in an appropriate dictionary with keys that describe their directionality Parameters ---------- fieldmap : BIDSFile Fieldmap's NIfTI layout : BIDSLayout BIDSLay...
227fa27d9ecb2f260700debc6b2837d60018bd61
3,639,175
def fit_plane_lstsq(XYZ): """ Fits a plane to a point cloud. Where z=a.x+b.y+c; Rearranging: a.x+b.y-z+c=0 @type XYZ: list @param XYZ: list of points @rtype: np.array @return: normalized normal vector of the plane in the form C{(a,b,-1)} """ [rows, cols] = XYZ.shape G = np.ones(...
c734cb17462e72c40bb65464c42d298c21e4a922
3,639,176
def clean_name(name: str) -> str: """Clean a string by capitalizing and removing extra spaces. Args: name: the name to be cleaned Returns: str: the cleaned name """ name = " ".join(name.strip().split()) return str(titlecase.titlecase(name))
e19354767d38164004c984c76827b2882ef4c4fd
3,639,177
from typing import Callable from re import T from typing import List def pull_list(buf: Buffer, capacity: int, func: Callable[[], T]) -> List[T]: """ Pull a list of items. """ items = [] with pull_block(buf, capacity) as length: end = buf.tell() + length while buf.tell() < end: ...
ab9833fdab157e05df00d65dee96080c98140bb2
3,639,178
def ResNet( stack_fn, preact, use_bias, model_name='resnet', include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation='softmax', bottomright_maxpool_test=False, use_group_norm=False, **kwargs): """Instantiates the Re...
810b04481eb6ad5d8b3723b87581b3f2136cc80f
3,639,179
import yaml def read_yaml(yaml_path): """ Read yaml file from the path :param yaml_path: :return: """ stream = open(yaml_path, "r") docs = yaml.load_all(stream) result = dict() for doc in docs: for k, v in doc.items(): result[k] = v return result
a3f32d6f5c6cb5c8e94ad9b68a0540aa001f83b2
3,639,180
def _server_allow_run_on_save() -> bool: """Allows users to automatically rerun when app is updated. Default: true """ return True
3a895abd8201ce97c8f2f928b841eb86bf6327d1
3,639,181
def _strip_schema(url): """Returns the url without the s3:// part""" result = urlparse(url) return result.netloc + result.path
9e7dc96c23d799f202603109cd08b2fe049951a5
3,639,182
def simple_word_tokenize(text, _split=GROUPING_SPACE_REGEX.split): """ Split text into tokens. Don't split by a hyphen. Preserve punctuation, but not whitespaces. """ return [t for t in _split(text) if t and not t.isspace()]
5b9e66d2a369340028b4ece2eee083511d0e9746
3,639,183
def merge_strategy(media_identifier, target_site, sdc_data, strategy): """ Check if the file already holds Structured Data, if so resolve what to do. @param media_identifier: Mid of the file @param target_site: pywikibot.Site object to which file should be uploaded @param sdc_data: internally forma...
0e59cc312e00cc7d492bfe725b0a9a297734a5e0
3,639,184
def convert_translations_to_dict(js_translations): """Convert a GNUTranslations object into a dict for jsonifying. Args: js_translations: GNUTranslations object to be converted. Returns: A dictionary representing the GNUTranslations object. """ plural, n_plural = _get_plural_forms(...
8db0fc022002504a943f46b429ca71b6e0e90b06
3,639,185
import asyncio def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None): """ Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, ...
64b55a082df11fa9d6b7971ecd1508c1e4c9f1c9
3,639,186
def sigm_temp(base_sim_param, assumptions, t_base_type): """Calculate base temperature depending on sigmoid diff and location Parameters ---------- base_sim_param : dict Base simulation assumptions assumptions : dict Dictionary with assumptions Return ------ t_base_cy :...
276af880050698a9f15dcd142aac952809807fdb
3,639,187
import select import socket def is_socket_closed(sock): """Check if socket ``sock`` is closed.""" if not sock: return True try: if not poll: # pragma nocover if not select: return False try: return bool(select([sock], [], [], 0.0)[...
e89ddec6e7603b5636f6a6d87831d12f0a76e9d9
3,639,188
def _fit_ovo_binary(estimator, X, y, i, j): """Fit a single binary estimator (one-vs-one).""" cond = np.logical_or(y == i, y == j) y = y[cond] y_binary = np.empty(y.shape, np.int) y_binary[y == i] = 0 y_binary[y == j] = 1 ind = np.arange(X.shape[0]) return _fit_binary(estimator, X[ind[co...
59325562549656d35b615a3274112357b0c4854c
3,639,189
def get_implicit_permissions_for_user(user: str, domain=None): """ GetImplicitPermissionsForUser gets implicit permissions for a user or role. Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles. For example: p, admin, data1, read p, alice, data2, re...
08477a3ac772597f66f36b7b04fc7d8a29f2522b
3,639,190
def Law_f(text): """ :param text: The "text" of this Law """ return '\\begin{block}{Law}\n' + text + '\n\\end{block}\n'
594b279c5971a9d379666179c4d0633fc02a8bd9
3,639,191
import operator from typing import OrderedDict def ordered_dict_intersection(first_dict, second_dict, compat=operator.eq): """Return the intersection of two dictionaries as a new OrderedDict. Items are retained if their keys are found in both dictionaries and the values are compatible. Parameters ...
cfef1a1d5c3cc9fc5b792a68bae0fe8279b752da
3,639,192
import scipy def get_cl2cf_matrices(theta_bin_edges, lmin, lmax): """ Returns the set of matrices to go from one entire power spectrum to one binned correlation function. Args: theta_bin_edges (1D numpy array): Angular bin edges in radians. lmin (int): Minimum l. lmax (int): Maxim...
0231218c8501409e3660ed6c446b0c163229ab8a
3,639,193
from operator import concat def series_to_supervised(data, n_in=1, n_out=1, dropnan=True): """ Frame a time series as a supervised learning dataset. Arguments: data: Sequence of observations as a list or NumPy array. n_in: Number of lag observations as input (X). n_out: Number of o...
1756380140dd74045880cc4501623c8b48ce5773
3,639,194
import torch def valid_from_done(done): """Returns a float mask which is zero for all time-steps after a `done=True` is signaled. This function operates on the leading dimension of `done`, assumed to correspond to time [T,...], other dimensions are preserved.""" done = done.type(torch.float) ...
0ca2bd0f9e23605091b2f8d1bc15e67e1632b82b
3,639,195
import logging def get_transfer_options(transfer_kind='upload', transfer_method=None): """Returns hostnames that the current host can upload or download to. transfer_kind: 'upload' or 'download' transfer_method: is specified and not None, return only hosts with which we can work using...
f5aea7498bf98d3be3fe9e97eda4e6eaa9181cea
3,639,196
def calc_utility_np(game, iter): """Calc utility of current position Parameters ---------- game : camel up game Camel up game class iter : int Iterations to run the monte carlo simulations Returns ------- np.array Numpy structured array with expected utilities ...
c69740652ea18d753c9a2a894f1ba36ab1eecff8
3,639,197
def add_masses(line, mass_light, mass_heavy): """ Add m/z information in the output lines """ new_line = "{} {} {}\n".format(round_masses(mass_light), round_masses(mass_heavy), line) return new_line
d8e92acf43d17e9a00de1e985e6cecadec0fa4b4
3,639,198
def load_r_ind_sent_bars(): """ Loads the random index-barcodes of the actual networks """ bars = [] for text in texts: bars.append(np.load('Textbooks/{}/r_ind_sent_bars.npy'.format(text))) return bars
331b217976bc5a03a4e3a20331f06ba33a7aaad1
3,639,199