content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def resolve(bears): """ Collects all dependencies of the given bears. This will also remove duplicates. :param bears: The given bears. Will not be modified. :return: The new list of bears, sorted so that it can be executed sequentially without dependency issues. """ r...
f71ddec693e533c64104f7d13ac15d8bca7f1a78
60,200
from datetime import datetime def unshare_post(post_id): """Remove a share from a given post.""" username = get_jwt_identity() login = Login.query.filter_by(username=username).first() if login is None: raise APIError(400, "User {username} does not exist on this server".format(username=userna...
c088d8806fa83ae522b149d988545d5743dbf641
60,201
import os def letters(dataset_dir): """ http://archive.ics.uci.edu/ml/datasets/Letter+Recognition TaskType:multiclass NumberOfFeatures:16 NumberOfInstances:20.000 """ url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/letter-recognition/letter-recognition.data' filename ...
63763f59a5a2814989d6655b85e241263c65f5cc
60,202
def debug_verbose_output(): """ print verbose output? """ return __VERBOSE_OUTPUT == 1
c3dbbf261b6b28fcb1691fed6b8acb390540f503
60,203
from typing import Sequence import copy def one_individual_per_error_vector(population: Population) -> Sequence[Individual]: """Preselect one individual per distinct error vector. Crucial for avoiding the worst case runtime of lexicase selection but does not impact the behavior of which individual gets s...
22f401f05fd07f6d8f06f972191079ea24a476d7
60,204
import os def get_download_url(image_message_download_url: str) -> str: """ Takes the `download_url` value from `image_message` and returns a modified version if the environment variable `USE_INTHUB2` is set to `YES` By default, the `link_fetcher` handler will grab `scihub` urls, if we are using ...
253c6a1c00954c1eceeffdfdc18f46d9d5145a5b
60,205
def delete_app_release(repo, tag_name, media_type, models_ref): """ Terminate a Tag/media-type couple It find the corresponding tag/manifest and remove from the manifestlistmanifest the manifest 1. it terminates the current tag (in all-cases) 2. if the new manifestlist is not empty, it creates a new tag for it ...
08482ea7163a574fa8a8a71b6ab5f4d3188f38b5
60,206
import six def ensure_str(value): """ Ensure value is string. """ if isinstance(value, six.string_types): return value else: return six.text_type(value)
524a9f46e97856894779492805dd4dc100bb79be
60,207
from typing import Union from typing import BinaryIO def parse_binary_string_on_buffer(buffer: Union[BinaryIO, BytesIO]) -> str: """ Strings ends with \0. We parse until we reach that. """ result = b'' tmp = buffer.read(1) while unpack('<b', tmp)[0] != 0: result = result + tmp ...
870a476b3602a5bdf94669bdebe9ee1e3eecc9fa
60,208
from typing import Any def query_2(author: str, year: str, db: Graph = Depends(get_db)) -> Any: """Find the co-authors of an author (name, number of co-authorships) for a particular year. """ query = "MATCH (a1:Author{name: $name})-[r1:CONTRIBUTED]->(n{year: $year})<-[r2:CONTRIBUTED]-(a2:Author)" \ ...
ea4c34469595c4ee93308fa1e66f7d12e98c7a8f
60,209
def write_before_line(to_write): """To write ``to_write`` at the beginning of the line. ``write_before_line`` uses ``0`` from the command mode to move the cursor to the beginning of the current line. ``to_write`` is then written before the cursor's position using the ``i`` command. Usage: ...
029f35dc16de53bf3f65416836f864a676fbbbfd
60,210
def multiply(x, y): """ This returns the result of a multiplation of the inputs """ some_global_var = 'this is actually a local variable...' result = x* y return result if result == 777: print("jackpot!")
04b0b57bce75e5523151bdcc85d81743a8eba573
60,211
def sanitise_coords(rectlist, width, height): """Treat negative numbers as the outer bound.""" def sanitise(rect): rect.x0 = max(rect.x0, 0) rect.y0 = max(rect.y0, 0) if rect.x1 < 0: rect.x1 = width if rect.y1 < 0: rect.y1 = height if rect.x0 > wid...
3d9895cff7b0616af55a246ccbbc555ec9641e24
60,212
def word_similarity(word_list, text_list): """ Computes the similarity between word and text word_list: a list containing all possible translations of a single word text_list: a list of lists containing all possible translations for a set of words """ max_sim_wordnet = 0 max_sim_yago = 0...
3bf4f954d2e49b685af0076b8a3b1f83f4219307
60,213
def humanize_duration(seconds): """Format specified time duration into human readable text. Parameters ---------- seconds : int | float Number of seconds, as the time duration. Returns ------- str The formatted time duration. """ if seconds < 0: seconds = -s...
0c168dab1df75bb624e4e740c4467a1c66bf05f2
60,214
def Date(year, month, day): """Constuct an object holding a date value. This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.date` """ return date(year, month, day)
46a17af69d72b9ba24991e29db5be07bb5bae0f0
60,215
def show_iface(iface_name=None, is_verbose=False, use_html=False): """enable the given interface by calling ifup.""" theResult = str("""UNKNOWN""") if is_verbose is True: theResult = str(get_iface_status_raw(iface_name)) else: try: if use_html: format_pattern = str("""{}{}{}{}""") else: format_pat...
c1838b6a04550433f38ee31a896e27ebf9d5d521
60,216
def create_harmonic_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( type=0, layers=3, blocks=2, dilation_channels=130, residual_channels=130, skip_channels...
55d07c4f2df65a3b18d342fa3ec623f23ab40e6e
60,217
import os def _find_virtualenv(bin_directory): """ :param bin_directory: directory to first use to find virtualenv :type bin_directory: str :returns: Absolute path to virutalenv program :rtype: str """ virtualenv_path = os.path.join(bin_directory, 'virtualenv') if not os.path.exists(v...
a380bdbb74008773d607def9e6b457708b46a229
60,218
def get_fnames_from_meta_dict(wp_info): """ docstring """ fnames = [] meeting = wp_info['Meeting_type'] + wp_info['Meeting_number'] pnum = wp_info['Abbreviation'] + str(wp_info['Number']).zfill(3) # zero pad if wp_info['Revision'] > 0: # a 'rev#' included in filename iff revisions ...
c529de7e7bd54f56dd627ccc82bdd5680c33b440
60,219
def is_title_case(line): """Determine if a line is title-case (i.e. the first letter of every word is upper-case. More readable than the equivalent all([]) form.""" for word in line.split(u' '): if len(word) > 0 and len(word) > 3 and word[0] != word[0].upper(): return False return Tr...
e769d589d0f84030768c901a5b5b2285788bdc97
60,220
def setOpenTreeDict(tree): """ This function creates a list of myOpenTree objects as well as the dict of list for all the childrens """ openTreeDict = {} for node in transverseTree(tree): if node.children != None: openTreeDict[node.name] = [child.name for child in node....
8a6be1883fc67d29dff251c5223bbc858eb78d9a
60,221
def page_list(parent=None): """ Generate and return list of help pages for being displayed. """ help_images_list = [ ["Level 1", resource_filename("help1.png")], ["Level 2", resource_filename("help2.png")], ["Level 3", resource_filename("help3.png")], ["Level 4", resource...
3491c6594ef591d0814902785c99395b3bc40be4
60,222
def _is_stack_frame(conscious: 'Conscious') -> bool: """ info: Checks if item on top of Stack is StackFrame. :param conscious: Conscious :return: bool """ return conscious[WORK_STACK].peak() is stack.StackFrame
b228cd3b5602e20f1f1301031d03064511746e59
60,223
def read_netcdf4_and_plot_all(filename): """Reads the file in filename and plots all the detectors """ # handle errors to plot with errors _error = False # read the dataset ds = xr.open_dataset(filename) logger.info('The dataset contains: {}'.format(ds)) if '_error_present' in ds.attrs.key...
6039b5b75113009ec919861985aa3e728c2a00c2
60,224
def gen_base_class(schema: UxsdSchema) -> str: """Generate a C++ base class of a root element.""" out = "" root = schema.root_element class_name = utils.to_pascalcase(root.name) out += "struct Default{pname}ContextTypes {{\n".format(pname=class_name) out += "\n\t".join("using {}ReadContext = void *;".format(utils...
9d383d975c3348a7a75ab08b4980a1560c0c90b7
60,225
def padded_cross_entropy(logits, labels, label_smoothing, weights_fn=weights_nonzero, reduce_sum=True): """Compute cross-entropy assuming 0s are padding. Computes a loss numerator (the sum of losses), and loss denom...
fc859a75c7c817450324a0e6c65e1adce2043241
60,226
import torch import tqdm def train(model, train_loader, valid_loader, args): """Trainer function """ # Set device assert args.cuda < 0 or torch.cuda.is_available() device_tag = "cpu" if args.cuda == -1 else "cuda:%d"%args.cuda device = torch.device(device_tag) # Set model and label weigh...
3db937ff6dc085dac5a866e41a3ae6929d71bc8e
60,227
def create_persistance_check_workflow(WFname): """ The purpose of this workflow is to debug the automatic deletion of files from the output directory. :param WFname: :return: """ PERSISTANCE_CHECKWF = pe.Workflow(name=WFname) inputsSpec = pe.Node( interface=IdentityInterface( ...
d72ada2b462bf23d901bbb4ee6261f0e7f41b318
60,228
def hanging_node( pred_tactics, predprob_tactics, pred_techniques, predprob_techniques, c, d ): """ Modify prediction of techniques depending on techniques and related tactics confidence score on a threshold basis. """ predprob_techniques_corrected = pred_techniques for i in range(len(pred_t...
18b06fb4cccf518ac59923ae766d526edd4e642b
60,229
def zero(x_i: np.ndarray, L: float = 2 * np.pi, gamma: float = 0.1) -> np.ndarray: """No interaction between particles""" return np.zeros_like(x_i)
59c995f48d2c2a665af90f6f66e0e9d177826172
60,230
def _pull_out_unaffected_blocks_rhs(rest, rhs, out_port, in_port): """Similar to :func:`_pull_out_unaffected_blocks_lhs` but on the RHS of a series product self-feedback. """ _, block_index = rhs.index_in_block(in_port) rest = tuple(rest) bs = rhs.block_structure (nbefore, nblock, nafter) = ...
cf120ee128326c409cae8c0a97da8108165ffaee
60,231
import configparser def parse_config(config_path): """ Parses the config present at config_path. Parameters ---------- config_path : string The path pointing to the location where the config file is stored. Returns ------- configparser.SectionProxy Returns the DEFAULT...
479abb217c26a48e67e83e8cff8fcd0dd76229bf
60,232
def sinusoidal(params): """ returns lxml nodes that contain projection parameters for fgdc Sinusoidal projection longcm = Longitude of Central Meridian feast = False Easting fnorth - False Northing Parameters ---------- params : dictionary geospatial parameters returned...
9d229e036b26ca8e5ede8a78ae64616d19f71d4c
60,233
from numpy import array def k_Wa92(wind_second_moment, temp_C): """ Calculates the gas transfer coeffcient for CO2 using the formulation of Wanninkhof (1992) Note: This is an old parameterization and we recommend using updated parameterisations that are calculated based on the wind pr...
a4d3a502c8aac16e45b09e359d43ca53a6810e22
60,234
def _get_x_y_from_training_validation(logger, training, validation, predictors, target): """Returns X & Y for training & validation data""" if training is not None: training_X, training_Y = _get_x_y_from_data( logger, training, predictors, target ) if validation is not None: ...
dae15a97fbaa57c3dbdaecbfe59918f90bd9682d
60,235
def PI_alpha_allspace(gp, alpha, idx_to_explore, X_to_minimize, X_to_explore, bounds = None, nrestart = 10, PI = True): """ alpha-Probability of improvement for each value in X_explore (U) """ total_grid = np.empty([len(X_to_explore), len(X_to_minimize)]) for index, x_fix in enumer...
0485871981362f134b1e2f61261511068ee66f45
60,236
from typing import Optional from typing import Sequence from typing import Tuple import requests def attempt_connect_test_nodes( chain: SubstrateChain, timeout: int = NODE_CONNECTION_TIMEOUT, node_names: Optional[Sequence[NodeName]] = None, ) -> DictNodeNameNodeAttributes: """Attempt to co...
731898d2f32628ffbf9938a73ce9b4012fd000b9
60,237
def load_config(config_dir): """Opens the config file, doesn't check for creds.""" config_path = config_module.find_config_file(config_dir) config = config_module.load_from_file(config_path) return config
b067fd7b0a030fccd00dc21dd793f55fd67f3f11
60,238
def get_model(task): """Create model.""" model_setenv() if task == "clean": checkpoint = "models/TOFlowClean.pth" model = CleanFlow() elif task == "slow": checkpoint = "models/TOFlowSlow.pth" model = SlowFlow() elif task == "zoom": checkpoint = "models/TOFlo...
29c27a33ca0e4216021ea93712cbc281ab06c7a9
60,239
from typing import Union from typing import Dict from typing import Any def translate_info(item: Union[str, Dict[str, Any]]) -> Dict[str, Any]: """Translate info from the client to as per fsspec requirements.""" assert not isinstance(item, str) return {mapping.get(key, key): value for key, value in item.i...
2fcc68e56776a43ad838b38c46e93e411543c28d
60,240
def asmatrix(data, dtype=None): """ Returns 'data' as a matrix. Unlike matrix(), no copy is performed if 'data' is already a matrix or array. Equivalent to: matrix(data, copy=False) """ return matrix(data, dtype=dtype, copy=False)
c9841930680b1f63067f829d78b415d6db4b20ce
60,241
def get_message_hash(*, message): """Return has of given message""" return sha3(sort_and_encode(message)).digest().hex()
95b4982009bc342f53be5460a9a16dba36e8a81d
60,242
def setup_movemap_from_resselectors(designable_selector, repackable_selector): """ Temporary function. Ultimately we want a more sophisticated movemap, probably a neighbor movemap or something using clash-based shell selector. """ mm = rosetta.core.kinematics.MoveMap() mm.set_chi(False) mm.s...
79e48d7d64999d2760efbae091fb4fc5a2d5dce0
60,243
def simple_permute(x, order): """ TODO: Implement a function that permute the dimensions of the given tensor x according to the given order and returns the result. """ return x.permute(order)
70e36014bc4893fb01cfb030c5e1f45cc69fdf83
60,244
def scoreWords(wordlist): """ Takes a list of words Create dictionary of word=key and score=val """ return dict()
e6afb09790c6fb0c1b9ebc5c0694ac00af8bb669
60,245
import re def find_latest_checkpoint(bucket_name, checkpoint_dir): """ Find the latest checkpoint file Returns tuple of (extra_data_file, tune_metadata_file) """ # Google Storage API not smart enough, need to end the checkpoint_dir with '/' if checkpoint_dir[-1] != '/': checkpoint_dir ...
131a2cd6dc4f522f20c1bc3209e0960f1eeb6274
60,246
import random def random_hex_seeded(length, seed): """Get a random hex string of a given lenth with a specific seed.""" random.seed(seed) return bytearray(random.getrandbits(8) for _ in range(length)).hex()
5737057a33063cd9c62bc6071f0ef98552001117
60,247
def Parse(token, token_end, error_handler): """Parses a type annotation and returns a TypeAnnotation object.""" return TypeAnnotationParser(error_handler).Parse(token.next, token_end)
56c38d6268b1b5f89d6c15d9375e3bdadf07cd6d
60,248
def conv_celcius_to_kelvin(celcius): """ Convert Celcius to Kelvin Returns ------- double : Kelvin """ return celcius + const.zero_celcius_in_kelvin
e25f23e38e0b578cdb0b63bacd5af126e94a6c14
60,249
import configparser def _get_config(): """ Either returns an already loaded configparser Or creates a configparser and loads ini config at /etc/cwlogd.ini """ global _config if _config is None: _config = configparser.ConfigParser() _config.read(CONFIG_PATH) return _config
a766e4c685d35862ed0e54861c0d001fe85059c2
60,250
def get_ratio_w_h(ratio): """ returns width and height from string e.g. '1-2' or '4-3' as integer """ w, h = ratio.split('-') return float(w), float(h)
41751e6056d4797e973d60c1e3691e7915a9e1ae
60,251
def message_get_multiplexor(message_info, message_binary_msb, message_binary_lsb, message_binary_length): """Extract the multiplexor information of the message if any. Arguments: message_info: dict, information about the message (name, signals) message_binary_msb: str, data of CAN message in MS...
facbb8fa1f7d7639f27dfacf134818f547af0694
60,252
def train_dictionary(train_dict: dict, test_dict: dict, iterations: int, model_dir: str, batch_size: int, tensors_to_log={}): """Trains the nn for given number of iterations from the given model directory with a given batch_size""" print("Given {} training examples and {} testing examples".format( ...
7cfa22995436e5832ee52ede7ea634a7351a2fdf
60,253
def create_app(config_object=None, blueprints=None): """Application factory. Explained in greater detail here: http://flask.pocoo.org/docs/patterns/appfactories/ """ if blueprints is None: blueprints = DEFAULT_BLUEPRINTS app = Flask(__name__, template_folder="browser/templates", ...
08454fab61996ddd13787fdce42c5341528462ea
60,254
def metropolis(initial_theta,proposal_params,lnpdf,pdf_params,symmetric=False, sample_proposal=sample_gaussian_proposal, eval_ln_proposal=eval_ln_gaussian_proposal, nsamples=1,randomize_directions=True,callback=None): """ NAME: metropolis PURPOSE: m...
96020af6c906a7cd68e615340a1d540514f25e42
60,255
def get_payment_plans(): """ Returns all financial payment plans. :returns: String containing xml or an lxml element. """ return get_anonymous('getPaymentPlans')
88651000305fc023bb3b82dc20124f8a30720b05
60,256
import torch def get_model(args: dict, device: torch.device, save=False): """ Returns a PyTorch Neural Net with specifications found in <args> and attached to the <device>. If <save> is True, saves the model locally with filename <args.save_as>. :param args: Dictionary of training specifications ...
007bf195eef3edda485afcd4e1ce81b61d2afc9d
60,257
def array_equal(a1, a2): """ True if two arrays have the same shape and elements, False otherwise. Parameters ---------- a1, a2 : array_like Input arrays. Returns ------- b : bool Returns True if the arrays are equal. See Also -------- allclose: Returns Tru...
018f3d3899f30efed2bca52dec7c63e6187140ba
60,258
import re def parse_define(line): """Check if the specified line contains an #define directive""" pattern = r'#(?:\s)*define\s*([\w_]+)(?:\s)*["\']?(.*)["\']' match = re.match(pattern, line, re.IGNORECASE) if match: return (match.group(1), match.group(2))
5fc15e792e1f457c7466d9ff0a97241cbdf0873f
60,259
import os def show_post(post_year, post_month, post_day, post_id): """ . """ post_name = "-".join([post_year, post_month, post_day, post_id]) content = update(path=os.path.join(content_path, "archive.json")) try: post = get_posts(posts_html, post_name)[0] except IndexError: abort(4...
7c5a33efc3c1db01c7a32a18be2bddded49f41b0
60,260
def _save_v3( *, dataset: tf.data.Dataset, tfdata_path: str, num_shards: int, ): """ tfdata saver v3. This implementation is identical to tfdata saver v2 because the backwards-compatible changes are on the loading side. """ return _save_v2(dataset=dataset, tfdata_path=tfdata...
3ca99f11e6c5e5b3336b3b0a04c988cd646ee7cf
60,261
import warnings def srtm(lon, lat): """ Return (elevation, crs, extent) for the given longitude latitude. Elevation is in meters. """ warnings.warn("This method has been deprecated. " "See the \"What's new\" section for v0.12.", DeprecationWarning, ...
d8a457f338d26424f9be13fb0db2d59d8ff0558d
60,262
def clone_field(field): """ Incomplete backport of field.clone in Django 1.7. """ # FIXME: field.clone() doesn't work if called before models settle # if hasattr(field, 'clone'): # return field.clone() cls = type(field) args = tuple() kwargs = {} if cls == models.ForeignKey: ...
a021b223f41f78533aca9836179f9821c78d9a57
60,263
from re import T def get_training_pair_images(file, centre_fraction, acceleration): """ :param file: The training image :param centre_fraction: randomly generated centre fraction :param acceleration: randomly generated :return: true gold standard and the fft of the masked k-space image """ ...
a10b05fa5b38e877334402d2e5aace7488913e56
60,264
def classification(x, y, **kwargs): """ Classification tasks #TODO """ x_train, x_test, y_train, y_test = check_xy_dims(x,y) model = RidgeClassifier(alpha=0.0, fit_intercept=True, **kwargs).fit(x_train, y_train) # estimate score #TODO - average accuracy across classes or something...
d39f956e6361a74477ab33fa2f66b5c92eb7a7a7
60,265
def pileupCorrespondences(bam, bamId, referenceLength, includeSoftClipped, progress): """ Get bases for offsets that correspond to the reference using pysam's pileup funciton. @param bam: An open BAM file. @param bamId: A C{str} reference name indicating which reference to...
b8cea33636f6b0862ee4987deda1c86f80caa313
60,266
def create_small_test_odml(): """ creates a small odml-document with only one section, property and value """ doc = odml.Document() doc.append(odml.Section(name='section1')) parent = doc['section1'] parent.append(odml.Property(name='property1', values='bla...
94172c9dcda913e45887c2a106161ce386c9bc5c
60,267
def format_iter(body: list) -> str: """ Formats an iterable into a multi-line bulleted string of its values. """ return "\n".join(sorted([f" - {getattr(v, 'value', v)}" for v in body]))
0f55b06276c45ef652e89df3dfd24d1fe9a4e844
60,268
def confidence_interval_std(std, num, confidence=0.95): """ calculates the confidence interval of the standard deviation given a standard deviation and a number of observations, assuming a normal distribution """ c = stats.chi(num - 1).ppf(0.5 + 0.5*confidence) lower_bound = np.sqrt(num - 1)*std/c ...
7b0f101095a7c5166d9c8ba7817d76359501afa6
60,269
def btc_to_sats(value_btc: Bitcoin) -> Satoshi: """Converts BTC to Sats. Args: value_btc: The value in BTC. Returns: The value in Sats. """ return value_btc * Decimal(1e8)
61cc55cc8f88b550e20affde667cb8669b26af95
60,270
def isolate_area_interval(df_loc: pd.DataFrame, loc_col: str, loc_name: str, start_date: str, end_date: str) -> pd.DataFrame: """Quickly isolate an area or region of intrest within a given timeframe. Args: df_loc: The timeseries DataFrame with location identifiers and cases. ...
c1325686c4b12f411df408552022c549db3dfb8d
60,271
def cert_chain_url_valid(cert_url): """ Ensure that the provided URL for the certificate chain is valid, by checking that: * it's HTTPS * the host is s3.amazonaws.com * the port, if specified, is 443 * the path starts with '/echo.api/' """ normalized = url_normalize(cert_url) parsed ...
1d9e58d9c66c6fc8fb6d797f1cebdcd1ba95cab5
60,272
import scipy def null_space(A: tn.Tensor) -> tn.Tensor: """ Returns the null space of the matrix A. Args: A: The tensor. pivot_axis: Where to matricize. Returns: The null space, shaped as a matrix. """ if A.backend.name == "numpy": N_arr = scipy.linalg.null_space(A.array) elif A.backend....
a466dc21117a9ae24699b528229c30e15621aca3
60,273
import os import uuid def create_dummy_simulation_data( directory_path, substance, force_field_id="dummy_ff_id", coordinate_file_name="output.pdb", trajectory_file_name="trajectory.dcd", statistical_inefficiency=1.0, phase=PropertyPhase.Liquid, number_of_molecules=1, calculation_id...
935ce61918347bfef56ca1d33346c73a6cfda73d
60,274
from mirp.imageFilters.waveletFilter import WaveletFilter from mirp.imageFilters.laplacianOfGaussian import LaplacianOfGaussianFilter from mirp.imageFilters.lawsFilter import LawsFilter from mirp.imageFilters.meanFilter import MeanFilter def transform_images(img_obj, roi_list, settings, compute_features=False, extrac...
ec7ca8a444662d1abf617c4eed5c44c7b99e3275
60,275
def preprocess_t5_data(dataset, training, n_devices, dynamic_batching = False, pack_examples = True, shuffle_buffer_size = 1024, max_length = 512, batch_size =...
908bfdb87bfb60f7c8647ebd8da3fa8285257ef9
60,276
def get_number_greenbonds_with_year(): """calculates the nb of green bonds the ECB invested in per year""" EIKON_greenbonds = readEikonData.eikon_data_environment[["ISIN", "Green Bond Flag"]] EIKON_greenbonds= EIKON_greenbonds.rename(columns={'Green Bond Flag' : 'Green_Bond_Flag'}) EIKON_greenbonds = E...
c5e600489dac2597c3e5859ceefeeb783b4d61a2
60,277
def is_neighbor(b1: Branch, b2: Branch, shard_size: int): """A naive algorithm to decide neighbor relationship TODO: a better algorithm, because the current one ensures 32 neighbors ONLY when there are 2^32 shards """ if shard_size <= 32: return True if b1.get_chain_id() == b2.get_chain_id()...
396a250952b7a65a7ccbe6dbb3bc36b55aff445e
60,278
def processMK1(a_np,b_np): """ Wrapper method that calls the various methods to create the merged map. :param a_np: Contains the map values, from one of the bigger maps, usualy Gmapping. :type a_np: Float matrix. :param b_np: Contains the map values, from the smaller map, usualy Karto. :type b_np: Float matrix. ...
38361c2bff0f328db4f24dbb22c4dc72b167d93c
60,279
import functools def model_inference_fn(features, training): """Builds just the inference part of the model graph. Args: features: input features tensor. training: True if the model is training. Returns: (policy_output, value_output, logits) tuple of tensors. """ my_batc...
f54560157574628193ac943366bcb0603543e94a
60,280
import re import os import tempfile import subprocess import sys import time def start_guppy_server(host, config, port, device): """Start guppy_basecall_server and return its Popen object, host and port. This starts new basecall server only if host is a path to guppy binary. Otherwise, it'll use host:po...
d776b0fb34c060398357999ed5af1dd578a8bf25
60,281
def ln_gx(w,S,X_i,x, kernel_type='Gaussian'): """logarithm of gradient of Kernel density function fx(w,S,X_i,x, kernel_type='Gaussian') ∇_f(x)=g(x)/f(x) inputs w: A python list which consists of weights of each kernel(weights should be floats) S: A python list which consists of coverian...
d1b8fb946d0830feabbf3a1701870b2998af5e56
60,282
def route_list_public_auctions(): """ Returns list of public auctions """ skip = int_or_default(request.args.get("skip"), 0) limit = int_or_default(request.args.get("limit"), 20) (auctions, total) = get_public_auctions(skip, limit) response = { "auctions": [convert_auction(a) for a...
e786a3001a9681d214a581861708b2f56786a2c2
60,283
def _Modify(resources, args, url_map, url_map_ref, backend_bucket_arg, backend_service_arg): """Returns a modified URL map message.""" replacement = encoding.CopyProtoMessage(url_map) if args.default_service: default_backend_uri = url_maps_utils.ResolveUrlMapDefaultService( args, backend_...
38c59b9e5daa05fd60d8a637633e96403e11286f
60,284
def copy_page_content(original_content): """Copy the PageContent object and deepcopy its placeholders and plugins. """ # Copy content object content_fields = { field.name: getattr(original_content, field.name) for field in PageContent._meta.fields # Don't copy the pk as we're...
704ede2e6e6965d57048fd09cd5341fc61732926
60,285
def backward_softmax(x, grad_outputs): """ Compute the gradient of the loss with respect to x. grad_outputs is the gradient of the loss with respect to the outputs of the softmax. Args: x: A 1d numpy float array of shape number_of_classes grad_outputs: A 1d numpy float array of shape n...
ca4a7d11e060357d083391e3a023f51e13162340
60,286
from pathlib import Path def calcpath(paths,streams): """calcpath(paths, streams) Takes an initial iterable of paths and an in-order iterable of jetstreams to add, and returns whatever finalminimum() returns. Which is a tuple of the lowest-cost path and the final cost over that path. Function signat...
961ebbb1598b09ad4f9d2fd7c694933f21b517d1
60,287
from pathlib import Path from re import T def frame3d_curv(file: Path, var: set[str], xg: dict[str, T.Any] = None) -> xarray.Dataset: """ curvilinear Parameters ---------- file: pathlib.Path filename to read var: set of str variable(s) to read """ if isinstance(var, ...
50ff85b8f914755ab38d5be04fc7803372c61d46
60,288
import json def request_token(auth_code, code_verifier): """Uses authorization code to request tokens.""" request_args = { 'code': auth_code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': REDIRECT_URI, 'grant_type': 'authorization_code', 'code_verifie...
9cf962486d6d6f670575ab0b1c98df373541d78a
60,289
from typing import List def lang_codes_to_one_hot(data: List[str], wili_codes: List[str]) -> np.ndarray: """ Convert an iterable of ISO 369-3 codes to a one-hot array. Parameters ---------- data : List[str] Each str is a WiLI language code wili_codes : List[str] List of WiLi l...
465e2eb5756e718aae7241e782330838dd109712
60,290
def read_gcode(filename): """ function to read gcode as raw text """ ##TODO: parse/read file line by line for memory considerations with open(filename, 'r') as fh_in: gcode_raw = fh_in.readlines() gcode_raw = [gcode.rstrip(';\n') for gcode in gcode_raw] # stripping off trailing semicolon and newlines return gco...
f282b09a31ddc1d735400ac52c4bd5e19c618608
60,291
import warnings def availability_summary_plots(power_system, power_subsystem, loss_total, energy_cumulative, energy_expected_rescaled, outage_info): """ Create a figure summarizing the availability analysis results. Because all of the paramete...
bf32ed3377e8aba847960f9a5c0fe53aef6a5efd
60,292
def lwrap(s, width=64): """ Wrap a C-prototype like string into a number of lines. """ ll = [] p = "" while len(s) > width: y = s[:width].rfind(',') if y == -1: y = s[:width].rfind('(') if y == -1: break ll.append(p + s[:y + 1]) s =...
9e01a1b956f37a648ff507ce65a2f6844844d28d
60,293
def get_button(text: str, *callback_postfixes) -> InlineKeyboardButton: """ Generates an InlineKeyboardButton with given text and callback contents :param text: Text of button :param callback_postfixes: collection of strings which'll form a dash(`-`) separated callback data :return: """ retu...
c3349dfa614d047c26aad5c9dbed341a6de963f2
60,294
def get_full_name(user): """Return user's fullname bugzilla style.""" return u'%s :%s' % (user.get_full_name(), user.userprofile.display_name)
ef84ec4ecba7d8fdf8da1d1bccf79f5bec551029
60,295
def dmtx_light(frametimes, paradigm=None, hrf_model='canonical', drift_model='cosine', hfcut=128, drift_order=1, fir_delays=[0], add_regs=None, add_reg_names=None, min_onset=-24, path=None): """Make a design matrix while avoiding framework Parameters ---------- see make_dm...
3dd4ce78a50c40ae1ef4e8c2a6e2c3027c7d6368
60,296
def NominalLink(ratio='canonical', **kwargs): """ """ return _ratio(ratio, dict(canonical = NominalCanonicalLink, reference = ReferenceLink), **kwargs)
85b60b8ce796e466f66b07e2a187863ef289591f
60,297
def subquery(alias, *args, **kwargs): """Return an :class:`.Alias` object derived from a :class:`.Select`. name alias name \*args, \**kwargs all other arguments are delivered to the :func:`select` function. """ return Select(*args, **kwargs).alias(alias)
d03bf955301286329461df9c44cc009d637dc41f
60,298
from typing import List def include_model(func=None, *, operations: List[str] = None, fields: List[str] = None): """ Decorator used for including specific models, despite potentially being ignored by the exclusion preferences set in the configuration. :param func: function to be decorated :param ...
ac0ce5be6f851b38084b802230f743a1e65a43ff
60,299