content
stringlengths
22
815k
id
int64
0
4.91M
def send_test_notifications_to_webhook(webhook_pk, user_pk=None) -> None: """Send test notification to given webhook.""" try: webhook = Webhook.objects.get(pk=webhook_pk) if user_pk: user = User.objects.get(pk=user_pk) else: user = None except Webhook.DoesNotE...
73,300
def _as_list(arr): """Make sure input is a list of mxnet NDArray""" if not isinstance(arr, (list, tuple)): return [arr] return arr
73,301
def random_number(): """Generate a random string of fixed length """ return random.randint(0, 9999)
73,302
def eh_posicao(pos): """ Verifica se um determinado valor e uma posicao valida Parametros: pos (universal): Possivel posicao. Retorna: (bool): True se for numero valido e False se nao for. """ return False if type(pos) != int or pos < 1 or pos > 9 else True
73,303
def get_channel_row(*args, **kwargs): """ 获取信息 :param args: :param kwargs: :return: None/object """ return db_instance.get_row(Channel, *args, **kwargs)
73,304
def parse(filepath): """ Simple method for fully specified path which split the string into three parts: folders, filename without suffix and suffix e.g. for ./myfolder/myfile.ext method returns ./myfolder/, myfile, ext :param filepath: str any form of os.path (relative or absolute) :ret...
73,305
def calc_hole(first_map, second_map, min_size=419430400): """ Calcul hole between 2 mappings. format of a Mapping Tuple: 2 integers : - physical_address - mapping_size formated as following ( physical_address, mapping_size ) Input : - first_map :...
73,306
def eval_ctx(*args, **kwargs) -> EmbeddingCtx: """Get the ``EmbeddingCtx`` with the ``PreprocessMode.EVAL`` mode.""" return EmbeddingCtx(PreprocessMode.EVAL, *args, **kwargs)
73,307
def Snu_rescale_axion(ma, ga, ma_ref, ga_ref, source_input=default_source_input): """ Computes the rescale factor for different axion parameters. Parameters ---------- ma : axion mass [eV] ga : axion-photon coupling [GeV^-1] ma_ref : reference axion mass [eV] ga_ref : reference axion-ph...
73,308
def _generate_screen_id_and_captions_pair(json_file_path): """Generates pair of screen id and MTurk labels for each screen.""" with tf.gfile.GFile(json_file_path) as f: screens = json.load(f) return list(screens.items())
73,309
def validate_indices(num_qubits: int, indices: List[int]) -> None: """Validates that the indices have values within range of num_qubits.""" if any(index < 0 for index in indices): raise IndexError('Negative index in indices: {}'.format(indices)) if any(index >= num_qubits for index in indices): ...
73,310
def test_repeated_increase_reg(namespace: TestNamespace) -> None: """Test removal of redundant loads and stores to a register.""" refA = namespace.addRegister("a") run_repeated_increase(namespace, refA, True)
73,311
def convert_atoms_id(list_atoms: tp.List[tp.Union[int, str]], to: tp.Optional[str] = 'atnum' ) -> tp.List[tp.Union[int, str]]: """Converts between atoms identifiers. Converts between atoms numbers (`atnum`) and labels (`atlab`). Attributes ---------- list_...
73,312
def to_image(X, filters=2, n=None): """ 1x1 convolution layer to convert output to an image """ output = weighted_conv2d(inputs=X, filters=filters, kernel_size=[1, 1], activation=None, #tf.nn.tanh, ...
73,313
def summarize_ranges(addrlist): """ Convert a list like [1,2,3,5] to ["1-3", "5"], but with IP addresses """ ranges = [] start = None prev_range_class = None for addr in addrlist: if start is None: start = addr.ip end = addr.ip prev_range_class = addr.rang...
73,314
def sphankel1(n, kr): """Spherical Hankel (first kind) of order n at kr. Parameters ---------- n : array_like Order kr: array_like Argument Returns ------- hn1 : complex float Spherical Hankel function hn (first kind) """ n, kr = scalar_broadcast_match(n...
73,315
def init_news_overview() -> OverviewDatabase: """ init the news overview Will store news overview -- number of hits, corresponding colour and other info :return: database.Database object """ if test() == 0: raise DatabaseError res = OverviewDatabase() init_db("public", "news_ove...
73,316
def add_singlestate_workflow(tool): """2.1.x to 2.2.0 upgrade step handler """ wf_tool = getToolByName(tool, 'portal_workflow') if wf_tool.getWorkflowById(_SINGLESTATE_WF_ID) is None: from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition wf = DCWorkflowDefinition(_SINGLESTATE_W...
73,317
def create_boxify_db_tables(gtf_file, genome_fasta, zip=True): """Create the boxify database tables from a GTF file Parameters ---------- gtf_file : str Input GTF annotation with exon and CDS regions genome_fasta : str Genomic fasta sequence zip : boolean Indicate wh...
73,318
def get_obs_route(value): """ obs-route = obs-domain-list ":" obs-domain-list = *(CFWS / ",") "@" domain *("," [CFWS] ["@" domain]) Returns an obs-route token with the appropriate sub-tokens (that is, there is no obs-domain-list in the parse tree). """ obs_route = ObsRoute() whi...
73,319
def del_gloabls_var(key): """删除值""" try: GLOBALS_DICT.pop(key) return True except KeyError: return "Not Found"
73,320
def get_centerline_tolerance(centerline, n=50): """ Finds tolerance based on average length between first N points along the input centerline. Args: centerline (vtkPolyData): Centerline data. n (int): Number of points Returns: tolerance (float): Tolerance value. """...
73,321
def _warn_on_missing_dependencies(missing_dependencies, patched_repodata): """ The following dependencies do not exist in the channel and are not declared as external dependencies: dependency1: - subdir/fn1.tar.bz2 - subdir/fn2.tar.bz2 dependency2: - subdir/fn3.tar.bz2 ...
73,322
def _api_action(url, req, data=None): """Take action based on what kind of request is needed.""" requisite_headers = {'Accept': 'application/json', 'Content-Type': 'application/json'} auth = (user, token) if req == "GET": response = requests.get(url, headers=requisite_h...
73,323
def detf(entry, evals): """Determines a function value given a number of evaluations. Let A be the algorithm considered. Let f=f_A(evals) be the smallest target value such that the average running time of algorithm A was smaller than or equal to evals. :keyword DataSet entry: data set :keyword...
73,324
def make_visit_output_schema(visual_attributes): """Return the visit output schema.""" schema = [ ("lid", pa.int64()), ("pid", pa.int64()), ("inf_prob", pa.float64()), ("n_contacts", pa.int32()), ] columns = set(k for k, _ in schema) for attr in visual_attributes: ...
73,325
def _xrank(a, w, b, vol, scale = 0 , reweight = False): """ performs a cross-sectional rank a = np.random.normal(0,1,20) a[np.random.normal(0,1,20) > 1] = np.nan w = np.full(20, 1.) b = np.full(20, 1.) scale = 0; vol = -1; reweight = False a _xrank(a, w, b, vol) ra...
73,326
def ML0_GetModelData(TrainData=None, ValidationData=None, TestData=None, ArgsList=None, TargetColumnName=None, NumericColumnNames=None, CategoricalColumnNames=None, TextColumnNames=None, WeightColumnName=None, Threads=-1, Processing='catboost', InputFrame='datatable'): """ # Goal: Create modeling objects fo...
73,327
def check_feature_names_in(estimator): """Checks that all transformers learn the variable names of the train set used during fit.""" # the estimator learns the parameters from the train set X, y = test_df(categorical=True, datetime=True) varnames = list(X.columns) estimator = clone(estimator) ...
73,328
def softmax(x): """ Compute softmax values for each sets of scores in x. Parameters: x (numpy.ndarray): array containing m samples with n-dimensions (m,n) Returns: x_softmax (numpy.ndarray) softmaxed values for initial (m,n) array """ e_x = np.exp(x - np.max(x)) # Subtract ...
73,329
def merge(): """ Merges two branches. Since we currently support only one branch, merge takes the commit from FETCH_HEAD for now """ had_conflict = False repo_root_path = get_repo_root_path() fetch_head_path = os.path.join(repo_root_path, '.git', 'FETCH_HEAD') if not os.path.exists(fetch_hea...
73,330
def redis_populate(filepath): """Function to populate keys in Redis Server""" configs = load_config(filepath) # client = redis.StrictRedis(host=configs["redis_host"], port=configs["redis_port"]) sentinel = Sentinel([(configs["redis_host"], configs["redis_port"])], socket_timeout=0.1) # sentinel.disc...
73,331
def exists(self, privilege, on, grant_target_name, user_name, dict_name, node=None): """Check that user is able to execute EXISTS on a dictionary if and only if the user has SHOW DICTIONARY privilege on that dictionary. """ exitcode, message = errors.not_enough_privileges(name=user_name) if node is...
73,332
def vareq(x1, x2): """Determine if two vars are equal. This does not check if they're values are the same, but if they are exactly the same pointer. Also note that it makes no difference at all if they have the same `name` value. @param x1: A Logic Variable @param x2: Another Logic Variable ...
73,333
def compute_induced_segment_family_coverage(path_family): """Compute induced segment family and coverage from path family Notebook: C4/C4S3_AudioThumbnailing.ipynb Args: path_family: Path family Returns segment_family: Induced segment family coverage: Coverage of pat...
73,334
def write_dictionary(savepath, dictionary): """ input-dict format key: word of transcript delimited by <space> (e.g. 국물이) value: phoneme of hangul-word decomposed into syllables (e.g. ㄱㅜㅇㅁㅜㄹㅣ) => i.e., input dictionary must define word-phoneme mapping """ with open(savepath, "w", encoding="utf-8") as ...
73,335
def slugify(text, delim=u'-'): """Generates an ASCII-only slug.""" result = [] for word in _punct_re.split(text.lower()): result.extend(undecode(word).split()) return unicode(delim.join(result))
73,336
def checkForGLError(locationDescription): """OpenGL-specific routine for error check, report, and exit""" # normally (when no error) just return lastGlError = glGetError() if (lastGlError == GL_NO_ERROR): return # otherwise print vaguely descriptive error message, then exit if lastGlError==GL_INVALID_ENUM: ...
73,337
def check_folder(): """Check folder.""" os.makedirs(PATH, exist_ok=True) os.makedirs(os.path.join(PATH, "clans"), exist_ok=True)
73,338
def _find_last_larger_than(target, val_array): """ Takes an array and finds the last value larger than the target value. Returns the index of that value, returns -1 if none exists in array. """ ind = -1 for j in range(len(val_array), 0, -1): if val_array[j - 1] > target: ind ...
73,339
def display_img(image_file: str): """ Displays the image from the given file location, and print out type, min/max values and shape properties of the the image :param image_file: the string location of a image file """ file = image_file.replace('\\', '//') img = image.imread(file); name = ge...
73,340
def requires_auth(f): """Wraps a request handler with token authentication.""" @wraps(f) def decorated(*args, **kwargs): self = args[0] request = args[1] if six.PY3: token = request.args.get(b'token', [b''])[0].decode("utf8") else: token = str(request...
73,341
def determine_valid_intersection_points( intersection_geoms: gpd.GeoSeries, ) -> List[Point]: """ Filter intersection points between trace candidates and geom. Only allows Point geometries as intersections. LineString intersections would be possible if geometries are stacked. """ assert isi...
73,342
def printEstimateModifiedPiSquared(): """ Prints the amount of summands, estimated value of Pi^2 (using estimateModifiedPiSquared), actual value of Pi^2, and the absolute error in the approximation in a neat 'table'. This is done for specific amount of summands: 10**6, ..., 10**9 """ summan...
73,343
def readStruct(fb, structFormat, seek=False, cleanStrings=True): """ Return a structured value in an ABF file as a Python object. If cleanStrings is enabled, ascii-safe strings are returned. """ if seek: fb.seek(seek) varSize = struct.calcsize(structFormat) byteString = fb.read(var...
73,344
def hello_world(event, context): """ Test function, calls algorithmia algorithm :param event: AWS lambdas function event :param context: AWS lambdas function context :return: """ if "algorithm" in event: algo_name = event['algorithm'] else: raise Exception("'algorithm' fi...
73,345
def remove_from_query(context, *args, **kwargs): """Renders a link with modified current query parameters""" query_params = [] # go through current query params.. for key, value_list in context["request"].GET.lists(): # skip keys mentioned in the args if key not in args: for ...
73,346
def trapz_int(x, y): """ This function computes the area underneath a curve (y) over time vector (x) including checking if the time vector is sorted. Parameters ---------- x : list Time vector. y : list Vector of the integrand. Returns ------- float Area...
73,347
def register(func, *args, **kwargs): """Register a specialization of a `Function` into the graph. This won't actually call the function with the inputs, and only put the function definition into graph. Register function with different input param will result into multiple version of functions registered in gra...
73,348
def calllogs_submenu(dev, pdmssp=False): """ Method - Show Call Logs Menu INPUTS: dev as object OUTPUT: none """ loop = True menu.clear() while loop: print("Call Logs Menu") print("==============") print("1. Show Missed Calls") print("2. Show Rece...
73,349
def chainable_batches(parent_batch_id, job_level): """Returns all batches that have completed and we could possibly chain from""" if job_level == 1: raise Exception("can't chain in job_level 1") if job_level == 2: return db.get_child_batch_metadata( parent_batch_id, BatchMetada...
73,350
def clean(): """キャッシュをゴミ箱に移動します""" user_cache_dir = os.getenv(_MLKOKUJI_CACHE_DIR) if user_cache_dir is not None: if os.path.exists(user_cache_dir): if not click.confirm('You are using a custom cache directory ({}). Do you want to continue?'.format(user_cache_dir)): rai...
73,351
def mask_rgb(rgb, mask): """ Apply a binary (T/F, 1/0) mask to a 3-channel RGB image and output the result. Args: rgb: RGB image as a NumPy array. mask: An image mask to determine which pixels in the original image should be displayed. Returns: NumPy array representing an RGB image with mask appli...
73,352
def create_tags_for_metadata(src_client, run, export_metadata_tags): """ Create destination tags from source run """ tags = run.data.tags.copy() for k in _databricks_skip_tags: tags.pop(k, None) if export_metadata_tags: uri = mlflow.tracking.get_tracking_uri() tags[TAG_PREFIX_MET...
73,353
def test_event_user_name_lower_attribute(mock_event): """ Test event_user_name_lower attribute """ mock_event.set_event_user_name("Username") mock_event.save() assert mock_event.get_event_user_name_lower() == "username"
73,354
def fit_table(lc, expect=1.0): """Generate a summary table from a light curve dataframe""" fits = lc.fit flux = fits.apply(lambda f: f.flux) errors = fits.apply(lambda f: (round(f.errors[0]-f.flux,3), rorebinnedund(f.errors[1]-f.flux ,3) ) ) sigma_dev = fits.apply(lambda f: round(f.poiss.sigma_dev(e...
73,355
def createDagNode(nodeType, nodeName, mDagMod): """ Create and rename node :param nodeType: string :param nodeName: string :param mDagMod: MDagModifier :return: MObjectHandle """ nodeMObj = mDagMod.createNode(nodeType) mDagMod.renameNode(nodeMObj, nodeName) mDagMod.doIt() no...
73,356
def get_ppis(reactome_ppis, threshold=5000.0): """ Get human co-expressed pairs of proteins. They are not necessarily ppi, but to keep same naming structure. :param reactome_ppis: dictionary one --> set :param threshold: Maximum correlation score to be considered co-expressed :return: dictionary one ac...
73,357
def is_denied_because_of_spider(ua_str): """检查user-agent是否因为是蜘蛛或机器人而需要ban掉""" ua_str = ua_str.lower() if 'spider' in ua_str or 'bot' in ua_str: if is_ua_in_whitelist(ua_str): infoprint("A Spider/Bot's access was granted", ua_str) return False infoprint('A Spider/Bot w...
73,358
def predict(model, dataset, out_channels, device, x=None, y=None, z=None): """ Return prediction masks by applying the model on the given dataset Args: model (Unet3D): trained 3D UNet model used for prediction dataset (torch.utils.data.Dataset): input dataset out_channels (int): num...
73,359
def arc_argmax(parse_probs, length, tokens_to_keep, ensure_tree=True): """ Adopted from Timothy Dozat https://github.com/tdozat/Parser/blob/master/lib/models/nn.py Parameters ---------- parse_probs : NDArray seq_len x seq_len, the probability of arcs length : NDArray real senten...
73,360
def addr(registers, a, b, c): """(add register) stores into register C the result of adding register A and register B.""" registers[c] = registers[a] + registers[b] return registers
73,361
def get_data_frame(): """A function to read the csv files and return dataframe objects""" roaster = pd.read_csv ("roaster.csv") activity = pd.read_csv ("activity.csv") headimpact = pd.read_csv ("headimpacts.csv") return roaster, activity,headimpact
73,362
async def delete_leaf(map_id: str, leaf_path: str): """ Database operation delete leaf from map by leaf path Args: map_id (str): which map to delete from leaf_path (str): path of the leaf """ query = (mindmap .delete() .where(and_(mindmap.c.id == map_id, min...
73,363
def latin1_to_ascii (unicrap): """This replaces UNICODE Latin-1 characters with something equivalent in 7-bit ASCII. All characters in the standard 7-bit ASCII range are preserved. In the 8th bit range all the Latin-1 accented letters are stripped of their accents. Most symbol characters are convert...
73,364
async def queue_clear_handler(): """ Clear the plan queue. """ msg = await zmq_to_manager.send_message(method="queue_clear") return msg
73,365
def create_rain_gauge_reading(r, loc_obj, sys_type, dev_obj): """Creat rain gauge object in database from array row""" datetime = r.get('datetime', None) rain = r.get('rain', None) accum_rain = r.get('AccumulatedRain', None) rgr = Raingaugereading.objects.create( LocationID=loc_obj, ...
73,366
def test_starting_darks(pocs, pocstime_flat): """ Test if the parking state transitions from sleeping into darks. """ pocs.initialize() pocs.set_config('simulator', ['camera', 'mount', 'power']) assert not pocs.observatory.dome.is_open os.environ['POCSTIME'] = pocstime_flat assert pocs.is_dark...
73,367
def write_asy_file(smc , file_name): """ smc : (StructureMoleculeComponent) """ fstream = open(file_name, 'w') fstream.write(HEAD) filter_data(smc.initial_scene_data, fstream) fstream.close()
73,368
def _pre_validate_int(value, name): """ Converts the given `value` to `int`. Parameters ---------- value : `Any` The value to convert. name : `str` The name of the value. Returns ------- value : `int` Raises ------ TypeError If `value` w...
73,369
def load_hessian(shess: str, dtype: str) -> np.ndarray: """Construct a Hessian array from any recognized string format. Parameters ---------- shess Multiline string specification of Hessian in a recognized format. dtype {"fcmfinal", "cfour", "gamess"} Hessian format name. ...
73,370
def as_rgb_visual(x, vallina=False, colors=None): """ Make tensor into colorful image. Args: x (torch.Tensor): shape in (C, H, W) or (N, C, H, W). vallina (bool) : if True, then use the `stack_visuals`. """ def batched_colorize(batched_x): n, c, h, w = batched_x.size() ...
73,371
def detach_dict(dict_tensor, to_numpy=False): """ Helper function to recursively detach a dictionary of tensors This should be used when storing elements that could accumulate gradients. """ for key, val in dict_tensor.items(): if isinstance(val, dict): dict_tensor[key] = detach_...
73,372
def model_query(session, model): """model query.""" if not issubclass(model, models.Base): raise exception.DatabaseException("model should be a subclass of BASE!") return session.query(model)
73,373
def test_hidden_columns(db, session): """Test that changes to hidden columns are tracked""" todo = db.Todo("Secret Todo", "Testing...") session.add(todo) session.commit() assert len(todo.versions()) == 1 # Modifying a hidden column does change the history table assert todo.done is False ...
73,374
def load_batch_gcnn(sample_files): """ Loads and concatenates a bunch of samples into one mini-batch. """ c_features = [] e_indices = [] e_features = [] v_features = [] candss = [] cand_choices = [] cand_scoress = [] # load samples for filename in sample_files: w...
73,375
def mutate_uniform(individual, lb, ub): """ Mutate one variable from the individual Uses uniform random within the range """ indi = np.copy(individual) mut_idx = np.random.choice(len(indi)) indi[mut_idx] = np.random.uniform(low=lb[mut_idx], ...
73,376
def test_atomic_g_day_max_inclusive_4_nistxml_sv_iv_atomic_g_day_max_inclusive_5_5(mode, save_output, output_format): """ Type atomic/gDay is restricted by facet maxInclusive with value ---31. """ assert_bindings( schema="nistData/atomic/gDay/Schema+Instance/NISTSchema-SV-IV-atomic-gDay-maxInclu...
73,377
def make_qfq(data, xdxr, fq_type='01'): """使用数据库数据进行复权""" # 过滤其他,只留除权信息 xdxr = xdxr.query('category==1') # data = data.assign(if_trade=1) if len(xdxr) > 0: # 有除权信息, 合并原数据 + 除权数据 # data = pd.concat([data, xdxr.loc[data.index[0]:data.index[-1], ['category']]], axis=1) # data[...
73,378
def compute_average_precision_detection(ground_truth, prediction, tiou_thresholds=np.linspace(0.5, 0.95, 10)): """Compute average precision (detection task) between ground truth and predictions data frames. If multiple predictions occurs for the same predicted segment, only the one with highest score is mat...
73,379
def parse_odp(path, dest_presentation): """Using odfdo for: - open possible ODP document: Document - copy content and merge styles """ lst = os.path.basename(path).split(".") suffix = lst[-1].lower() if suffix != "odp": return # Check the document unicity if not check_known(p...
73,380
def data_augmenter(image, label, shift, rotate, scale, intensity, flip): """ Online data augmentation Perform affine transformation on image and label, which are 4D tensor of shape (N, H, W, C) and 3D tensor of shape (N, H, W). """ image2 = np.zeros(image.shape, dtype=np.float32) ...
73,381
def test_description(request): """Test description for the feature.""" @scenario( 'description.feature', 'Description' ) def test(): pass assert test.__scenario__.feature.description == """In order to achieve something I want something Because it will be cool Some descript...
73,382
def test_cannot_change_function_code(): """Prevent (accidentally) changing the function_code via kwargs in the constructor.""" assert ModbusRequest() assert ReadHoldingRegistersRequest(function_code=3) with pytest.raises(ValueError) as e: assert ModbusRequest(function_code=12) assert ( ...
73,383
def test_0(): """Test template.""" assert bool(1) is True
73,384
def validate_content_length_header_is_int( request_headers: Dict[str, str], ) -> None: """ Validate the ``Content-Length`` header is an integer. Args: request_headers: The headers sent with the request. Raises: ContentLengthHeaderNotInt: ``Content-Length`` header is not an integer....
73,385
def RidPreviouslyProcessed(dtCurrentHosts,sPreviousProcessedFileName): """Remove host-guests processed for NEB calculations previously. [dtHosts]: dict, key: host name; value: int, binary flags for presence of each guest for this host. [sPreviousProcessedFileName]: string, name of file listing previously processed f...
73,386
def test_pareto_classify(binh_korn_points): # pylint:disable=too-many-locals """Test the Pareto classification case on a 2D case, which I can easily draw and understand""" pareto_optimal_points = np.array([[0.5, 2], [3, 1], [4, 0.5]]) discarded_points = np.array([[0.5, 0.5]]) unclassified_points =...
73,387
def abspath(newpath, curpath): """Return the absolute path to the given 'newpath'. The current directory string must be given by 'curpath' as an absolute path. """ assert newpath assert curpath assert curpath.startswith('/') subdirs = newpath.split('/') if not subdirs[0] or curpath...
73,388
def loadSiteLocalConfig(): """ _loadSiteLocalConfig_ Runtime Accessor for the site local config. Requires that CMS_PATH is defined as an environment variable """ overVarName = "WMAGENT_SITE_CONFIG_OVERRIDE" if os.getenv(overVarName, None): overridePath = os.getenv(overVarName) ...
73,389
def p_deleteStmt(t): """deleteStmt : R_DELETE R_FROM ID optAlias whereCl"""
73,390
def test_half_life_unstable_isotopes(): """Test that `half_life` returns `None` and raises an exception for all isotopes that do not yet have half-life data.""" for isotope in _Isotopes.keys(): if 'half_life' not in _Isotopes[isotope].keys() and \ not _Isotopes[isotope].keys(): ...
73,391
def icbm_v1_nifti(): """ Returns the ICBM v1 test nifti data """ return NiftiImageContainer( nifti_img=nib.load( os.path.join(definitions.ROOT_DIR, "data", "hrgt_ICBM_2009a_NLS_v1.nii.gz") ) )
73,392
def _create_vector_Iqxy(model_info): """ Define Iqxy as a vector function if it exists, or default it from Iq(). """ Iq, Iqxy = model_info.Iq, model_info.Iqxy if callable(Iqxy): if not getattr(Iqxy, 'vectorized', False): #print("vectorizing Iqxy") def vector_Iqxy(qx, ...
73,393
def load_geo_adwords(filename='AdWords API Location Criteria 2017-06-26.csv.gz'): """ WARN: Not a good source of city names. This table has many errors, even after cleaning""" df = pd.read_csv(filename, header=0, index_col=0, low_memory=False) df.columns = [c.replace(' ', '_').lower() for c in df.columns] ...
73,394
def from_protos( proto_list: List[american_option_pb2.AmericanEquityOption], config: "AmericanOptionConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for am_option_proto in proto_list: short_position = am_option_proto.short_position h, ...
73,395
def truncate_tiles(layer_name=None, srs=4326, geoserver_base_url=None, **kwargs): """ Args: layer_name: The GWC layer to remove tiles from. srs: The projection default is 4326. geoserver_base_url: A string where geoserver is accessed(i.e. "http://localhost:8080/geoserver") ...
73,396
def optimal_step_weights(): """Return the optimal weights for the neural network with a step activation function. This function will not be graded if there are no optimal weights. See the PDF for instructions on what each weight represents. The hidden layer weights are notated by [1] on the pr...
73,397
def get_remote_file_content( url, as_text=True, headers_only=False, headers=None, _delay=0, ): """ Fetch and return a tuple of (headers, content) at `url`. Return content as a text string if `as_text` is True. Otherwise return the content as bytes. If `header_only` is True, return o...
73,398
def crop_img_padded( img: np.ndarray, cropping_range: Sequence[int], dtype: Optional["DTypeLike"] = None ) -> np.ndarray: """Crop image or mask with padding. Parameters ---------- img : np.ndarray Input image/mask as 2D (height, width) or 3D (height, width, channel) array croppi...
73,399