content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def add_port_fwd( zone, src, dest, proto="tcp", dstaddr="", permanent=True, force_masquerade=False ): """ Add port forwarding. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.add_port_fwd public 80 443 tcp force_masquerade when a zone is c...
15c3cc5cbfb3e2921232df0508ea18d727d7861c
25,288
def reduce_puzzle(values): """Reduce a Sudoku puzzle by repeatedly applying all constraint strategies Parameters ---------- values(dict) a dictionary of the form {'box_name': '123456789', ...} Returns ------- dict or False The values dictionary after continued application o...
0a952caf700216e67c7dd81958dd62d7734bb0fe
25,289
import struct def read_int(handle): """ Helper function to parse int from file handle Args: handle (file): File handle Returns: numpy.int32 """ return struct.unpack("<i", handle.read(4))[0]
cd175251fed79c8d79ea4a73d713457c06cbda6b
25,290
def prem_to_av(t): """Premium portion put in account value The amount of premiums net of loadings, which is put in the accoutn value. .. seealso:: * :func:`load_prem_rate` * :func:`premium_pp` * :func:`pols_if_at` """ return prem_to_av_pp(t) * pols_if_at(t, "BEF_DECR")
7d72e7e2e0b10ffb3958383817ddb7cc5f72a06a
25,291
from scipy.spatial import cKDTree def remove_close(points, radius): """ Given an nxd set of points where d=2or3 return a list of points where no point is closer than radius :param points: a nxd list of points :param radius: :return: author: revised by weiwei date: 20201202 """ tree...
42f8727488018e7f27802e81dbecfd300b38f45a
25,292
import torch def pose_mof2mat_v1(mof, rotation_mode='euler'): """ ### Out-of-Memory Issue ### Convert 6DoF parameters to transformation matrix. Args: mof: 6DoF parameters in the order of tx, ty, tz, rx, ry, rz -- [B, 6, H, W] Returns: A transformation matrix -- [B, 3, 4, H, W] ...
78d42b36e64c0b6ba0eab46b6c19a96d44ed29fb
25,293
def update(isamAppliance, local, remote_address, remote_port, remote_facility, check_mode=False, force=False): """ Updates logging configuration """ json_data = { "local": local, "remote_address": remote_address, "remote_port": remote_port, "remote_facility": remote_facil...
ed8af5d9d1b2f59726622ca6ebdfb4a20b88982f
25,295
from typing import Tuple def get_model_and_tokenizer( model_name_or_path: str, tokenizer_name_or_path: str, auto_model_type: _BaseAutoModelClass, max_length: int = constants.DEFAULT_MAX_LENGTH, auto_model_config: AutoConfig = None, ) -> Tuple[AutoModelForSequenceClassification, AutoTokenizer]: ...
b65cc9cb6e32c65b4d91becb51358146651fddb8
25,296
def get_forecast_by_coordinates( x: float, y: float, language: str = "en" ) -> str: """ Get the weather forecast for the site closest to the coordinates (x, y). Uses the scipy kd-tree nearest-neighbor algorithm to find the closest site. Parameters ---------- x : float L...
061007f152328929f2ed1c70f5a8b1401f3268f7
25,297
def get_calculated_energies(stem, data=None): """Return the energies from the calculation""" if data is None: data = {} stem = stem.find('calculation') for key, path in VASP_CALCULATED_ENERGIES.items(): text = get_text_from_section(stem, path, key) data[key] = float(text.split()[...
d2c0fcf9023874e6890b34e6950dc81e8d2073ce
25,298
def reshape(spectra): """Rearrange a compressed 1d array of spherical harmonics to 2d Args: spectra (np.ndarray): 1 dimensional storage of 2d spherical modes Returns: np.ndarray: 2-dimensional array of the reshaped input with zonal and meridional wavenumber coordina...
af6bf177a860dd8f7d37a9d3586ab54f76e05a1f
25,300
def dict_factory(cursor, row): """ This method is used to convert tuple type to dict after execute SQL queries in python. :param cursor: :param row: :return: """ d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
4f44cb368cff38db313e476a9b3a3bcabcca3bb3
25,301
import torch def predict_batch(model, x_batch, dynamics, fast_init): """ Compute the softmax prediction probabilities for a given data batch. Args: model: EnergyBasedModel x_batch: Batch of input tensors dynamics: Dictionary containing the keyword arguments for the rel...
61102cfa3bcb3e7d52e9f3eca8c97db4d726c1a7
25,302
def render_openapi(api, request): """Prepare openapi specs.""" # Setup Specs options = dict(api.openapi_options) options.setdefault('servers', [{ 'url': str(request.url.with_query('').with_path(api.prefix)) }]) spec = APISpec( options['info'].pop('title', f"{ api.app.cfg.name.ti...
96e49080a6c66f05210676c71a6e169f4caeca95
25,303
def apply_transformations(initial_representation: list, events: list) -> float: """Apply the transformations in the events list to the initial representation""" scale = 1 rot_angle = 0 trans_vector = [0, 0] for item in events: for event in item["events"]: if event["type"] == "TR...
a96be8bafe3b3cde3411f9c8efbf95629319b3cb
25,304
def affine_transform(transform, points): """ Transforms a set of N x 2 points using the given Affine object. """ reshaped_points = np.vstack([points.T, np.ones((1, points.shape[0]))]) transformed = np.dot(affine_to_matrix(transform), reshaped_points) return transformed.T[:,:2]
b976466d688003c7822f363949168d4acb6addb0
25,305
from datetime import datetime def get_current_time_in_millisecs(): """Returns time in milliseconds since the Epoch.""" return get_time_in_millisecs(datetime.datetime.utcnow())
17348e6c4994b3da0669be0ab39a7e8b01fd0e1c
25,306
import math def get_test_paths(paths, snaps): """ Return $snaps paths to be tested on GLUE """ if snaps == -1: return paths interval = len(paths) * 1. / snaps test_paths = [] for i in range(1, snaps+1): idx = int(math.ceil(interval * i)) - 1 test_paths.append(paths[...
a2ac1f89740e85b6322e553559850c0e686a28c8
25,308
def is_success(code): """Return that the client's request was successfully received, understood, and accepted.""" return 200 <= code <= 299
8a6e64c0f218ca5a866a444c730e1ebf7628727e
25,309
def is_palindrome_v3(s): """ (str) -> bool Return True if and only if s is a palindrome. >>> is_palindrome_v3('noon') True >>> is_palindrome_v3('racecar') True >>> is_palindrome_v3('dented') False >>> is_palindrome_v3('') True >>> is_palindrome_v3(' ') True """ ...
70f3393e39b30198879dbc5856c0c73b4be9601d
25,310
from typing import BinaryIO def read(fd: BinaryIO) -> Entity: """Read mug scene from `fd` file object. Args: fd: File object to read from. Returns: Root entity. """ if fd.read(4) != b'MUGS': raise ValueError("not a valid mug file format") return read_recursive(fd)
2cb0b695ec1d75987940e862226166be22bad91d
25,311
def transform(x,y): """ This function takes an input vector of x values and y values, transforms them to return the y in a linearized format (assuming nlogn function was used to create y from x) """ final = [] for i in range(0, len(y)): new = y[i]#/x[i] final.append(2 ** new)...
119db625f5ebf469794bf3bdacd20a1c70ccd133
25,312
def _GRIsAreEnabled(): """Returns True if GRIs are enabled.""" return (properties.VALUES.core.enable_gri.GetBool() or properties.VALUES.core.resource_completion_style.Get() == 'gri')
55713933090509944dc42333bb478c11db9a4176
25,313
def fatorial(n, show=False): """ -> Calcula o Fatorial de um número :param n: O número a ser calculado. :param show: (opcional) Mostrar ou não a conta. :return: O valor do Fatorial de um número n. """ contador = n resultado = guardado = 0 print('-' * 35) while contador >= 0: ...
ddb4d91b3813e270e746bb0d463a5da595366b86
25,314
def start_job(job, hal_id, refGenome, opts): """Set up the structure of the pipeline.""" hal = hal_id # Newick representation of the HAL species tree. newick_string = get_hal_tree(hal) job.fileStore.logToMaster("Newick string: %s" % (newick_string)) tree = newick.loads(newick_string)[0] rero...
5ddade182d045d7a6384d7e6c8d133650dafebbd
25,315
def cleanup_databases(): """ Returns: bool: admin_client fixture should ignore any existing databases at start of test and clean them up. """ return False
63fa94389609b8e28779d1e9e55e9b1ecde502b6
25,318
def spot_centroid(regions): """Returns centroids for a list of regionprops. Args: regions (regionprops): List of region proposals (skimage.measure). Returns: list: Centroids of regionprops. """ return [r.centroid for r in regions]
f53f403dddf0af123afd207e33cc06254a0f2538
25,321
def one_election_set_reg(request, election): """ Set whether this is open registration or not """ # only allow this for public elections if not election.private_p: open_p = bool(int(request.GET['open_p'])) election.openreg = open_p election.save() return HttpResponseRedirect(settings.SECURE_U...
5486c8b277528204260189f1f248aadc20cd9354
25,323
def overrides(conf, var): """This api overrides the dictionary which contains same keys""" if isinstance(var, list): for item in var: if item in conf: for key, value in conf[item].items(): conf[key] = value elif var in conf: for key, value in c...
18375dc43a0d684feaf9089756ecb45eb5a366f3
25,324
def annual_to_daily_rate(rate, trading_days_in_year=TRADING_DAYS_IN_YEAR): """ Infer daily rate from annual rate :param rate: the annual rate of return :param trading_days_in_year: optional, trading days in year (default = 252) :return: the daily rate """ return subdivide_rate(rate, trading_...
a93ce4e3b0ba247f37b5a867025670a7f064022e
25,325
def make_hashable(data): """Make the given object hashable. It makes it ready to use in a `hash()` call, making sure that it's always the same for lists and dictionaries if they have the same items. :param object data: the object to hash :return: a hashable object :rtype: object """ if...
e4b88978ddee6d4dfc354845184a0e80b1f434bf
25,326
from typing import Dict from typing import Tuple def prepare_model_parameters( parameters: Dict[str, FloatOrDistVar], data: DataFrame, beta_fun, splines, spline_power ) -> Tuple[Dict[str, FloatLike], Dict[str, NormalDistVar]]: """Prepares model input parameters and returns independent and dependent param...
c68692148115aa8aa5b9a0b600d6b335cd7ed99f
25,327
import logging def paper_features_to_author_features( author_paper_index, paper_features): """Averages paper features to authors.""" assert paper_features.shape[0] == NUM_PAPERS assert author_paper_index.shape[0] == NUM_AUTHORS author_features = np.zeros( [NUM_AUTHORS, paper_features.shape[1]], dtyp...
6394c57d2b48461287cc77cca021d25c377efaae
25,328
def set_chart_time_horizon(request) -> JsonResponse: """ Set the x-axis (time horizon) of a chart. API Call: /set_chart_time_horizon? monitor_name=<monitor name>& value=<time horizon to set> :param request: HTTP request that expects a 'monitor_name' and 'value' argument. 'value...
94eb982090da2e761032aa5fef4f210c2ff312ee
25,329
def get_single_io_arg(info): """ Get single input/output arg from io info :param info: :return:input/output arg """ if 'valid' not in info: raise ValueError("Json string Errors, key:valid not found.") if info['valid']: check_arg_info(info) del info['valid'] de...
6062f5e1ea61d6a999d106e40e72610b2373b26a
25,330
from typing import Dict from typing import Any def new_credentials( client_id: str, consumer_secret: str, data: Dict[str, Any] ) -> Credentials: """Create Credentials from config and json.""" return Credentials( access_token=str_or_raise(data.get("access_token")), token_expiry=arrow.utcnow...
2f582de9863ed15122678d8268c5f2a9c8a0484e
25,331
def get_chains(table, ipv6=False): """ Return the existing chains of a table """ iptc_table = _iptc_gettable(table, ipv6) return [iptc_chain.name for iptc_chain in iptc_table.chains]
659119d90befb241a205f2a70eeafc273098a91a
25,332
def unscale_fundamental_matrix(fundamental_matrix, M): """ Unscale fundamental matrix by coordinate scaling factor :param fundamental_matrix: :param M: Scaling factor :return: Unscaled fundamental matrix """ T = np.diag([1 / M, 1 / M, 1]) unscaled_F = T.T.dot(fundamental_matrix).dot(T) ...
968c924870a93363cf78bfcc593b5c4367375692
25,334
def initialize_server_request(request): """Shortcut for initialization.""" # Django converts Authorization header in HTTP_AUTHORIZATION # Warning: it doesn't happen in tests but it's useful, do not remove! auth_header = {} if 'Authorization' in request.META: auth_header = {'Authorization': r...
f844a677e48a933401dbd6028ce7faf8e58e77cd
25,335
from .sky_coordinate import SkyCoord from typing import Sequence def _parse_coordinate_arg(coords, frame, units, init_kwargs): """ Single unnamed arg supplied. This must be: - Coordinate frame with data - Representation - SkyCoord - List or tuple of: - String which splits into two value...
6ed456c07b407476a9c02d7d87c9351d27fb7513
25,336
from typing import Tuple def build_names(dependency: Dependency, version_in_url: bool = True) -> Tuple[RemoteResolver, str, str]: """ A function to build directory and file names based on the given dependency.. :param dependency: the dependency to create the file container for. :param version_in_url:...
83a3c063e69a6a8e16e0af6f2e6f43d9f423cd3e
25,337
def convert_apc_examples_to_features(examples, label_list, max_seq_len, tokenizer, opt=None): """Loads a data file into a list of `InputBatch`s.""" configure_spacy_model(opt) bos_token = tokenizer.bos_token eos_token = tokenizer.eos_token label_map = {label: i for i, label in enumerate(label_list,...
8eb8570e4d6f2f5fa22583ff216cbf216ac10145
25,338
from datetime import datetime from pathlib import Path def write_output(opts: AppOptions, out_lines): """ Writes the modified document lines to a new file with "MODIFIED" and a date_time tag added to the file name. Returns the file name. """ ds = datetime.now().strftime("%Y%m%d_%H%M%S") out_n...
613bb6a3290e8a86eb8c945248b6088db3e9dc91
25,339
def ssh_pub_key(key_file): """Creates a string of a public key from the private key file. """ key = paramiko.RSAKey(filename=key_file) pub = "{0} {1} autogenerated by polyphemus" pub = pub.format(key.get_name(), key.get_base64()) return pub
bf46c62031a7d761278612e5835b829a32f7fbe2
25,340
def _variable_with_weight_decay(name, shape, stddev, wd, use_xavier=True, use_zeros=False, init=None): """Helper to create an initialized Variable with weight decay. Note that the Variable is initialized with a truncated normal distribution. A weight decay is added only if one is specified. Args: name: na...
a3d43147508bd10040521dc59cfc49de81bbb70b
25,341
def build_mobile_vit(config): """Build MobileViT by reading options in config object Args: config: config instance contains setting options Returns: model: MobileViT model """ model = MobileViT(in_channels=config.MODEL.IN_CHANNELS, dims=config.MODEL.DIMS, # XS:...
7c8eb92214240b922f4df242f937ba05985c3d2c
25,342
from functools import reduce from bs4 import BeautifulSoup def search_youtube(query, retries = 4, max_num_results = -1): """ Unlimited youtube search by web scrapping """ transformed_query = reduce(lambda s_ant, s_sig : s_ant + '+' + s_sig, query) if len(query) != 0 else '' scrapped_data = [] num_of_r...
119305a5e6ad562fa9f537d42fd36617338b2472
25,344
from typing import List from typing import Tuple from typing import OrderedDict def define_empty_source_parallel_buckets(max_seq_len_target: int, bucket_width: int = 10) -> List[Tuple[int, int]]: """ Returns (source, target) buckets up to (None, max_seq_len_target). Th...
3e5261191c5a55f4d82ee84b9000e0996e06c9f9
25,346
def _hue_scaling(args): """return scaled hue values as described in http://dlmf.nist.gov/help/vrml/aboutcolor args : ndarray of args / angle of complex numbers between in the open interval [0, 2*pi) q : scaled values returned in the interval [0, 1) """ q = 4.0*_np.mod((args/(2*_np.pi...
42fa445d5e790eed13d692613771d02cc55fad94
25,347
from qharv.inspect import axes_pos def get_orbs(fp, orbs, truncate=False, tol=1e-8): """ return the list of requested Kohn-Sham orbitals Args: fp (h5py.File): wf h5 file orbs (list): a list of 3-tuples, each tuple species the KS state by (kpoint/twist, spin, band) i.e. (ik, ispin, ib) truncate (...
d4b7bf639b81f1d776f29bb736a51b7b8684c42d
25,348
def geturlcgivars(baseurl, port): """ Extract CGI variables from baseurl >>> geturlcgivars("http://host.org/base", "80") ('host.org', '80', '/base') >>> geturlcgivars("http://host.org:8000/base", "80") ('host.org', '8000', '/base') >>> geturlcgivars('/base', 8000) ('', '8000', '/base') ...
116ace2bb8275de5faddb4c40e9de05d8a7aee95
25,349
def prepare_log_for_upload(symbolized_output, return_code): """Prepare log for upload.""" # Add revision information to the logs. app_revision = environment.get_value('APP_REVISION') job_name = environment.get_value('JOB_NAME') components = revisions.get_component_list(app_revision, job_name) component_revi...
78e41f67be726f2fb0fb4fb59aa23d124a371055
25,351
import math def bucketize(point, bucket_size): """floor the point to the next lower multiple of bucket_size""" return bucket_size * math.floor(point / bucket_size)
ff152cb5b646df1fe883bd943033c05e83623f31
25,352
def find_unit(df): """find unit in the df, add column to df indicating which token contains unit and return the unit as string.""" doc_unit = "" # thousand = "(\$)(0){3}|thousand|€(\s*)thous|TEUR|T(\s*)€|Tsd|Tausend" # million = "millions|million|£(\s*)m|$(\s*)m|€(\s*)m|mn|mio(\s*)€|in(\s+)mio|MM|\d...
a46eede3e5dc928f90969ff89df15c5e0039991d
25,353
import torch def regular_channels(audio ,new_channels): """ torchaudio-file([tensor,sample_rate])+target_channel -> new_tensor """ sig ,sr =audio if sig.shape[0 ]==new_channels: return audio if new_channels==1: new_sig =sig[:1 ,:] # 直接取得第一个channel的frame进行操作即可 else: ...
5b055d965f35fc4cf0f434b34e8f579f321fee89
25,354
from typing import Union from typing import Callable def is_less_than(maximum: Union[int, float, Decimal]) -> Callable[[Union[int, float, Decimal]], bool]: """ :param maximum: A number :return: A predicate that checks if a value is less than the given number """ def predicate(i: Union[int, float, ...
9f381ae1901581f24af1f3b51f9d64a3b976d6e9
25,355
def a_function(my_arg, another): """ This is the brief description of my function. This is a more complete example of my function. It can include doctest, code blocks or any other reST structure. >>> a_function(10, [MyClass('a'), MyClass('b')]) 20 :param int my_arg: The first argument of ...
8624edfe3ec06b53e065a6672c3b21682cdefe06
25,356
from datetime import datetime def _safe_filename(filename): """ Generates a safe filename that is unlikely to collide with existing objects in Google Cloud Storage. ``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext`` """ filename = secure_filename(filename) date = date...
2ea94c9d18240cf1f1c4dadd19f2bd87b39e6538
25,358
import collections def _make_with_custom_variables(func, variables): """Calls func and replaces any trainable variables. This returns the output of func, but whenever `get_variable` is called it will replace any trainable variables with the tensors in `variables`, in the same order. Non-trainable variables w...
a36923223d22b6b09d9697da3a072c3eef4e739a
25,360
def create_loss_and_learner( model, labels, learning_rate, momentum_coef=0.0, wdecay=0.0, nesterov=False, gradient_clip_norm=None, gradient_clip_value=None): """ Auxiliary function to create loss function (cross entropy and softmax) and trainer using stochastic gradient descent with ...
49669aa109f748b13b3c52efea7cbadb94d492b7
25,361
def mesh_subdivide_tri(mesh, k=1): """Subdivide a mesh using simple insertion of vertices. Parameters ---------- mesh : Mesh The mesh object that will be subdivided. k : int Optional. The number of levels of subdivision. Default is ``1``. Returns ------- Mesh A ...
54912f1777dc1d508a9ab55289e90bcb28b9586f
25,363
import cartopy.crs as ccrs def make_projection(proj_params): """ turn a set of proj4 parameters into a cartopy laea projection introduced in read_resample.ipynb Parameters ---------- proj_params: dict dictionary with parameters lat_0, lon_0 datum and ellps Returns...
1852115888107b5ae9353dd746d56fb3896c1992
25,364
import pandas import logging def _shape(df): """ Return DataFrame shape even if is not a Pandas dataframe.""" if type(df) == pandas.DataFrame or type(df) == pandas.Series: return df.shape try: shape = (len(df), len(df.columns)) except Exception as e: logging.error(e) ra...
d5af0e3f92ee649091d9fc8b904e60931fb0f2f7
25,365
from typing import List from pathlib import Path def hvplot_line( df, title, x, y: List[str], output_dir: Path, vlines=None, save_figure=True, **kwargs ): """Draw line splot with optional vertical lines. Example: hvplot_line( df, title=col, x="t...
1f7400bc12b492648074b2cb2dc52835cb509a1e
25,366
def load_zstack(fn): """ Returns zstack, [zmin, zmax] """ with open(fn, "rb") as f: d = np.fromfile(f,dtype=header_dtype,count=1,sep="") version, shape, zrange = d[0] zstack = np.fromfile(f,dtype='<f4',sep="").reshape(shape) return zstack, zrange
19fd400b0b341569b448e45d482df264310c9cf7
25,367
def parseFile(path): """ Read sections headed by :SectionName into lists by section name in a dictionary blank lines, line preceeding and ending whitespace and #Comments are stripped """ d={} currentList=None f = open(pathPrefix()+path, 'r') for t in f.readlines(...
db5a73b5a46fc1026df775de994da150d33e3aad
25,368
def setName(name): """ Sets the name of the robot. This is cleared with a power cycle and displayed on the robot screen during idle times Name will be shortened to 11 characters Args: name (any): Name to set for the robot. Will be cast to a string Returns: None """ name = ...
5f1e12635df0cf4c95b3ce90e97a51492a477914
25,369
def twoBodyCMmom(m_0, m_1, m_2): """relative momentum for 0 -> 1 + 2""" M12S = m_1 + m_2 M12D = m_1 - m_2 if hasattr(M12S, "dtype"): m_0 = tf.convert_to_tensor(m_0, dtype=M12S.dtype) # m_eff = tf.where(m_0 > M12S, m_0, M12S) # p = (m_eff - M12S) * (m_eff + M12S) * (m_eff - M12D) * ...
5b8576dc33a4570f976efc1bab67a432032b02ff
25,371
def svn_repos_post_commit_hook(*args): """svn_repos_post_commit_hook(svn_repos_t repos, apr_pool_t pool) -> char""" return _repos.svn_repos_post_commit_hook(*args)
bbb9eb6fe81e80ef4729791448e5abe1d7b6ab12
25,372
def slot_selection_is_free(effect): """ all slots ar selected when participant applies """ activity = effect.instance.activity return activity.slot_selection == 'free'
153efa36dda70de02613201540d97e8f22f2bdd9
25,374
def get_consumption_tax(amount, tax_rate, decimal_type): """消費税を取得する。 :param amount: :param tax_rate: :param decimal_type: :return: """ if not amount: return 0 return get_integer(decimal_type, float(amount) * float(tax_rate))
d982d2ebc65770477a9ec06e1305115ecf2eab9e
25,375
def homology(long_sequence, short_sequence): """ Cross-compare to find the strand of long sequence with the highest similarity with the short sequence. :param long_sequence: str :param short_sequence: str :return ans: str, the strand of long sequence with the highest similarity with the short sequen...
1865e7b60cfce3b1ca4e7884377a5a218ecba96a
25,376
def oneliner_to_phylip(line): """Convert one-liner to phylip format.""" seqs = line.strip(";\n").split(',') label_seqs = zip(seqs[:-1:2], seqs[1::2]) taxa_count = len(label_seqs) seq_length = len(label_seqs[0][1]) # pad all names to length of longest name + 1 space max_name_length = max([len...
783d9e68172d4d30de44564b88001d30af4d8e45
25,377
def get_final_histogram(n_states, logfile, temp): """ This function analyzes the log file and performs the following tasks: 1. Output the counts of each lambda state at the last time frame (for plotting histogram) 2. Estimate the uncertainty of free energy difference from the final histogram Parane...
a72ecd4aa6b47e2c8d1368a03ea5b5887abc27c2
25,378
import logging def create_sql_delete_stmt(del_list, name): """ :param del_list: list of records that need to be formatted in SQL delete statement. :param name: the name of the table :return: SQL statement for deleting the specific records """ sql_list = ", ".join(del_list) sql_stmt = f"DEL...
aec744198f1b0dd30836f431ac51a4080911f8ae
25,379
def parse_track(trackelement): """Extract info from every track entry and output to list.""" print(trackelement) if trackelement.find('artist').getchildren(): #artist info is nested in loved/banned tracks xml artistname = trackelement.find('artist').find('name').text artistmbid = ...
e5cd49d765885fd0e701864831f9a2958076ca93
25,380
from typing import Mapping def _coord_matrix(model, pos, noutp): """ Create an array representing inputs and outputs of a simple model. The array has a shape (noutp, model.n_inputs). Parameters ---------- model : `astropy.modeling.Model` model pos : str Position of this m...
841b2ba8df26e424f2fcafc0d3180c3409078896
25,381
def showp2rev(context, mapping): """Integer. The repository-local revision number of the changeset's second parent, or -1 if the changeset has no second parent.""" ctx = context.resource(mapping, 'ctx') return ctx.p2().rev()
854225fca900e5e46ecd18efeab9fc8d3e1f9168
25,382
from typing import Optional def puan_kam(text: str = 'สวัสดี', first: Optional[bool] = None, keep_tone: Optional[bool] = None, all: Optional[bool] = False, skip_tokenize: Optional[bool] = None): """Puan kum (ผวนคำ) is a Thai toung twister, This API convert strin...
5b49aab2437a906ea23122722a45bb472011bbbb
25,383
import wx def get_app_wx(*args, **kwargs): """Create a new wx app or return an exiting one.""" app = wx.GetApp() if app is None: if 'redirect' not in kwargs: kwargs['redirect'] = False app = wx.PySimpleApp(*args, **kwargs) return app
ad4f79e57562e199833d0d948934ec6e9211eea4
25,385
def do_part_1(): """ Solve the puzzle. """ data = input_lines(1) total = 0 for line in data: val, op = interpret_line(line) total = op(total, val) print(total) return total
af8c96a3963bf2732b0281a2b425da73a1ab26e5
25,386
def handle_rpc_errors(fnc): """Decorator to add more context to RPC errors""" @wraps(fnc) def wrapper(*args, **kwargs): try: return fnc(*args, **kwargs) except grpc.RpcError as exc: # lnd might be active, but not possible to contact # using RPC if the wal...
4f1cb19918fa5410bef4f14540a35c9f75d113bd
25,387
import ast def _check_BoolOp_expr(boolop, t, env): """Boolean Operations.""" assert boolop.__class__ is ast.BoolOp op = boolop.op es = boolop.values assert op.__class__ in bool_ops, "%s not in bool ops" % cname(op) # (BoolOp) assignment rule. return all(check_expr(e, t, env) for e in e...
528f55894a60ec8f781e5600a82f32697382e4bb
25,388
def get_matproj(dbpath, cutoff, api_key, dataset_properties): """ Args: dbpath (str): path to the local database cutoff (float): cutoff radius api_key (str): personal api_key for materialsproject.org dataset_properties (list): properties of the dataset Returns: Atoms...
d40b3578a5ac315e1b4d5180113d517d88b5305b
25,389
def parse_change_values_from_opts(opts): """ Convert optparse style options into a dictionary for changing. :param opts: optparse style options :returns: a dictonary with change values to filter devices, supported parameters are ip, port, replication_ip, replication_port ...
d8168163c308b510f12a5cd2baf9dd800b80912a
25,390
def xr_linear_trends_2D(da, dim_names, with_nans=False): """ calculate linear trend of 2D field in time ! slow, use xr_2D_trends instead input: da .. 3D xr DataArray with (dim_names) dimensions dim_names .. tuple of 2 strings: e.g. lat, lon dimension names output: da_trend ...
ba948729cd8e8bde037ad91bde788443cd7eb54c
25,392
def sanitize_email(email): """ Returns an e-mail address in lower-case and strip leading and trailing whitespaces. >>> sanitize_email(' MyEmailAddress@example.com ') 'myemailaddress@example.com' """ return email.lower().strip()
b99e9c38db4fe889e1d0a9175d6535c4790f2f43
25,393
import numba def draw_perm_reps(data_1, data_2, func, size=1, args=()): """ Generate permutation replicates of `func` from `data_1` and `data_2` Parameters ---------- data_1 : array_like One-dimensional array of data. data_2 : array_like One-dimensional array of data. ...
6a5e46e39ace1815297812fbe17acd7db7fb89db
25,394
def get_attachment_form(parser, token): """ Get a (new) form object to upload a new attachment Syntax:: {% get_attachment_form for [object] as [varname] %} {% get_attachment_for for [app].[model] [object_id] as [varname] %} """ return AttachmentFormNode.handle_token(parser, token)
5ae8c049eef6618f358755e5363520a3bc126780
25,396
def greet(name): """Greet message, formatted differently for johnny.""" if name == "Johnny": return "Hello, my love!" return "Hello, {name}!".format(name=name)
86efdaccd65a870fd80e402491e9468669cdcd40
25,397
import numpy def get_naca_points(naca_digits, number_of_points=100, sharp_trailing_edge=True, abscissa_map=lambda x: 0.03*x+0.97*x**2, verbose=False): """ Return a list of coordinates of NACA 4-digit and 5-digit series airfoils. """ if verbose: def explain(*s): ...
ec7f4b2c0104639e727febc6ea1a0ab0f1575f9e
25,398
def get_request_now(): """ When constructing the SOAP request, the timestamps have to be naive but with localtime values. E.g. if the current offset is utc+1 and the utc now is 2016/03/30 0:00, the SOAP endpoint expects 2016/03/30 1:00 without tzinfo. That's pretty ugly but ¯\_(ツ)_/¯ In order to do...
8563eeb9757a7d09b7a0c3253e64cb30443aaa55
25,399
def _make_decorator( obj: Wrappable, to_wrap: tp.Iterable[str] ) -> tp.Callable[[tp.Type[WrapperInjector]], tp.type[WrapperInjector]]: """Makes the decorator function to use for wrapping. Parameters ---------- obj : :obj:`ModuleType`, :obj:`type` or :obj:`object` The source object to wr...
33ab2d7670f518f15c55ebafcde3667447c73c4d
25,400
import numbers import warnings def logistic_regression_path(X, y, pos_class=None, Cs=10, fit_intercept=True, max_iter=100, tol=1e-4, verbose=0, solver='lbfgs', coef=None, class_weight=None, dual=False, penalty='l2', ...
8f42d708532d255f0d61f7e695eab778b5aad99c
25,401
def merge_labels_below_minsize(labels: np.array, min_size: int, connectivity: int = 8) -> np.array: """ Takes labels below min_size and merges a label with a connected neighbor (with respect to the connectivity description). Ignores label 0 as ...
9d9af5e1ddcc288149304d8138f8076dccab1ad8
25,402
def custom_cnn_model(config, labels, model_weights=None): """ Convolutional Neural network architecture based on 'Photonic Human Identification based on Deep Learning of Back Scattered Laser Speckle Patterns' paper. :param conf: Configuration list of models hyper & learning params :param labels: Lis...
1440c1ac911c4fc4dce06e10ced5b94ae97f407b
25,403
def check_day_crossover(tRxSeconds, tTxSeconds): """ Checks time propagation time for day crossover :param tRxSeconds: received time in seconds of week :param tTxSeconds: transmitted time in seconds of week :return: corrected propagation time """ tau = tRxSeconds - tTxSeconds if tau > ...
f44b5ef90e130fbcbc741f79bea69ee79f55a574
25,404
def matrix2xyx_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray: """ Rx(k3) @ Ry(k2) @ Rx(k1) = [[c2, s1s2, c1s2], [s2s3, -s1c2s3+c1c3, -c1c2s3-s1c3], [-s2c3, s1c2c3+c1s3, c1c2c3-s1s3]] """ rotation_matrices = rotation_matrices.reshap...
74185b505e54239128e4b22eb709e1d08f50b206
25,405
def _merge_low_rank_eigendecomposition(S1, V1, S2, V2, rank=None): """Private helper function for merging SVD based low rank approximations. Given factors S1, V1 and S2, V2 of shapes [K1], [M, K1] and [K2], [M, K2] respectively of singular value decompositions A1 = U1 @ np.diag(S1) @ V1.T ...
9a04fb922e87b78ee217890c0094f3cdd8690f60
25,406
def usgs(path): """Reads USGS-formatted ASCII files. Reads the ascii format spectral data from USGS and returns an object with the mean and +/- standard deviation. Reference: https://www.sciencebase.gov/catalog/item/5807a2a2e4b0841e59e3a18d Args: path: file path the the USGS spectra text file....
329df0fe919cf126ae363f384619c8fc5419b073
25,407