content
stringlengths
22
815k
id
int64
0
4.91M
def parse_single_example(serialized, # pylint: disable=invalid-name names=None, sparse_keys=None, sparse_types=None, dense_keys=None, dense_types=None, dense_defaults=No...
5,320,400
def delta_date_feature(dates): """ Given a 2d array containing dates (in any format recognized by pd.to_datetime), it returns the delta in days between each date and the most recent date in its column """ date_sanitized = pd.DataFrame(dates).apply(pd.to_datetime) return (date_sanitized ...
5,320,401
def benchmark_training(model, opts): """Benchmarks training phase. :param obj model: A model to benchmark :param dict opts: A dictionary of parameters. :rtype: tuple: :return: A tuple of (model_name, list of batch times) """ def _reduce_tensor(tensor): reduced = tensor.clone() ...
5,320,402
def test_files(generate_calc_job, generate_code): """Test the ``files`` input.""" inputs = { 'code': generate_code(), 'files': { 'xa': SinglefileData(io.StringIO('content')), 'xb': SinglefileData(io.StringIO('content')), } } dirpath, calc_info = generate_c...
5,320,403
def runprog(*args): """Runs specified program and args, returns (exitcode, stdout, stderr).""" p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() return (p.returncode, out, err)
5,320,404
def inhib_kin_query(inhib_pubchem_cid): """ Query to pull targeted kinases using inhib CID :param inhib_pubchem_cid: string inhib CID :return: Flask_Table Kinase object """ session = create_sqlsession() q = session.query(Inhibitor).filter_by(inhib_pubchem_cid= inhib_pubchem_cid) inh = q....
5,320,405
def abstract_methods_of(cls) -> Set[str]: """ Gets the abstract methods of a class. :param cls: The class to get the abstract methods from. :return: """ return getattr(cls, ABSTRACT_CLASS_ATTRIBUTE, set())
5,320,406
def p_optional_specification_part(p): """optional_specification_part : specification_part | empty """ p[0] = p[1]
5,320,407
def rotate(): """Rotate keys. """ validate_rotation_check() validate_rotation_interval() persistence_type = os.environ.get("GLUU_PERSISTENCE_TYPE", "ldap") ldap_mapping = os.environ.get("GLUU_PERSISTENCE_LDAP_MAPPING", "default") rotator = KeyRotator(manager, persistence_type, ldap_mapping,...
5,320,408
def extract_ini(project, locale, path, entities=False): """Extract .ini file with path and save or update in DB.""" parser = silme.format.ini.FormatParser extract_silme(parser, project, locale, path, entities)
5,320,409
def write_text_header(output_file, message): """Writes the file header Arguments: output_file {string} -- the file (path) to save to message {string} -- the text to write as header """ try: with open( os.path.join( os.path.dirname(__file__), outpu...
5,320,410
def parse_cmd_line_args(): """ Parse command line parameters """ from optparse import OptionParser parser = OptionParser() parser.add_option("-m", "--model", dest="model", default='standard_glm', help="Type of model to use. See model_factory.py for available types.") ...
5,320,411
def parameterized_qubit_qnode(): """A parametrized qubit ciruit.""" def qfunc(a, b, c, angles): qml.RX(a, wires=0) qml.RX(b, wires=1) qml.PauliZ(1) qml.CNOT(wires=[0, 1]).inv() qml.CRY(b, wires=[3, 1]) qml.RX(angles[0], wires=0) qml.RX(4 * angles[1], wire...
5,320,412
def fem_context( filename, comm=MPI.COMM_WORLD ): """ Create tensor-product spline space and mapping from geometry input file in HDF5 format (single-patch only). Parameters ---------- filename : str Name of HDF5 input file. comm : mpi4py.Comm MPI communicator. Results ...
5,320,413
def main(): """ Función principal del programa. Crea el estado inicial de Game of LIfe y muestra la simulación paso a paso mientras que el usuario presione Enter. """ life = life_crear([ '..........', '..........', '..........', '.....#....', '......#...',...
5,320,414
def handle_start(update: Update, context: CallbackContext) -> None: """Displays welcome message to the bot and manages pm messages.""" update.message.delete() delete_old_chat_message(update, context) arguments = context.args if not arguments: update.message.reply_html(START, reply_markup=ut...
5,320,415
def get_indicators_from_fred(start=start, end=end): """ Fetch quarterly data on 6 leading indicators from time period start:end """ # yield curve, unemployment, change in inventory, new private housing permits yc_unemp_inv_permit = ( web.DataReader(["T10Y2Y", "UNRATE", "CBIC1", ...
5,320,416
def test_VideoDataset_split_file( ar_milk_bottle_path, ar_milk_bottle_split_files, ) -> None: """ Tests VideoDataset initializing using split file. """ dataset = VideoDataset( ar_milk_bottle_path, train_split_file=ar_milk_bottle_split_files[0], test_split_file=ar_milk_bottle_split_fi...
5,320,417
def set_gcp_project(project_id: str, zone: str): """Set GCP project ID""" try: run('gcloud config set project {}'.format(project_id)) run('gcloud config set compute/zone {}'.format(zone)) except exceptions.UnexpectedExit: print('Bad command')
5,320,418
def permission_denied_exception_handler(exc, context): """If the object exist but the user does not have permission for it, change the status code and message.""" # Call REST framework's default exception handler first to get the standard error response. response = exception_handler(exc, context) if co...
5,320,419
def get_current_placement_group() -> Optional[PlacementGroup]: """Get the current placement group which a task or actor is using. It returns None if there's no current placement group for the worker. For example, if you call this method in your driver, it returns None (because drivers never belong to a...
5,320,420
def init_config_file() -> None: """Initialize configuration file by default configs.""" if config_path().exists(): raise PyDSConfException( "Initialize configuration false to avoid overwrite configure by accident, file already exists " "in %s, if you wan to overwrite the exists c...
5,320,421
def _GenerateManifest(args, service_account_key_data, image_pull_secret_data, upgrade, membership_ref, release_track=None): """Generate the manifest for connect agent from API. Args: args: arguments of the command. service_account_key_data: The contents of a Google IAM service account...
5,320,422
def save_image(img_type, elem): """ Save post cover or user avatar to local filesystem in dev or to S3 in prod :param img_type: 'avatars' or 'covers' :param elem: post or user obj on which to save the image :return: name of the file to be saved """ image = request.files['file'] if elem: ...
5,320,423
def check_conjunctions(sentence: str) -> list or None: """ Returns the list of messages about a punctuation error with conjunctions if there is one. """ sentence = sentence.lower() conjunctions = {'а', 'але', 'однак', 'проте', 'зате', 'хоч', 'хоча'} errors = [] for word in conjunctions: ...
5,320,424
def plot_pde(T, C, legend, xlabel="", ylabel="", title="", figname=""): """ Plotting the pde solution. Only bulk concentrations (all radiuses have the same value) """ # Get the numbers Nr = len(C) Nc = len(C[0]) # PLOTING fig = pyplot.figure() ax = pyplot.subplot(111) for i in range(N...
5,320,425
def decompose(poly: PolyLike) -> ndpoly: """ Decompose a polynomial to component form. In array missing values are padded with 0 to make decomposition compatible with ``chaospy.sum(output, 0)``. Args: poly: Polynomial to decompose. Returns: Decomposed polynomial wi...
5,320,426
def letter_to_vec(letter): """returns one-hot representation of given letter """ index = ALL_LETTERS.find(letter) return _one_hot(index, NUM_LETTERS)
5,320,427
async def test_triggers(opp, tag_setup, calls): """Test tag triggers.""" assert await tag_setup() assert await async_setup_component( opp, automation.DOMAIN, { automation.DOMAIN: [ { "alias": "test", "trigger": {"pla...
5,320,428
def Hellinger2D(dist1, dist2, x_low=-np.inf, x_high=np.inf, y_low=None, y_high=None): """ Computes the Hellinger distance between two bivariate probability distributions, dist1 and dist2. inputs: dist1: a function that returns the probability of x, y dist2: a function...
5,320,429
def outline_to_mask(line, x, y): """Create mask from outline contour Parameters ---------- line: array-like (N, 2) x, y: 1-D grid coordinates (input for meshgrid) Returns ------- mask : 2-D boolean array (True inside) Examples -------- >>> from shapely.geometry import Poin...
5,320,430
def download_images(wiki_api, images, local_filenames): """ This method downloads all images from a wiki. :param wiki_api: The API location of the wiki. :param images: The names of images to download. :return: A pinkie party!! """ global batch_size direct_urls = [] for i in range(...
5,320,431
def check_ContentType(): """ HowTo make Pre-Processing for all requests. But: it also can be managed in View Class, just like django-rest-framework """ if request.method != 'GET': if (not request.content_type) or ('application/json' not in request.content_type): msg = jsonify( ...
5,320,432
def iterflatten(array, is_deep=False, depth=0): """Iteratively flatten a list shallowly or deeply.""" for item in array: if isinstance(item, (list, tuple)) and (is_deep or depth == 0): for subitem in iterflatten(item, is_deep, depth + 1): yield subitem else: ...
5,320,433
def _hash_feature(feature): """Calculate SHA256 hash of feature geometry as WKT""" geom = shape(feature["geometry"]) return hashlib.sha256(geom.to_wkt().encode("utf-8")).hexdigest()
5,320,434
def ignore_biasbn(directions): """ Set bias and bn parameters in directions to zero """ for d in directions: if d.dim() <= 1: d.fill_(0)
5,320,435
def ssdp_scan(address=None, service=None, timeout=None): """ Returns a list of responses to an SSDP request """ if address is None: address = DEFAULT_ADDR if service is None: service = DEFAULT_SERVICE if timeout is None: timeout = DEFAULT_TIMOUT message = MESSAGE_T...
5,320,436
def trainer(elec): """ Trainer's options are defined. Args: elec: We pass the trainer as a parameter. """ codes = bytes(str(TRAINER_CHOOSE),"utf-8") code_id = bytes("0"+elec,"utf-8") img = bytes(str(TRAINER_CHOOSE),"utf-8") client.sendall(codes + code_id + img) al = client.re...
5,320,437
def assert_cert_count_for_lineage(config_dir: str, lineage: str, count: int) -> None: """ Assert the number of certificates generated for a lineage. :param str config_dir: location of the certbot configuration :param str lineage: lineage domain name :param int count: number of expected certificates ...
5,320,438
def random_walk_timeseries(length: int = 10, freq: str = 'D', mean: float = 0, std: float = 1, start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> 'TimeSeries': """ Creates a random walk TimeSeries by sampling a gaussian distribution with mean 'mean' and standard deviation 's...
5,320,439
def provider_for(platform: str, source: str) -> ContentProvider: """ A factory method that returns the appropriate data provider. Throws an exception to let you know if the arguments are unsupported. :param platform: One of the PLATFORM_* constants above. :param source: One of the PLATFORM_SOURCE>* ...
5,320,440
def create_app(config_name: str = "development") -> Flask: """ Factory for the creation of a Flask app. :param config_name: the key for the config setting to use :type config_name: str :return: app: a Flask app instance """ app = Flask(__name__) app.config.from_object(config[conf...
5,320,441
def write_notes(notes: str, table_path: str) -> None: """Write notes for a table. Args: notes (str): String to write to disk. table_path (str): The filepath of the accompanying LaTeX table. Returns: None: Writes ``notes`` to ``<table_path_root>_notes.tex``. So if ``table_pa...
5,320,442
def test_wpli(): """Test the Weighted PLI algorithm.""" # Groundtruth expected = np.load("groundtruth/fc/wpli.npy") expected = np.nan_to_num(expected) # Data data = np.load("sample_data/fc/eeg_32chans_10secs.npy") # Run csdparams = {"NFFT": 256, "noverlap": 256 / 2.0} wpliv = wpl...
5,320,443
def oneorzero(argument): """Conversion function for the various options that let you choose between 1 and 0.""" return directives.choice(argument, ('0', '1'))
5,320,444
def move_to_stage_4(chosen_batch: str, manual: bool = False): """ A function which moves batches from stage 3 to stage 4. :return: None """ if manual: chosen_batch = input( "Please input the name of the batch you would like to move to stage 3.\n>> " ) for...
5,320,445
def encode(s, c): """ s is the scret code c is the clear text """ secret_code_list = list(s) clear_text_list = list(c) encoded_text_list= [] count = 0 for letter in clear_text_list: if letter == ' ': encoded_text_list.append(' ') continue enc...
5,320,446
def test_ap_wpa2_eap_sql(dev, apdev, params): """WPA2-Enterprise connection using SQLite for user DB""" try: import sqlite3 except ImportError: return "skip" dbfile = os.path.join(params['logdir'], "eap-user.db") try: os.remove(dbfile) except: pass con = sqlit...
5,320,447
def polyfit(data, time_axis, masked_array, outlier_threshold): """Fit polynomial to data.""" if not masked_array: if outlier_threshold: data, outlier_idx = timeseries.outlier_removal(data, outlier_threshold) coeffs = numpy.ma.polyfit(time_axis, data, 3)[::-1] elif data.mask....
5,320,448
def update_board(position, board, player): """ Update the board with the user input position if position not taken returns board, True=position taken or False=position not taken and board updated args: position (int 1-9, user input) board (np.array 2d) player ("X" or "O") """ ...
5,320,449
def find_deployed_version(package_name, environment, version=None, revision=None, apptypes=None, apptier=False): """Find a given deployed version for a given package in a given environment for all related app types; search for full tier or host only deployment specifically ...
5,320,450
def stochastic_block_model(sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True): """Returns a stochastic block model graph. This model partitions the nodes in blocks of arbitrary sizes, and places edges between pairs of nodes independently, with a pro...
5,320,451
def get_text_and_links(wikitext): """ Obtain text and links from a wikipedia text. """ parsed = wtp.parse(wikitext) basic_info = parsed.sections[0] saved_links = {} num_links = len(basic_info.wikilinks) for i in range(num_links): index = num_links - i - 1 link = basic_in...
5,320,452
def SobelOperator(image, n): """ 构建了 Sobel 平滑算子和差分算子后,通过这两个算子来完成图像矩阵与 Sobel 算子的 same 卷积, 函数 SobelOperator 实现该功能: 图像矩阵先与垂直方向上的平滑算子卷积得到的卷积结果, 再与水平方向上的差分算子卷积, 这样就得到了图像矩阵与sobel_x 核的卷积。 与该过程类似,图像矩阵先与水平方向上的平滑算子卷积得到的卷积结果, 再与垂直方向上的差分算子卷积, 这样就得到了图像矩阵与 sobel_y 核的卷积。 A...
5,320,453
def read_model(model_file: typing.IO) -> SVR: """Read the model from the given file.""" return pickle.loads(model_file.read())
5,320,454
def create_nonfixations(stimuli, fixations, index, adjust_n = True, adjust_history=True): """Create nonfixations from fixations for given index stimuli of different sizes will be rescaled to match the target stimulus """ x_factors, y_factors = calculate_nonfixation_factors(stimuli, index) non...
5,320,455
def remove(ctx, key): """Remove the config value for a key.""" log.debug('chemdataextractor.config.remove') del config[key]
5,320,456
def get_commit_log(url, revnum): """Return the log message for a specific integer revision number.""" out = launchsvn("log --incremental -r%d %s" % (revnum, url)) return recode_stdout_to_file("".join(out[1:]))
5,320,457
def cov(x, rowvar=False, bias=False, ddof=None, aweights=None): """ Estimates covariance matrix like numpy.cov https://github.com/pytorch/pytorch/issues/19037 """ # ensure at least 2D if x.dim() == 1: x = x.view(-1, 1) # treat each column as a data point, each row as a variable ...
5,320,458
def write_lammps_data(filename: str, geom: ase.Atoms, element_list: List, **kwargs): """ Wrapper for ase.io.lammpsdata.write_lammps_data(). Args: filename (str): path to lammps data. geom (ase.Atoms): configuration of interes...
5,320,459
def tle_fmt_int(num, digits=5): """ Return an integer right-aligned string with DIGITS of precision, all blank if num=0 Ignores sign. """ if num: num = abs(num) else: return " "*digits string_int = "{:>{DIGITS}d}".format(num,DIGITS=digits) return string_int
5,320,460
def weight_graph_with_cohd_frequency(g, default_value=0, normalized=False): """ Weight a graph with the cohd frequency data :param g: networkx graph :param default_value: default value for the property :param normalized: if you want the results to all sum to 1 or not :return: None (modifies graph directly) """ ...
5,320,461
def SignalCollection(metasignals): # noqa: C901 """Class factory for ``SignalCollection`` objects.""" @six.add_metaclass(MetaCollection) class SignalCollection(object): _metasignals = metasignals def __init__(self, psr): self.psrname = psr.name # instantiate all th...
5,320,462
def get_status(): """Return classifier status.""" return 'ok'
5,320,463
def get_config_info() -> dict: """Gets the config from core sqlfluff and sqlfluff plugins and merges them.""" plugin_manager = get_plugin_manager() configs_info = plugin_manager.hook.get_configs_info() return { k: v for config_info_dict in configs_info for k, v in config_info_dict.items() }
5,320,464
def landing_page(request, page): """Return resource landing page context.""" edit_resource = check_resource_mode(request) return get_page_context(page, request.user, resource_edit=edit_resource, request=request)
5,320,465
def test_error_on_zero_ref(schema: Type[BaseModel], data: Dict[str, Any]): """ Test that a region_from_or_ref is not under zero """ with pytest.raises(ValidationError) as exc_info: schema(ref_region_from=0, **data) assert len(exc_info.value.errors()) == 1 assert exc_info.value.errors()[...
5,320,466
def _smooth_l1_loss(pred: Tensor, target: Tensor, beta: float = 1.) -> Tensor: """(F.smooth_l1_loss()) :param pred: shape(N, In) :param target: shape(N, In) :param beta: smooth线 :return: ()""" diff = torch.abs(target - pred) return torch.mean(torch.where(diff < beta, 0.5 * diff ** 2 / beta...
5,320,467
def get_suffixes( txt_file, suffix_file, stdout_file="", threshold=sys.maxint, prefix=u'__' ): """ Replace all words in <txt_file> with suffixes where possible. Set of suffixes must be provided in <suffix_file> The new corpus is written to <stdout_file> or to standard output if no file provided <prefix> -- st...
5,320,468
def make_all_1d_figures(folders, save_folder='../figures/decomposition/', prefix='', rescale=False, data_folder=None, skip_kernel_evaluation=False, unit='year', all_depths=False): """Crawls the results directory, and makes decomposition plots for each file. prefix is an optional string prepended to the out...
5,320,469
def solve_assignment(weights, exclude_zero=False): """Finds matching that maximizes sum of edge weights. Args: weights: 2D array of edge weights. exclude_zero: Exclude pairs with zero weight from result. Returns: Integer array of pairs with shape [num_matches, 2]. """ rs, cs = scipy.optimize.lin...
5,320,470
def _initXDG(): """Initialize config path per XDG basedir-spec and resolve the final location of state file storage. Returns: str: file path to state file as per XDG spec and current env. """ # per the XDG basedir-spec we adhere to $XDG_CONFIG_HOME if it's set, otherwise assume $HOME/.config ...
5,320,471
def get_stdout(jobname, jobid): """Get stdout for job <jobid> Returns: 200 OK: file (on success) 404 Not Found: Job not found (on NotFoundWarning) 404 Not Found: Result not found (on NotFoundWarning) 500 Internal Server Error (on error) """ user = set_user() try: ...
5,320,472
def test_attributes_added(): """ . """ obj = Validatable({"an-attribute": True}, ["an-attribute"]) assert obj._validate_attributes == ["an-attribute"], "Attributes set" assert obj._validator_map == {"an-attribute": True}, "Map set" obj._add_validate_attribute("other-attribute") assert o...
5,320,473
def stepwise_kpca(X, gamma, n_components): """ Implementation of a RBF kernel PCA. Arguments: X: A MxN dataset as NumPy array where the samples are stored as rows (M), and the attributes defined as columns (N). gamma: A free parameter (coefficient) for the RBF kernel. n_c...
5,320,474
def make_val_and_grad_fn(value_fn): """Function decorator to compute both function value and gradient. For example: ``` @tff.math.make_val_and_grad_fn def quadratic(x): return tf.reduce_sum(scales * (x - minimum) ** 2, axis=-1) ``` Turns `quadratic` into a function that accepts a point as a `Tensor...
5,320,475
def set_north_angle(north_angle:float) -> None: """ Args: north_angle (float): a angle value """
5,320,476
def showCatalog(): """This showCatalog handler will diplay the home page for both a user not logged in and one for a logged in user. """ categories = session.query(Category).order_by(asc(Category.name)) # Limit the query to a maximum of 10 and order by the most recent # items added, which is id...
5,320,477
def is_fill_compute_seq(seq): """Test whether *seq* can be converted to a FillComputeSeq. True only if it is a FillCompute element or contains at least one such, and it is not a Source sequence. """ if is_source(seq): return False is_fcseq = False try: is_fcseq = any(map...
5,320,478
def upload_model(uploadfile, name=None): # noqa: E501 """upload_model # noqa: E501 :param uploadfile: The model YAML file to upload. Can be a GZip-compressed TAR file (.tgz, .tar.gz) or a YAML file (.yaml, .yml). Maximum size is 32MB. :type uploadfile: werkzeug.datastructures.FileStorage :param ...
5,320,479
def visual_callback_3d(fig=None, plot_each=1): """ Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. Only works for 3D images. Parameters --------...
5,320,480
def _erfint(x): """ Integral of the error function. Parameters ---------- x : float or array Argument. Returns ------- float or array Integral of the error function. """ return x * erf(x) - 1.0/np.sqrt(np.pi) * (1.0-np.exp(-x**2))
5,320,481
def model(x, n_pos, mask_miss1, mask_miss2, is_train=False, reuse=None, data_format='channels_last'): """Defines the entire pose estimation model.""" def _conv2d(x, c, filter_size, strides, act, padding, name): return Conv2d( x, c, filter_size, strides, act, padding, W_init=W_init, b_init=b...
5,320,482
def zeros(shape: Optional[Union[int, tuple, list]] = None) -> 'ArrayInterval': """ Instantiate an `ArrayInterval` filled with zeros. Note: The difference from numpy is that the argument shape is optional. When shape is None, some operations aren't supported because the length is unknown...
5,320,483
def anova_total_mean_square(Ns, means, sigmas): """ This function performs an average over multiple sets of observations, each with its own standard deviation. For example: 5 simulations compute RMSDs+-Sigma of the same protein. What is the aggregate? See: http://www.burtonsys.com/climate/composite_stan...
5,320,484
def compute_lsb(n_bits, fsr_min, fsr_max, half_bit=None): """ Computes the least significant bit (LSB) magnitude in the stage MDAC and sub-ADC to achieve a desired full scale range (FSR). The input FSR and output FSR are assumed to be the same so only one value is returned. :param n_bits: Number of...
5,320,485
def test_comparison(): """ Function should be called when being compared to other values """ fn, lazy = get_lazy() fn.return_value = 1 assert lazy < 2 assert lazy > 0 assert lazy == 1 assert lazy >= 1 assert lazy <= 1 assert lazy != 0 assert fn.call_count == 6, "Expected 6 calls,...
5,320,486
def save_regression_result(result, filename, **meta): """ Save a regression result to a pickle file. Parameters ---------- result : linearmodels.panel.results.PanelEffectsResults the panel regression result filename : str the name of the file to save the result to **meta : k...
5,320,487
def proximity_matrix(rf, X, normalize=True): """ Calculate proximity matrix :param rf: :param X: :param normalize: :return: """ leaves = rf.apply(X) n_trees = leaves.shape[1] prox_mat = np.zeros((leaves.shape[0], leaves.shape[0])) for i in range(n_trees): a = leaves...
5,320,488
def upload_to_s3_v2(local_path: str, bucket_name: str, object_name: str): """ path_output: local dir file path bucket_name: name of s3 bucket key_path: key path + file name = object name """ s3 = boto3.client("s3") response = s3.upload_file(local_path, bucket_name, object_name) return re...
5,320,489
def marks(category, mark=None, category_marks=None, public=False): """Assign marks to a test or suite of tests, grouped by a category.""" def decorator(test_item): if mark is None and category_marks is None: raise ValueError("One of mark or category_marks must be defined") test_item...
5,320,490
def get_random_ua(): """return a random user-agent string from file""" # stop condition, file does not exists, not readable... # + file operation with open('headers.txt') as hbuffer: all = hbuffer.readlines() return secrets.choice(all).strip()
5,320,491
def is_nondecreasing(arr): """ Returns true if the sequence is non-decreasing. """ return all([x <= y for x, y in zip(arr, arr[1:])])
5,320,492
def underscore_to_camelcase(value): """ Converts underscore notation (something_named_this) to camelcase notation (somethingNamedThis) >>> underscore_to_camelcase('country_code') 'countryCode' >>> underscore_to_camelcase('country') 'country' >>> underscore_to_camelcase('price_GBP') 'pri...
5,320,493
def findCenter(S): """Find the approximate center atom of a structure. The center of the structure is the atom closest to (0.5, 0.5, 0.5) Returns the index of the atom. """ best = -1 bestd = len(S) center = [0.5, 0.5, 0.5] # the cannonical center for i in range(len(S)): d = S....
5,320,494
def add_noise(rots, level): """adds random noise to a rotation matrix.""" noised_rots = [[np.random.uniform(-level,level,4)]*23]*rots.shape[0] noised_rots = Quaternions(np.array(noised_rots)) return rots+noised_rots
5,320,495
def content_tree_update(request): """Returns all content of a given contenttree.""" assert request.contenttree.patched, "contenttree should be patched here..." # SANITIZE JSON DATA jsoncontent = request.json_body['content'] data = remove_unvalidated_fields(jsoncontent, peerreview_update_schema) ...
5,320,496
def compute_overlap_region(db_ref, db_new): """ Computes the overlapping/shared region between two images. Outputs: - Corner coordinates of the overlapping region in the SRS - Corresponding pixel indexes in both input images """ cornerCoord_ref = gdal.Info(db_ref, format='json')['co...
5,320,497
def main(): """Make a jazz noise here""" args = get_args() text = args.file.read().strip() candidate_tags = re.findall('<([^!/]+?)>', text) real_tags = [tag for tag in candidate_tags if re.search(f'</{tag}>', text)] if not real_tags: sys.exit("This doesn't look like an html page") ...
5,320,498
def _calculate_team_size_score( projects: List[dict], assignments: List[AssignmentTuple], project: dict, student: dict ) -> int: """Calculates the weighted score based on how far away from the average team size this project would be after assigning the student Args: projects (List[dict]): Al...
5,320,499