content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compute_local_coordinates(cx, cy, x, y, newton_tol=1e-12, interpolation_scheme='nufft', guess_ind=None, verbose=False, max_iterations=30): """ Find (s, r) given (x, y) using the coordinates: x = X(s) + r n_x(s) y = Y(s) + r n_y(s) Where X, Y is given by cx, cy Uses a NUFFT based...
7ef363d65f73122dd358a08885fe22e73a40d25c
43,758
from time import localtime def parse_search(interms): """We go to the trouble of parsing searches ourselves because ADS's syntax is quite verbose. Terms we support: (integer) -> year specification if this year is 2014, 16--99 are treated as 19NN, and 00--15 is treated as 20NN (for "2015 in ...
6734b9a204a024cc53bd7dce7b4a3a734c8f9e68
43,759
import traceback def gunicorn_sync_wrapper(wrapped, _instance, args, kwargs): """ Wraps the gunicorn sync worker handle request. Catches request handling errors and finally sending the trace. :param wrapped: wrapt's wrapped :param _instance: wrapt's instance :param args: wrapt's args :para...
da1b0047de8f439ead29c72693c2e9b8fb9f81ed
43,760
from typing import List from typing import Any from typing import Optional def make_table( rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False ) -> str: """ :param rows: 2D list containing objects that have a single-line representation (via `str`). All rows must be of the...
3837a50395a215206dff1af1836545ea8620c26c
43,761
def _get_max_mem(): """Return the current cgroup's memory high water mark.""" try: with open("/sys/fs/cgroup/memory/memory.max_usage_in_bytes") as f: return float(f.read().strip()) except Exception: return 0
6031fdc75c6ca2fd8f74e52951316e708b0eb36e
43,762
def gaussian_lowpass(sigma: tf.Tensor, filter_size: int): """Generates gaussian windows centered in zero, of std sigma. Args: sigma: tf.Tensor<float>[1, 1, C, 1] for C filters. filter_size: length of the filter. Returns: A tf.Tensor<float>[1, filter_size, C, 1]. """ sigma = tf.clip_by_value( ...
b27997c1af357d9b335f4b4b60d7f2ad18112470
43,764
from typing import List def predict_on_structure_par_en(structure: Structure, gp: GaussianProcess, n_cpus: int = None, write_to_structure: bool = True, selective_atoms: List[int] = None, ski...
e0c1a58ea5cd0fdf2fc0de73f94e2cbd186de41d
43,765
import unittest def suite(): """Gather all the tests from this package in a test suite.""" test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(TestRevokeReport, "test")) return test_suite
1d868b629232e65bc24d0db9171e7284faab7cad
43,766
import re def get_sender(msg): """ Returns the best-guess sender of an email. Arguments: email -- the email whose sender is desired Returns: Sender of the email. """ sender = msg['From'] m = re.match(r'(.*)\s<.*>', sender) if m: return m.group(1) ...
3d88a6861df26d4ca7a5269346cbd14c09d248dc
43,767
def coord_arg_to_coord(carg): """ Parameters ---------- carg : str Argument from parser for coordinates Eligible formats are like: J081240.7+320809 122.223,-23.2322 07:45:00.47,34:17:31.1 Returns ------- icoord : str or tuple Allowed format for c...
16a6cb8090dc040b7b5f6a1a4ba873ea65e0dfdf
43,768
def clear_geolocation_override() -> dict: """Clears the overriden Geolocation Position and Error.""" return {"method": "Emulation.clearGeolocationOverride", "params": {}}
92c77ab41a443bda9bc0d132228f37b73581cfa7
43,769
def amount_in_location(obj, user): """ Returns how many instances of this product are at the current user's location """ return obj.get_amount_stocked(user)
4b722cb9e5721cbc2c7d87ff30046087853cd5c0
43,770
def getRayCircleIntersections(startPoint, direction, center, radius): """ Calculate distances, from start, where a ray intersects a circle. Returns a list of distances of length 0, 1 or 2. The smallest distance always appears 1st and can be negative to represent the case of the intersection being "b...
ae8c67aa80c65a94bffec0542523ca42ffd8adb9
43,771
def ip_attributes(system, request, row, row_counter, model): """ IP addresses are set depending on config """ # remove existing IP addresses for this system (not relevant for newly created systems) if model.csv_remove_ip: # remove many to many relation between system and ip without deleting existin...
72c43f970a7ffcf222c5dfd8f5a5b6d337d2c3fd
43,772
def is_tree_super_balanced(root): """Check if the tree is super balanced or not.""" d_max = depth_of_tree(root) d_min = depth_of_tree(root, False) if d_max - d_min > 1: return False else: return True
d3e9c9c7440d7b2c63bf02b43bfc15a51821c3f7
43,773
def load_user(user_id): """This function loads the user.""" user = session.query(User).filter_by(id=user_id).first() if not user: flash('invalid username or password') abort(400) return user
4ea98d86eb7abac727d4e0c0e32530753176f12c
43,774
def CombinatorialAuction( df, id_label="id", price_label="price", element_label="element", buyer_label="buyer", limit=-1, **kwargs, ): """ 組合せオークション問題 要素を重複売却せず、購入者ごとの候補数上限を超えないように売却金額を最大化 入力 df: 候補のDataFrameもしくはCSVファイル名 id_label: 候補番号の属性文字 price_l...
cb860df0093ad243a834322761815939b9220f80
43,775
def format_string(): """Returns the format string of the binary file""" return "IIccccI?cccc"
f833be1ff5ffcbc538ba0b785e9fe43c0513b688
43,776
def crear_actualizar_ciudadano_reniec(numero_documento, uuid=None): """ Obtiene datos de ciudadano desde RENIEC :param numero_documento: Número de documento a consultar en RENIEC :param uuid: UUID de ciudadano a actualizar :return: ciudadano """ verificar_conexion_internet() ciudadano ...
05d7bef4719537ba08424fca95f47b6b57fd60c3
43,777
def obj_box_zoom( im, classes=None, coords=None, zoom_range=(0.9, 1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12. ): """Zoom i...
1669ee2b2aae25dd16141b040cfb28f358bee82d
43,778
def view_points_in_water(reconstructor, cam_id, pts3d, water, distorted=True): """ pts3d : (N,3) array of 3D points returns: (2,N) projection of 3D points """ assert isinstance(water, WaterInterface) pts3d = np.array(pts3d) assert pts3d.ndim == 2 assert pts3d.shape[1] == 3 # pt...
bee3d04674d3562d25766a30bc17a9c47eefbdc8
43,779
from .variable import Variable from typing import Hashable from typing import Mapping from typing import Union from typing import Tuple from typing import Optional def isel_variable_and_index( name: Hashable, variable: "Variable", index: Index, indexers: Mapping[Hashable, Union[int, slice, np.ndarray,...
ef98d01bfd4b034df31a0d4a872a45f0b5767b81
43,780
def respostas_iguais(r1,r2): """ respostas_iguais: resposta x resposta --> logico respostas_iguais(r1,r2) devolve o valor verdadeiro se as respostas r1 e r2 contiverem os mesmos tuplos, e falso caso contrario. """ return resposta_string(r1) == resposta_string(r2)
aafbef254acd7a3d7910caa113816ac37d23efae
43,781
def getCountryData(df): """ Implement a function to get counts of data based on show type """ country_df = df[["country","type","index"]] country_df = country_df.groupby(['country','type']).count().unstack() country_df.columns = ['Movie','TV Show'] country_df = country_df.reset_index().filln...
bde3247bc95c4914d3b665225aee9dd2a0bfe2b6
43,782
def GetBptEA(n): """ Get breakpoint address @param n: number of breakpoint, is in range 0..GetBptQty()-1 @return: addresss of the breakpoint or BADADDR """ bpt = idaapi.bpt_t() if idaapi.getn_bpt(n, bpt): return bpt.ea else: return BADADDR
baaf2f086ac0b9869236ad582a290ede568446e9
43,783
import warnings def flexible_pileup(features, data_select, data_snip, mapper=map): """ TAKEN from cooltool.snipping.pileup -> patched in a fashion that allows differently sized windows. Handles on-diagonal and off-diagonal cases. Parameters ---------- features : DataFrame Table of ...
925a917708111edea33bca38c32e8ce1df959229
43,784
def delete_customer(request, customer_id): """deleting customer""" # verify that the calling user has a valid token token = request.headers.get('Token') if token is None: return request_response(badRequestResponse, ErrorCodes.INVALID_CREDENTIALS, "Token is missing in the request headers") #...
15de13abf8d3b251d10c01ef13693e6d2c2f8a67
43,785
def list_conferences_groups(request_ctx, group_id, per_page=None, **request_kwargs): """ Retrieve the list of conferences for this context This API returns a JSON object containing the list of conferences, the key for the list of conferences is "conferences" Examples: curl 'https:...
03df9fa860dae497a8797813927f27d5062663b4
43,786
def all_success(mgmt_commands): """Determines if all child processes were successful. Args: mgmt_commands : A list of all Command objects Returns: True if all child processes succeeded """ for mgmt_command in mgmt_commands: if mgmt_command.retcode != 0: return False return True
1bc0d32491711e0d20106f1f294093b30e77bd55
43,787
import re def get_nameservice(hdfs_site): """ Multiple nameservices can be configured for example to support seamless distcp between two HA clusters. The nameservices are defined as a comma separated list in hdfs_site['dfs.nameservices']. The parameter hdfs['dfs.internal.nameservices'] was introduced in Had...
65a86316112a94b6f361daea88cd5658d8019668
43,788
def checkChanList(chanprof, profile, chanList): """ Return non-zero value if any element of chanlist is not in the channel list of profile """ for c in chanList: if c not in chanprof[profile-1]: return 1 return 0
face301b61634bcff8721fcafb1cbc09e2bd0e5f
43,789
from typing import List from pathlib import Path def someweta_de(data: List[List[str]], model=None) -> ( List[List[str]], List[str]): """ model (Default: None) Preloaded instance of the NLP model. See nlptasks.pos.get_model """ # (1) load model if not model: model = somewet...
43efb04e17f830114996acaeead91ba8f017047c
43,790
def contest_login(request, contest_id): """Generates a contest-local SID for a contest.""" sid = srvctl_sid(request) hdrs, resp = _runcgi(request, "new-master", SID=sid, action=3, contest_id=contest_id) if "Location" not in hdrs: if _xpath(resp, "//title").text.endswith("Permission denied"): ...
47dd7d68ef04aab671a9e85533cf8647cb6d53ea
43,791
def is_pyflakes_available(): """ Checks if pyflakes is availalbe. :returns: **True** if we can use pyflakes and **False** otherwise """ return _module_exists('pyflakes.api') and _module_exists('pyflakes.reporter')
886af673c6dca3691f42945d91ce95bb427ed04f
43,792
import json def load_polys(jsonfile): """load info of polygons(=puzzle state) from json file. Args: jsonfile (pathlib.Path): json file to be loaded """ try: with jsonfile.open('r') as fi: jsondata = json.load(fi) except (IsADirectoryError, FileNotFoundError, json.JSON...
7d33d4b1d1f97fd8152b4723f961b0be055dbb25
43,793
def make_tree_defs(mod_files_list): """get a list of 2-uple (module, list_of_files_which_import_this_module), it will return a dictionary to represent this as a tree """ tree_defs = {} for mod, files in mod_files_list: node = (tree_defs, ()) for prefix in mod.split('.'): ...
40b10ccb940af9c6c7bb48ba5b07b59036914dbd
43,794
def verify_identifiers(identifiers, n_items): """Ensure that identifiers has a compatible length and that its elements are unique""" if identifiers is None: return identifiers identifiers = np.array(identifiers, copy=False) # Check length for consistency if len(identifiers) != n_items:...
b84796e411ae9937855f4de23292d362823ea655
43,795
import json def image_get_class_cn_dict(cn_imagenet_class_path): """ 获得分类的中文对照词典 :param cn_imagenet_class_path: :return: """ fn = open(cn_imagenet_class_path, "r", encoding='UTF-8') str_json = fn.read() dic = json.loads(str_json) fn.close() return dic
190cb80d929bdef3fe33b082fa12149c1c290446
43,796
def reveal_type(value: _T) -> _T: """Inspect the inferred type of an expression. Calling this function will make pyanalyze print out the argument's inferred value in a human-readable format. At runtime it does nothing. This is automatically exposed as a global during type checking, so in code that...
fa51fe603fa1d60dbf48526e3e15cdba8303ff5e
43,797
def f5_update_policy_method_command(client: Client, policy_md5: str, method_id: str, method_name: str, act_as_method: str) -> CommandResults: """ Update allowed method from a certain policy.. Args: client (Client): f5 client. policy_md5 (str): MD5 hash of...
553c9b0efa8fa35c099caefc8a7699a327f37e04
43,798
def convertKerasType(dtype): """Convert a numpy type into a tensorflow type """ if dtype not in O.mapping.NP_TYPE_TO_TENSOR_TYPE: logger.warning("Unknown data type %s is treated as float", str(dtype)) dtype = np.dtype('float32') return O.mapping.NP_TYPE_TO_TENSOR_TYPE[dtype]
d2995303e22afc7d7a92e95dd4131a26ad289388
43,799
from typing import Tuple def do_ed_lines_mod_job(port_input_name: str, min_line_length: int, operator: str, gradient_thr: int = 36, anchor_thr: int = 8, scan_interval: int = 1, line_fit_err_thr: int = 1, max_edges: int = 5000, max_points_edge: int = 500, max_lines: int ...
bd674664170636d09d3db845d54c190fe696ac87
43,800
def hess_smith(x_coord,y_coord,alpha,Re,npanel,batch_analyis): """Computes the incompressible, inviscid flow over an airfoil of arbitrary shape using the Hess-Smith panel method. Assumptions: None Source: "An introduction to theoretical and computational aerodynamics", ...
b7ea2e94366002fb1a772f9f86a9b04d57d0e8fa
43,801
def filter_folders_by_predicate(walk: OsWalk, predicate: WalkPredicate, abs_path: bool = False, prune: bool = False) -> OsWalk: """ Filters a walk's folder collection using the given predicate. :param walk: The walk 'object' to filter :param predicate: The condition to check; should take in the folder ...
10e4a35bc6a9e1101a610a0fb8133aa14396a7ac
43,802
def get_default_baseconf_settings_filenames(): """Returns the filename string where the basic configuration will be read from. :return: filename string """ return (_baseconf_settings_filename,_baseconf_settings_filename_comments)
0f026dd4f3f330cc2cd92311818819de37baaab2
43,804
def sample_tag(user, name='main course'): """ create and return a sample tag""" return Tag.objects.create(user=user, name=name)
106fe0b97b2a311d62ec6c14099bec2d6ef4a110
43,805
def markUnexpectedSigmaPeaks(x, y, x_sigma, y_sigma, status, max_sigma, min_sigma, r_neighbors): """ For each peak, check if it has an unexpected sigma. If it does not mark the peak for removal (by setting the status to ERROR) and the neighbors as running. """ assert (x.flags['C_CONTIGUOUS']),...
db93e5a210df9db5852285fbcfbe3cd8c330424a
43,806
def cron_clean_view(): """Clean-ups every outdated article or bias pair.""" return {"cleaned": clean_articles()}
74a9f5bb69643380faa3ac288bc7028024940f4a
43,807
def calculate_plane_histogram(plane, doseplane, dosegridpoints, maxdose, dd, id, structure, hist): """Calculate the DVH for the given plane in the structure.""" contours = [[x[0:2] for x in c['data']] for c in plane] # Create a zero valued bool grid grid = np.zeros((dd['ro...
9866588a25c90fbe7fdd0db69cef413074081764
43,808
def log_model(spark_model, artifact_path, conda_env=None, jars=None, dfs_tmpdir=None, sample_input=None): """ Log a Spark MLlib model as an MLflow artifact for the current run. This uses the MLlib persistence format, and the logged model will have the Spark flavor. :param spark_model: Pip...
fccd98f6ff2a52491d850b5eba4d1ecba3065df7
43,809
def acorr(x, axis=-1, onesided=False, scale='none'): """Compute autocorrelation of x along given axis. Parameters ---------- x : array-like signal to correlate. axis : int axis along which autocorrelation is computed. onesided: bool, optional if True, only returns the ri...
11b2c4495b7f3b73d63000c7ccd694f0cfdd4c65
43,810
def jsonp(func): """ Decorator for the following JSON API functions for the connection test. """ def dec(request, *args, **kw): resp = func(request, *args, **kw) cb = request.GET.get('callback') if not cb: cb = '' resp['Content-Type'] = 'application/javascrip...
ccf8bfbffdd1ac865eb2d001f212925c332f1f82
43,811
def vtkmatrix_to_numpy(matrix): """ Copies the elements of a vtkMatrix4x4 into a numpy array. :param matrix: The matrix to be copied into an array. :type matrix: vtk.vtkMatrix4x4 :rtype: numpy.ndarray """ m = np.ones((4, 4)) for i in range(4): for j in range(4): m[i,...
779e0cad713953ddab1edb4b09b6a3d9d8006413
43,812
def PnCPjInvDyn(robot, q, qdot, qddot, s_jp, s_jd): """ q: np.array, qdot: np.array, qddot: np.array, s_jp: np.array, s_jd: np.array """ # print(qddot[0]) # print(qddot[1]) assert IsClose(qddot[0], qddot[1]) mass, mass_inv, b, g, lambda_i, jac_i_bar, null_i = UpdateRobotSystem( rob...
3c8dda501f64e77c8cbf019d46e0ea7ca3c8dd71
43,813
from typing import Dict def Tbeam( depth: RealNumber, web_thickness: RealNumber, flange_width: RealNumber, flange_thickness: RealNumber, ) -> Dict[str, float]: """ Calculates the Centroid, Area, Moment of Inetia, and Section Modulus of a T beam. The assumed orientation is with the dep...
299df21bbd0ee6bd0bb92f717ee511eb5ee8a7e5
43,815
def get_base_required_field_types(): """ Get field types for UI asset required fields. 2016-08-24: removed 'coordinates': 'floatlist', 2016-08-26" remove 'augmented': 'bool', 'Ref Des': 'string','hasDeploymentEvent': 'bool','remoteDocuments': 'list', added 'editPhase' can have values: EDIT, STAGED, OPER...
0cb8b6041aeaf25efe8ad29e3986237efe5e382f
43,816
def _index_p(es_client: elasticsearch.Elasticsearch, index_name: str) -> bool: """ Checks if the given index exists. """ indices = IndicesClient(es_client) return indices.exists(index_name)
93946793a51ac6a19ddf93d3bc99c84a13403fc0
43,817
def histogram(arg, nbins=None, binwidth=None, base=None, closed='left', aux_hash=None): """ Compute a histogram with fixed width bins Parameters ---------- arg : numeric array expression nbins : int, default None If supplied, will be used to compute the binwidth binwidth...
f835099297f3c4062e29478cd4289b8fe8a6adcc
43,818
def load_cam_params(path): """Loads camera parameters from a JSON file. :param path: Path to the JSON file. :return: Dictionary with the following items: - 'im_size': (width, height). - 'K': 3x3 intrinsic camera matrix. - 'depth_scale': Scale factor to convert the depth images to mm (optional). """ ...
7564e81de1c3451bff47d61dfd81b07d5684298d
43,819
from typing import Set def _create_new_wells(field_id: int, well_names: Set[str]) -> None: """Create new wells if not exists""" return Well.objects.bulk_create( [Well(name=well_name, field_id=field_id) for well_name in well_names], ignore_conflicts=True )
5c085afa0be5e01c0d57e2a177060dda202659ca
43,820
import _io def _shell_lookup(args): """This function is called when the script is used from command line: [jakni@nissen scripts]$ python unifetch.py -a A6XGL2 -ncis Name: A6XGL2_HUMAN Data class: Unreviewed TaxID: 9606 Sequence: MALWMRLLPLLALLALWGPDPAAAFVNQHLCGSHLVEALYLVCGERGFFYTPKTRRE [ ... ...
64a12b15f9188bbc0b3a6608f1dbfeb824c1fed3
43,821
def get_feature_symbolic_learning(df, gp_config): """ Parameters ---------- df: pd.DataFrame,the input dataFrame. gp_config: GPConfig object, the config object of gplearn.SymbolicTransformer. Returns ------- df_t: pd.DataFrame, df with the features of SymbolicTransformer trans. ...
abda49c0c16934f631a50a39c3debc6a2a439dae
43,822
import torch def top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')): """ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering Args: logits: logits distribution shape (vocabulary size) top_k > 0: keep only top k tokens with highest ...
621d9622e87063edc9918655061550e5cbdd5bb8
43,823
def compute_angular_error(input_: np.array, target_: np.array) -> float: """ Args: input_: N*2 numpy array containing the predicted yaw and pitch angle target_: N*2 numpy array containing the corresponding target_ yaw and pitch angle. Returns: Average angular error (in degree) ""...
05feac332b52885c39c463c7c030fa65e8afc4e9
43,824
import json from datetime import datetime def messages(request): """ need to check user login or not""" if request.POST.get("mode") == "get_messages": data = get_messages(request) return HttpResponse(json.dumps(data)) if request.POST.get("post_message"): data = { "messa...
cc87f8b4d28d68451d2ae94b483859f429585476
43,825
from typing import Dict def from_strings_to_dict(data: Dict[str, str]): """ Makes a model for a given list of string like : "mission.document.name": "test" => { mission: { document: { name: "test" } } } This way we will merge the model with ...
78f8295f84b294827a7279887587cd9ccbf8a2ec
43,826
def to_rgb(img): """ Converts the given array into a RGB image. If the number of channels is not 3 the array is tiled such that it has 3 channels. Finally, the values are rescaled to [0,255) :param img: the array to convert [nx, ny, channels] :returns img: the rgb image [nx, ny, 3] ...
b5e4a2dc8d0bc6c8590f4e09db8b2d6b26c2e120
43,827
from datetime import datetime def stopwatch(): """Track the running time.""" if not hasattr(stopwatch, "start"): stopwatch.start = datetime.now() return str(datetime.now() - stopwatch.start)[:-7]
bfd8ff043661dfad1c81f84ac3b86eb10b61f14d
43,828
from typing import List from typing import Tuple def get_list_probs( mutation_list: List[Tuple[Mutation]], mutate_probs: SequenceProbsList, length_mutations: List[int], ) -> Tuple[List[List[float]], List[List[float]]]: """This function build a list of mutate and native probabilities to compute the...
b5642dbcb912237a58e1feb34f7c07e7d946e37e
43,829
def centerOfRect(rect): """ Returns the center of NSRect rect as an NSPoint. """ x = rect.origin.x + rect.size.width * 0.5 y = rect.origin.y + rect.size.height * 0.5 return NSPoint(x,y)
5bc670d3f4bfd888d51e65039d3aa9eae37a56ca
43,830
import math def gcj02towgs84(coor): """ GCJ02(火星坐标系)转GPS84 :param lng:火星坐标系的经度 :param lat:火星坐标系纬度 :return: """ lng = coor[0] lat = coor[1] if out_of_china(lng, lat): return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - ...
b79280228ee3fb2351edd44e1aa44037c4e7235c
43,831
import numpy def encode_data(labeldata,hot_vector = 1): """ Takes array of label data, and transforms it into array of one-hot encoded vectors. Args: labeldata (iterable): Array or list of data labels hot_vector: value assingned for hot, default 1 Returns: ...
92f4bb37428fa2023047abf9d368876bb6d529e5
43,832
from typing import Union def get_delay(delay_str: Union[str, int]) -> float: """Get the delay from an api call Args: json (List[str]): The delay from the json body Returns: int: The delay in seconds, 0 if no delay was found """ delay = 0 # Already in seconds if isinstanc...
41b5cbbad4d153509d7ce30a251a161dfe643218
43,833
def is_polymorphic(v, on_types=None): """ Tests if a function is polymorphic. If `on_types` is provided, checks to see if a function is generic on the set of provided types. """ if isinstance(v, Function) and v.polymorphic: if on_types is not None: gens = set(on_types) ...
4376c475b779e2d54c51077103effe96b9fb5f90
43,834
import random def get_random_word(min_word_length): """Get a random word from the wordlist using no extra memory.""" num_words_processed = 0 curr_word = None with open(WORDLIST, 'r') as f: for word in f: if '(' in word or ')' in word: continue word = wor...
5060073041076a4989c32fce1a7c267a88e028b5
43,835
def get_copysetup(copytools, copytool_name): """ Return the copysetup for the given copytool. :param copytools: copytools list from infosys. :param copytool name: name of copytool (string). :return: copysetup (string). """ copysetup = "" for ct in copytools.keys(): if copytool_...
1181352a178f954d17cf7d7b8fc6c798b441d4a6
43,836
def last_occurence_of_tag_chain(sequence, tag_type): """ Takes a sequence of tags. Assuming the first N tags of the sequence are all of the type tag_type, it will return the index of the last such tag in that chain, i.e. N-1 If the first element of the sequence is not of type tag_type, it will return -...
0edcf25e18ff4b3701f92c13bab2b634b738c158
43,837
def supports_parenting(): """Does this Engine support parenting of objects, aka nesting of transforms or attaching objects. This is important when sending transformation values. """ return False
0dd8fc9e5c1917f10cf9d09a1fb75b470abc6eec
43,839
def dec_to_deg(degree: float, minute: float, second: float) -> float: """ Convert Dec from (deg, arcmin, arcsec) -> degree """ deg_sign = 1. if (degree + np.absolute(degree)) > 0 else - 1. return deg_sign * (np.absolute(degree) + minute / 60. + second / 3600.)
5ca7c3b36a16c7d603c8aae1100431b15f3323de
43,840
def sigmoidDerivative(X): """ input : array of features output : Sigmoid derivative of the input """ return stable_sigmoid(X) * (1.0 - stable_sigmoid(X))
21f4ac50d04da07e7525ded5954f890131cee6d4
43,841
def extract_sub_type(vfm_array): """ Extracts the subtype for each element of the array. Its interpretation depends on whether the feature is an aerosol, cloud, or Polar Stratospheric Cloud. Aerosol: 0 = not determined 1 = clean marine 2 = dust 3 = polluted co...
446f3ebc8a46e35bde092c9ec22e4748d422d0ec
43,842
def set_enabled_equivalencies(equivalencies): """ Sets the equivalencies enabled in the unit registry. These equivalencies are used if no explicit equivalencies are given, both in unit conversion and in finding equivalent units. This is meant in particular for allowing angles to be dimensionless. ...
aa338c62b16764a2b7b4f7116a51867238480445
43,843
def tune_clf_binary_grid(X, y_true, clf_name, n_splits_cv=5, refit_score='precision'): """ Tune a classifier using grid search cross validation """ scorers = { 'precision': metrics.make_scorer(metrics.precision_score), 'recall': metrics.make_scorer(metrics.recall_sco...
b7c3ec61d04accd342c33c901a9056c9e76d426e
43,846
def ESMP_GridGetCoordBounds(grid, staggerloc=constants.StaggerLoc.CENTER, localde=0): """ Preconditions: An ESMP_Grid has been created and coordinates have been added via ESMP_GridAddCoord().\n Postconditions: Two numpy arrays containing the grid coordinate ...
46362dd13a37ed0f9b9ec88c6c96dae508aab20c
43,847
def set_user_stared(oauth_id, uindex): """ 设置用户收藏,保存一年时间 """ key = settings.REDIS_USER_STAR_KEY % (oauth_id, uindex) return R.set(key, '1', 365 * 24 * 3600)
761bae38a3f1fa052ff337e6d7d71d64efebd601
43,848
def isChar(ch): """This function is DEPRECATED. Use xmlIsChar_ch or xmlIsCharQ instead """ ret = libxml2mod.xmlIsChar(ch) return ret
3d044a38070e753107a940883790d262a6006871
43,849
def scipy_graduate_walk(*args, **kwargs): """Scipy-compatible graduate_walk function wrapper. parameters: args[0]: target, function to be minimized args[1]: x0, starting point for minimization dx=1e-8: step in change of the point dx_start=0.1: starting value for dx step. Must be...
d1339eb0c879aa58e508fe0744edb9d12f1be515
43,850
from pathlib import Path def extract_doc(pdf_path, window_len): """Create a Document with features extracted from a pdf.""" pdf_path = Path(pdf_path) tokens = tokenize_pdf(pdf_path) # Remove tokens shorter than three characters. df = tokens[tokens["token"].str.len() >= 3] df = add_base_feature...
4ccdc178f467490eadbd61f9d484867732b4f4a0
43,852
def get_version(rel_path): """Fetch the version of package by parsing the __init__ file """ for line in read(rel_path).splitlines(): if line.startswith('__version__'): delim = '"' if '"' in line else "'" return line.split(delim)[1] else: raise RuntimeError("Unable...
d034e637301c2cbfd9a7f8ab7f94d091789a8648
43,853
def get_job_class_from_module(user_bp_module): """Returns Job class given a module""" UserJob = None for item in dir(user_bp_module): obj = getattr(user_bp_module, item) if isinstance(obj, (type(Job))): if obj.__bases__[0] == Job: UserJob = obj return UserJo...
27e8b672b969c3f0a36ccb5c7711b80f314392c3
43,854
def welford_simulatenous_update(prev_avg, prev_M2, new_value, count): """Perform Welford's simulatenous update on mean and variance M2 = n*sigma_n^2 Parameters ---------- prev_avg: array_like Vector of (count-1)th step averages prev_M2: array_like Vector of (count-1)...
b7b02af85e03d0b0fce8b035d24fb0872134ee39
43,855
def gitCommitId(path, ref): """Return the commit id of *ref* in the git repository at *path*. """ cmd = gitCmdBase(path) + ['show', ref] try: output = runSubprocess(cmd, stderr=None, universal_newlines=True) except sp.CalledProcessError: print(cmd) raise NameError("Unknown gi...
9fe5ab16bfa0da97146bd2b2c5b647482dcf56ef
43,860
def cvFree(*args): """cvFree(void ptr)""" return _cv.cvFree(*args)
e518b9e502f7620d81a3c311d3e4200676de4621
43,861
def make_constant_schedule(step, cutoff_idx=np.inf): """ step - - - ▖▖▖▖▖▖▖▖▖▖▖▖ 0.0 - - - - - - - - - -▖▖▖▖▖▖ | | 0 cutoff_idx """ def schedule(n): if n >= cutoff_idx: return 0. return step return schedule
737e9e6995c252ac2b242cb756770a92856f659a
43,862
def delete_custom_data(request_ctx, user_id, scope, ns, **request_kwargs): """ Delete custom user data. Arbitrary JSON data can be stored for a User. This API call deletes that data for a given scope. Without a scope, all custom_data is deleted. See `UsersController#set_custom_data <https://g...
3aa7256294cf4ce64503c70931d4fbbbe3852b6e
43,863
from datetime import datetime def clean_date(date): """ Ensure a date has the correct English format. :param (str) date: date to clean. """ try: dt = datetime.datetime.fromisoformat(date) except ValueError: return '' else: return datetime.datetime.strftime(dt, "%m/...
3251b7620446ed689115631e85984f7479066ab6
43,865
def returnCAM(feature_conv, weight_softmax, class_idx): """create cam image""" # generate the class activation maps upsample to 256x256 size_upsample = (256, 256) nc, h, w = feature_conv.shape output_cam = [] for _ in class_idx: cam = weight_softmax[class_idx].dot(feature_conv.reshape((n...
e0039bfd3c3b47716b78db685e6191dab99bdfa4
43,866
import ast import collections import six def to_str(tree, astlib=ast): """Convenient function to get the python source for an AST.""" class Printer(annotate.get_base_visitor(astlib)): """Traverses an AST and generates formatted python source code. This uses the same base visitor as annotating the AST, b...
e2998c263ffed4a8dc3d0745d99f558b4b93d308
43,867
from pathlib import Path import errno import json def _load_config(path: str) -> dict: """Load the JSON formatted config file. Parameters ---------- path : str The path of the JSON file we should load. Return ------ dict The parsed data from the JSON file. """ pat...
f1b9a0f8b902c5bfe1b282f589f5bb337cf6bcd9
43,868
def _add_dummy_encoder(circ): """add a dummy parameterized gate""" para_name = circ.para_name index = 0 while True: name = f'_d_{index}' if name not in para_name: dummy_circ = Circuit().rx(name, 0).no_grad() return dummy_circ + circ, name index += 1
041074ff48dea4318165328e6a1e1973bcee7741
43,869