content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def generate(*, artifacts: artifacts_types.ModelArtifacts, name: str) -> str: """ Generate the class source from the schema. Args: schema: The schema of the model. name: The name of the model. Returns: The source code for the model class. """ model_artifacts = models_f...
6a510f031a9971a49057e114cc129f05737226df
22,400
def get_rot_mat_kabsch(p_matrix, q_matrix): """ Get the optimal rotation matrix with the Kabsch algorithm. Notation is from https://en.wikipedia.org/wiki/Kabsch_algorithm Arguments: p_matrix: (np.ndarray) q_matrix: (np.ndarray) Returns: (np.ndarray) rotation matrix """ ...
2cdd46af7f6f05acec23a6cf20e8ca561126c4f2
22,401
def _msrest_next(iterator): """"To avoid: TypeError: StopIteration interacts badly with generators and cannot be raised into a Future """ try: return next(iterator) except StopIteration: raise _MsrestStopIteration()
fe1877cfe4c05adb8bc082ea6a7d1ef54e324386
22,402
def record_export(record=None, export_format=None, pid_value=None, permissions=None): """Export marc21 record page view.""" exporter = current_app.config.get("INVENIO_MARC21_RECORD_EXPORTERS", {}).get( export_format ) if exporter is None: abort(404) options = current_app.config.get(...
2875c0fb019d5b8851c7cdcc31ac6ccd8e6b4002
22,403
from typing import List from typing import Tuple from typing import Optional def body_range( operators: List[str], font_changes: List[Tuple]) -> Tuple[Optional[int], Optional[int]]: """given some assumptions about how headers and footers are formatted, find the operations describing the body ...
aac320631a53653a770ba362c4826fca9f8fe673
22,404
import math def sine(value, default=_SENTINEL): """Filter and function to get sine of the value.""" try: return math.sin(float(value)) except (ValueError, TypeError): if default is _SENTINEL: warn_no_default("sin", value, value) return value return default
48cfcdef750ce497f8f36acee74c440ec244d31f
22,405
def wmt_affine_base_1e4(): """Set of hyperparameters.""" hparams = wmt_affine_base() hparams.kl_reg = 1e-4 hparams.learning_rate_constant = 2.0 hparams.learning_rate_warmup_steps = 8000 return hparams
f6d047737846aa0d4518045709f87b7b5f66d6fa
22,406
import random def random_crop_with_constraints(bbox, size, height, width, min_scale=0.3, max_scale=1, max_aspect_ratio=2, constraints=None, max_trial=1000): """Crop an image randomly with bounding box constraints. This data augmentation is used...
787c341f3f496eeedce18c42462efa5f5ba6515b
22,407
import re def unravelContent(originalData): """ This is the primary function responsible for creating an alternate data stream of unraveled data. Args: contentData: Script content Returns: contentData: Unraveled additional content """ contentData = normalize(originalData) ...
16c5c5b0bc1de026aa4ed8f931e171e11d3ecacc
22,408
import os import pickle import subprocess def fcwrapper(pyenv='python2', instruction=None, data=None, reprint_output=False): """Wrapper to isolate FreeCAD Python 2.7 calls from the Python 3 code base. :param str pyenv: Python interpreter, defaults to 'python2'. :param str instruction: A r...
376c1ee11d8b4b55ac3ac7ad479aad7b487aa0eb
22,409
import hashlib import struct def quote_verify(data, validation, aik, pcrvalues): """Verify that a generated quote came from a trusted TPM and matches the previously obtained PCR values :param data: The TPM_QUOTE_INFO structure provided by the TPM :param validation: The validation information provided...
bf23af17310252ff4a6fe73d16fbd2fffbc49618
22,410
def _rectify_base(base): """ transforms base shorthand into the full list representation Example: >>> assert _rectify_base(NoParam) is DEFAULT_ALPHABET >>> assert _rectify_base('hex') is _ALPHABET_16 >>> assert _rectify_base('abc') is _ALPHABET_26 >>> assert _rectify_base(10...
d88ce9edc3a4e134d04b97c6e5804590da90eb67
22,411
import gzip import json def loadjson(filename): """ Load a python object saved with savejson.""" if filename.endswith('.gz'): with gzip.open(filename, "rb") as f: obj = json.loads(f.read().decode("ascii")) else: with open(filename, 'rt') as fh: obj = json.load(fh) ...
5c8bc1446c5d48ebee51f11711b38ddce74835d2
22,412
def _write_ffxml(xml_compiler, filename=None): """Generate an ffxml file from a compiler object. Parameters ---------- xml_compiler : _TitratableForceFieldCompiler The object that contains all the ffxml template data filename : str, optional Location and name of the file to save. If...
b74434aeb481b11b7a9537932778fb596be205e7
22,413
from typing import List from typing import Union from datetime import datetime import pytz def get_utctime( md_keys: List[str], md: Union[pyexiv2.metadata.ImageMetadata, None] ) -> Union[datetime, None]: """Extract the datetime (to the nearest millisecond)""" utctime = None dt_key = "Exif.Image.DateT...
6f95e50725e865b36a31be48722376301cca4cc1
22,414
def find_file_recursively(file_name, start_dir=getcwd(), stop_dir=None): """ This method will walk trough the directory tree upwards starting at the given directory searching for a file with the given name. :param file_name: The name of the file of interest. Make sure it does ...
a7100e37a4f6244090c8b4363cda2b9893d27768
22,415
def text_cleaning(any_text, nlp): """ The function filters out stop words from any text and returns tokenized and lemmatized words """ doc = nlp(any_text.lower()) result = [] for token in doc: if token.text in nlp.Defaults.stop_words: continue # if token.is_punct: ...
7383f075a501c7c11565eac2c825c55f37e2a637
22,416
def shave(q,options,undef=MISSING,has_undef=1,nbits=12): """ Shave variable. On input, nbits is the number of mantissa bits to keep out of maximum of 24. """ # no compression, no shave # ------------------------ if not options.zlib: return q # Determine shaving parameters # ...
7d5f907f46a703c49f02f9cff3107d67ecc8c2a6
22,417
from typing import Union from typing import List from typing import Sized from typing import Iterable def any_none_nan(values: Union[List, np.ndarray, pd.Series, pd.DataFrame, object]) -> bool: """Can be used with a single value or a collection of values. Returns `True` if any item in `values` are `None`, `np...
659e3d90fe02487820a3cdc711422a7054500b89
22,418
def get_or_create_package(name, epoch, version, release, arch, p_type): """ Get or create a Package object. Returns the object. Returns None if the package is the pseudo package gpg-pubkey, or if it cannot create it """ package = None name = name.lower() if name == 'gpg-pubkey': retu...
e8a13b1a34e16c5f4e6de96bb66fb314fd301c10
22,419
def sort_dict(value, case_sensitive=False, by='key', reverse=False, index=0): """ 字典排序 :param value: 字典对象 :param case_sensitive: 是否大小写敏感 :param by: 排序对象 :param reverse: 排序方式(正序:True、倒序:False) :param index: 索引号(此处针对 value 为 list 情况下可根据 list 的某一 index 排序) :return: """ if by == 'key...
a41034cbd9ebd35cddcd0b4f321ffe8dc2613791
22,420
def initialize_system(name=None): """Initializes a distributed NPU system for use with TensorFlow. Args: name: Name of ops. Returns: The npu init ops which will open the NPU system using `Session.run`. """ return NPUInit(name)
3b1d50862954e57c8206af974412f79492982e23
22,421
def zmap_1perm_2samp(X, cat1, cat2=None, rand_seed=-1, fstat=None, name=None): """ une permutation X (D, N, P) K points, N subjects, D dim return: Y (D,) zvalue at each point """ if fstat is None: fstat = hotelling_2samples #name = "MP-Hotelling" if cat2 is None: cat...
87ffc6a0c49750e9a39295c2775483c4812d0205
22,422
def grids_have_same_coords(grid0, grid1): """Whether two `ESMF.Grid` instances have identical coordinates. :Parameters: grid0, grid1: `ESMF.Grid`, `ESMF.Grid` The `ESMF` Grid instances to be compared :Returns: `bool` Whether or not the Grids have identical coordin...
2fc5001a85694ac9b7b31a383436cc8792b665a4
22,423
import logging import os import subprocess def _CreateTargetProfDataFileFromProfRawFiles(target, profraw_file_paths): """Returns a relative path to target profdata file by merging target profraw files. Args: profraw_file_paths: A list of relative paths to the profdata data files th...
18ce49fbbea79b683824cc0270c74a25a2c3429b
22,424
def get_mwa_eor_spec(nu_obs=150.0, nu_emit=1420.40575, bw=8.0, tint=1000.0, area_eff=21.5, n_stations=50, bmax=100.0): """ Parameters ---------- nu_obs : float or array-like, optional observed frequency [MHz] nu_emit : float or array-like, optional rest frequency...
5bc97d666df938c4e5f42d2d429505e2b7f74004
22,425
def baseModel(data): """ 原有模型 """ formula = "label_code ~ education_num + capital_gain + capital_loss + hours_per_week" model = sm.Logit.from_formula(formula, data=data) re = model.fit() return re
7d66020dc2b527198c0b432b8c8fa9b703335d72
22,426
def load_screen(options: list) -> int: """Callback for loading a screen.""" return get_selection(options)
2c48fad6a644dad3ccf9ce1d2b4cbff8b841b043
22,427
import requests def retrieve_url(url): """ Retrieve the URL and parse the response for success/failure and a structured data output. :param url: The fully qualified URL which you want to query. Example: https://www.google.com.au :type url: string :return resp_ok: A True/False boolean...
55b26ab56c5f15a003e3139ed24ae66bae771708
22,428
def count_cells(notebook): """ The function takes a notebook and returns the number of cells Args: notebook(Notebook): python object representing the notebook Returns: len(nb_dict["cells"]): integer value representing the number of cells into the notebook A way ...
19ec2631888ecbba51fa51870694a7217024e5ae
22,429
from typing import OrderedDict def assignments(): """ This is called for the assignments tab on the instructor interface When an assignment is selected get_assignment is called to gather the details for that assignment. """ response.title = "Assignments" cur_assignments = db(db.assignments...
ac7834a96b876cadbcc91a7df9b59b9e51794142
22,430
from typing import Iterable from typing import Dict def get_sentences(data: Iterable[JSON_Object], match_by: str) -> Dict[Hash, JSON_Object]: """ Collect sentence objects w.r.t. matching criteria. :param data: Iterable of sentence objects :param match_by: Matching criteria / method ...
53430fcd65315dc98bd4bd0ac0c8a4d51dcef651
22,431
import re def getInterfaceText(caller_text, callee_method): """ This method parses method text that we grabbed from getMethodSignature for potential interface text that is present. It makes a sort of 'best guess' as to which lines of the caller method text invoke the callee This current implement...
98856a0db522a143274e79ad3841597498aa41d0
22,432
def str2bool(value): """ Args: value - text to be converted to boolean True values: y, yes, true, t, on, 1 False values: n, no, false, off, 0 """ return value in ['y', 'yes', 'true', 't', '1']
876a58c86b449ba3fac668a4ef2124ea31fda350
22,433
def numeric_float(max_abs: float = 1e3) -> st.SearchStrategy: """Search strategy for numeric (non-inf, non-NaN) floats with bounded absolute value.""" return st.floats(min_value=-max_abs, max_value=max_abs, allow_nan=False, allow_infinity=False)
b44764d88147793792ef90d96c17ec9770737fde
22,434
def add2dict(dict, parent_list, key, value): """ Add a key/value pair to a dictionary; the pair is added following the hierarchy of 'parents' as define in the parent_list list. That is if parent list is: ['5', '1'], and key='k', value='v', then the new, returned dictionary will have a value: ...
32252d3253283110eee2edb2eb216cfd777a710f
22,435
def transform(x): """ transform x1 x2 ---> 1 x1 x2 x1**2 x2**2 x1x2 |x1 - x2| |x1 + x2| """ ones = np.ones(len(x)) x1 = x[:,0] x2 = x[:,1] x1_sqr = x1**2 x2_sqr = x2**2 x1x2 = x1 * x2 abs_x1_minus_x2 = abs(x1-x2) abs_x1_plus_x2 = abs(x1+x2) return np.stack([ones, x...
380cc6e8f181cc192b11e3fd466526093a75e74b
22,436
import json def gen_new_contact_json(csv_data): """ Generate json with data about Subnets and theirs Contacts :param csv_data: entry data :return: Stats about created subnets """ dist = {"subnets": csv_data} with open(f'{PATH}{CONTACTS_SUFIX}', 'w') as out_file: out_file.write(json...
7615c76ea1c9fe392bd6d6d689b2b33a53beaa22
22,437
def resize(a, shape): """ if array a is larger than shape, crop a; if a is smaller than shape, pad a with zeros Args: a (numpy array): 2D array to resize shape: desired shape of the return Returns: numpy array: array a resized according to shape """ if...
40e0829b8680ea5753b12b4bd24e591b9b222bcf
22,438
def _Run(args, holder, url_map_arg, release_track): """Issues requests necessary to import URL maps.""" client = holder.client url_map_ref = url_map_arg.ResolveAsResource( args, holder.resources, default_scope=compute_scope.ScopeEnum.GLOBAL, scope_lister=compute_flags.GetDefaultScopeListe...
a04b277fa704e3cc8889a7a1feb7cf16b6040e91
22,439
import logging def resolve_function(module, function): """ Locate specified Python function in the specified Python package. :param module: A Python module :type module: ``types.ModuleType.`` :param function: Name of Python function :type ``str`` :return: Function or None if not found. ...
5885755f485d4dc243075aa9df6677cd52f3ebf8
22,440
import select def from_table(table, engine, limit=None): """ Select data in a database table and put into prettytable. Create a :class:`prettytable.PrettyTable` from :class:`sqlalchemy.Table`. **中文文档** 将数据表中的数据放入prettytable中. """ sql = select([table]) if limit is not None: s...
df66b3f179d3bde600786b3bc590810ac410b6eb
22,441
import tqdm import requests import zipfile from io import StringIO def futures_sgx_daily(trade_date: str = "2020/03/06", recent_day: str = "3") -> pd.DataFrame: """ Futures daily data from sgx P.S. it will be slowly if you do not use VPN :param trade_date: it means the specific trade day you want to f...
4b2aba7adb48066db1343469541b2007caa82d37
22,442
def draw_spectra(md, ds): """ Generate best-fit spectra for all the test objects Parameters ---------- md: model The Cannon spectral model ds: Dataset Dataset object Returns ------- best_fluxes: ndarray The best-fit test fluxes best_ivars: The ...
03344230339e66ac03ffa0ac2d5744475c311591
22,443
def get_response( schema, # type: GraphQLSchema params, # type: RequestParams catch_exc, # type: Type[BaseException] allow_only_query=False, # type: bool **kwargs # type: Any ): # type: (...) -> Optional[ExecutionResult] """Get an individual execution result as response, with option to ...
c451514b588956c59046140c42c18d79bb151170
22,444
def _get_status_arrays(): """ Get status for all arrays. """ results = [] try: # Get array(s) status for a site. result = get_status_arrays() if result is not None: results = result return results except Exception as err: message = str(err) ...
911a418f728e10949e756098414b7e0809fc2108
22,445
def get_cycle_amplitude(data, cycle, metric_to_use, hourly_period_to_exclude): """ given data (eg results[opposite_pair] [substratification][ substratification_level] ['take_simple_means_by_group_no_individual_mean']) and a cycle and a metric to use (max_minus_min or average_absolute_difference_...
bbbb3a0e7d97da4710319135deb583705fbb5a55
22,446
import subprocess def submit_job(scheduler_args, command): """Submit a job to the scheduler, returning the supplied job ID. """ cl = ["qsub", "-cwd", "-b", "y", "-j", "y"] + scheduler_args + command status = subprocess.check_output(cl) match = _jobid_pat.search(status) return match.groups("job...
81c85e652959501e622531553a77aaed6151413b
22,447
import requests import tqdm def _download(url: str, dst: str) -> int: """ @param: url to download file @param: dst place to put the file """ file_size = int(urlopen(url).info().get("Content-Length", -1)) r = requests.get(url, stream=True) with open(get_full_data_path(dst), "wb") as f: ...
55d748465d83d9d2a5408d4995c2363cf88090b2
22,448
def target2line(target, img_size, k, eval=False): """ target: line representetitve in grid [L, grid_h, grid_w] img_size: (width, height): Input image size, PIL Image size eval=False : Default. For inference. Line width not big. eval=True : For iou. Line width is bigger. return line_img """...
ca0ad3938261cdb31de5c1ad502bef2d16d3e6cb
22,449
import types def unmarshal(raw, signature): """Unmarshal objects. The elements of the returned tuple will be of types according to the column *Python OUT* in the :ref:`types summary <ref-types-table>`. :param RawData raw: raw message data :param signature: see :class:`~dcar.signature.Signature` ...
958761030418450cb65aeef2d966ef3d9157167c
22,450
def remove_keys(d, to_remove): """ This function removes the given keys from the dictionary d. N.B., "not in" is used to match the keys. Args: d (dict): a dictionary to_remove (list): a list of keys to remove from d Returns: dict: a copy of d, excluding...
94146bb19e8d39ea28c0940307c4c998fe5b7063
22,451
import os def parse_line(line_str): """ Parse a line from sha1sum output into tuple of hash, directory path and file name. Eg. line '3af30443352a5760cb0f88e619819cee1b1599e0 foo/bar/baz' would be parsed into tuple ('3af30443352a5760cb0f88e619819cee1b1599e0', 'foo/bar', 'baz'). """ lin...
6a643e7b121e54b224a257c615568c617d0f216f
22,452
def get_crypto_quotes(**kwargs): """ Top-level function for obtaining all available cryptocurrency quotes """ return CryptoReader(**kwargs).fetch()
1eb94bf698e10b43e0cb4c794d7fb66a823295c3
22,453
def mutual_information(y_true, y_pred): """Mutual information score. """ # This is a simple wrapper for returning the score as given in y_pred return y_pred
fae45b40fb3ca285bef57e06b30c42d7f87b5286
22,454
from typing import Sequence from typing import Optional def AvgPool(window_shape: Sequence[int], strides: Optional[Sequence[int]] = None, padding: str = Padding.VALID.name, normalize_edges: bool = False, batch_axis: int = 0, channel_axis: int = -1) -> Intern...
17e523a6092db0d90eb6960e76a3f8fece94d57a
22,455
def pairwise_distances(x, y): """Computes pairwise squared l2 distances between tensors x and y. Args: x: Tensor of shape [n, feature_dim]. y: Tensor of shape [m, feature_dim]. Returns: Float32 distances tensor of shape [n, m]. """ # d[i,j] = (x[i] - y[j]) * (x[i] - y[j])' # = sum(x[i]^2, 1) +...
4928e02c0580f97b4a97db48c6d67f8e15000d46
22,456
import re def timerange(rstring): """ range from string specifier | 2010-M08 -> range of August 2010 | 2009-Q1 -> range of first quarter, 2009 | 2001-S1 -> range of first "semi" 2001 | 2008 -> range of year 2008 :param rstring: range string :rtype: timerange dictionary """ ...
d623e28ad4b040f833d96fed932117b8873f28ac
22,457
def comp_height_wire(self): """Return bar height Parameters ---------- self : CondType21 A CondType21 object Returns ------- H: float Height of the bar [m] """ return self.Hbar
98f98d021774166aa960080f353b6fbc01229eab
22,458
from datetime import datetime import logging def get_update_seconds(str_time: str) -> int: """This function calculates the seconds between the current time and the scheduled time utelising the datetime module. Args: str_time (str): Time of scheduled event taken from user input as a string...
0440ac847bc6c19290bdfa231971d33236335904
22,459
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. :param decl: :class:`declaration_t` :type decl: :class:`declaration_t` :rtype: full name of declarati...
b9828bf4045baa2edbec0c5007406309d90391c5
22,460
import time import sys def aggregate_metrics_by_nodesets(df, nodelists, nodeset_names=None, weightlists=None, level_name="node", use_metrics=None, print_looptime=True): """Aggregates a dataframe by nodes (into nodesets), returning a data frame with same structure but with nod...
5f844915fdc78696a3f0f3bcaeeb3ff88a6af438
22,461
def zero_pad(data, window_size): """ Pads with window_size / 2 zeros the given input. Args: data (numpy.ndarray): data to be padded. window_size (int): parameter that controls the size of padding. Returns: numpy.ndarray: padded data. """ pad_width = ceil(window_size / 2) padded = np.pad(data...
234f27f06bba9dff3a38292e1190b01a767bd56b
22,462
import requests def get_results(url_id): """Get the scanned results of a URL""" r = requests.get('https://webcookies.org/api2/urls/%s' % url_id, headers=headers) return r.json()
be5b660acd847066ec4c476dfe25d2fe21f8e2c4
22,463
def build_dense_constraint(base_name, v_vars, u_exprs, pos, ap_x): """Alias for :func:`same_act`""" return same_act (base_name, v_vars, u_exprs, pos, ap_x)
b35b07c3825a76ac046d8b32490cb5836ae6176a
22,464
from typing import Tuple from typing import Union def list_snapshots(client, data_args) -> Tuple[str, dict, Union[list, dict]]: """ List all snapshots at the system. :type client: ``Client`` :param client: client which connects to api. :type data_args: ``dict`` :param data_args: r...
5452b162d372a016fc63fded510e9361869581b8
22,465
def data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get(uuid, topology_uuid, link_uuid): # noqa: E501 """data_context_path_computation_context_pathuuid_linktopology_uuidlink_uuid_get returns tapi.topology.LinkRef # noqa: E501 :param uuid: Id of path :type uuid: str :para...
98c1b8721fb3edcc8cb3acc196e8c5aa8eb8a4f6
22,466
def ipfs_qm_hash_to_32_bytes(ipfs_qm: str) -> str: """ Transform IPFS base58 Qm... hash to a 32 bytes sting (without 2 heading '0x' bytes). :param ipfs_qm: IPFS base58 Qm... hash. :return: 32 bytes sting (without 2 heading bytes). """ return f"0x{b58decode(ipfs_qm).hex()[4:]}"
e60386928c3836edcd3ebef3740e1bbc8b095724
22,467
def get_service_state(scheduler): """Return the current state of the job service.""" return {"state": get_service_state_str(scheduler)}, 200
e18f66a2d2a2a97a37aed427178b65c2a9c8d919
22,468
def determine_file_type(filename): """ :param filename: str :rtype: FileType """ if filename.endswith('.cls'): return FileType.CLS elif filename.endswith('.java'): return FileType.JAVA elif filename.endswith('.js'): return FileType.JAVASCRIPT elif filename.endswi...
030d11266a8b93056c1d82778ba95a67fea7a799
22,469
def sanitise_text(text): """When we process text before saving or executing, we sanitise it by changing all CR/LF pairs into LF, and then nuking all remaining CRs. This consistency also ensures that the files we save have the correct line-endings depending on the operating system we are running on. ...
1d7d047fba7c8697748d0cf115e0f74fcad8c1c4
22,470
import string def create_regression( n_samples=settings["make_regression"]["n_samples"] ) -> pd.DataFrame: """Creates a fake regression dataset with 20 features Parameters ---------- n_samples : int number of samples to generate Returns ------- pd.DataFrame of features and ta...
b1d91b5e56366a8a2df7731550baedcf154e8c9a
22,471
def _divide_no_nan(x, y, epsilon=1e-8): """Equivalent to tf.math.divide_no_nan but supports bfloat16.""" # need manual broadcast... safe_y = tf.where( tf.logical_and(tf.greater_equal(y, -epsilon), tf.less_equal(y, epsilon)), tf.ones_like(y), y) return tf.where( tf.logical_and( tf.gre...
c7dc806bbdd7968fe61a9c7be76369b5608d9636
22,472
def make_release(t, **params_or_funcs): """Create particle release table to be used for testing""" t = np.array(t) i = np.arange(len(t)) params = { k: (p(i, t) if callable(p) else p) + np.zeros_like(t) for k, p in params_or_funcs.items() } start_date = np.datetime64("2000-01-0...
3dd2778dcf6962171d585244fc276832a300557c
22,473
import re def get_apartment_divs(driver): """Scrapes the url the driver is pointing at and extract any divs with "listitems". Those divs are used as apartment objects at Immowelt. Args: driver (Webdriver): A Webdriver instance. Returns: list: returns a list of all divs of class l...
ccef9159d7731ce78d5deeff92364e4bc43f5f3e
22,474
def smart_apply(tensor, static_fn, dynamic_fn): """ Apply transformation on `tensor`, with either `static_fn` for static tensors (e.g., Numpy arrays, numbers) or `dynamic_fn` for dynamic tensors. Args: tensor: The tensor to be transformed. static_fn: Static transformation function. ...
e2798377891ff6fc0ba4440357b83f927760bc59
22,475
import time def new_scan(host, publish = "off", start_new = "on", all = "done", ignoreMismatch = "on"): """This function requests SSL Labs to run new scan for the target domain.""" if helpers.is_ip(host): print(red("[!] Your target host must be a domain, not an IP address! \ SSL Labs will onyl scan do...
7c7341778028fac5d7c7829f9b57174f0fdb251c
22,476
def removeBubbles(I, kernelSize = (11,11)): """remove bright spots (mostly bubbles) in retardance images. Need to add a size filter Parameters ---------- I kernelSize Returns ------- """ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, kernelSize) Bg = cv2.morphologyEx(I...
193863cb63ed3a1a785aa2c64367eb7a3518c671
22,477
import operator import json def assert_json_response(response, status_code, body, headers=None, body_cmp=operator.eq): """Assert JSON response has the expected status_code, body, and headers. Asserts that the response's content-type is application/json. body_cmp is a callable that takes the JSON-decoded...
db910cb0cb68bdbf9ad4b9490f3bbc6a87d1545d
22,478
def variable(value, dtype=None, name=None, constraint=None): """Instantiates a variable and returns it. # Arguments value: Numpy array, initial value of the tensor. dtype: Tensor type. name: Optional name string for the tensor. constraint: Optional projection function to be ...
3dbb67493e4529469ca0da73159ec495b1d30f07
22,479
from typing import Protocol import json def autoprotocol_protocol(protocol_id): """Get autoprotocol-python representation of a protocol.""" current_protocol = Protocol.query.filter_by(id=protocol_id).first() if not current_protocol: flash('No such specification!', 'danger') return redirec...
85d0a3d5a215c50124c86b17114c82c60b07fae5
22,480
from re import T def tensor_to_P(tensor, wig3j = None): """ Transform an arbitray SO(3) tensor into real P which transforms under the irreducible representation with l = 1. Wigner-3j symbols can be provided or calculated on the fly for faster evaluation. If providedn, wig3j should be an array with...
c4cf2746ac0376b29df437e1938644c9df8e1dd2
22,481
from soc.modules.ghop.logic.helper import notifications as ghop_notifications from soc.modules.ghop.logic.models import comment as ghop_comment_logic from soc.modules.ghop.logic.models import task_subscription as \ def createNotificationMail(request, *args, **kwargs): """Appengine task that sends mail to the subscr...
859372c83fb37d440456c380cf313a27b029f018
22,482
def mergediscnodes(tree): """Reverse transformation of ``splitdiscnodes()``.""" treeclass = tree.__class__ for node in tree.subtrees(): merge = defaultdict(list) # a series of queues of nodes # e.g. merge['VP_2*'] = [Tree('VP_2', []), ...] # when origin is present (index after *), the node is moved to where ...
300aaebe95604c611ecf1f65373ba83f97361438
22,483
import sys def main(): # type: () -> typing.Any """Parse the command line options and launch the requested command. If the command is 'help' then print the help message for the subcommand; if no subcommand is given, print the standard help message. """ colorama.init(strip=not sys.stdout.isatt...
4726833f091bd5c1b9f4e305f26278a87330f946
22,484
def count_go_nogo_trials(eventcode): """ :param eventcode: list of event codes from operant conditioning file :return: number of go and no go trials in the go/no go tasks """ lever_on = get_events_indices(eventcode, ['RLeverOn', 'LLeverOn']) (go_trials, nogo_trials) = (0, 0) for lever in le...
2de71a663f158a0942d2c3f01973ed5dc999b3d7
22,485
def getScriptExecutionContext(): """ Returns the repository description instance and the set of items selected on script action execution. @return: Script execution context. @rtype: L{ScriptExecutionContext<datafinder.gui.user.script_api.ScriptExecutionContext>} """ scriptExecution...
e49e8cfd140f967859cf0e0c75bfe69fac87835f
22,486
import copy import numpy def electrondensity_spin(ccdata, volume, mocoeffslist): """Calculate the magnitude of the electron density at every point in a volume for either up or down spin Inputs: ccdata -- ccData object volume -- Volume object (will not be altered) mocoeffslist -- list ...
7a232f2dbae8ff7905b2eff680a44521b010334e
22,487
def create_missing_dataframe(nrows, ncols, density=.9, random_state=None, index_type=None, freq=None): """Create a Pandas dataframe with random missingness. Parameters ---------- nrows : int Number of rows ncols : int Number of columns density: float Amount of availa...
e3c7f44f5238f929928ee5ec65c33bdb91fd8705
22,488
def decode_name_value_pairs(buffer): """ Decode a name-value pair list from a buffer. :param bytearray buffer: a buffer containing a FastCGI name-value pair list :raise ProtocolError: if the buffer contains incomplete data :return: a list of (name, value) tuples where both elements are unicode stri...
ef302eb2c6c55605fdc9b4a9ef06f59782ba1d94
22,489
def host_is_local(host: str) -> bool: """ Tells whether given host is local. :param host: host name or address :return: True if host is local otherwise False """ local_names = { "localhost", "127.0.0.1", } is_local = any(local_name in host for local_name in local_names...
ce823b8c309ec842ed1dd5bb04e41356db500658
22,490
import os def find_in_path(name, path): """Search PATH for a binary. Args: name: the filename to search for path: the path ['./', './path/to/stuff'] Returns: The abspath to the fie or None if not found. """ for dir in path: binpath = os.path.join(dir, name) if...
14d24a51e9c885c469b3f36ff13bc3aa3740e811
22,491
def sigma_function(coeff_matU, coeff_matX, order, V_slack): """ :param coeff_matU: array with voltage coefficients :param coeff_matX: array with inverse conjugated voltage coefficients :param order: should be prof - 1 :param V_slack: slack bus voltage vector. Must contain only 1 slack bus :retu...
1accad7b95360a0652143ca367c54bca372662a7
22,492
import logging import sys def get_logger(verbose=0): """ set up logging according to the verbose level given on the command line """ global LOGGER if LOGGER is None: LOGGER = logging.getLogger(sys.argv[0]) stderr = logging.StreamHandler() level = logging.WARNING lformat...
973f7024664144728a74319e02bb1d2a2fe71774
22,493
from typing import List def get_dbs(db_names: List[str], db_file: str = "./db_info.pub.json") -> List: """Read the db_file and get the databases corresponding to <<db_name>> Args: db_name (List[str]): A list of names of the database we want db_file (str): The db_file we are reading from ...
ab0074f3cc5d846f7c24bf4bca6b348bfa3d6bf3
22,494
from sklearn import neighbors def knn_threshold(data, column, threshold=15, k=3): """ Cluster rare samples in data[column] with frequency less than threshold with one of k-nearest clusters Args: data - pandas.DataFrame containing colums: latitude, longitude, column column - the ...
37de2c0b4c14cdbb6a0dd10ee7ea1e270fe6ef56
22,495
from mitsuba.core import (Float, UInt32, UInt64, Vector2f, is_monochromatic, is_rgb, is_polarized, DEBUG) from mitsuba.render import ImageBlock from mitsuba.core import depolarize from mitsuba.core import spectrum_to_xyz, xyz_to_srgb def _render_helper(scene, spp=None, sensor_index=0): """ Internally used fun...
54aba5d9051953dc4ac94160432b21ceee4acdb4
22,496
def format_formula(formula): """Converts str of chemical formula into latex format for labelling purposes Parameters ---------- formula: str Chemical formula """ formatted_formula = "" number_format = "" for i, s in enumerate(formula): if s.isdigit(): if ...
c3c87ffcdc5695b584892c643f02a7959b649935
22,497
def ParseQuery(query): """Parses the entire query. Arguments: query: The command the user sent that needs to be parsed. Returns: Dictionary mapping clause names to their arguments. Raises: bigquery_client.BigqueryInvalidQueryError: When invalid query is given. """ clause_arguments = { '...
b3348b10ec7aeb57916366b96409666b71c9a9ce
22,498
def primary_astigmatism_00(rho, phi): """Zernike primary astigmatism 0°.""" return rho**2 * e.cos(2 * phi)
031bb068b4384dc2cd15bebf3450faa25e0177bc
22,499