content
stringlengths
22
815k
id
int64
0
4.91M
def get_args(): """ read parser and return args (as args namespace) """ parser = argparse.ArgumentParser(description='Ask an host for Serial Number') parser.add_argument('-d', '--debug', action='store_true', help='Active le debug') parser.add_argument('-H', '--host', nargs=1, type=str, help=...
5,293,800
def create_dir(ctx, param, value): """ a command option callback to create parent directories if does not exist """ pardir = os.path.dirname(value.name) if hasattr(value, 'name') else None if pardir: os.makedirs(pardir, exist_ok=True) return value
5,293,801
def get_result(filename): """ This route returns the details of the analysis relative to the filename specified along with the source code analyzed """ response = { "success": True, "data" : { "by_context" : utils.getAnalysisResultByContext(app.config, filename), ...
5,293,802
def reader_mock() -> AsyncMock: """Cria um objeto reader mock para os testes.""" reader = AsyncMock() return reader
5,293,803
def _blkidx(n_s=3): """Calculate indices for a 3x3x3 grid around an index of 0""" return (np.array(np.where(np.zeros((n_s, n_s, n_s)) == 0)).T - ( (n_s - 1) / 2)).astype(int)
5,293,804
def cdsem_bend180( width: float = 0.5, radius: float = 10.0, wg_length: float = LINE_LENGTH, straight: ComponentFactory = straight_function, bend90: ComponentFactory = bend_circular, cross_section: CrossSectionFactory = strip, text: ComponentFactory = text_rectangular_mini, ) -> Component: ...
5,293,805
def EWMA(inputs, *args, **kwargs): """EWMA of an inputted list, returns the weighted list. """ if "alpha" in kwargs: alpha = kwargs.get("alpha") if alpha > 1 or alpha < 0: print("Alpha value cannot exced range of [0,1]!!!") return else: alpha = 0.5 # init, default alpha S1 = inputs.sum()/len(inputs) ...
5,293,806
def pray(var, wrapper, message): """Receive divine visions of who has a role.""" if wrapper.source in PRAYED: wrapper.pm(messages["already_prayed"]) return if not message: wrapper.pm(messages["not_enough_parameters"]) return # complete this as a match with other roles (...
5,293,807
def desaturate(img_paths, percent=30, write=True): """ desaturate(img_paths, percent=30, write=True) Takes image(s) and desaturates them. :type img_paths: pyifx.misc.PyifxImage, pyifx.misc.ImageVolume, list :param img_paths: The image(s) to be desaturated. :type percent: int :param percent: How much the i...
5,293,808
def density_standard(components): """ Natural gas density at standard temperature, kg/m3 :param components: (list) List of gas components. Each item is an object of class GasComponent :return: (float) The density of natural gas an standard parameters, kg/m3 """ return sum([component.density_sta...
5,293,809
def get_latlongrid(dset, xindx, yindx): """ INPUTS dset : xarray data set from ModelBin class xindx : list of integers yindx : list of integers RETURNS mgrid : output of numpy meshgrid function. Two 2d arrays of latitude, longitude. """ llcrnr_lat = dset.attrs["Concentra...
5,293,810
def test_ap_ft_over_ds_many(dev, apdev): """WPA2-PSK-FT AP over DS multiple times""" ssid = "test-ft" passphrase="12345678" params = ft_params1(ssid=ssid, passphrase=passphrase) hapd0 = hostapd.add_ap(apdev[0]['ifname'], params) params = ft_params2(ssid=ssid, passphrase=passphrase) hapd1 = ...
5,293,811
def get_WOA_array_1x1_indices(lons=None, lats=None, month=9, debug=False): """ Get the indices for given lats and lons in 1x1 WAO files Parameters ------- lons (np.array): list of Longitudes to use for spatial extraction lats (np.array): list of latitudes to use for spatial extraction month...
5,293,812
def Network_RosslerSystem(Y,t, F,w, A, b, c, Nsys): """Defines a set of coupled Rossler Systems in a Network structure. Coupling is done through the y variable. The coupling and the network topology is defined by the matrix A. The sistem is (where (i) * is multiplication element wise ...
5,293,813
def plot_flux_boxplot(ENSEMBLE_DIR, sample_id, popfva_df, react_plot_list, pheno_id, obj_direction,pre_y=False, savefig=True,whis=1.5,s_size=100,width=0.5,labelsizes=10,notch=True,jitter=True,linewidth=1, dodge=True,palette=["#2020FF", "#FF0303"],f_scale=1.0,figSIZE=(40,5),pl...
5,293,814
def getStudentByID(studentID): """ 根据学生ID获取学生 """ condition = 'studentID={}'.format(studentID) return generalGet('student', 0, condition)
5,293,815
def range_address_number(num, include_last=True): """ '5-7' -> [5, 6, 7] '5' -> ['5'] :param num: :return: """ range_re = re.search('(\d+)-(\d+)', num) if range_re: min, max = list(map( lambda i: int(i), list(range_re.groups()) )) max = m...
5,293,816
def generate_test_uuid(tail_value=0): """Returns a blank uuid with the given value added to the end segment.""" return '00000000-0000-0000-0000-{value:0>{pad}}'.format(value=tail_value, pad=12)
5,293,817
def copy_cluster_decoys(decoy_list, target_dir, create_dir=True, verbose=True, **kwargs): """ Copy cluster decoys specified in <decoy_list> to <target_dir>. Args: decoy_list (list): | output of abinitio.get_decoy_list() | or cluster.rank_cluster_decoys(return_path=True) ...
5,293,818
def deploy(k8s_conf, user): """ Installs and configures a Kubernetes cluster :param k8s_conf: the k8s configuration dict :param user: the sudo user used to apply the playbook :raises: Exception should snaps-kubernetes fail to deploy successfully """ logger.info('Setting up k8s cluster') ...
5,293,819
def download(url, destination, overwrite=False): """ Download a file :param url: URL to download from :type url: str|unicode :param destination: target path and filename for downloaded file :type destination: str|unicode :param overwrite: specify whether or not an existing destination shou...
5,293,820
def create_sub_graph_copy(graph: Graph, nodes_to_extract: list): """ Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The returned sub-graph is a deep copy of the provided graph nodes. :param graph: graph to create a sub-graph from. :param n...
5,293,821
def descent_direction_i(X, i): """ Returns the 3D vector for the direction of decreasing energy at point i. Parameters ---------- X : numpy.nadarray, with shape (N, 3) Current configuration of points. Each row of `X` is the 3D position vector for the corresponding point in the curre...
5,293,822
def java_args(spark: SparkSession, args: List[str]): """ Convert a Python list into the corresponding Java argument array. """ rv = SparkContext._gateway.new_array(spark._jvm.java.lang.String, len(args)) # https://stackoverflow.com/a/522578 for index, arg in enumerate(args): rv[index] =...
5,293,823
def is_file(path: str) -> str: """ Returns true or false if path points to an existing file :param path: A path to a file :return: True if file exists and is a file, False otherwise :raises FileNotFoundError if file does not exist """ if not os.path.exists(path): raise FileNotFoundEr...
5,293,824
def format_revision_list(revisions, use_html=True): """Converts component revision list to html.""" result = '' for revision in revisions: if revision['component']: result += '%s: ' % revision['component'] if 'link_url' in revision and revision['link_url'] and use_html: result += '<a target="...
5,293,825
def order_table(headers, table, order_column, natural_order=None, limit=None): """ :type natural_order: list :param natural_order: define the order for each column. if the value in natural_order is true, the reverse is True else False [True, False, True] build the table """ if len(head...
5,293,826
def test_RandomVariable_incorrect_none_defined(): """ Test if the random variable object raises an error when the distribution is not empirical and no parameters are provided. """ with pytest.raises(ValueError) as e_info: RandomVariable(name='A', distribution='normal')
5,293,827
def respond_to_build(slack_client, branch, build_num, build_id, thread_ts): """Take action on successful build results.""" logging.debug("Responding to build: Branch-%s; BuildNum-%s; BuildID-%s; ThreadID-%s", branch, build_num, build_id, thread_ts) is_production = False if branch == 'develop': m...
5,293,828
def test_empty_locale_html(): """locale_html must still work if field is None.""" s = helpers.locale_html(None) assert not s, 'locale_html on None must be empty.'
5,293,829
def find_new_centroids(parameters: Parameters, data_eng: DataEng) -> DataEng: """Find new cluster centroids by taking the mean of the data points in the cluster, Take the mean of all x points: this is our x of the new centroid, Take the mean of all y points: this is ou...
5,293,830
async def total() -> Dict: """ Sum of a list of numbers --- tags: - Total get: parameters: - N/A response: 200: description: returns a dictionary with a total sum of a list of numbers """ return {"total": sum(list(rang...
5,293,831
def is_extension(cls): """ Check if a class is a MudPi Extension. Accepts class or instance of class """ if not inspect.isclass(cls): if hasattr(cls, '__class__'): cls = cls.__class__ else: return False return issubclass(cls, BaseExtension)
5,293,832
def kalman_xy(x, P, measurement, R, motion = np.matrix('0. 0. 0. 0.').T, Q = np.matrix(np.eye(4))): """ Parameters: x: initial state 4-tuple of location and velocity: (x0, x1, x0_dot, x1_dot) P: initial uncertainty convariance matrix measurement: observed position ...
5,293,833
def create_droplet_click(token): """ Creates a droplet in your DigitalOcean account. Accepts one option (the Digital Ocean API token key). token: [env var name | path to file | token str] Resolved in that order. Example: droplet -t MY_TOKEN The above will first look at an environment var...
5,293,834
def plot_WCA_preturbation_terms(ljs): """Plot the Weeks–Chandler–Anderson perturbation terms""" fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2) T_star = [0.6, 0.75, 1.0, 2.0, 4.0] colors = ["g", "b", "r", "grey", "k"] rho_star = np.linspace(0.0, 0.9, 50) a1 = np.zeros_like(rho_star) a2 = ...
5,293,835
def init_network(network, num_nodes): """Initialize network by adding nodes Arguments: network {Network} num_nodes {Integer} -- Number of nodes """ num_added = 0 for i in range(2 * num_nodes): print("Adding node " + str(i)) node_hash = hash_int(i) print(n...
5,293,836
def activate_cli(ser: serial.Serial): """ Enter the CLI on the currently connected board. """ ser.write(b"#\r\n") wait_for(ser, b"Entering CLI Mode")
5,293,837
def is_view_loaded(view): """returns a buf if the view is loaded in sublime and the buf is populated by us""" if not G.AGENT: return if not G.AGENT.joined_workspace: return if view.is_loading(): return buf = get_buf(view) if not buf or buf.get('buf') is None: ...
5,293,838
def full_chromosomes(reader): """Return list of regions of all chromosomes of VCF reader.""" for line in reader.header.get_lines("contig"): if line.id in CHROMS: name = line.id length = line.length yield "{}:{}-{}".format(name, 1, length)
5,293,839
def linearmap(x, ymin, ymax, flag='linear'): """ Maps given function in the range of ymin, ymax """ if flag =='log': x = np.log10(x) ymin = np.log10(ymin) ymax = np.log10(ymax) xmin = Utils.mkvc(x).min() xmax = Utils.mkvc(x).max() y = (ymax-ymin)*(x-xmin)/(xmax-xmin) + ...
5,293,840
def Log_SetRepetitionCounting(*args, **kwargs): """Log_SetRepetitionCounting(bool bRepetCounting=True)""" return _misc_.Log_SetRepetitionCounting(*args, **kwargs)
5,293,841
def add_system_to_existing_database(runner): """ Fixture to add and delete system from existing database """ result = runner.invoke(sap_cli, args=["add", "-system", "zzz", "-mandant", "100", ...
5,293,842
def get_optimal_index_keys_v2( nb_vectors: int, dim_vector: int, max_index_memory_usage: str, flat_threshold: int = 1000, quantization_threshold: int = 10000, force_pq: Optional[int] = None, make_direct_map: bool = False, should_be_memory_mappable: bool = False, ivf_flat_threshold: i...
5,293,843
def laplacian_ij(X,hi,hj): """ Compute the LAPLACIAN OPERATOR of an image """ M,N = X.shape D2i = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((M-2,1))))/(hi**2)); D2j = (toeplitz(scipy.append(scipy.array([-2,1]),scipy.zeros((N-2,1))))/(hj**2)); D2i[0,1] = 2/(hi**2) ...
5,293,844
def memoize(f): """ A simple memoize implementation. It works by adding a .cache dictionary to the decorated function. The cache will grow indefinitely, so it is your responsibility to clear it, if needed. to clear: `memoized_function.cache = {}` """ def _memoize(func, *args, **kw): ...
5,293,845
def ensure_file_dir(path): """Create path if it does not exist""" ensure_dir(os.path.dirname(path))
5,293,846
def tidy_concentrations(): """ tidy the gardner_mt_catastrophe_only_tubulin.csv dataset melts, removes nan, adds concentration_int columns """ # defining path for data fname = os.path.join(data_path, "gardner_mt_catastrophe_only_tubulin.csv") df = pd.read_csv(fname, skiprows = 9) df =...
5,293,847
def bishijie_info_parse(parse_str:str = ''): """ 传入一个待解析的字符串 """ # html_info = etree.HTML(parse_str,parser=None) soup = BeautifulSoup(parse_str,features="lxml") info_list = soup.find_all('div',class_="content") result_info_list = [] for info in info_list: title = info.find('h3')...
5,293,848
def connect_tcp(host, port): """ return Client connected to the TCP socket """ c = Client() c.setup_tcp_socket(host, port) c.connect() return c
5,293,849
def parse_args(): """ Handles argument parsing for bvauto. """ res = {} nargs = len(sys.argv) if nargs < 2: print "usage:" print " Test build_visit on current machine:" print " bvauto.py [bvauto.input]" print " Test build_visit on current machine and post result...
5,293,850
def test_serverspec_binary_exists(host): """ Tests if simplescreenrecorder binary exists. """ assert host.file(PACKAGE_BINARY).exists
5,293,851
def test_delete_old(ftp_root, ftp_server, work_dir): """Test if old versions of files will be deleted.""" # create file to upload work_dir.join('filename-0.0.4.tgz').write(CONTENT) make_files(ftp_root, [ 'filename-0.0.0.tgz', 'filename-0.0.1.tgz', 'filename-0.0.2.tgz', 'filename-0.0.3.tgz' ...
5,293,852
def state_store(decoy: Decoy) -> StateStore: """Get a mocked out StateStore.""" return decoy.mock(cls=StateStore)
5,293,853
def get_model_specs(model_name): """Return a dict with configurations required for configuring `model_name` model.""" if model_name == "lm": return lm_wikitext2.get_model_config() elif model_name == "seq": return offload_seq.get_model_config() else: raise RuntimeError("Unrecogni...
5,293,854
def store_artefacts(artefacts: Artefacts, artefacts_location: Path) -> None: """ Store artefacts to file in the specified paper_config. Args: artefacts: the artefacts to store artefacts_location: the location for the artefacts file. Can be either a path to a pape...
5,293,855
def rbf_lmsq_error_d_wrt_ith_g(x, y, g, w, u, i): """ radial basis function least mean square error derivative with respect to the ith gamma g : gammas w : weights u : centers """ return -2 * w[i] * np.linalg.norm(x - u[i]) * gaussian(g[i], x, u[i]) * (rbf_h(x, g, w, u) - y)
5,293,856
def schedule_pool(outs, layout): """Schedule for various pooling operators. Parameters ---------- outs: Array of Tensor The computation graph description of pool in the format of an array of tensors. layout: str Data layout. Returns ------- s: Schedule ...
5,293,857
def html_url_parser(url, save_dir, show=False, wait=False, file_number=10): """ HTML parser to download images from URL. Params:\n `url` - Image url\n `save_dir` - Directory to save extracted images\n `show` - Show downloaded image\n `wait` - Press key to continue executing """ webs...
5,293,858
def Hamiltonian(N,V): """ Generates the 'N'-dimensional Hamiltonian matrix of a 1-d tight binding model for an array nearest neighbor site couplings 'V' """ H = np.zeros((N,N)) H[0][1] = V[0] H[N-1][N-2] = V[N-1] for i in range(1,N-1): H[i][i+1] = V[i] H[i][i-1] = V[i] ...
5,293,859
def get_mask(mask_root, mask_paths, ignore_path, use_ignore=True): """ Ignore mask is set as the ignore box region \setminus the ground truth foreground region. Args: mask_root: string. mask_paths: iterable of strings. ignore_path: string. Returns: mask: numpy.ndarr...
5,293,860
def _create_lines_for_order( manager: "PluginsManager", checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"], discounts: Iterable[DiscountInfo], ) -> Iterable[OrderLineData]: """Create a lines for the given order. :raises InsufficientStock: when there is not enough items in stock ...
5,293,861
def single_mode(ell, m, **kwargs): """WaveformModes object with 1 in selected slot and 0 elsewhere Additional keyword arguments are passed to `modes_constructor`. Parameters ---------- ell, m : int The (ell, m) value of the nonzero mode """ if kwargs: import pprint ...
5,293,862
def files_by_date() -> Response: """TODO --- responses: '200': description: TODO """ return redirect("https://explorer.ooni.org/search", 301)
5,293,863
def test_function_validation() -> None: """Tests the function validation mechanism.""" with pytest.raises(AssertionError): Job(1) # type: ignore with pytest.raises(AssertionError): Job('test')
5,293,864
def extractAliasFromContainerName(containerName): """ Take a compose created container name and extract the alias to which it will be refered. For example bddtests_vp1_0 will return vp0 """ return containerName.split("_")[1]
5,293,865
def sell(): """Sell shares of stock""" # Retrieve current symbols and shares of stocks owned by the user stocks = db.execute( "SELECT stock AS symbol, SUM(CASE WHEN transaction_type='buy' THEN shares WHEN transaction_type='sell' THEN -shares ELSE NULL END) AS shares FROM transactions WHERE user_id ...
5,293,866
def _check_mode_valid(mode): """Raises ValueError if the given mode is invalid.""" if (mode != model_fn.ModeKeys.TRAIN and mode != model_fn.ModeKeys.INFER and mode != model_fn.ModeKeys.EVAL): raise ValueError("mode=%s unrecognized." % str(mode))
5,293,867
def bootstrap_CIs_on_pain_gap_reduction(y, yhat, yhat_from_klg, ids, all_ses_vars, n_bootstraps, quantities_of_interest=None): """ Confidence intervals on how much we reduce the pain gap. """ if quantities_of_interest is None: quantities_of_interest = ['No controls gap', 'Rival gap', 'yhat gap'...
5,293,868
def disable_fetcher(): """arg: fetcher_id""" disable_user_fetcher( get_current_user_id(), request.values['fetcher_id']) return {'success': 1}
5,293,869
def jupyter_show_as_svg(g): """ Shows object as SVG (by default it is rendered as image). @param g: digraph object """ return HTML(g.pipe(format='svg').decode("utf-8"))
5,293,870
def extract_od(input_dir, output_dir, workflow): """ For each image in input directory, run either interpolation or registration of fiducials (default) workflow. An xlsx file (and potentially debug plots) will be written to output directory. :param str input_dir: Input directory path :param str...
5,293,871
def parse_data(train, test): """Load data from train and test files respectively.""" # Scale X and Y features in train to 0 mean, unit variance xy_scaler = StandardScaler() xy_scaler.fit(train[["X", "Y"]]) train[["X", "Y"]] = xy_scaler.transform(train[["X", "Y"]]) train = train[abs(train["Y"]) ...
5,293,872
def process_win_conditions(room: str, players: list, state: str, state_name: str, result_general_list: list, result_private_dict: dict): """Moves the game to the next state based on whether the win condition has been met or not. Args: room (str): The room code of the players. players (list): Al...
5,293,873
def primes(n: int) -> Sequence[int]: """Returns the first n prime numbers in sorted order.""" _compute_primes(n) return _prime_sequence[:n]
5,293,874
def _create_docstring_df(): """creates the df used in the docstring of single_val_cols_to_dict""" return pd.DataFrame(index=pd.date_range(time, periods=3, freq='1H'), columns=['col1', 'col2', 'col3'], data=[[1.0, 2.0, 3.0], [1.0, 4.0, 3.0], [1.0, 6.0, 3.0]])
5,293,875
def test_if_df(data: pd.DataFrame) -> bool: """Test if passed data instance is from class DataFrame Arguments: data {pd.DataFrame} -- This is data input Returns: bool -- Returns bool if passed data is data """ return isinstance(df, pd.DataFrame)
5,293,876
def load_data(projection: dict) -> pd.DataFrame: """ Load the data from the Mongo collection and transform into a pandas dataframe :projection: A dictionary with the fields to load from database :return: A pandas dataframe with the data """ articles = db.read_articles( projection=pro...
5,293,877
def block_to_actions(block, delete_existing=False): """Converts a block vector representation into actions that create the block. The idea here is that a block with the properties of `block` will be created when the returned actions are executed in the unity environment. Note that if delete_existing=False, an...
5,293,878
def get_stack(token, stack_id): """ Asks OpenStack Heat for stack details """ url = token.get_service_url(OPENSTACK_SERVICE.HEAT) if url is None: raise ValueError("OpenStack Heat URL is invalid") api_cmd = url + "/stacks/%s" % stack_id response = rest_api_request(token, "GET", api_...
5,293,879
def is_log_i18n_msg_with_mod(n): """LOG.xxx("Hello %s" % xyz) should be LOG.xxx("Hello %s", xyz)""" if not isinstance(n.parent.parent, compiler.ast.Mod): return False n = n.parent.parent if isinstance(n.parent, compiler.ast.CallFunc): if isinstance(n.parent.node, compiler.ast.Getattr): ...
5,293,880
def toc_dir(dir_): """A directory was passed to doctoc. Return bool whether any file was modified and the number of warnings.""" files = glob.glob(os.path.join(dir_, "*.md")) modified_any = False warnings = 0 for file_ in files: if "API-categories.md" in file_ or "API-index.md" in file_:...
5,293,881
def run_worker(*args, **kwargs): """ Called by console_scripts `gmalt-api-worker` to launch the workers It is a wrapper around the standard `celery` command. It accepts the same arguments with an additionnal option `-gmalt-config` Usage : `gmalt-file-server -P gevent -c 10 -gmalt-config conf/gmal.cfg`...
5,293,882
def _unpack_series(json_data, product): """Returns a list of time series from get-netcdf-data JSON.""" key = 'long_range_mem1' if product == 'long_range' else product time_step_hrs = PRODUCTSv1_1[key]['step_hrs'] offset_hrs = PRODUCTSv1_1[key]['offset_hrs'] data_list = json_data.itervalues().next(...
5,293,883
def initUserDB(app): """ Called at startup to initialize user/passwd dictionary from a password text file """ log.info("initUserDB") if "user_db" in app: msg = "user_db already initilized" log.warn(msg) return if config.get("aws_dynamodb_gateway") and \ c...
5,293,884
def HexToByte( hexStr ): """ Convert a string hex byte values into a byte string. The Hex Byte values may or may not be space separated. """ # The list comprehension implementation is fractionally slower in this case # # hexStr = ''.join( hexStr.split(" ") ) # return ''.join( [...
5,293,885
def gabor(sigma, theta, Lambda, psi, gamma): """Gabor feature extraction.""" sigma_x = float(sigma) / gamma sigma_y = float(sigma) / gamma # Bounding box nstds = 3 # Number of standard deviation sigma xmax = max(abs(nstds * sigma_x * np.cos(theta)), abs(nstds * sigma_y * np.sin(theta))) xm...
5,293,886
def build_haplotype_sequences(records, args): """Build consensus sequence for each seed.""" logger.info("Building building haplotype sequences...") ref_seqs = load_fasta(REF_FILE) base_dir = os.path.dirname(args.in_tsv) results = {} # actually consensus seeds for record in records: ou...
5,293,887
def test_follows_username(): """ Test followers and and following by username. """ found = 0 for pages, users in enumerate(T.following('jack')): pages += 1 found += len(users["data"]) if pages == 2: break assert found >= 1000 found = 0 for pages, u...
5,293,888
def brier_score_loss_for_true_class(y_true, y_proba): """ Calculates Brier score for from a set of class probabilities. :param y_true: True class labels. :type y_true: list :param y_proba: Predicted class probabilities. :type y_proba: array-like :return: Brier score """ if y_proba is...
5,293,889
def reload_storage_policies(): """ Reload POLICIES from ``swift.conf``. """ global _POLICIES policy_conf = ConfigParser() policy_conf.read(SWIFT_CONF_FILE) try: _POLICIES = parse_storage_policies(policy_conf) except PolicyError as e: raise SystemExit('ERROR: Invalid Stora...
5,293,890
def _truncate_term_length(term, taken=0): """truncate the length of a term string length to the maximum allowed for xapian terms :param term: the value of the term, that should be truncated :type term: str :param taken: since a term consists of the name of the term and its actual value, thi...
5,293,891
def families_sextupoles(): """.""" return []
5,293,892
def parse_config_file(conf_file): """ Parse a divvy configuration file. :param str conf_file: path to divvy configuration file :return Mapping: compute settings as declared in config file """ with open(conf_file, 'r') as f: _LOGGER.info("Loading divvy config file: %s", conf_file) ...
5,293,893
def h2oinitname(): """ Python API test for h2o.init :return: """ try: h2o.init(strict_version_check=False, name="test") # Should initialize h2o.init(strict_version_check=False, name="test") # Should just connect assert h2o.cluster().cloud_name == "test" except H2OConnec...
5,293,894
def test_stm_trace_events(dut): """ Check if STM properly generates trace events """ yield _init_dut(dut) yield _activate_module(dut) for _ in range(0, TRACE_EVENT_TEST_COUNT): # Randomly wait between trace events for _ in range(0, random.randint(0, 100)): yield Ri...
5,293,895
def test_find_in_grandparent_path(): """Should find a project in the grandparent directory""" directory = os.path.dirname(os.path.realpath(__file__)) subdirectory = os.path.join(directory, 'fake', 'fake') result = steptest.find_project_directory(subdirectory) assert directory == result
5,293,896
def get_schema_from_list(schema_list): """ Create a bigquery schema from a list :param schema_list: Columns definitions separate by "," character, A column definition is NAME: TYPE :return: bigquery schema """ schema = [] columns_def = schema_list.split(',') for column_def in co...
5,293,897
def calcError(svm, alpha_k): """ 计算误差: E = g(X) - y """ g_k = float(np.multiply(svm.alphas, svm.label).T * svm.kernel_mat[:, alpha_k] + svm.b) error_k = g_k - float(svm.label[alpha_k]) return error_k
5,293,898
def ma30_cross_func(data): """ MA均线金叉指标 """ MA5 = talib.MA(data.close, 5) MA10 = talib.MA(data.close, 10) MA30 = talib.MA(data.close, 30) MA90 = talib.MA(data.close, 90) MA120 = talib.MA(data.close, 120) MA30_CROSS = pd.DataFrame(np.c_[MA5, MA10, ...
5,293,899