content
stringlengths
22
815k
id
int64
0
4.91M
def _get_opd_info(self, opd=None, HDUL_to_OTELM=True): """ Parse out OPD information for a given OPD, which can be a file name, tuple (file,slice), HDUList, or OTE Linear Model. Returns dictionary of some relevant information for logging purposes. The dictionary has an OPD version as an OTE LM. ...
5,303,000
def latlon(sec3, npoints): """Computes latitudes and longitudes of grid points. Parameters ---------- sec3 : bytes Section 3 of GRIB2 message. npoints : int Number of points in grid. Returns ------- lon, lat : tuple Longitudes and latitudes of grid point...
5,303,001
def load_file(path): """Loads file and return its content as list. Args: path: Path to file. Returns: list: Content splited by linebreak. """ with open(path, 'r') as arq: text = arq.read().split('\n') return text
5,303,002
def mean_autocorrelation(x): """ Calculates the average autocorrelation (Compare to http://en.wikipedia.org/wiki/Autocorrelation#Estimation), taken over different all possible lags (1 to length of x) .. math:: \\frac{1}{n} \\sum_{l=1,\ldots, n} \\frac{1}{(n-l)\sigma^{2}} \\sum_{t=1}^{n-l}(X_{t...
5,303,003
def LF_screw(c): """ Checking if a screw is mentioned """ return ABNORMAL_VAL if "screw" in c.report_text.text.lower() else ABSTAIN_VAL
5,303,004
def _enum_help(msg: str, e: Type[enum.Enum]) -> str: """ Render a `--help`-style string for the given enumeration. """ return f"{msg} (choices: {', '.join(str(v) for v in e)})"
5,303,005
def DeleteOlderFiles(workfolder, days): """ Used to delete older backups in a folder, days is retention days Sample use to delete all files in C:temp with created date older than 3 days: DeleteOlderFiles(r'c:\temp', 3) """ # os, time already imported now = time.time() cutoff = now - (d...
5,303,006
def distance_numpy_einsum(ps, p1): """ Distance calculation using numpy einstein sum """ flat_units = (item for sublist in ps for item in sublist) units_np = np.fromiter(flat_units, dtype=float, count=2 * len(ps)).reshape((-1, 2)) point_np = np.fromiter(p1, dtype=float, count=2).reshape((-1, 2)) del...
5,303,007
def without_keywords(url,API_KEY): """ :type url: string :param url: url of the website :type API_KEY: string :param API_KEY: google news api API Key This method returns two types of dictionary if the algorithm manages to find relevent articlesit returns a dictionary with keys sta...
5,303,008
def test_add_with_zero_len_pattern(matcher: TokenMatcher) -> None: """Trying to add zero-length patterns raises a ValueError.""" with pytest.raises(ValueError): matcher.add("TEST", [[]])
5,303,009
def orient_az_diff(err): """Differences between two azimuthal angles wraps around the circle and should be centered about the subtractend (reference direction). Parameters ---------- diff Returns ------- reoriented_diff """ return ((err + np.pi) % (2 * np.pi)) - np.pi
5,303,010
def volume_fraction(pvms): """ Computes the :abbr:`ICV (intracranial volume)` fractions corresponding to the (partial volume maps). :param list pvms: list of :code:`numpy.ndarray` of partial volume maps. """ tissue_vfs = {} total = 0 for k, lid in list(FSL_FAST_LABELS.items()): ...
5,303,011
def to_timestamp(arg, format_str, timezone=None): """ Parses a string and returns a timestamp. Parameters ---------- format_str : A format string potentially of the type '%Y-%m-%d' timezone : An optional string indicating the timezone, i.e. 'America/New_York' Examples -------- ...
5,303,012
def edit_example(session): """Open the example Jupyter notebook with a dev install of this module""" session.install("-e", ".", "Jupyter") session.run("Jupyter", "notebook", "Observable_Embed_Example.ipynb")
5,303,013
def get_timestamp(node): """ Return a dokuwiki-Compatible Unix int timestamp for a mediawiki API page/image/revision """ dt = simplemediawiki.MediaWiki.parse_date(node['timestamp']) return int(calendar.timegm(dt.utctimetuple()))
5,303,014
def test_local_entropy_wrongwintype(): """Test 1D local entropy calculation with invalid tuple type.""" C = classifier.BinaryClassifier(np.array([0, 1, 0]), 0.5) with pytest.raises(TypeError): core.local_entropy(C, 'invalid')
5,303,015
def calc_hot_dirs(dirlist, cliargs): """This is the calculate hotdirs worker function. It gets a directory list from the Queue, iterates over the path list and searches index2 for the same path and calculates change percent between the two. If path not in index2, change percent is 100%. Updates inde...
5,303,016
def FOM(t0,dM,P,step=None,**kwargs): """ Plot the figure of merit """ if step is None: step = np.nanmax(dM.data) Pcad = int(round(P/lc)) dMW = tfind.XWrap(dM,Pcad,fill_value=np.nan) dMW = ma.masked_invalid(dMW) dMW.fill_value=np.nan res = tfind.ep(t0,dM,Pcad) fom = res...
5,303,017
def validate_fetch_params(max_fetch: int, max_events_fetch: int, fetch_events: bool, first_fetch: str, status_filter_list: list) -> None: """ Validate the parameters for fetch incident command. Args: max_fetch: (int): The maximum number of incidents for one fetch. ...
5,303,018
def send_ticket(registration): """Send the ticket to access the CERN site by email.""" start_dt, end_dt = get_access_dates(get_last_request(registration.event)) template = get_template_module('cern_access:emails/ticket_email.html', registration=registration, start_dt=start...
5,303,019
def test_checkout_create_no_email(api_client, stock, graphql_address_data, channel_USD): """Create checkout object using GraphQL API.""" variant = stock.product_variant variant_id = graphene.Node.to_global_id("ProductVariant", variant.id) shipping_address = graphql_address_data variables = { ...
5,303,020
def array_remove_duplicates(s): """removes any duplicated elements in a string array.""" return list(OrderedDict.fromkeys(s))
5,303,021
def get_scholia_iri(prefix: str, identifier: str) -> Optional[str]: """Get a Scholia IRI, if possible. :param prefix: The prefix in the CURIE :param identifier: The identifier in the CURIE :return: A link to the Scholia page >>> get_scholia_iri("pubmed", "1234") 'https://scholia.toolforge.org/...
5,303,022
def _save(document): """Save the parsed JSON document (dict)""" with open(_JSON_PATH, 'w') as jsonhandle: json.dump(document, jsonhandle, indent=4, sort_keys=True)
5,303,023
def timestamp_of_last_action(user, grid): """ Template filter implementing `time_of_last_action` from models/place.py. """ if not user.is_authenticated: return 0 return time_of_last_action(user, grid).timestamp()
5,303,024
def test_calculate_temperature_factor_no_subcategory(): """calculate_temperature_factor() should raise a KeyError when passed an unknown subcategory ID.""" with pytest.raises(KeyError): _pi_t = integratedcircuit.calculate_temperature_factor(14, 1, 1, 52.95)
5,303,025
def _print_template(config, imgur_links): """Generates initial ESPN league note template based on imgur_links""" logging.info("Use the ESPN league note template below as a starting place...") if config.description: print(config.description + "\n") for ndx in range(len(imgur_links)): prin...
5,303,026
def kullback_leibler_divergence(weights=1.0, name='KullbackLeiberDivergence', scope=None, collect=False): """Adds a Kullback leiber diverenge loss to the training procedure. Args: name: name of the op. scope: The scope for the operations performed in computing t...
5,303,027
def get_gateway_counts(bpmn_graph): """ Returns the count of the different types of gateways in the BPMNDiagramGraph instance. :param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model. :return: count of the different types of gateways in the BPMNDiagramGraph instance """ ...
5,303,028
def build_5_cycle_graph(): """Builds a 5-cycle graph, C5. Ref: http://mathworld.wolfram.com/CycleGraph.html""" graph = build_cycle_graph(5) return graph
5,303,029
def get_git_log_command( verbose: bool, from_commit: Optional[str] = None, to_commit: Optional[str] = None, is_helm_chart: bool = True, ) -> List[str]: """ Get git command to run for the current repo from the current folder (which is the package folder). :param verbose: whether to print verb...
5,303,030
def xcorr(a, b, ds): """ :param a: x1 :param b: x2 :param ds: sampling rate :return: corrs, lags """ S = len(a) a_norm = (a - np.mean(a)) / np.std(a) b_norm = (b - np.mean(b)) / np.std(b) corrs = np.correlate(a_norm, b_norm / S, 'full') lags_half = np.arange(0, ds * S, ds) ...
5,303,031
def switch_directory(dir): """Switch to a directory. :param dir: directory :type dir: str """ if not os.path.exists(dir): os.makedirs(dir, exist_ok=True) owd = os.getcwd() try: os.chdir(dir) yield dir finally: os.chdir(owd)
5,303,032
def start_new_report_logger(): """ This reinitialize the report logger in `pdoc.Loggers`. Note that new files will be generated in the process. """ Loggers.report = ControlledLogger(f"report_log_{datetime.datetime.utcnow()}", "./logs/report")
5,303,033
def gt_comparison(): """>: Greater than operator.""" class _Comparable: def __gt__(self, other): return 'big' in other return _Comparable() > 'big' and "masperpiece"
5,303,034
def internal_server_error(error): """ Handles unexpected server error with 500_SERVER_ERROR """ message = str(error) app.logger.error(message) return ( jsonify( status=status.HTTP_500_INTERNAL_SERVER_ERROR, error="Internal Server Error", message=message, ...
5,303,035
def minimum_separation(lon1, lat1, lon2, lat2, unit='deg'): """Compute minimum distance of each (lon1, lat1) to any (lon2, lat2). Parameters ---------- lon1, lat1 : array_like Primary coordinates of interest lon2, lat2 : array_like Counterpart coordinate array unit : {'deg', 'ra...
5,303,036
def tau_references_json(): """Show the modifiers of the Tau protein.""" rows = get_tau_references(graph) return jsonify([ dict(zip(('type', 'reference'), row)) for row in rows ])
5,303,037
def get_version_name(args, version_hash): """ Returns current version name based on the git commit history. """ if BRANCH != get_branch(args): return "non-main-branch" output = subprocess.check_output("git log --pretty=oneline", shell=True).decode().strip() list_git_commit_hash = revers...
5,303,038
def createWallet(password, blockHash, remoteNode): """ CREATES NEW WALLET AND SENDS IT TO FULL NODE Returns: Wallet address """ # Create wallet ID uid = uuid.uuid4().hex hsh = hashlib.sha3_224((password+uid).encode()).hexdigest() # Generate keys pair key = RSA.generate(1024...
5,303,039
def _attempt_nocopy_reshape(context, builder, aryty, ary, newnd, newshape, newstrides): """ Call into Numba_attempt_nocopy_reshape() for the given array type and instance, and the specified new shape. The array pointed to by *newstrides* will be filled up if successful. ...
5,303,040
def main(): """ Main Entry Point """ import __main__ parser = argparse.ArgumentParser( usage='%(prog)s [options] command\n\nVersion\n %(prog)s version ' + str(tero.__version__), formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--version', action='vers...
5,303,041
def unlockfile(lf): """ Unlock a file locked using lockfile() """ try: # If we had a shared lock, we need to promote to exclusive before # removing the lockfile. Attempt this, ignore failures. fcntl.flock(lf.fileno(), fcntl.LOCK_EX|fcntl.LOCK_NB) os.unlink(lf.name) ex...
5,303,042
def get_aim_matrix(origin, target, up_vector=om.MGlobal.upAxis()): """Return the aim matrix aiming from the origin to the target. The aim vector will be the Y Axis Args: origin(om.MPoint): origin point target(om.MPoint): target point """ aim_vector = om.MVector(target - origin).nor...
5,303,043
def new_event_loop(): """Return a new event loop.""" return Loop()
5,303,044
def execCopySourceTarget(TargetSkinCluster, SourceSkinCluster, TargetSelection, SourceSelection, smoothValue=1, progressBar=None): """ copy skincluster information from one vertex group to another based on closest proximity :param TargetSkinCluster: the skincluster to gather information from :type Targ...
5,303,045
def get_ipv4_for_hostname(hostname, static_mappings={}): """Translate a host name to IPv4 address format. The IPv4 address is returned as a string, such as '100.50.200.5'. If the host name is an IPv4 address itself it is returned unchanged. You can provide a dictionnary with static mappings. Follo...
5,303,046
async def test_form_cannot_connect(hass): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "custom_components.truenas.config_flow.Machine.create", side_effect=Inval...
5,303,047
def handler(event, context): """ Gets credentials by email address or domain. :param event: object containing 'email' or 'domain' string but not both :return: a list of credentials in the form "<email address>:<password>" """ domain: str = event.get('domain') email: str = event.get('email'...
5,303,048
def visualize_results(model, config, datagen): """Visualization of predictions """ for i in range(len(datagen)): print('Processing sample n°', i, '...') # IF there is no depth data if config.generator.depth_dir is None: X, Y = datagen[i] prediction = model.pr...
5,303,049
def create_subgraph_for_op(input_shape: tuple, op_string: str) -> tf.Graph: """ Create and return the TensorFlow session graph for a single Op. A well known input named "aimet_input" and a well known output named "aimet_identity" are used along with the Op for the purposes of traversing the graph for th...
5,303,050
def add_id_to_db(_id): """ Ajoute l'id d'une équipe/joueur inconnu à la base de données """ if is_id_in_db(_id): # Pour éviter les ajouts intempestifs (précaution) return url = "http://www.comparateur-de-cotes.fr/comparateur/football/Angers-td" + str(_id) soup = BeautifulSoup(urllib.req...
5,303,051
def configure_audit_decorator(graph): """ Configure the audit decorator. Example Usage: @graph.audit def login(username, password): ... """ include_request_body = int(graph.config.audit.include_request_body) include_response_body = int(graph.config.audit.include_res...
5,303,052
def read_geopackage(file_path, layer): """Read file as GeoDataFrame.""" src = fiona.open(file_path, "r", layer=layer) rows = [] columns = list(src.schema["properties"].keys()) + ["geometry"] dtypes = normalize_fiona_schema(src.schema)["properties"] crs = src.crs for feature in src: #...
5,303,053
def getpalette(data): """ Helper to transform a StringIO object into a palette """ palette = [] string = StringIO(data) while True: try: palette.append(unpack("<4B", string.read(4))) except StructError: break return palette
5,303,054
def parse_privs(privs, db): """ Parse privilege string to determine permissions for database db. Format: privileges[/privileges/...] Where: privileges := DATABASE_PRIVILEGES[,DATABASE_PRIVILEGES,...] | TABLE_NAME:TABLE_PRIVILEGES[,TABLE_PRIVILEGES,...] """ if privs...
5,303,055
def adjust_learning_rate(optimizer, epoch, args): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" """Sets the learning rate to the initial LR decayed by 10 every 10 epochs""" lr = args.lr * (0.1 ** (epoch // args.step)) for param_group in optimizer.param_groups: para...
5,303,056
def season_ts(ds, var, season): """ calculate timeseries of seasonal averages Args: ds (xarray.Dataset): dataset var (str): variable to calculate season (str): 'DJF', 'MAM', 'JJA', 'SON' """ ## set months outside of season to nan ds_season = ds.where(ds['time.season'] == season)...
5,303,057
def register(model, parent_attr='parent', left_attr='lft', right_attr='rght', tree_id_attr='tree_id', level_attr='level', tree_manager_attr='tree', order_insertion_by=None): """ Sets the given model class up for Modified Preorder Tree Traversal. """ if model in registry: ...
5,303,058
def _create_sub_sequences(sequence, th=1): """ create list of perfect subsequence """ out = [] if not sequence: return out sub_sequence = [sequence[0]] sequence = sequence[1:] while sequence: p1 = sub_sequence[-1] _next = None for i, p2 in enumerate(sequence): ...
5,303,059
def interpolate_contour( points: numpy.array, interval: float, method: str = 'linear' ) -> numpy.array: """ Calculate a set of points along an arbitrary polygon to enforce a regular interval between particles. :param points: array of x and y values of starting polygon :param interval: desired inter...
5,303,060
def augment_train_data_with_replacement(train_data: pd.DataFrame, replace_entity: str, synonym_func: Union[str, Callable], fraction: float = .2) -> tuple: """ 在pandas数据中对数据进行增强,主要也是同义词替换操作 ...
5,303,061
def tile_images(img_nhwc): """ Tile N images into one big PxQ image. (P,Q) are chosen to be as close as possible, and if N is square, then P=Q. Parameters ---------- img_nhwc: list or array of images, ndim=4 once turned into array n = batch index, h = height, w = width, c = chann...
5,303,062
def get_top_menu(user: AbstractUser, admin_site: str = "admin") -> List[Dict]: """ Produce the menu for the top nav bar """ options = get_settings() menu = make_menu(user, options.get("topmenu_links", []), options, admin_site=admin_site) children = [ {"name": child.app_name, "url": child...
5,303,063
def _calculate_share_known_cases(df): """Calculate the share of known cases from detected and undetected cases. Args: df (pandas.DataFrame): Dataframe with columns "date", "type" and "count". Each date and type is a row. Returns: share_known_cases (pandas.Series): s...
5,303,064
def test_list_string_length_4_nistxml_sv_iv_list_string_length_5_4(mode, save_output, output_format): """ Type list/string is restricted by facet length with value 10. """ assert_bindings( schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-length-5.xsd", instance="...
5,303,065
def prog_log_disable(program): """ This function disables the log transfer for a `ProgramModel` by sending a command to the slave. If the slave is offline an error will be returned. Parameters ---------- program: ProgramModel A valid `ProgramModel`. Raises ------ ...
5,303,066
def device_get_all_by_filters(filters): """Returns Compute devices filtered by name of the field.""" return IMPL.device_get_all_by_filters(filters)
5,303,067
def print_ordered_dict(dictionary): """Takes a dictionary and prints a sorted version of the dictionary. """ ordered_dictionary = collections.OrderedDict(sorted(dictionary.items())) for entry in ordered_dictionary: print(entry, ":", ordered_dictionary[entry])
5,303,068
def fv_creator(lamp, lams, lamda_c, int_fwm, betas, M, P_p,P_s, Df_band=1): """ Cretes 7 split frequency grid set up around the waves from degenerate FWM. The central freuency of the bands is determined by the non-depleted pump approximation and is power dependent. The wideness of these bands is det...
5,303,069
def read_select_def(line: str): """Attempt to read SELECT definition line""" select_match = FRegex.SELECT.match(line) select_desc = None select_binding = None if select_match is None: select_type_match = FRegex.SELECT_TYPE.match(line) if select_type_match is None: select_...
5,303,070
def getSubString(string, firstChar, secondChar,start=0): """ Gives the substring of string between firstChar and secondChar. Starts looking from start. If it is unable to find a substring returns an empty string. """ front = string.find(firstChar,start) back = string.find(secondChar,front+1) ...
5,303,071
def slopePythonPlane(inBlock, outBlock, inXSize, inYSize, A_mat, z_vec, winSize=3, zScale=1): """ Calculate slope using Python. Algorithm fits plane to a window of data and calculated the slope from this - slope than the standard algorithm but can deal with noisy data batter. The ...
5,303,072
def unmount(mpoint, prompt=False, fail=True): """ Unmount a block device if it's mounted. Prompt if prompt=True """ mpoint = _strip_double_slash(mpoint) # If its already not mounted, nothing to do if not is_mounted(mpoint): return # Sometimes we should check with the user first before doing ...
5,303,073
def die_with_usage(): """ HELP MENU """ print 'split_mxm_dataset.py' print ' by T. Bertin-Mahieux (2011) Columbia University' print ' tb2332@columbia.edu' print 'This code splits the full musiXmatch dataset based on the' print 'artist split used for automatic music tagging.' print 'Th...
5,303,074
def decTimeToDeg(sign_sym, deg, min, sec): """Convert dec sign, degrees, minutes, seconds into a signed angle in degrees. sign_sym may represent negative as either '-' or numeric -1.""" if sign_sym == -1 or sign_sym == '-': sign = -1 else: sign = 1 return dmsToDeg(sign, deg, min, ...
5,303,075
def return_task_from_stack(tb) -> dict: """ Function returns task information from stack trace if available Used to tag :param tb: traceback :return return_task: dict """ return_task = {} if not tb: tb = sys.exc_info()[2] while 1: if not tb.tb_next: break ...
5,303,076
def new_lanternfish(puzzle_input: list, days: int) -> int: """ Extract the list of fish ages from the puzzle input. Rather than add to the existing list with new numbers, instead create a new dictionary where each key is the days left (0 to 8) and the value is the total count of fish at that age. ...
5,303,077
def clone( model, input_tensors=None, layer_fn=to_monotonic, input_dim=-1, dc_decomp=False, convex_domain={}, mode="backward", slope_backward=V_slope.name, IBP=True, forward=True, finetune=False, ): """ :param model: Keras model :param input_tensors: List of input...
5,303,078
def OddCore(G): """ Subgraph of vertices and edges that participate in odd cycles. Aka, the union of nonbipartite biconnected components. """ return Graphs.union(*[C for C in BiconnectedComponents(G) if not isBipartite(C)])
5,303,079
def pv(td1,p1,df1): """ returns the vapour partial pressure for given dew-frost point at pressure :param td1: known dew-frost point :param p1: known total pressure :param df1: calculate over dew(1) or frost (0) :return: vapour partial pressure (Pa) """ return vp(td1, df1)*ef(td1, p1, df...
5,303,080
def FExist(filedisk, err): """ Test if FITS file exists returns True or False * file = File name * disk = disk number, 0->CWD * err = Python Obit Error/message stack, """ ################################################################ # Checks if err.isErr: ...
5,303,081
def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar): """Estimate the diagonal covariance vectors. Parameters ---------- responsibilities : array-like of shape (n_samples, n_components) X : array-like of shape (n_samples, n_features) nk : array-like of shape (n_components,) ...
5,303,082
def mediation_covariates(intervention, run, mediation_year, num_mediators): """Build the causal dataset.""" # Just use all of the states at the moment of treatment assignment confounders = run[intervention.time].values() mediators = run[mediation_year].values()[:num_mediators] return np.concatenate(...
5,303,083
def get_hepmass_data(train_test_split=True, decorrelate=False, normalize=False, return_dequantize_scale=True, remove_outliers=True, whiten=True, retrieve_files=['1000_train', '1000_test'], data_folder='/tmp/hepmass/'): # language=rst """ Load the HEPMASS dataset. :param data_folder: Where to download t...
5,303,084
def get_azimuth(inclination: float, launchpad_latitude: float) -> float: """Gets the required Azimuth of the launch in order to satisfy the orbit inclination. The azimuth changes in function of the targeted orbit as well as the position of the launchpad. Args: inclination (float): inclination (in d...
5,303,085
def create_wsgi_request(event_info, server_name='zappa', script_name=None, trailing_slash=True): """ Given some event_info, create and return a valid WSGI request environ. """ method = event_info['httpMethod'] params = event_info['pathParameters']...
5,303,086
def run_ner(): """run ner task""" args_opt = parse_args() epoch_num = args_opt.epoch_num assessment_method = "f1" load_pretrain_checkpoint_path = args_opt.load_pretrain_checkpoint_path save_finetune_checkpoint_path = args_opt.save_finetune_checkpoint_path load_finetune_checkpoint_path = args...
5,303,087
def knapsack_polynomial_estimation(W, weights, costs, eps): """Полиномиальное приближение задачи о рюкзаке. W - вместимость рюкзака weights - веса предметов costs - стоимости предметов eps - точность приближения (должна быть 0 < eps < 1) """ assert W >= 0 assert weights.shape == costs.shape...
5,303,088
def extract_watermark(fileName, base=2) -> str: """ 从STL文件中提取水印 fileName: 文件名 base: 返回水印的进制,默认为二进制 """ solid = Solid(fileName) __ref = __get_ref(solid) __ord = __ord2S(__ref) # 一个参数标识提取水印 __ord = __ord[:128] # 除去后缀0 if base == 2: return __ord elif base =...
5,303,089
def make_figure84(): """ Returns initial conditions for a 4-body system in a 8-shaped orbit. """ ps = ParticleSystem(4) ps.mass[...] = [1.0, 1.0, 1.0, 1.0] ps.rx[...] = [+1.382857, 0.0, -1.382857, 0.0] ps.ry[...] = [0.0, +0.157030, 0.0, -0.157030] ps.rz[...] = [0.0, 0.0, 0.0, 0.0] ...
5,303,090
def save_properties(data): """ Save props data into either memcache (heroku only) or pickle to local file :param data: Dictionary of props data """ if running_on_heroku: mc.set('props', data) else: with open(prop_file, 'w+') as login_prop_file: pickle.dump(data, login...
5,303,091
def pca(data,k=5,frac=0.99,whiten=0): """Computes a PCA and a whitening. The number of components can be specified either directly or as a fraction of the total sum of the eigenvalues. The function returns the transformed data, the mean, the eigenvalues, and the eigenvectors.""" n,d = data.sh...
5,303,092
def isatty(file): """ Returns `True` if `file` is a tty. Most built-in Python file-like objects have an `isatty` member, but some user-defined types may not, so this assumes those are not ttys. """ if (multiprocessing.current_process().name != 'MainProcess' or threading.current_thre...
5,303,093
def update_networkipv6(networkv6, user): """Updates a NetworkIPv6.""" netv6_obj = get_networkipv6_by_id(networkv6.get('id')) netv6_obj.update_v3(networkv6) return netv6_obj
5,303,094
def smart_open(filename: str = None, mode: str = 'r') -> TextIO: """ File OR stdout open :param str filename: filename :param str mode: file opening mode :return: file handle object """ if filename and filename != '-': return open(filename, mode) else: return sys.stdout
5,303,095
def clear(with_boost): """ 清除当前编译设置及结果 """ if os.path.lexists('.xmake'): print('delete .xmake') shutil.rmtree('.xmake') if os.path.lexists('build'): print('delete build') shutil.rmtree('build') if os.path.lexists('Hikyuu.egg-info'): print('delete Hikyuu.egg-info')...
5,303,096
def publish_camera(): """ Publish camera video stream to specified Kafka topic. Kafka Server is expected to be running on the localhost. Not partitioned. """ # Start up producer producer = KafkaProducer(bootstrap_servers=brokers, value_serializer=lambda v: json.dum...
5,303,097
def saveJsonConfig(fn=None): """Saves the visualization options to a JSON object or file. If fn is provided, it's saved to a file. Otherwise, it is returned. """ return scene().saveJsonConfig(fn)
5,303,098
def compute_ocr_score(E: Text) -> float: """Compute the phrase score. FIXME: These methods effectively mutate entities, which we don't do anywhere except in the clustering code. They add the phrase/cluster scores as metadata fields. We could use memoization here, but it would incur a permanent memory penalty...
5,303,099