content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def get_dftd3_energy(ipt): """ Grimme's D3 correction to energy """ fxyz, func, iabc = ipt sabc = ' -abc' if iabc else '' cmd = "dftd3 %s -func %s -bj%s | grep Edisp | awk '{print $NF}'"%(fxyz,func,sabc) #print(cmd) #; sys.exit(2) e = eval(os.popen(cmd).read().strip()) return e
9c0098fd619e202b867b956b56227124d10cae8a
28,000
import itertools def get_state_vect_cols(prefix=''): """Get the column names of the state vector components with the provided `prefix`. :param prefix: The prefix that is used in front of the state vector components in the column names, examples are `physics_pred` and `physics_err` or none...
d61c5ebd2aad8c679dda50fa1e310ebf11480e01
28,001
import types def set_df_index(typingctx, df_t, index_t=None): """used in very limited cases like distributed to_csv() to create a new dataframe with index """ # TODO: make inplace when dfs are full objects def codegen(context, builder, signature, args): in_df_arg = args[0] index =...
7bdbdee58bc2a8a71583d43d637a6fa9ab7e8224
28,002
import six import shlex def parse_options(options=None, api=False): """ Parse given option string :param options: :type options: :param api :type api: boolean :return: :rtype: """ if isinstance(options, six.string_types): args = shlex.split(options) options = v...
f8a2b3671dab3ffc5f23bd937181324bc1c0d9c7
28,003
import random from datetime import datetime def data_for_column(column: dict, kwargs: dict, size: int) -> list: """Generates data for schema column :param dict column: Column definition :param dict kwargs: Faker keyword arguments :param int size: Number of rows :return: List of random data for a ...
d2ba76d48d80cc256f1959d8fa617b81301119d0
28,004
def peak_bin(peaks, i): """Return the (bin) index of the ith largest peak. Peaks is a list of tuples (i, x[i]) of peak indices i and values x[i], sorted in decreasing order by peak value.""" if len(peaks) > i: return peaks[i][0] else: return np.nan
fc667fe04c856e3090ded9ca8eb0a45d51cda74a
28,005
def fetch_all(path, params=None, client=default_client): """ Args: path (str): The path for which we want to retrieve all entries. Returns: list: All entries stored in database for a given model. You can add a filter to the model name like this: "tasks?project_id=project-id" """...
d663414388b9b6e105fab42d8e4d9cde558322cf
28,006
from datetime import datetime import calendar def plotter(fdict): """ Go """ pgconn = get_dbconn('coop') cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) ctx = get_autoplot_context(fdict, get_description()) station = ctx['station'] table = "alldata_%s" % (station[:2],) nt...
4b11cee286494963afb43cfc5b6ab7e56c281476
28,007
def link_library_dynamic(hs, dep_info, object_files, my_pkg_id): """Link a dynamic library for the package using given object files. Returns: File: Produced dynamic library. """ dynamic_library = hs.actions.declare_file( "lib{0}-ghc{1}.{2}".format( pkg_id.library_name(hs, my_pkg_id), hs.too...
5171d75c71b52e2487ff1d349add86c042a84062
28,008
def save_mvgcca_latents_space(X, W, model, path, prefix, epochs): """Saves the list containing the common latent space Z and all the views latent space Z_m. - X : [np.array(n x d1),...,np.array(n x dM)] multivews features ; n number of instances; dm dimension of views m ; M number of views ...
dc0fbb15dd73e44bf1b1b2c74b173cfb6b8cf1d8
28,009
def TDC_sampling(in_channels, mode='downsampling'): """ wrapper_function: -> TIC_sampling [B, in_channels, T, F] => [B, in_channels, T, F//2 or F*2] in_channels: number of input channels """ return TIC_sampling(in_channels, mode)
8458e9fe9bfd6bc92af2940b4c3ea5d2f09eb40a
28,010
def bmxbm(s, t, batch_first=True): """ Batched matrix and batched matrix multiplication. """ if batch_first: equation = "aij,ajk->aik" else: equation = "ija,jka->ika" return tf.einsum(equation, s, t)
6ac60eb1ffeed2caad312fd4691d689e705986c0
28,011
import re def get_all_semantic_case_ids(): """Get iterator over test sorted IDs of all cases in the SBML semantic suite""" pattern = re.compile(r'\d{5}') return sorted(str(x.name) for x in SBML_SEMANTIC_CASES_DIR.iterdir() if pattern.match(x.name))
d4a5cba008010f02398bb61c32f06450610de350
28,012
def generate_points(n=500, min_=0, max_=1): """ Generate a list of n points. Parameters ---------- n : int min_ : float max_ : float Returns ------- list List of length n with tuples (x, y) where x is in [min_, max_] and y is either 0 or 1. """ assert ma...
fe2dbe0ed281716a465804d67014badab96fb414
28,013
def gce(nvf): """ Write the necessary code for launch the VNF using GCE :param nvf: :return: vagrantfile code """ element = Template(u'''\ config.vm.box = "{{image}}" config.vm.provider :google do |google, override| google.google_project_id = {{google_project_id}} google.google_client_email = {...
588c2472b2a957a1eda64bef526b6410103b72b2
28,014
import os def save_pretrained_models( model: nn.Module, config: DictConfig, path: str, ) -> DictConfig: """ Save the pretrained models and configs to local to make future loading not dependent on Internet access. By loading local checkpoints, Huggingface doesn't need to download pr...
f33fb55d8a152581c906470156a0dc8c87dadef4
28,015
from datetime import datetime def get_ethpm_birth_block( w3: Web3, from_block: int, to_block: int, target_timestamp: int ) -> int: """ Returns the closest block found before the target_timestamp """ version_release_date = datetime.fromtimestamp(target_timestamp) while from_block < to_block: ...
c2448152cea2a3c9a9dd227a5126e2dd0767b773
28,016
def Line(p0, p1=None, c="r", alpha=1, lw=1, dotted=False, res=None): """ Build the line segment between points `p0` and `p1`. If `p0` is a list of points returns the line connecting them. A 2D set of coords can also be passed as p0=[x..], p1=[y..]. :param c: color name, number, or list of [R,G,B] c...
1a56c260ad0d3478b51db03fa267898c637bf819
28,017
def date_dd(dataset, source): """Display 3 blocks: 1. image of the patent, 2. choice block, 3. text block for date. 2 is artifical and should be ignored""" def get_stream(): # Load the directory of images and add options to each task stream = Images(source) for eg in stream: ...
fae232b97ab4d758aceea806ebc95816db3cb044
28,018
def sort(array=[12,4,5,6,7,3,1,15]): """Sort the array by using quicksort.""" less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) ...
bc31df069f8e985d620032b9053bd8f13880780f
28,019
def _derive_country_JP(place): """Derive Japanese place names.""" derived = [] if _JP_FU_SUFFIX.search(place.asciiname): bare = _JP_FU_SUFFIX.sub("", place.asciiname) derived += [bare, bare + " prefecture", bare + " pref"] elif _JP_KEN_SUFFIX.search(place.asciiname): bare = _JP_K...
aea2aec9611457e63de335c3fe333be74c0efa6f
28,020
from typing import Optional async def remove_completed_game(player_id: str, game_id: str) -> Optional[dict]: """ Updates the player's current games by removing a game from it. :param player_id: the object id of the player :param game_id: the object id of the game :return: an awaitable resolving ...
2e5f4ec3af053d1f1685e6a576d8027db585bc87
28,021
def triangulate_dlt(Ps, ys): """Triangulate 3D position between two 2D correspondances using the direct linear transformation (DLT) method. If any 2D correspondance is missing (i.e. NaN), returns triangulated position as NaN value as well. TODO: Normalize input data (see HZ, p104. "4.4 Transformat...
0e291bdcd3b95eb6dd29f3f5a305d0fe88c07072
28,022
def is_multioutput(y): """Whether the target y is multi-output (or multi-index)""" return hasattr(y, "shape") and y.ndim == 2 and y.shape[1] > 1
bcdaa46c304fec50c173dffca5f1f1d5d8871a58
28,023
def read_all(db: Session): """ Get all dimensions. :param db: :return: List[QuestionModel] """ question = db.query(QuestionModel).all() return question
a854c4667dc30918cd1e9ec767d65fa8ad1fb5ca
28,024
def get_all_tenants(context): """Returns a list of all tenants stored in repository. :param context: context of the transaction """ return context.session.query(db_models.AristaProvisionedProjects)
62d8fed653f5b8e380caa47f5f408ecab860a58b
28,025
import os def load_sample_nni(series='short'): """Returns a short-term (5min) or long-term (60min) series of sample NNI found in the pyhrv/files/ directory. Docs: Parameters ---------- series : string, optional If 'long', returns a 60min NNI series, if 'short', returns a 5min NNI series Returns ------- ...
d3ffd2208321f432312f87922deb4aac22c87ce5
28,026
def total_sub_pixels_2d_from(mask_2d: np.ndarray, sub_size: int) -> int: """ Returns the total number of sub-pixels in unmasked pixels in a mask. Parameters ---------- mask_2d : np.ndarray A 2D array of bools, where `False` values are unmasked and included when counting sub pixels. sub_...
98461ffe073172db596570630ccfbd27384c7e3a
28,027
import logging import sys def connectOutputLogger(file=None, logger_name='output'): """ Function that connects the output logger. This is always enabled and hardwired to generate logging.INFO level messages only. @params file : Output file to store these messages into. @default None : If file...
ce3b0f2a9910afd1ea364177f746353559f63bd2
28,028
from simtk import unit as simtk_unit import torch def formaldehyde_conformer(formaldehyde) -> torch.Tensor: """Returns a conformer [A] of formaldehyde with an ordering which matches the ``formaldehyde`` fixture.""" formaldehyde.generate_conformers(n_conformers=1) conformer = formaldehyde.conformers[...
f5a9a19f6dd8e26a121e496161fa6da7b8f63047
28,029
import warnings def reduce_function(op_func, input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None): """ Handler function for Tensorflow depreciation of keep_dims for tf 1.8 and above, but tf 1.4 requires keep_dims :param op_func: expects the function to handle ...
f6433479bcb01a8fc5dfc2c08dd70bf2fe500e94
28,030
from typing import Mapping def filter_dict(function_or_value, dict_to_filter): """ Filter by value >>> filter_dict(123, {'a': 123, 'b': 1234}) {'b': 1234} Filter by value not applicable >>> filter_dict(123, {'a': 1234, 'b': 5123}) {'a': 1234, 'b': 5123} Embedded filter by val...
6403f716c21a1cfef046174899183858837bb92e
28,031
import click from typing import OrderedDict import json import sys def _buy(config, client, machine_auth, resource, info_only=False, payment_method='offchain', header=(), method='GET', output_file=None, data=None, data_file=None, maxprice=10000): """Purchase a 402-enabled resource via CLI. This func...
52a139a4c0ac7cff9fb788b646d2e2744f3506dd
28,032
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) return model
ba0f11d8645f3dcc5ccc48ec718de0c6ff624930
28,033
import torch import math def irfft(x, res): """ :param x: tensor of shape [..., m] :return: tensor of shape [..., alpha] """ assert res % 2 == 1 *size, sm = x.shape x = x.reshape(-1, sm) x = torch.cat([ x.new_zeros(x.shape[0], (res - sm) // 2), x, x.new_zeros(x....
8f383523bc0c4ed6895d8aad0aca2758401d2fe5
28,034
import torch def calc_ranks(idx, label, pred_score): """Calculating triples score ranks. Args: idx ([type]): The id of the entity to be predicted. label ([type]): The id of existing triples, to calc filtered results. pred_score ([type]): The score of the triple predicted by the model....
1f3d56c9a93afdd314c9a244319ef78668426481
28,035
def GBT(trainingData, testData): """ Gradient Boosted Tree Regression Model :param trainingData: :param testData: :return: Trained model, predictions """ gbt = GBTRegressor( maxIter=100, maxDepth=6, seed=42) model = gbt.fit(trainingData) predictions = model.transform(testData) r...
4e17c7188ccdd2676463a705a4e3ab4ccbc5adeb
28,036
def fromcolumns(cols, header=None, missing=None): """View a sequence of columns as a table, e.g.:: >>> import petl as etl >>> cols = [[0, 1, 2], ['a', 'b', 'c']] >>> tbl = etl.fromcolumns(cols) >>> tbl +----+-----+ | f0 | f1 | +====+=====+ | 0 | 'a'...
c033e0fbc11e18a73eb8216e4a3a2c79a0756bb8
28,037
import re def function_sql(field, mysql_result_list): """ 替换MySQL查询结果的方法 :param field: 第一个参数是yaml文件里面定义的字段 :param mysql_result_list: 第二个参数是MySQL查询结果列表 :return: """ if "{__SQL" in field: mysql_index_list = re.findall("{__SQL(.+?)}", field) # 获取索引列表 for i in mysql_in...
769881ae5e3a7caa036c977785827e219e5ab92b
28,038
import os def get_data_path(): """ Return the location of the settings file for the data readers. """ return os.path.dirname(__file__)
aaae8a5c9b5b18c8b2d9513cb4b7be6e466bb443
28,039
def enable_dropout(model, rate=None, custom_objects={}): """ Enables the droput layer - used for monte carlo droput based uncertainty computation Note: the weights needs to be reloaded after calling this model >>> model = enable_dropout(model) >>> model.load_weights('path to model weight') :par...
2268c23bc5598fcf0befe76a15f0dbc444e28828
28,040
import ctypes def get_max_torque_norm(p_state, idx_image=-1, idx_chain=-1): """Returns the current maximum norm of the torque acting on any spin.""" return float(_Get_MaxTorqueNorm(ctypes.c_void_p(p_state), ctypes.c_int(idx_image), ctypes.c_int(idx_chain)))
b6ae73ef269a192b5aafc96e939a0ab1f9a937be
28,041
def filter_by_zscore(data, features, remove_z): """Remove rows with |z scores| > remove_z""" return data[(np.abs(np.nan_to_num(zscore(data[features]), posinf=0.0, neginf=0.0)) < remove_z).all(axis=1)]
bbaad3ee7879d64dafb2e45062c6cbe97ff457bc
28,042
def _GetProperty(obj, components): """Grabs a property from obj.""" if obj is None: return None elif not components: return obj elif (isinstance(components[0], _Key) and isinstance(obj, dict)): return _GetProperty(obj.get(components[0]), components[1:]) elif (isinstance(components[0], _...
d887613e06078fcde887d51c8f83cc9ddc8f16f8
28,043
def make_similarity_function(similarity=None, distance=None, radius=None): """ Function creating a similarity function returning True if the compared items are similar from a variety of functions & parameters. Basically, if a distance function is given, it will be inverted and if a radius is given,...
b8eeeeb466f21f2b3605941253f56392c3e41e88
28,044
from typing import Optional def prepare_error_message(message: str, error_context: Optional[str] = None) -> str: """ If `error_context` is not None prepend that to error message. """ if error_context is not None: return error_context + ": " + message else: return message
ea95d40797fcc431412990706d5c098a07986156
28,045
def _options_from_args(args): """Returns a QRCodeOptions instance from the provided arguments. """ options = args.get('options') if options: if not isinstance(options, QRCodeOptions): raise TypeError('The options argument must be of type QRCodeOptions.') else: # Convert t...
ff895e537a0d2c00f42e10f827b8176865902774
28,046
def calc_q_rq_H(region, R_type): """単位面積当たりの必要暖房能力 Args: region(int): 省エネルギー地域区分 R_type(string): 暖冷房区画の種類 Returns: float: 単位面積当たりの必要暖房能力 Raises: ValueError: R_type が '主たる居室' または 'その他の居室' 以外の場合に発生する """ table_3 = get_table_3() if R_type == '主たる居室': return t...
1b413f0d83d723e1ef01c558cbc54e8afddc65ac
28,047
def tuple_compare_lt(left, right): """Compare two 'TupleOf' instances by comparing their individual elements.""" for i in range(min(len(left), len(right))): if left[i] > right[i]: return False if left[i] < right[i]: return True return len(left) < len(right)
8f93d0c1336fd63d7c7f04cf54680de25acfdafb
28,048
def multilevel_roi_align(inputs, boxes, image_shape, crop_size: int = 7): """Perform a batch multilevel roi_align on the inputs Arguments: - *inputs*: A list of tensors of shape [batch_size, width, height, channel] representing the pyramid. - *boxes*: A tensor and shape [batch_size, num_b...
3b150e6b6bcada3d3633f1edf61a99a566792849
28,049
def login(): """Login user""" # Instantiate login form form = LoginForm() username = form.username.data if form.validate_on_submit(): # Query database for username and validate form submission user = User.query.filter_by(username=username).first() # if user exists i...
fa1e1814d71bcbf04fda08b282f3f1a58965dcfb
28,050
from datetime import datetime import uuid def serialize(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, datetime.datetime): serial = obj.isoformat(sep='T') return serial if isinstance(obj, uuid.UUID): serial = str(obj) retur...
c20abaac68e8f8c8314a6dbbaee128b54110705c
28,051
def clean_names_AZ(col): """ Removes any non-alpha characters (excluding spaces) from a string. Replaces these characters with an empty space. Trims outer whitespace. Example -------- >>> Input: "JOHN SMITH 2000" >>> Output: "JOHN SMITH" """ return trim(regexp_replace(col, "[^A-Z ]+...
4db710ec573087df59109046ea2a965c7545f1a2
28,052
def check_continent_node_membership(continents, continent_node_id): """The function checks that a node continent is bound to the corresponding relation through 'label' membership. """ assert continent_node_id[0] == 'n', ("A node expected in " "check_continent...
7ef0895e26fdd495f54ac58ea35513178f00eb19
28,053
import string def remove_punctuation(input_string): """ remove the punctuation of input Parameters ---------- input_string : string Returns ------- output_string : string string without punctuation ###from assignment encoder """ out_...
2bbd1dc90d37c1ad16698092b6269c0fe601d902
28,054
from typing import Any def field_value_between(value: Any = None, field: str = None, lower: float = None, upper: float = None) -> bool: """ Validate value at the given field to be between the lower/upper boundaries. """ if not value: return False if not isinstance(...
4ff2dfa814f0ddda7efca3ce19f137a0d86b9f40
28,055
import yaml def j2_to_json(path_in, path_out, **kwargs): """Render a yaml.j2 chart to JSON. Args: path_in: the j2 template path path_out: the JSON path to write to kwargs: data to pass to the j2 template Returns: the file path and JSON string """ return pipe( rend...
2cd41eb29e293e44772855f7d66e7425eedaec8d
28,056
def user_logged_out(connection,user): """ update login status to false when user has logged out :param connection: :param user: :return: """ with connection: return connection.execute(UPDATE_USER_LOGIN_STATUS_TO_FALSE,(user,))
b355fa6e74180adb7504e60602cb164095e1898d
28,057
def findGrayscaleTilesInImage(img): """ Find chessboard and convert into input tiles for CNN """ if img is None: return None, None # Convert to grayscale numpy array img_arr = np.asarray(img.convert("L"), dtype=np.float32) # Use computer vision to find orthorectified chessboard corners in image cor...
d3431c519f53c0a56b144dde8196d58000f2f788
28,058
def run(df, docs, columns): """ converts each column to type int :param df: :param columns: :return: """ for doc in docs: doc.start("t07 - Change type of {} to int".format(str(columns).replace("'", "")), df) for column in columns: df[column] = df[column].astype(int) ...
5d360a764ad30a80c39d58f9aeb520d7c57f7903
28,059
import requests def get_articles(): """ Retreives the articles list (via an API request) """ endpoint = "%s%s" % ( settings.API_BASE_URL, reverse("api:articles-list") ) headers = DEFAULT_REQUESTS_HEADERS r = requests.get( endpoint, headers=DEFAULT_REQUE...
fb2b59cc301890b8c6f4c6c115b6f08f4a4cbe72
28,060
import numpy def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0, callback=None, preconditioner = None): """ Unconstrained minimization of a function using the Newton-CG method. Parameters ...
bb2d4c3d1303adebe856f6c3ac13cd92beeee0ab
28,061
def add_missing_flow_by_fields(flowby_partial_df, flowbyfields): """ Add in missing fields to have a complete and ordered :param flowby_partial_df: Either flowbyactivity or flowbysector df :param flowbyfields: Either flow_by_activity_fields, flow_by_sector_fields, or flow_by_sector_collapsed_fields ...
49eb8810c7c2c4e852a40aa86e2d2d2a8506f253
28,062
from datetime import datetime def calcular_diferencia_dias(fin_dia): """ Obtiene la diferencia de dias entre una fecha y hoy """ hoy = datetime.now() end = datetime.strptime(str(fin_dia), '%Y-%m-%d') return abs(end - hoy).days
41b732f3bb09d2deca4be034273a5fed74971386
28,063
def matrix_base_mpl(matrix, positions, substitutions, conservation=None, secondary_structure=None, wildtype_sequence=None, min_value=None, max_value=None, ax=None, colormap=plt.cm.RdBu_r, colormap_conservation=plt.cm.Oranges, na_color="#bbb...
ef661fd556b3ba2e4c313e032e8ef3be532bb73d
28,064
def gaussian_laplace(input, sigma, output=None, mode="reflect", cval=0.0, **kwargs): """Multi-dimensional Laplace filter using Gaussian second derivatives. Args: input (cupy.ndarray): The input array. sigma (scalar or sequence of scalar): Standard deviations for each axis ...
6b5f184b658dd446a4f3ec7de0ee126f33663b0c
28,065
def get_commits_after_forkpoint(main_dir, base_sha, head_sha, repo_name, log, secure_repo_name): """List commit hashes between base_sha and head_sha :param main_dir: model directory :param base_sha: base SHA i.e. point of the history when the branch started diverging from the main branch. :para...
6b8f8609adb80903215fc11f08380db3f8deffcd
28,066
def perimeter_mask(image, corner_fraction=0.035): """ Create boolean mask for image with a perimeter marked as True. The perimeter is the same width as the corners created by corner_mask. Args: image : the image to work with corner_fraction: determines the width of the perimeter Re...
afc755dccfffa9ff68e060a6af3da0d38d323178
28,067
def vgg13_bn(**kwargs): """VGG 13-layer model (configuration "B") with batch normalization""" model = VGG(make_layers(cfg['B'], batch_norm=True), **kwargs) return model
1fa3ffdbb301b55a48fc1912baab84006705e15f
28,068
import regex def convert_version_to_tuple(version: str) -> VersionTuple: """ Convert version info from string representation to tuple representation. The tuple representation is convenient for direct comparison. """ m = regex.fullmatch(r"(?P<major>\d+)\.(?P<minor>\d+)", version) if not m: ...
6c197988ae2c98481f9b16f90f9ae3f7072ac7c8
28,069
from typing import Callable def SU3GradientTF( f: Callable[[Tensor], Tensor], x: Tensor, ) -> tuple[Tensor, Tensor]: """Compute gradient using TensorFlow GradientTape. y = f(x) must be a real scalar value. Returns: - (f(x), D), where D = T^a D^a = T^a ∂_a f(x) NOTE: Use real v...
93b029e0a2854e651d4c6ea5995f8d952f9a64e6
28,070
def create_app(config): """Flask application factory. Returns: Flask Application with BrazilDataCubeDB extension prepared. """ app = Flask(__name__) BrazilDataCubeDB(app) return app
d8ba6d7306508e4a55f9f3dbee5d17df16c56820
28,071
import string def genpass_comprehension(length=8, chars=string.letters+string.digits): """Generate password using a list comprehension. """ # Can be rewritten as a list comprehension. return ''.join([choice(chars) for i in range(length)])
d77b89e2872eef92390d08f555adbb52f9da1c34
28,072
import functools def typed(*types): """Type annotation. The final type is the output type. """ if len(types) < 1: raise SyntaxError('Too few arguments: typed{}'.format(types)) if len(types) > 3: raise NotImplementedError('Too many arguments: typed{}'.format(types)) result_typ...
90f100bebd5778d36eee1ad04b7c831b003ce604
28,073
from typing import Tuple def insert_linebreaks( input_fragments: StyleAndTextTuples, max_line_width: int, truncate_long_lines: bool = True) -> Tuple[StyleAndTextTuples, int]: """Add line breaks at max_line_width if truncate_long_lines is True. Returns input_fragments with each charact...
ec9faf8ff80e3500487634b759a136dc2deca684
28,074
def score_reactant_combination(candidate_combination, scoring_fcn): """ Generates a score for a combination of reactant candidates according to the criteria. """ # Extract only the reactant candidate compound ID's. reactant_ids = [combo[0] for combo in candidate_combination] # Score the reactant candi...
715a21bf24af0a60ba3ea421b7bf8dcebcca17fc
28,075
import sys def main(argv=None): """Provide the main entry point.""" help_builder.init("charmcraft", GENERAL_SUMMARY, COMMAND_GROUPS) emit.init(EmitterMode.NORMAL, "charmcraft", f"Starting charmcraft version {__version__}") if argv is None: argv = sys.argv extra_global_options = [ ...
6adf05b9883b698a69c3845df2f58f48953e98e8
28,076
import logging import os import json def xmind_testsuite_to_json_file(xmind_file): """Convert XMind file to a testsuite json file""" xmind_file = get_absolute_path(xmind_file) logging.info('Start converting XMind file(%s) to testsuites json file...', xmind_file) testsuites = get_xmind_testsuite_list(x...
d8c7c7aec99c76e7e2d1195dd4f557e68be3adfa
28,077
def get_named_entities(df): """ Count the named entities that are neither A nor B. Hopefully this correlates with class "Neither". :param df: competition data with one extra field spacy_nlp_doc: precomputed nlp(text) :return: """ named_df = pd.DataFrame(0, index=df.index, columns=["named_e...
65469fe65c8808943343d952fd82ebe62bb9df97
28,078
def normalize(vectors): """ Normalize a set of vectors. The length of the returned vectors will be unity. Parameters ---------- vectors : np.ndarray Set of vectors of any length, except zero. """ if len(vectors.shape) == 1: return vectors / np.linalg.norm(vectors) ...
839104d17a3ccbfd1191474bf95076445b4b0464
28,079
def get_all_requests(current_user): """Gets all requests""" all_requests = [] for request in request_model.requests.values(): all_requests.append(request) return jsonify(all_requests)
bcadfb936826b3a33f809cc95af1a991c5bf741e
28,080
def RunManifestExe(target, source, env): """Calls RunManifest for updating an executable (resource_num=1).""" return RunManifest(target, source, env, resource_num=1)
629ffccb7b163514bd91c790894bdfec3683110e
28,081
import torch def dist_reduce_tensor(tensor, dst=0): """Reduce to specific rank""" world_size = get_world_size() if world_size < 2: return tensor with torch.no_grad(): dist.reduce(tensor, dst=dst) if get_rank() == dst: tensor.div_(world_size) return tensor
d64d153145bffaf454dd3f46154db156b600bac3
28,082
def upload_blob(bucket_name, source_file_name, destination_blob_name): """Uploads a file to the bucket.""" storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_file(source_file_name) print('File {} uploaded ...
b63d6bb0ede33d68d684b98968e3e94efbd0c5df
28,083
def get_lines(matrix, loc): """Returns lines that pass though `loc`. Matrix can be indices. Args: matrix: a N by N matrix representing the board loc: a tuple of loc coordinates Returns: Numerical values on the horizontal, vertical, and diagonal lines that pass through loc. ...
43909460e847d5dde88216cc37b902a56ba2d261
28,084
from bs4 import BeautifulSoup from typing import Dict def process_citations_in_paragraph(para_el: BeautifulSoup, sp: BeautifulSoup, bibs: Dict, bracket: bool) -> Dict: """ Process all citations in paragraph and generate a dict for surface forms :param para_el: :param sp: :param bibs: :param br...
74418fafc2a2d828b702555b79b515d9b16d9f10
28,085
def duration(start_time, end_time=None): """Get a timedelta between end_time and start_time, where end_time defaults to now(). WARNING: mixing tz-aware and naive datetimes in start_time and end_time will cause an error. """ if not start_time: return None last_time = end_time if end_...
89febebf342225525bf7543342b884f130e7b3f2
28,086
def get_commands(cfg, clargs, *, what, **kwargs): """ Delegates the creation of commands lists to appropriate functions based on `what` parameter. Parameters ---------- cfg: dict Configuration dictionary. clargs: Namespace Command line arguments. cmds: iter(tuple(str)) what: str...
360410064a24d547729722c4f5843d78af9444c8
28,087
def heappush(heap, item): """ >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13], 7) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7], 10) [4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10] >>> heappush([4, 4, 8, 9, 4, 12, 9, 11, 13, 7, 10], 5) [4, 4, 5, 9, 4, 8, 9, 11, 13, 7, ...
99e6814828e42da8a14f4d0873e62af920a800b8
28,088
def dx(scalar_field): """ Computes first derivative of a 1D scalar field :param scalar_field: :return: """ first_derivative = np.zeros((scalar_field.size - 1)) for i_scalar in range(scalar_field.size - 1): i_next_scalar = i_scalar + 1 first_derivative[i_scalar] = scalar_fiel...
b0af862210a2a395dcdfdab2e921f2c305a536d2
28,089
import argparse def makeParser(): """ Make a command-line argument parser. @return: An C{argparse.ArgumentParser} instance. """ parser = argparse.ArgumentParser( description=('Print a JSON object containing reference to read ' 'distances extracted from a SAM file.')) ...
d1dd832d1533eb5a506eca19a35499362b03feb7
28,090
def get_genetic_profiles(study_id, profile_filter=None): """Return all the genetic profiles (data sets) for a given study. Genetic profiles are different types of data for a given study. For instance the study 'cellline_ccle_broad' has profiles such as 'cellline_ccle_broad_mutations' for mutations, 'ce...
b409a1511112cafab0330a23684b3e255fa0a60c
28,091
import string def cipher(sentence, n_rotate): """ Cipher string with Caesar algorithm ( Anything else than letters stays the same. ) :param sentence: String containing sentence/sentences/word/words. :param n_rotate: number to translate letters :return: string with ciphered words """ upper ...
e0606949f254971431faf7899bd254f4792176d4
28,092
from typing import Union from typing import List def _assert_in_fc( r: RestClient, uuids: Union[str, List[str]], all_keys: bool = False ) -> StrDict: """Also return data.""" if isinstance(uuids, str): uuids = [uuids] if all_keys: data = r.request_seq('GET', '/api/files', {'all-keys': ...
908f12309a93abc472e05598abbb0e5ee29cc798
28,093
def power_law(uref, h, href, shear): """ Extrapolate wind speed (or other) according to power law. NOTE: see https://en.wikipedia.org/wiki/Wind_profile_power_law :param uref: wind speed at reference height (same units as extrapolated wind speed, u) :param h: height of extrapolated wind speed (same ...
cb5d002dfeed022af694060bfe9e516191835742
28,094
import os def get_defaults(): """ Returns default frequencies to project intensities onto as well as default paths for locations of the pure and mixture spectroscopic data. Returns ------- frequency_range: numpy.ndarray Frequencies over which to project the intensities. p...
a38f8a1aa9f74cf5736c87e1ad6a6fbd556aa472
28,095
def binary_weight_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True):...
3cae56fee85ba0c7679e9de7fd2743c9ce252d1a
28,096
def dataset2Xy(dataset): """Convert a dataset (pd.DataFrame) to X, y and output_dim where X is the features, y is the labels (one-hot vectors), and output_dim is the number of labels overall. Args: dataset: A pandas dataframe that is composed of features columns and th...
ef07873db639a7a9c34b149959acd419d4a0b9d3
28,097
from typing import Callable import sys def sysexit(func: Callable) -> Callable: """ use the function return value as the system exit code """ @wraps(func) def wrapper(*args, **kwargs): sys.exit(func(*args, **kwargs)) return wrapper
826b9b265a3df5d79cc1fa61cdccefbd5eca87fa
28,098
def pairwise_list(a_list): """ list转换为成对list "s -> (s0,s1), (s1,s2), (s2, s3), ..." :param a_list: list :return: 成对list """ if len(a_list) % 2 != 0: raise Exception("pairwise_list error!") r_list = [] for i in range(0, len(a_list) - 1, 2): r_list.append([a_list[i], a...
5142fb2e00c931ab57fc9028eb9b6df5a98c0342
28,099