content
stringlengths
22
815k
id
int64
0
4.91M
def mock_imap_search_error(): """Mock imap class values.""" with patch( "custom_components.mail_and_packages.helpers.imaplib" ) as mock_imap_search_error: mock_conn = mock.Mock(spec=imaplib.IMAP4_SSL) mock_imap_search_error.IMAP4_SSL.return_value = mock_conn mock_conn.login.return_value = ( "OK", [b"user@fake.email authenticated (Success)"], ) mock_conn.list.return_value = ( "OK", [b'(\\HasNoChildren) "/" "INBOX"'], ) mock_conn.search.side_effect = Exception("Invalid SEARCH format") mock_conn.select.return_value = ("OK", []) yield mock_conn
7,000
def delete_models_shares_groups(id, group_id, client=None): """Revoke the permissions a group has on this object Use this function on both training and scoring jobs. Parameters ---------- id : integer The ID of the resource that is shared. group_id : integer The ID of the group. client : :class:`civis.APIClient`, optional If not provided, an :class:`civis.APIClient` object will be created from the :envvar:`CIVIS_API_KEY`. Returns ------- None Response code 204: success """ return _unshare_model(id, group_id, entity_type='groups', client=client)
7,001
def step1ddiffusionanalytical(q, dt, alpha, beta, prng=np.random, **kwargs): """Analytical time stepping as proposed in Jenkins, Spano arXiv:1506.06998 Uses the asymptotic normality of the death process for small times (see Griffiths, J. Math. Bio, 1984) """ theta = alpha+beta beta_ = 0.5*(theta-1.0)*dt if beta_ == 0.0: eta = 1.0 sigma = (2.0/(3.0*dt))**.5 else: eta = beta_/np.expm1(beta_) # calculation can sometimes give negative numbers due to numerical precision factor = max(0, 2.0*eta/dt *(1.0 + eta/(eta+beta_)-2.0*eta)) sigma = max((eta+beta_) * factor**.5 / beta_, 1e-16) mu = 2.0*eta/dt m = max(int(round(prng.normal(mu, sigma))), 0) l = prng.binomial(m, q) qnew = prng.beta(alpha+l, beta+m-l) return qnew
7,002
def no_vtk(): """ Checks if VTK is installed and the python wrapper is functional """ global _vtk_version return _vtk_version is None
7,003
def _download_type( archive, manifest, model_class, batch_size, privacy_transform_fn): """Downloads a set of files and adds them to the archive.""" json_path = os.path.join( os.path.dirname(archive.path), '%s.json' % model_class) _LOG.info( 'Adding entities of type %s to temporary file %s', model_class, json_path) json_file = transforms.JsonFile(json_path) json_file.open('w') model_map_fn = functools.partial( _write_model_to_json_file, json_file, privacy_transform_fn) _process_models( db.class_for_kind(model_class), batch_size, model_map_fn=model_map_fn) json_file.close() internal_path = _AbstractArchive.get_internal_path( os.path.basename(json_file.name), prefix=_ARCHIVE_PATH_PREFIX_MODELS) _LOG.info('Adding %s to archive', internal_path) archive.add_local_file(json_file.name, internal_path) manifest.add(_ManifestEntity(internal_path, False)) _LOG.info('Removing temporary file ' + json_file.name) os.remove(json_file.name)
7,004
def get_request_list(flow_list: list) -> list: """ 将flow list转换为request list。在mitmproxy中,flow是对request和response的总称,这个功能只获取request。 :param flow_list: flow的列表 :return: request的列表 """ req_list = [] for flow in flow_list: request = flow.get("request") req_list.append(request) return req_list
7,005
def safety(session: Session) -> None: """Scan dependencies for insecure packages.""" poetry = Poetry(session) with poetry.export("--dev", "--without-hashes") as requirements: install(session, "safety") session.run("safety", "check", f"--file={requirements}", "--bare")
7,006
def query_total_production(start_date, end_date) -> Tuple[int]: """Total count of semi production on the given time interval""" semi_count = None fg_count = None try: with stSession() as s: semi_count = ( s.query(ProductionScan) .filter( sa.and_( ProductionScan.date >= start_date, ProductionScan.date <= end_date, ) ) .count() ) fg_count = ( s.query(StorageScan) .filter( sa.and_( StorageScan.date >= start_date, StorageScan.date <= end_date, ) ) .count() ) except sa.exc.OperationalError as e: logging.error(f"Operational error occured\n{e}") return None except Exception as e: logging.error("Unknown Error", exc_info=True) return None finally: s.close() return (semi_count, fg_count)
7,007
def createPolyPlaneCtx(*args, **kwargs): """ Flags: - attachToSubdivisionsAll : asa (bool) [] - attachToSubdivisionsHeight : ash (bool) [] - attachToSubdivisionsWidth : asw (bool) [] - axis : ax (int) [] - createUVs : cuv (int) [] - doDragEdit : dde (bool) [] - doSubdivisionsCapsEdit : dsc (bool) [] - exists : ex (bool) [] - height : h (float) [] - history : ch (bool) [] - image1 : i1 (unicode) [] - image2 : i2 (unicode) [] - image3 : i3 (unicode) [] - name : n (unicode) [] - subdivisionsHeight : sh (int) [] - subdivisionsWidth : sw (int) [] - width : w (float) [] Derived from mel command `maya.cmds.createPolyPlaneCtx` """ pass
7,008
def add_fields(_, level, event_dict): """ Add custom fields to each record. """ now = dt.datetime.now() event_dict['timestamp'] = TZ.localize(now, True).astimezone(pytz.utc).isoformat() event_dict['level'] = level if session: event_dict['session_id'] = session.get('session_id') if request: try: event_dict['ip_address'] = request.headers['X-Forwarded-For'].split(',')[0].strip() except Exception: event_dict['ip_address'] = 'unknown' return event_dict
7,009
def Smith_set(A,P,params,election_ID,printing_wanted=False): """ Compute and return a list of the candidates in the Smith set. This is the smallest set of candidates such that every candidate in the Smith set beats every candidate not in the Smith set in one-on-one contests. In this implementation, "a beats b" if at least half the voters prefer a to b. Thus, a beats b and vice versa if they are tied; this gives probably the most reasonable notion for a Smith set when there are ties. The algorithm uses the fact that the Smith set will be the *last* strongly connected component discovered by the usual DFS SCC algorithm. Here A = set of alternatives (candidates), and P = profile (dict mapping ballots to counts). """ if printing_wanted: print "%s: Computing Smith set."%election_ID pref = pairwise_prefs(A,P,params) # pref[(i,j)] gives number preferring i to j n = number_of_ballots_in_profile(P) stack = [] in_stack = set() index = 0 # DFS node counter I = { } # gives indices of vertics L = { } # gives lowlinks of vertices for a in A: if not I.has_key(a): # Start a DFS at each node we haven't seen yet (index,scc)=Smith_aux(a,A,index,I,L,stack,in_stack,pref,n) scc = sorted(scc) if printing_wanted: print indent+"Smith set is: "+string.join(scc) return scc
7,010
def run_async_from_thread(func: Callable[..., Coroutine[Any, Any, T_Retval]], *args) -> T_Retval: """ Call a coroutine function from a worker thread. :param func: a coroutine function :param args: positional arguments for the callable :return: the return value of the coroutine function """ try: asynclib = _local.current_async_module except AttributeError: raise RuntimeError('This function can only be run from an AnyIO worker thread') return asynclib.run_async_from_thread(func, *args)
7,011
def check_tensor_shape(tensor_tf, target_shape): """ Return a Tensorflow boolean graph that indicates whether sample[features_key] has the specified target shape. Only check not None entries of target_shape. :param tensor_tf: Tensor to check shape for. :param target_shape: Target shape to compare tensor to. :returns: True if shape is valid, False otherwise (as TF boolean). """ result = tf.constant(True) for i, target_length in enumerate(target_shape): if target_length: result = tf.logical_and( result, tf.equal(tf.constant(target_length), tf.shape(tensor_tf)[i])) return result
7,012
def print_as_markdown_table(l, heading=None): """print(`l` as a markdown formatted table) Parameters ---------- l : list of lists or list of tuples or pandas.Series the list of data you want printed. All rows must be same length heading : list a list of column headings. Must be same width as items of l """ if type(l) != list and type(l) != pd.Series: raise TypeError("only supports printing list or pandas.Series") if type(l) == pd.Series: new_l = list() for key in l.keys(): value = l.get_value(key) if type(value) != tuple: value = (value,) new_l.append(key + value) l = new_l output = '' if heading is not None: output += ' | '.join([str(x) for x in heading]) + '\n' output += '-|-'.join(['-'*len(str(x)) for x in heading]) + '\n' for item in l: output += ' | '.join([str(x) for x in item]) + '\n' print(output)
7,013
def main(bind, workers): """Run the WSGI service.""" BarrierApplication(app, locals()).run()
7,014
def LabelAddressPlus(ea, name, force=False, append_once=False, unnamed=False, nousername=False, named=False, throw=False): """ Label an address with name (forced) or an alternative_01 :param ea: address :param name: desired name :param force: force name (displace existing name) :param append_once: append `name` if not already ending with `name` :param named: [str, callable(addr, name)] name for things with existing usernames :return: success as bool """ def ThrowOnFailure(result): if not result and throw: raise RuntimeError("Couldn't label address {:x} with \"{}\"".format(ea, name)) return result def MakeUniqueLabel(name, ea=idc.BADADDR): fnLoc = idc.get_name_ea_simple(name) if fnLoc == idc.BADADDR or fnLoc == ea: return name fmt = "%s_%%i" % name for i in range(100000): tmpName = fmt % i fnLoc = idc.get_name_ea_simple(tmpName) if fnLoc == idc.BADADDR or fnLoc == ea: return tmpName return "" if nousername: unnamed = nousername if ea < idc.BADADDR: if HasUserName(ea): if named: if callable(named): _name = idc.get_name(ea) _name = named(ea, _name, name) else: name = named elif unnamed: return fnName = idc.get_name(ea) if append_once: if not fnName.endswith(name): name += fnName else: return ThrowOnFailure(False) fnLoc = idc.get_name_ea_simple(name) if fnLoc == idc.BADADDR: return ThrowOnFailure(idc.set_name(ea, name, idc.SN_NOWARN)) elif fnLoc == ea: return ThrowOnFailure(True) else: if force: idc.set_name(fnLoc, "", idc.SN_AUTO | idc.SN_NOWARN) idc.Wait() return ThrowOnFailure(idc.set_name(ea, name, idc.SN_NOWARN)) else: name = MakeUniqueLabel(name, ea) return ThrowOnFailure(idc.set_name(ea, name, idc.SN_NOWARN)) else: print("0x0%0x: Couldn't label %s, BADADDR" % (ea, name)) return False
7,015
def do_match(station1, station2, latitude, elevation, distance): """ Perform the match between two stations. Do initial latitude check to speed up the test (not longitude as this isn't a constant distance) Return probabilities for elevation, separation and Jaccard Index :param Station Class station1: :param Station Class station2: :returns: list of 3 probabilities [elev, dist, jaccard] """ # latitude - pre check to make quicker if np.abs(station1.lat - station2.lat) > LATITUDE_THRESHOLD: return False # elevation height = np.abs(station1.elev - station2.elev) if height < (ELEVATION_THRESHOLD*4): height_Pr = np.exp(-1.0 * height / ELEVATION_THRESHOLD) else: height_Pr = 0 # latitude & longitude distance, bearing = utils.get_dist_and_bearing([station1.lat, station1.lon],[station2.lat, station2.lon]) if distance < (DISTANCE_THRESHOLD*4): dist_Pr = np.exp(-1.0 * distance / DISTANCE_THRESHOLD) else: dist_Pr = 0. # Jaccard Index on name - remove all whitespace jac_Pr = jaccard(station1.name.strip(), station2.name.strip()) # Jaccard Index on METAR call sign if station1.call != "" and station2.call != "": jac_Pr_metar = jaccard(station1.call, station2.call) # name matching return [height_Pr, dist_Pr, jac_Pr]
7,016
def rotation_matrix_from_vectors(vec1, vec2): """ Find the rotation matrix that aligns vec1 to vec2 Args ---- vec1 (numpy.ndarray): A 3d "source" vector vec2 (numpy.ndarray): A 3d "destination" vector Returns ------- numpy.ndarray: A transform matrix (3x3) which when applied to vec1, aligns it with vec2. """ a, b = (vec1 / np.linalg.norm(vec1)).reshape(3), (vec2 / np.linalg.norm(vec2)).reshape(3) v = np.cross(a, b) c = np.dot(a, b) s = np.linalg.norm(v) kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) rotation_matrix = np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s ** 2)) return rotation_matrix
7,017
def get_file_from_cache_if_exists(file_path, update_modification_time_on_access=True): """Get file from nfs cache if available.""" cache_file_path = get_cache_file_path(file_path) if not cache_file_path or not file_exists_in_cache(cache_file_path): # If the file does not exist in cache, bail out. return False # Fetch cache file size before starting the actual copy. cache_file_size = get_cache_file_size_from_metadata(cache_file_path) # Copy file from cache to local. if not shell.copy_file(cache_file_path, file_path): return False # Update timestamp to later help with eviction of old files. if update_modification_time_on_access: update_access_and_modification_timestamp(cache_file_path) # Return success or failure based on existence of local file and size # comparison. return (os.path.exists(file_path) and os.path.getsize(file_path) == cache_file_size)
7,018
def audio(src, type="audio/ogg", other_attr={}): """ add audio file args: src <str> : source file type <str> : type of audio file other_attr <dict> : other attributes """ return f""" <audio {_parse_attr(other_attr)}> <source src="{src}" type="{type}"> </audio> """.strip()
7,019
def test_triangle(dim): """ Tests if dimensions can come from a triangle. dim is a list or tuple of the three dimensions """ dim = [int(x) for x in dim] dim.sort() if dim[0] + dim[1] > dim[2]: return True else: return False
7,020
def arg_parser(data: str): """parse "x[a1, a2, a3], y[k1=a1, a2, k3=a3], z" nested [] are ignored. """ res: List[NameWithAttrs] = _ARG_WITH_ATTR_PARSER.parse(data) return res
7,021
def _get_resource(span): """Get resource name for span""" if "http.method" in span.attributes: route = span.attributes.get("http.route") return ( span.attributes["http.method"] + " " + route if route else span.attributes["http.method"] ) return span.name
7,022
def merge( _0: dask.dataframe.core.DataFrame, _1: dask.dataframe.core.DataFrame, /, *, how: Literal["inner"], left_on: Literal["x"], right_index: bool, shuffle: Literal["disk"], ): """ usage.dask: 1 """ ...
7,023
def preprocess_hedge_funds(csv, fund_name): """ Get hedge funds holding from their 13F filling. Data is from https://whalewisdom.com/. You need to sign up a free account to access the csv files. Data is updated quarterly. Parameters ---------- csv: str csv file path fund_name: str name of the csv file you want to save. I would advice you to name it the same as the names inside scheduled_tasks/hedge_funds_description.json. """ df = pd.read_csv(csv) df.fillna("N/A", inplace=True) df = df.apply(lambda x: x.astype(str).str.upper()) del df["Qtr first owned"] del df["Recent Price"] del df["Ranking"] df = df[df["source_type"] == "13F"] df.index = df.index + 1 df = df.reset_index() df.columns = ["Rank", "Stock", "Ticker", "Type", "Quantity", "Market Value", "% Portfolio", "Previous % Portfolio", "Change", "% Change", "Change Type", "% Ownership", "Sector", "Source Type", "Source Date", "Avg Price"] df.to_csv(os.path.join("../database", "hedge_funds_holdings", "{}.csv".format(fund_name)), index=False)
7,024
def get_draw_title(kdata): """根据typ值,返回相应的标题,如 上证指数(日线) 参数:kdata: KData实例 返回:一个包含stock名称的字符串,可用作绘图时的标题 """ if not kdata: return "" query = kdata.getQuery() stock = kdata.getStock() if stock.isNull(): return "" s1 = '' if query.kType == KQuery.KType.DAY: s1 = u' (日线)' elif query.kType == KQuery.KType.WEEK: s1 = u' (周线)' elif query.kType == KQuery.KType.MONTH: s1 = u' (月线)' elif query.kType == KQuery.KType.QUARTER: s1 = u' (季线)' elif query.kType == KQuery.KType.HALFYEAR: s1 = u' (半年线)' elif query.kType == KQuery.KType.YEAR: s1 = u' (年线)' elif query.kType == KQuery.KType.MIN: s1 = u' (1分钟线)' elif query.kType == KQuery.KType.MIN5: s1 = u' (5分钟线)' elif query.kType == KQuery.KType.MIN15: s1 = u' (15分钟线)' elif query.kType == KQuery.KType.MIN30: s1 = u' (30分钟线)' elif query.kType == KQuery.KType.MIN60: s1 = u' (60分钟线)' name = stock.name if stock.code == "": stitle = "Block(%s) %s" % (stock.id, name) + s1 else: stitle = stock.market + stock.code + ' ' + name + s1 return stitle
7,025
def _B(slot): """Convert slot to Byte boundary""" return slot*2
7,026
def nll(perm, true): """ perm: (n, n) or (s, n, n) true: (n) """ n = true.size(-1) # i = torch.arange(n, device=perm.device) # j = true.to(perm.device) # print("perm.nll:", perm.size(), true.size()) elements = perm.cpu()[..., torch.arange(n), true] # elements = perm.cpu()[torch.arange(n), true] nll = -torch.sum(torch.log2(elements.to(perm.device))) if perm.dim() == 3: # normalize by number samples nll = nll / perm.size(0) # print("nll", nll) return nll
7,027
def _peaks_colors_from_points(points, colors=None, points_per_line=2): """ Returns a VTK scalar array containing colors information for each one of the peaks according to the policy defined by the parameter colors. Parameters ---------- points : (N, 3) array or ndarray points coordinates array. colors : None or string ('rgb_standard') or tuple (3D or 4D) or array/ndarray (N, 3 or 4) or array/ndarray (K, 3 or 4) or array/ndarray(N, ) or array/ndarray (K, ) If None a standard orientation colormap is used for every line. If one tuple of color is used. Then all streamlines will have the same color. If an array (N, 3 or 4) is given, where N is equal to the number of points. Then every point is colored with a different RGB(A) color. If an array (K, 3 or 4) is given, where K is equal to the number of lines. Then every line is colored with a different RGB(A) color. If an array (N, ) is given, where N is the number of points then these are considered as the values to be used by the colormap. If an array (K,) is given, where K is the number of lines then these are considered as the values to be used by the colormap. points_per_line : int (1 or 2), optional number of points per peak direction. Returns ------- color_array : vtkDataArray vtk scalar array with name 'colors'. colors_are_scalars : bool indicates whether or not the colors are scalars to be interpreted by a colormap. global_opacity : float returns 1 if the colors array doesn't contain opacity otherwise -1. """ num_pnts = len(points) num_lines = num_pnts // points_per_line colors_are_scalars = False global_opacity = 1 if colors is None or colors == 'rgb_standard': # Automatic RGB colors colors = np.asarray((0, 0, 0)) color_array = numpy_to_vtk_colors(np.tile(255 * colors, (num_pnts, 1))) elif type(colors) is tuple: global_opacity = 1 if len(colors) == 3 else -1 colors = np.asarray(colors) color_array = numpy_to_vtk_colors(np.tile(255 * colors, (num_pnts, 1))) else: colors = np.asarray(colors) if len(colors) == num_lines: pnts_colors = np.repeat(colors, points_per_line, axis=0) if colors.ndim == 1: # Scalar per line color_array = numpy_support.numpy_to_vtk(pnts_colors, deep=True) colors_are_scalars = True elif colors.ndim == 2: # RGB(A) color per line global_opacity = 1 if colors.shape[1] == 3 else -1 color_array = numpy_to_vtk_colors(255 * pnts_colors) elif len(colors) == num_pnts: if colors.ndim == 1: # Scalar per point color_array = numpy_support.numpy_to_vtk(colors, deep=True) colors_are_scalars = True elif colors.ndim == 2: # RGB(A) color per point global_opacity = 1 if colors.shape[1] == 3 else -1 color_array = numpy_to_vtk_colors(255 * colors) color_array.SetName('colors') return color_array, colors_are_scalars, global_opacity
7,028
def log_verbose(message): """Logs a message to stdout if VERBOSE is True""" if VERBOSE: print(message)
7,029
def epi_reg(epi, t1, t1brain, out='epi_reg', **kwargs): """Wrapper for the ``epi_reg`` command. :arg epi: Input EPI image :arg t1: Input wholehead T1 image :arg t1brain: Input brain extracted T1 image :arg out: Output name """ asrt.assertIsNifti(epi) asrt.assertIsNifti(t1) asrt.assertIsNifti(t1brain) valmap = { 'nofmapreg' : wutils.SHOW_IF_TRUE, 'noclean' : wutils.SHOW_IF_TRUE, 'v' : wutils.SHOW_IF_TRUE, } cmd = ['epi_reg', '--epi='+epi, '--t1='+t1, '--t1brain='+t1brain, '--out='+out] cmd += wutils.applyArgStyle('--=', valmap=valmap, singlechar_args=True, **kwargs) return cmd
7,030
def load_towns(): """Sample of Wikipedia dataset that contains informations about Toulouse, Paris, Lyon and Bordeaux. Examples -------- >>> from pprint import pprint as print >>> from cherche import data >>> towns = data.load_towns() >>> print(towns[:3]) [{'article': 'Paris (French pronunciation: \u200b[paʁi] (listen)) is the ' 'capital and most populous city of France, with an estimated ' 'population of 2,175,601 residents as of 2018, in an area of more ' 'than 105 square kilometres (41 square miles).', 'id': 0, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}, {'article': "Since the 17th century, Paris has been one of Europe's major " 'centres of finance, diplomacy, commerce, fashion, gastronomy, ' 'science, and arts.', 'id': 1, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}, {'article': 'The City of Paris is the centre and seat of government of the ' 'region and province of Île-de-France, or Paris Region, which has ' 'an estimated population of 12,174,880, or about 18 percent of ' 'the population of France as of 2017.', 'id': 2, 'title': 'Paris', 'url': 'https://en.wikipedia.org/wiki/Paris'}] """ with open(pathlib.Path(__file__).parent.joinpath("towns.json"), "r") as towns_json: return json.load(towns_json)
7,031
def nonce_initialization(params: InitializeNonceParams) -> TransactionInstruction: """Generate an instruction to initialize a Nonce account. Args: params: The nonce initialization params. Returns: The instruction to initialize the nonce account. """ return TransactionInstruction.from_solders(ssp.initialize_nonce_account(params.to_solders()))
7,032
def to_weeknr(date=''): """ Transforms a date strings YYYYMMDD to the corresponding week nr (e.g. 20200713 becomes w29) """ week_nr = pd.to_datetime(date).to_pydatetime().isocalendar()[1] return f"w{week_nr}"
7,033
def build_logisticregression(X_loc, y_loc, args): """finds best parameters for logistic regression""" Printer(colored('(training) ', 'green') + 'searching for best parameters for logistic regression') # specify parameters and distributions to sample from param_dist = {"C": np.logspace(-9, 3, 13), "solver": ['newton-cg', 'lbfgs', 'liblinear', 'sag'], "dual": [False], "tol": np.logspace(-9, 3, 13) } clf = LogisticRegression(penalty='l2') random_search = RandomizedSearchCV(clf, param_distributions=param_dist, scoring='accuracy', n_iter=int(args.iter), n_jobs=-1, refit=True, cv=3) random_search.fit(X_loc, y_loc) acc = random_search.cv_results_['mean_test_score'] filename = 'cv/logisticregression_' + str(np.mean(acc)) + '.pkl' # save model savemodel(random_search, filename) # save best params filename_param = 'cv/logisticregression_param_' + str(np.mean(acc)) + '.json' saveparams(random_search.best_params_, filename_param) return random_search
7,034
def load_data(experiments, remove_outlier=True, peptides=["A5cons", "A6cons", "phage_ctl_0", "phage_ctl_1", "phage_ctl_2", "phage_ctl_4", "phage_ctl_5", "phage_ctl_6", "phage_ctl_7", "phage_ctl_8", "phage_ctl_9"]): """ Convenience function that allows one to load a whole bunch of experiments, with different peptides, into a single data frame. experiments should be a list of dictionaries of the following form: [{"protein":"hA6", "name_in_file":"hA6_4.3", "Kd":45, "prot_conc":4.2, "probe_conc":4.2, "data_file":"13_main-collection.txt", "plate_file":"13_plate-layout.xlsx"},...] remove_outlier: whether or not to look for outlier points and remove them when averaging technical reps peptides: list of peptides. these are used to build regular expressions to match peptides in each data file. It looks for an exact match at the start of the string, allowing any trailing characters. NOTE: this could lead to problems if you had peptides with names like pep10, pep100. """ pep_patterns = [re.compile(f"{p}") for p in peptides] proteins = set([e["protein"] for e in experiments]) times_pep_was_seen = dict([(protein,dict([(p,0) for p in peptides])) for protein in proteins]) all_df = [] for expt in experiments: df, _ = read_file(expt["data_file"],expt["plate_file"]) df = df[df.protein == expt["name_in_file"]] peptide_Kd_scalar = get_peptide_Kd_scalar(Kd=expt["Kd"], Mt=expt["prot_conc"], Xt=expt["probe_conc"]) peps_in_df = np.unique(df.peptide) for p in peps_in_df: for pattern in pep_patterns: if pattern.match(p): pep_df = df[df.peptide == p] plates = np.unique(pep_df.plate) protein = expt["protein"] peptide = pattern.pattern for plate in plates: times_pep_was_seen[protein][peptide] += 1 single_rep = pep_df[pep_df.plate == plate] fit_df = average_tech_reps(single_rep,remove_outlier=remove_outlier) fit_df["protein"] = protein fit_df["peptide"] = peptide fit_df["rep_number"] = times_pep_was_seen[protein][peptide] fit_df["Kd_scalar"] = peptide_Kd_scalar fit_df["plate_file"] = expt["plate_file"] fit_df["data_file"] = expt["data_file"] fit_df["name_in_file"] = expt["name_in_file"] fit_df["plate_number"] = plate all_df.append(fit_df) break return pd.concat(all_df)
7,035
def get_lines(clearance): """ Add lines per reference well interval between the closest points on the reference well and the offset well and color them according to the calculated Separation Factor (SF) between the two wells at these points. Parameters ---------- clearance: welleng.clearance object Returns ------- lines: vedo.Lines object A vedo.Lines object colored by the object's SF values. """ assert VEDO, "ImportError: try pip install welleng[easy]" c = clearance.SF start_points, end_points = clearance.get_lines() lines = Lines(start_points, end_points).cmap('hot_r', c, on='cells') lines.addScalarBar(title='SF') return lines
7,036
def generate_md5_hash(filepath): """Returns md5 hash of file. Args: filepath: str. Absolute path to the file. Returns: str. Hexadecimal hash of specified file. """ m = hashlib.md5() with python_utils.open_file(filepath, 'rb', encoding=None) as f: while True: buf = f.read(HASH_BLOCK_SIZE) if not buf: break m.update(buf) return m.hexdigest()
7,037
def app(): """Provide the initialized Flask app.""" init_app(app_, None) with app_.app_context(): yield app_
7,038
def status(): """Return status.""" return jsonify(STATUS)
7,039
def get_entitlement(account_id: Optional[str] = None, customer_id: Optional[str] = None, entitlement_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEntitlementResult: """ Returns the requested Entitlement resource. Possible error codes: * PERMISSION_DENIED: The customer doesn't belong to the reseller. * INVALID_ARGUMENT: Required request parameters are missing or invalid. * NOT_FOUND: The customer entitlement was not found. Return value: The requested Entitlement resource. """ __args__ = dict() __args__['accountId'] = account_id __args__['customerId'] = customer_id __args__['entitlementId'] = entitlement_id if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('google-native:cloudchannel/v1:getEntitlement', __args__, opts=opts, typ=GetEntitlementResult).value return AwaitableGetEntitlementResult( association_info=__ret__.association_info, commitment_settings=__ret__.commitment_settings, create_time=__ret__.create_time, name=__ret__.name, offer=__ret__.offer, parameters=__ret__.parameters, provisioned_service=__ret__.provisioned_service, provisioning_state=__ret__.provisioning_state, purchase_order_id=__ret__.purchase_order_id, suspension_reasons=__ret__.suspension_reasons, trial_settings=__ret__.trial_settings, update_time=__ret__.update_time)
7,040
def test_mitpe_extract(settings, base_url): """Verify that BeautifulSoup tags are returned per listing and course detail""" settings.MITPE_BASE_URL = base_url results = extract() assert len(results) == (1 if base_url else 0) assert results == ( [ { "url": "https://professional.mit.edu/course-catalog/mitpe-course-detail", "title": title, "dates": [ ( datetime.datetime(2020, 7, 13, 12, 0, tzinfo=pytz.utc), datetime.datetime(2020, 7, 17, 12, 0, tzinfo=pytz.utc), ) ], "price": Decimal("5500"), "topics": ["Innovation", "Systems Engineering"], "short_description": short_description, "full_description": full_description, "instructors": [["Marcus", "Aurelius I"]], } ] if base_url else [] )
7,041
def skip_to_home(fxn): """ Skips past page straight to home page if logged in """ @wraps(fxn) def skipped_page_fxn(*arg, **kwargs): if session.get('logged_in'): return redirect(url_for('home')) else: return fxn(*arg, **kwargs) return skipped_page_fxn
7,042
def compute(infile, cmpdfile='compounds.txt', rxnfile='reactions.txt', sinkfile='sinks.txt', reverse=False): """Convert the output from the RetroPath2.0 workflow.""" # Get content content = dict() with open(infile, 'r') as fh: reader = csv.DictReader(fh) for row in reader: # Skip if we are in a "header" if row['Initial source'] == 'Initial source': continue # Regroup by transformation ID tid = row['Transformation ID'] if tid not in content.keys(): content[tid] = [row] else: content[tid].append(row) # 1) Check consistency and 2) Populate compounds all_cmpds = dict() for tid in sorted(content.keys()): # Order determine CMPD IDs first = True for row in content[tid]: # .. if first: first = False # Parse the Reaction SMILES tmp = row['Reaction SMILES'].split('>>') subs_from_rxn = set(tmp[0].split('.')) prods_from_rxn = set(tmp[1].split('.')) # Prep for parsing Substrate and Product columns subs_from_cmpd = set() prods_from_cmpd = set() # Accumulate compounds from Substrate and Product columns subs_from_cmpd.add(row['Substrate SMILES']) prods_from_cmpd.add(row['Product SMILES']) # Double check that each SMILES substrate/product is also present # in the description of the reaction try: assert subs_from_rxn == subs_from_cmpd except AssertionError: print('Assertion error: differences in substrates') print(tid) print(subs_from_rxn, subs_from_cmpd) sys.exit(0) try: assert prods_from_rxn == prods_from_cmpd except BaseException: print('Assertion error: differences in products') print(tid) print(prods_from_rxn, prods_from_cmpd) sys.exit(0) # Populate for smi in sorted(list(subs_from_rxn | prods_from_rxn)): if smi not in all_cmpds.keys(): cmpd = Compound(smi) all_cmpds[smi] = cmpd # Populate transformations all_trs = dict() for tid in content.keys(): first = True for row in content[tid]: if first: first = False trs = Transformation(row) all_trs[tid] = trs # Update Sink information for tid in content.keys(): for row in content[tid]: if row['In Sink'] == '1': cids = row['Sink name'].lstrip('[').rstrip(']').split(', ') smi = row['Product SMILES'] for cid in cids: all_cmpds[smi].AddCid(cid) all_cmpds[smi].SetIsSink(True) # Make accessible compounds information from Transformation objects Transformation.SetAllCompounds(compounds=all_cmpds) # Retrieve target compounds (substrate appearing in first iteration) # then set a specific compound IDs target_ids_handler = IDsHandler(length=10, prefix='TARGET') target_visited = set() for tid, trs in all_trs.items(): if trs.iteration == '0': for target_smi in trs.left.keys(): if target_smi not in target_visited: target_visited.add(target_smi) new_uid = target_ids_handler.MakeNewID() all_cmpds[target_smi].SetUid(new_uid) # Write the compounds file with open(cmpdfile, 'w', newline='') as fh: header = ['Compound ID', 'Structure'] writer = csv.DictWriter(fh, fieldnames=header, delimiter='\t', quoting=csv.QUOTE_NONE) writer.writeheader() for cmpd in sorted(all_cmpds.values(), key=lambda x: x.GetCids()): for cid in cmpd.GetCids(): towrite = {'Compound ID': cid, 'Structure': cmpd.GetSmiles()} writer.writerow(towrite) # fh.write(cid + '\t' + cmpd.GetSmiles() + '\n') # Write the sink file with open(sinkfile, 'w') as fh: for cmpd in sorted(all_cmpds.values(), key=lambda x: x.GetCids()): if cmpd.IsSink(): for cid in cmpd.GetCids(): fh.write(cid + '\n') # Write the reactions file with open(rxnfile, 'w') as fh: for trs in sorted(all_trs.values(), key=lambda x: x.trs_id): fh.write(trs.ToStr(reverse=reverse) + '\n')
7,043
def get_all_paths_from_directory(directory: Path, recursive: bool, paths: [str] = [], ) -> [Path]: """ Gets a list of file paths for all files in the given directory (and its subdirectories if recursive is true) :param directory: The starting directory to get file paths from :param recursive: Whether files in subdirectories should be included :param paths: The list that file paths will be added to :return: A list of file paths from the given directory (and subdirectories if recursive is true) """ directories = [] for file in directory.iterdir(): # If the file is a subdirectory and we are processing subdirectories, add it to the list for later processing if file.is_dir(): if recursive: directories.append(file) else: # If the file is just a normal file then add it to the paths list paths.append(file) # If we are processing subdirectories then go through all the subdirectories and process them if recursive: for file in directories: get_all_paths_from_directory(file, recursive, paths) return paths
7,044
def check_contigs_for_dupes(matches): """check for contigs that match more than 1 UCE locus""" node_dupes = defaultdict(list) for node in matches: node_dupes[node] = len(set(matches[node])) dupe_set = set([node for node in node_dupes if node_dupes[node] > 1]) return dupe_set
7,045
def substitute(P, x0, x1, V=0): """ Substitute a variable in a polynomial array. Args: P (Poly) : Input data. x0 (Poly, int) : The variable to substitute. Indicated with either unit variable, e.g. `x`, `y`, `z`, etc. or through an integer matching the unit variables dimension, e.g. `x==0`, `y==1`, `z==2`, etc. x1 (Poly) : Simple polynomial to substitute `x0` in `P`. If `x1` is an polynomial array, an error will be raised. Returns: (Poly) : The resulting polynomial (array) where `x0` is replaced with `x1`. Examples: >>> x,y = cp.variable(2) >>> P = cp.Poly([y*y-1, y*x]) >>> print(cp.substitute(P, y, x+1)) [q0^2+2q0, q0^2+q0] With multiple substitutions: >>> print(cp.substitute(P, [x,y], [y,x])) [q0^2-1, q0q1] """ x0,x1 = map(Poly, [x0,x1]) dim = np.max([p.dim for p in [P,x0,x1]]) dtype = chaospy.poly.typing.dtyping(P.dtype, x0.dtype, x1.dtype) P, x0, x1 = [chaospy.poly.dimension.setdim(p, dim) for p in [P,x0,x1]] if x0.shape: x0 = [x for x in x0] else: x0 = [x0] if x1.shape: x1 = [x for x in x1] else: x1 = [x1] # Check if substitution is needed. valid = False C = [x.keys[0].index(1) for x in x0] for key in P.keys: if np.any([key[c] for c in C]): valid = True break if not valid: return P dims = [tuple(np.array(x.keys[0])!=0).index(True) for x in x0] dec = is_decomposed(P) if not dec: P = decompose(P) P = chaospy.poly.dimension.dimsplit(P) shape = P.shape P = [p for p in chaospy.poly.shaping.flatten(P)] for i in range(len(P)): for j in range(len(dims)): if P[i].keys and P[i].keys[0][dims[j]]: P[i] = x1[j].__pow__(P[i].keys[0][dims[j]]) break P = Poly(P, dim, None, dtype) P = chaospy.poly.shaping.reshape(P, shape) P = chaospy.poly.collection.prod(P, 0) if not dec: P = chaospy.poly.collection.sum(P, 0) return P
7,046
def munkres(costs): """ Entry method to solve the assignment problem. costs: list of non-infinite values entries of the cost matrix [(i,j,value)...] """ solver = Munkres(costs) return solver.munkres()
7,047
def train(fold=C.TRAIN.SAMPLES.CURRENT_FOLD): """Do the main training loop, as described in the config. """ warnings.filterwarnings('always') training_data = RgbLidarDataset('train', fold=fold) eval_data = RgbLidarDataset('test', fold=fold) train_sampler = make_stratified_sampler(training_data, C.TRAIN.CLASS_BALANCE) eval_sampler = make_stratified_sampler(eval_data, C.TRAIN.CLASS_BALANCE) trn_loader = torch.utils.data.DataLoader(training_data, batch_size=C.TRAIN.BATCH_SIZE, sampler=train_sampler) val_loader = torch.utils.data.DataLoader(eval_data, batch_size=C.TRAIN.BATCH_SIZE, sampler=eval_sampler) torch.set_default_tensor_type('torch.cuda.FloatTensor') net = Architecture(shape=(C.TRAIN.PATCH_SIZE, C.TRAIN.PATCH_SIZE), lidar_channels=C.VOLUME.Z.STEPS, rgb_channels=3, num_features=C.TRAIN.NUM_FEATURES) solver = Solver(trn_loader, val_loader, net=net) solver.train() eval_data = [(h.epoch, h.trn_loss, h.val_loss, h.f_measure, h.accuracy, h.precision, h.recall, h.f1, h.iou, h.l1, h.l2) for h in solver.history] columns = ['epoch', 'trn_loss', 'val_loss', 'f_2', 'accuracy', 'precision', 'recall', 'f_1', 'iou', 'L_1', 'L_2'] pd.DataFrame(np.array(eval_data), columns=columns).to_csv('history_fold{}.csv'.format(fold))
7,048
def compute_mean_std(dataset): """ https://stats.stackexchange.com/questions/25848/how-to-sum-a-standard-deviation """ # global_mean = np.zeros((3 * 64), dtype=np.float64) # global_var = np.zeros((3 * 64), dtype=np.float64) n_items = 0 s = RunningStatistics() for image_fname in dataset: dct_file = np.load(fs.change_extension(image_fname, ".npz")) y = torch.from_numpy(dct_file["dct_y"]) cb = torch.from_numpy(dct_file["dct_cb"]) cr = torch.from_numpy(dct_file["dct_cr"]) dct = torch.stack([y, cb, cr], dim=0).unsqueeze(0).float() dct = sd2(dct)[0] s.update(dct) # dct = to_numpy() # global_mean += dct.mean(axis=(1, 2)) # global_var += dct.std(axis=(1, 2)) ** 2 # n_items += 1 return s.mean, s.std
7,049
def test_clean_connections_p0(monkeypatch): """Add a connection, fake a closed thread and make sure it is removed.""" db_disconnect_all() class mock_connection(): def __init__(self) -> None: self.value = _MOCK_VALUE_1 def close(self): self.value = None def mock_connect(*args, **kwargs): return mock_connection() monkeypatch.setattr(database, 'connect', mock_connect) db_connect(_MOCK_DBNAME, _MOCK_CONFIG) monkeypatch.setitem(database._connections, _MOCK_CONFIG['host'], {_MOCK_DBNAME: {1234: None}}) _clean_connections() assert database._connections[_MOCK_CONFIG['host']][_MOCK_DBNAME].get(1234, None) is None
7,050
def linkrref(rref:RRef, subdirs:List[str]=[], verbose:bool=False)->None: """ Create a 'result-' symlink under the Pylightnix experiments folder """ linkrrefs([rref], subdirs, verbose)
7,051
def add(request): """ Add contact information. **Templates:** * ``rolodex/add.html`` **Template Variables:** * form * results: the list of similar names to allow user to check for dupes * name: the new name that is submitted """ results = [] name = None if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): request.session['post_data'] = request.POST # search to see if contact already exists name = form.cleaned_data['name'] results = Alias.objects.filter(name=name) if not results: return HttpResponseRedirect('../add-proceed/') else: form = NameForm() return render_to_response('rolodex/add.html', { 'form': form, 'results': results, 'name': name}, RequestContext(request, {}), )
7,052
def convert_total (letter1,number1, letter2, number2): """ Description ----------- Converting the letter of a column and the number of a line from an exceldata to a range Context ---------- is called in wrapp_ProcessUnits and wrapp_SystemData Parameters ---------- letter1 : String, "A", "B" etc. number1 : Integer letter2 : String, "A", "B" etc. number2 : Integer Returns ------- None. """ Range = range (convert_numbers(number1), convert_numbers(number2)+1), range(convert_letters(letter1)-1, convert_letters(letter2)) return(Range)
7,053
def scale_facet_list(facet_list, scale): """ Scale list of facets by the given scaling factor """ new_facet_list = [] for facet in facet_list: new_facet_list.append(scale_facet(facet, scale)) return new_facet_list
7,054
def assert_mask_equal(m1, m2, err_msg=''): """ Asserts the equality of two masks. """ if m1 is nomask: assert_(m2 is nomask) if m2 is nomask: assert_(m1 is nomask) assert_array_equal(m1, m2, err_msg=err_msg)
7,055
def options(): """ Prints the options for the player to choose: to Play or Quit game """ options_font_size = 50 options_font = pygame.font.SysFont('impact', options_font_size) options_pos = [(100,500),(570,500)] play_text = options_font.render("Play", True, black) quit_text = options_font.render("Quit", True, black) window.blit(play_text, options_pos[0]) window.blit(quit_text, options_pos[1])
7,056
def move_lines_to_index(uwline_index_to, lineno, uwlines, lines): """Method moves all lines in the list to the proper index of uwlines and update lineno on these lines. This is useful when you want to change the order of code lines. But note: it is not updating lineno on other lines @:returns positions (indexes) from original source where lines are taken from """ # saving positions of imports here, that will be used for restoring 'lineno' lineno_where_line_was_taken_from = list() for line in lines: lineno_where_line_was_taken_from.append(line.lineno) for token in line.tokens: # here we will restore correct lineno for moved lines token.node.lineno = lineno # hack to remove newlines between imports that we moved to top pytree_utils.SetNodeAnnotation(token.node, pytree_utils.Annotation.NEWLINES, 0) lineno += get_lineno_delta(token) # need to update lineno on import lines to have consistency lineno += 1 # filtering moved values and removing them from uwlines uwlines[:] = [line for line in uwlines if line not in lines] uwlines[uwline_index_to:uwline_index_to] = lines return lineno_where_line_was_taken_from
7,057
def birch(V, E0, B0, BP, V0): """ From Intermetallic compounds: Principles and Practice, Vol. I: Principles Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos paper downloaded from Web case where n=0 """ E = (E0 + 9.0/8.0*B0*V0*((V0/V)**(2.0/3.0) - 1.0)**2 + 9.0/16.0*B0*V0*(BP-4.)*((V0/V)**(2.0/3.0) - 1.0)**3) return E
7,058
def test_zarr_dask_nD(make_napari_viewer): """Test adding nD zarr image.""" viewer = make_napari_viewer() data = zarr.zeros((200, 100, 50), chunks=(40, 20, 10)) data[53:63, 10:20, :] = 1 zdata = da.from_zarr(data) viewer.add_image(zdata) assert np.all(viewer.layers[0].data == zdata)
7,059
def debloat(edges: set, nodes: int, threshold: tuple = (0.95, 0.95)) -> Set[Tuple[str, str]]: """Remove nodes with inflow and/or ourflow > threshold""" df = pd.DataFrame(list(edges), columns=["source", "target"]) checkpoint_shape = df.shape[0] df_inflow = df.groupby("target").count().reset_index().rename(columns={"source": "inflow"}) df_outflow = df.groupby("source").count().reset_index().rename(columns={"target": "outflow"}) df = df.merge(df_inflow, on="target", how="left") df = df.merge(df_outflow, on="source", how="left") df["inflow_ratio"] = df["inflow"] / nodes df["outflow_ratio"] = df["outflow"] / nodes df = df[(df["inflow_ratio"] <= threshold[0]) & (df["outflow_ratio"] <= threshold[1])] print(f"{checkpoint_shape - df.shape[0]} edges removed") df.drop(["outflow", "inflow", "outflow_ratio", "inflow_ratio"], axis=1, inplace=True) return set(tuple(i) for i in df.values.tolist())
7,060
def result(jid): """ Displays a job result. Args: jid (str): The job id. """ job = q.fetch_job(jid) statuses = { 'queued': 202, 'started': 202, 'finished': 200, 'failed': 500, 'job not found': 404, } if job: job_status = job.get_status() result = job.result else: job_status = 'job not found' result = None resp = { 'status': statuses[job_status], 'job_id': jid, 'job_status': job_status, 'result': result} return jsonify(**resp)
7,061
def install_(ca_path, password, ca_url): """Create a ca workspace.""" install(ca_path, ca_url, password)
7,062
def fd_nabla_1( x: np.ndarray, fun: Callable, delta_vec: np.ndarray, ) -> np.ndarray: """Calculate FD approximation to 1st order derivative (Jacobian/gradient). Parameters ---------- x: Parameter vector, shape (n_par,). fun: Function returning function values. Scalar- or vector-valued. delta_vec: Step size vector, shape (n_par,). Returns ------- nabla_1: The FD approximation to the 1st order derivatives. Shape (n_par, ...) with ndim > 1 if `f_fval` is not scalar-valued. """ # parameter dimension n_par = len(x) nabla_1 = [] for ix in range(n_par): delta_val = delta_vec[ix] delta = delta_val * unit_vec(dim=n_par, ix=ix) fp = fun(x + delta / 2) fm = fun(x - delta / 2) nabla_1.append((fp - fm) / delta_val) return np.array(nabla_1)
7,063
def test_api_export_spacy_model(temp_folder: Path) -> None: """spaCy model loading is one of the things we need to support""" use_fs(temp_folder) bucket = Pathy("gs://my-bucket/") bucket.mkdir(exist_ok=True) model = spacy.blank("en") output_path = Pathy("gs://my-bucket/models/my_model") model.to_disk(output_path) sorted_entries = sorted([str(p) for p in output_path.glob("*")]) expected_entries = [ "gs://my-bucket/models/my_model/meta.json", "gs://my-bucket/models/my_model/tokenizer", "gs://my-bucket/models/my_model/vocab", ] assert sorted_entries == expected_entries
7,064
def init(options, configuration, plugin): """ initializes the plugin """ plugin.log("spiderpay.py initializing") # maps destination to list of paths each of which has some score # window corresponding to its max capacity and how much we use it plugin.routes_in_use = {} # per-destination queue at the sender of payments to be sent plugin.queue = {} # maps the payments already sent out to the route index that they were # sent on plugin.payment_hash_to_route = {} # maps the payments already sent out to their requests to set result # eventually plugin.payment_hash_to_request = {} # window decrease and increase factors plugin.beta = 1 plugin.alpha = 10
7,065
def get_ref_len_from_bam(bam_path, target_contig): """ Fetch the length of a given reference sequence from a :py:class:`pysam.AlignmentFile`. Parameters ---------- bam_path : str Path to the BAM alignment target_contig : str The name of the contig for which to recover haplotypes. Returns ------- end_pos : int The 1-indexed genomic position at which to stop considering variants. """ bam = pysam.AlignmentFile(bam_path) end = bam.lengths[bam.get_tid(target_contig)] bam.close() return end
7,066
def matches_geometry(block, coords, tolerances): """ Given the interactions of a block and some coordinates, verify that the coordinates match the geometry as defined in the block interactions within accpatable deviations. """ for bond in itertools.chain(block.interactions["bonds"], block.interactions["constraints"]): ref = float(bond.parameters[1]) dist = np.linalg.norm(coords[bond.atoms[0]] - coords[bond.atoms[1]]) assert np.isclose(dist, ref, atol=tolerances['bonds']) for inter in block.interactions["angles"]: ref = float(inter.parameters[1]) ang = angle(coords[inter.atoms[0]], coords[inter.atoms[1]], coords[inter.atoms[2]]) print(ref, ang) assert np.isclose(ang, ref, atol=tolerances['angles']) # only improper dihedrals for inter in block.interactions["dihedrals"]: if inter.parameters[0] == "2": ref = float(inter.parameters[1]) ang = dih(coords[inter.atoms[0]], coords[inter.atoms[1]], coords[inter.atoms[2]], coords[inter.atoms[3]]) assert np.isclose(ang, ref, atol=tolerances["dihedrals"]) for virtual_site in block.interactions["virtual_sitesn"]: ref_coord = construct_vs("virtual_sitesn", virtual_site, coords) vs_coords = coords[virtual_site.atoms[0]] assert np.allclose(ref_coord, vs_coords)
7,067
def vstd(df, n=10): """ 成交量标准差 vstd(10) VSTD=STD(Volume,N)=[∑(Volume-MA(Volume,N))^2/N]^0.5 """ _vstd = pd.DataFrame() _vstd['date'] = df.date _vstd['vstd'] = df.volume.rolling(n).std(ddof=1) return _vstd
7,068
def createMonatomicGas(elm, pascal): """createMonatomicGas(elm, pascal) Create a gas of single atoms of the specified element at the specified pressure in Pascal and 300 K""" return epq.Gas((elm,), (1,), pascal, 300.0, elm.toString() + " gas at %f Pa" % pascal)
7,069
def _create_campaign_feed( client, customer_id, campaign_id, feed_mapping, feed_resource_name, chain_id ): """Creates the campaign feed. Args: client: The Google Ads API client. customer_id: The Google Ads customer ID. campaign_id: The campaign ID to which the affiliate location extensions will be added. feed_mapping: The affliate location extension feedmapping for the feed resource name. feed_resource_name: The feed resource name. chain_id: The retail chain ID. """ # Get the CampaignFeedService. campaign_feed_service = client.get_service("CampaignFeedService") feed_service = client.get_service("FeedService") attribute_id_for_chain_id = _get_attribute_id_for_chain_id( client, feed_mapping ) feed_id = feed_service.parse_feed_path(feed_resource_name)["feed_id"] matching_function = ( f"IN(FeedAttribute[{feed_id}, {attribute_id_for_chain_id}], {chain_id})" ) # Add a CampaignFeed that associates the feed with this campaign for # the AFFILIATE_LOCATION placeholder type. campaign_feed_operation = client.get_type("CampaignFeedOperation") campaign_feed = campaign_feed_operation.create campaign_feed.feed = feed_resource_name campaign_feed.placeholder_types.append( client.enums.PlaceholderTypeEnum.AFFILIATE_LOCATION ) campaign_feed.matching_function.function_string = matching_function campaign_feed.campaign = client.get_service( "CampaignService" ).campaign_path(customer_id, campaign_id) mutate_campaign_feeds_response = campaign_feed_service.mutate_campaign_feeds( customer_id=customer_id, operations=[campaign_feed_operation] ) # Display the result. print( "Campaign feed created with resource name: " f"{mutate_campaign_feeds_response.results[0].resource_name}." ) # [END add_affiliate_location_extensions_3]
7,070
def boxes_to_central_line_torch(boxes): """See boxes_to_central_line Args: boxes (tensor[..., 7]): (x, y, z, l, w, h, theta) of each box Returns: boxes_lp (tensor[..., 3]): (a, b, c) line parameters of each box """ # in case length is shorter than width bmask = boxes[..., 3] < boxes[..., 4] theta = -boxes[..., 6] # not sure why minus is needed theta[bmask] -= 0.5 * np.pi a = torch.tan(theta) b = -torch.ones_like(a) c = -a * boxes[..., 0] - b * boxes[..., 1] boxes_lp = torch.stack((a, b, c), dim=-1) boxes_lp /= torch.linalg.norm(boxes_lp, dim=-1, keepdim=True) return boxes_lp
7,071
def load_as_spark(url: str) -> "PySparkDataFrame": # noqa: F821 """ Load the shared table using the give url as a Spark DataFrame. `PySpark` must be installed, and the application must be a PySpark application with the Apache Spark Connector for Delta Sharing installed. :param url: a url under the format "<profile>#<share>.<schema>.<table>" :return: A Spark DataFrame representing the shared table. """ try: from pyspark.sql import SparkSession except ImportError: raise ImportError("Unable to import pyspark. `load_as_spark` requires PySpark.") spark = SparkSession.getActiveSession() assert spark is not None, ( "No active SparkSession was found. " "`load_as_spark` requires running in a PySpark application." ) return spark.read.format("deltaSharing").load(url)
7,072
def surface_plot_go(fields, is_note_book=False): """Plots 3D surface plot over given theta/phi range in Fields by calculating cartesian coordinate equivalent of spherical form.""" print("Processing SurfacePlot...") # Finds the phi & theta range phiSize = fields.shape[0] thetaSize = fields.shape[1] # Prepare arrays to hold the cartesian coordinate data. X = np.ones((phiSize, thetaSize)) Y = np.ones((phiSize, thetaSize)) Z = np.ones((phiSize, thetaSize)) for phi in range(phiSize): for theta in range(thetaSize): e = fields[phi][theta] xe, ye, ze = sph2cart1(e, math.radians(theta), math.radians(phi)) X[phi, theta] = xe Y[phi, theta] = ye Z[phi, theta] = ze surface = go.Surface(x=X, y=Y, z=Z) data = [surface] layout = go.Layout( title='Surface Plot of EH Plane', scene=dict( xaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), yaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ), zaxis=dict( gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', showbackground=True, backgroundcolor='rgb(230, 230,230)' ) ) ) fig = go.Figure(data=data, layout=layout) if is_note_book: iplot(fig) else: plotly.offline.plot(fig)
7,073
def calClassSpecificProbPanel(param, expVars, altAvMat, altChosen, obsAv): """ Function that calculates the class specific probabilities for each decision-maker in the dataset Parameters ---------- param : 1D numpy array of size nExpVars. Contains parameter values. expVars : 2D numpy array of size (nExpVars x (nRows)). Contains explanatory variables. altAvMat : sparse matrix of size (nRows x nObs). The (i, j)th element equals 1 if the alternative corresponding to the ith column in expVars is available to the decision-maker corresponding to the jth observation, and 0 otherwise. altChosen : sparse matrix of size (nRows x nObs). The (i, j)th element equals 1 if the alternative corresponding to the ith column in expVars was chosen by the decision-maker corresponding to the jth observation, and 0 otherwise. obsAv : sparse matrix of size (nObs x nInds). The (i, j)th element equals 1 if the ith observation in the dataset corresponds to the jth decision-maker, and 0 otherwise. Returns ------- np.exp(lPInd) : 2D numpy array of size 1 x nInds. Identifies the class specific probabilities for each individual in the dataset. """ v = np.dot(param[None, :], expVars) # v is 1 x nRows ev = np.exp(v) # ev is 1 x nRows ev[np.isinf(ev)] = 1e+20 # As precaution when exp(v) is too large for machine ev[ev < 1e-200] = 1e-200 # As precaution when exp(v) is too close to zero nev = ev * altAvMat # nev is 1 x nObs nnev = altAvMat * np.transpose(nev) # nnev is nRows x 1 p = np.divide(ev, np.transpose(nnev)) # p is 1 x nRows p[np.isinf(p)] = 1e-200 # When none of the alternatives are available pObs = p * altChosen # pObs is 1 x nObs lPObs = np.log(pObs) # lPObs is 1 x nObs lPInd = lPObs * obsAv # lPInd is 1 x nInds return np.exp(lPInd) # prob is 1 x nInds
7,074
def build_expression_tree(tokens): """Returns an ExpressionTree based upon by a tokenized expression.""" s = [] # we use Python list as stack for t in tokens: if t in '+-x*/': # t is an operator symbol s.append(t) # push the operator symbol on the stack elif t not in '()': # consider t to be a literal s.append(ExpressionTree(t)) # push trivial tree storing value elif t == ')' : # compose a new tree from three constituent parts right = s.pop() # right subtree as per LIFO op = s.pop() # operator symbol left = s.pop() # left subtree s.append(ExpressionTree(op, left, right)) # reconstruct tree and push it back on the stack # ignore the parenthesis return s.pop() # the last reconstructed tree
7,075
def unpack_blockchain(s: str) -> block.Blockchain: """Unapck blockchain from JSON string with b64 for bytes.""" blocks = json.loads(s) return [_unpack_block(block) for block in blocks]
7,076
def parse(options,full_path): """ Parse the data according to several regexes """ global p_entering_vip_block, p_exiting_vip_block, p_vip_next, p_vip_number, p_vip_set in_vip_block = False vip_list = [] vip_elem = {} order_keys = [] if (options.input_file != None): with open(options.input_file, mode=fd_read_options) as fd_input: for line in fd_input: line = line.strip() # We match a vip block if p_entering_vip_block.search(line): in_vip_block = True # We are in a vip block if in_vip_block: if p_vip_number.search(line): vip_number = p_vip_number.search(line).group('vip_number') vip_number = re.sub('["]', '', vip_number) vip_elem['id'] = vip_number if not('id' in order_keys): order_keys.append('id') # We match a setting if p_vip_set.search(line): vip_key = p_vip_set.search(line).group('vip_key') if not(vip_key in order_keys): order_keys.append(vip_key) vip_value = p_vip_set.search(line).group('vip_value').strip() vip_value = re.sub('["]', '', vip_value) vip_elem[vip_key] = vip_value # We are done with the current vip id if p_vip_next.search(line): vip_list.append(vip_elem) vip_elem = {} # We are exiting the vip block if p_exiting_vip_block.search(line): in_vip_block = False return (vip_list, order_keys) else: # for files in os.listdir(os.path.abspath(options.input_folder)): with open(full_path, mode=fd_read_options) as fd_input: for line in fd_input: line = line.strip() # We match a vip block if p_entering_vip_block.search(line): in_vip_block = True # We are in a vip block if in_vip_block: if p_vip_number.search(line): vip_number = p_vip_number.search(line).group('vip_number') vip_number = re.sub('["]', '', vip_number) vip_elem['id'] = vip_number if not('id' in order_keys): order_keys.append('id') # We match a setting if p_vip_set.search(line): vip_key = p_vip_set.search(line).group('vip_key') if not(vip_key in order_keys): order_keys.append(vip_key) vip_value = p_vip_set.search(line).group('vip_value').strip() vip_value = re.sub('["]', '', vip_value) vip_elem[vip_key] = vip_value # We are done with the current vip id if p_vip_next.search(line): vip_list.append(vip_elem) vip_elem = {} # We are exiting the vip block if p_exiting_vip_block.search(line): in_vip_block = False return (vip_list, order_keys)
7,077
def launch(**kwargs): """ Connects to PM320E and instantiates server :param kwargs: (dict) containing relevant kwargs :logger: instance of LogClient for logging purposes :port: (int) port number for the Cnt Monitor server """ try: settings = load_device_config('thorlabs_pm320e', kwargs['config'], logger=kwargs['logger'] ) except KeyError: kwargs['logger'].warn('No config file was provided') try: pm = Driver( logger=kwargs['logger'], gpib_address=settings['device_id'], ) # Handle error of wrong GPIB address by allowing user to select # NOTE: this will fail if used from the main script launcher, since script client # will automatically try to connect (even though server isn't launched) # # TLDR: if you want to use launch-control, please fill in GPIB variable with # the correct resource string except: kwargs['logger'].error('Please check GPIB address, could not connect') pm_service = Service() pm_service.assign_module(module=pm) pm_service.assign_logger(logger=kwargs['logger']) pm_server = GenericServer( service=pm_service, host=get_ip(), port=kwargs['port'] ) pm_server.start()
7,078
def update_wishlist_games(cur, table, wishlist_args, update_delay): """A function to update wishlist games. :param cur: database cursor object :type cur: Cursor :param table: name of table to work on :type table: str :param wishlist_args: list of wishlist games to add to database :type wishlist_args: list :param update_delay: the amount of time that must pass before updating :type update_delay: timedelta """ # Figure out which games need updating outdated_games = DB_Calls.wishlist_needs_updating(cur, table, update_delay) # Fetch deals for new and existing wishlist games if(wishlist_args or outdated_games): if(table == DB_Tables.PC_WISHLIST.value): _table = DB_Tables.PC_WISHLIST.value games_to_update, new_games = ( PC.get_wishlist_deals(cur, outdated_games+wishlist_args)) elif(table == DB_Tables.PS_WISHLIST.value): _table = DB_Tables.PS_WISHLIST.value games_to_update, new_games = ( PS.get_wishlist_deals(cur, outdated_games+wishlist_args)) if(new_games): DB_Calls.add_games(cur, _table, new_games, games_to_update) return True return False
7,079
def WrapSignal(signal): """Wrap a model signal with a corresponding frontend wrapper.""" if type(signal) is M.BitsSignal: return BitsFrontend(signal) elif type(signal) is M.ListSignal: return ListFrontend(signal) elif type(signal) is M.BundleSignal: return BundleFrontend(signal) else: assert False, f'Cannot wrap signal of type {type(signal)}'
7,080
def is_array_like(element: Any) -> bool: """Returns `True` if `element` is a JAX array, a NumPy array, or a Python `float`/`complex`/`bool`/`int`. """ return isinstance( element, (jnp.ndarray, np.ndarray, float, complex, bool, int) ) or hasattr(element, "__jax_array__")
7,081
def parse(javascript_code): """Returns syntax tree of javascript_code. Syntax tree has the same structure as syntax tree produced by esprima.js Same as PyJsParser().parse For your convenience :) """ p = PyJsParser() return p.parse(javascript_code)
7,082
def twitterAuth(): """ Authenticate user using Twitter API generated credentials """ auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_KEY, ACCESS_SECRET) return tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)
7,083
def GetInstalledPackageUseFlags(pkg_str, board=None): """Gets the list of USE flags for installed packages matching |pkg_str|. Args: pkg_str: The package name with optional category, version, and slot. board: The board to inspect. Returns: A dictionary with the key being a package CP and the value being the list of USE flags for that package. """ cmd = ['qlist'] if board: cmd = ['qlist-%s' % board] cmd += ['-CqU', pkg_str] result = cros_build_lib.RunCommand( cmd, enter_chroot=True, capture_output=True, error_code_ok=True) use_flags = {} if result.returncode == 0: for line in result.output.splitlines(): tokens = line.split() use_flags[tokens[0]] = tokens[1:] return use_flags
7,084
async def test_clear_snapshots(coresys: CoreSys, tmp_path): """Test snapshot cleanup.""" for slug in ["sn1", "sn2", "sn3", "sn4", "sn5"]: temp_tar = Path(tmp_path, f"{slug}.tar") with SecureTarFile(temp_tar, "w"): pass snapshot = Snapshot(coresys, temp_tar) snapshot._data = { # pylint: disable=protected-access ATTR_SLUG: slug, ATTR_DATE: utcnow().isoformat(), ATTR_TYPE: SNAPSHOT_PARTIAL if "1" in slug or "5" in slug else SNAPSHOT_FULL, } coresys.snapshots.snapshots_obj[snapshot.slug] = snapshot newest_full_snapshot = coresys.snapshots.snapshots_obj["sn4"] assert newest_full_snapshot in coresys.snapshots.list_snapshots assert ( len( [x for x in coresys.snapshots.list_snapshots if x.sys_type == SNAPSHOT_FULL] ) == 3 ) coresys.resolution.storage.clean_full_snapshots() assert newest_full_snapshot in coresys.snapshots.list_snapshots assert ( len( [x for x in coresys.snapshots.list_snapshots if x.sys_type == SNAPSHOT_FULL] ) == 1 )
7,085
def test_scorekeeper_retrieve_by_slug(scorekeeper_slug: str): """Testing for :py:meth:`wwdtm.scorekeeper.Scorekeeper.retrieve_by_slug` :param scorekeeper_slug: Scorekeeper slug string to test retrieving scorekeeper information """ scorekeeper = Scorekeeper(connect_dict=get_connect_dict()) info = scorekeeper.retrieve_by_slug(scorekeeper_slug) assert info, f"Scorekeeper slug {scorekeeper_slug} not found" assert "name" in info, f"'name' was not returned for slug {scorekeeper_slug}"
7,086
def make_cursor(): """ Creates a cursor for iterating through results GetParams: account: an account user: a user handle: a shark client handle Returns: a json object container the cursor handle """ data, statusCode = cursor() return jsonify(data), statusCode
7,087
def run_result_factory(data: list[tuple[Any, Any]]): """ We need to handle dt.datetime and agate.table.Table. The rest of the types should already be JSON-serializable. """ d = {} for key, val in data: if isinstance(val, dt.datetime): val = val.isoformat() elif isinstance(val, agate.table.Table): # agate Tables have a few print methods but they offer plain # text representations of the table which are not very JSON # friendly. There is a to_json method, but I don't think # sending the whole table in an XCOM is a good idea either. val = { k: v.__class__.__name__ for k, v in zip(val._column_names, val._column_types) } d[key] = val return d
7,088
def compute_steepness(zeroth_moment, peak_wavenumber): """Compute characteristic steepness from given peak wave number.""" return np.sqrt(2 * zeroth_moment) * peak_wavenumber
7,089
def test_getting_monthly_annual_temp_values(): """ Test that prior_months and prior_year values are correct Values were hand-verified using panoply tables""" ct = AlaskaTemperature() ct.initialize_from_config_file() # Test prior months values # These are values starting from 2/1901 # actualvalues = [-28.700001, -24.799999, -16.600000, -2.700000, # 7.800000, 11.000000, 7.100000, -0.300000, # -13.400000, -22.100000, -26.500000, -25.700001] # actualmean = -11.241668 # These values start with 1/1902 actualvalues = [ -25.7, -27.0, -26.6, -16.9, -2.8, 8.1, 11.4, 7.3, -0.3, -13.6, -22.1, -28.9, ] actualmean = -11.425 vallist = [] for i in np.arange(0, 12): vallist.append(ct.T_air_prior_months[i][0, 0]) for i in np.arange(0, 12): assert vallist[i] == pytest.approx(actualvalues[i]) # Test prior year value assert ct.T_air_prior_year[0, 0] == pytest.approx(actualmean)
7,090
def secondary_side_radius(mass_ratio, surface_potential): """ Side radius of secondary component :param mass_ratio: float; :param surface_potential: float; :return: float; side radius """ return calculate_side_radius(1.0, mass_ratio, 1.0, surface_potential, 'secondary')
7,091
def pts_from_rect_inside(r): """ returns start_pt, end_pt where end_pt is _inside_ the rectangle """ return (r[0], r[1]), ((r[0] + r[2] - 1), (r[1] + r[3] - 1))
7,092
def minimum_distance(object_1, object_2): """ Takes two lists as input A list of numpy arrays of coordinates that make up object 1 and object 2 Measures the distances between each of the coordinates Returns the minimum distance between the two objects, as calculated using a vector norm Stops the calculation and returns 0 if two coordinates overlap """ # package import import numpy as np # main algorithm minimum_distance = 100000 for coord_1 in object_1: for coord_2 in object_2: distance_btwn_coords = np.linalg.norm(coord_1 - coord_2) if distance_btwn_coords == 0: minimum_distance = distance_btwn_coords return float(minimum_distance) elif distance_btwn_coords < minimum_distance: minimum_distance = distance_btwn_coords return float(minimum_distance)
7,093
def _park_ship(board: MyBoard, ship: Ship): """ Send our ship to the nearest shipyard """ moves_left = board.moves_left shipyard_to_distance = _get_shipyard_to_distance(board, ship.position, board.me) shipyards = [s for s, d in shipyard_to_distance.items() if d <= moves_left] if not shipyards: # create new one, if there are enough halite if ( ship.halite > board.configuration.convert_cost and not board.is_danger_position(ship.position, ship) ): board.create_shipyard(ship) return shipyards = sorted(shipyards, key=lambda x: shipyard_to_distance[x]) for sy in shipyards: if _sent_ship_to_shipyard(board, ship, sy): return for sy in shipyards: if shipyard_to_distance[sy] < moves_left - 1: if _sent_ship_to_shipyard(board, ship, sy, can_wait=True): return for sy in shipyards: if _sent_ship_to_shipyard(board, ship, sy, allow_collision=True): return
7,094
def retrieve_pkl_file(filename, verbose = False): """ Retrieve and return contents of pkl file """ if verbose == True: start_time = timelib.time() print("\n * Retrieving %s file ..."%filename) data = pd.read_pickle(filename) if verbose == True: print("\n %s retrieved in %.1f seconds."%(filename, timelib.time() - start_time)) return data;
7,095
def extractIpsFile(containerFile,newSimName): """ Given a container file, get the ips file in it and write it to current directory so that it can be used """ oldIpsFile=os.path.splitext(containerFile)[0]+os.extsep+"ips" zf=zipfile.ZipFile(containerFile,"r") foundFile="" # Assume that container file contains 1 ips file. oldIpsFile=fnmatch.filter(zf.namelist(),"*.ips")[0] ifile=zf.read(oldIpsFile) ipsFile=newSimName+".ips" if os.path.exists(ipsFile): print "Moving "+ipsFile+" to "+"Save"+ipsFile shutil.copy(ipsFile, "Save"+ipsFile) ff=open(ipsFile,"w") ff.write(ifile) ff.close() return ipsFile
7,096
def nplr(measure, N, rank=1, dtype=torch.float): """ Return w, p, q, V, B such that (w - p q^*, B) is unitarily equivalent to the original HiPPO A, B by the matrix V i.e. A = V[w - p q^*]V^*, B = V B """ assert dtype == torch.float or torch.cfloat if measure == 'random': dtype = torch.cfloat if dtype == torch.float else torch.cdouble # w = torch.randn(N//2, dtype=dtype) w = -torch.exp(torch.randn(N//2)) + 1j*torch.randn(N//2) P = torch.randn(rank, N//2, dtype=dtype) B = torch.randn(N//2, dtype=dtype) V = torch.eye(N, dtype=dtype)[..., :N//2] # Only used in testing return w, P, B, V A, B = transition(measure, N) A = torch.as_tensor(A, dtype=dtype) # (N, N) B = torch.as_tensor(B, dtype=dtype)[:, 0] # (N,) P = rank_correction(measure, N, rank=rank, dtype=dtype) AP = A + torch.sum(P.unsqueeze(-2)*P.unsqueeze(-1), dim=-3) w, V = torch.linalg.eig(AP) # (..., N) (..., N, N) # V w V^{-1} = A # Only keep one of the conjugate pairs w = w[..., 0::2].contiguous() V = V[..., 0::2].contiguous() V_inv = V.conj().transpose(-1, -2) B = contract('ij, j -> i', V_inv, B.to(V)) # V^* B P = contract('ij, ...j -> ...i', V_inv, P.to(V)) # V^* P return w, P, B, V
7,097
def read_data(oldest_year: int = 2020, newest_year: int = 2022): """Read in csv files of yearly covid data from the nytimes and concatenate into a single pandas DataFrame. Args: oldest_year: first year of data to use newest_year: most recent year of data to use """ df_dicts = {} # dictionary to hold the data for each year before concatenation for year in range(oldest_year, newest_year + 1): df_dicts[f"df_{year}"] = pd.read_csv( f"https://raw.githubusercontent.com/nytimes/covid-19-data/master/rolling-averages/us-counties-{year}.csv", index_col="date", ) logger.info("data read in successfully") return pd.concat(df_dicts.values())
7,098
def ip_is_v4(ip: str) -> bool: """ Determines whether an IP address is IPv4 or not :param str ip: An IP address as a string, e.g. 192.168.1.1 :raises ValueError: When the given IP address ``ip`` is invalid :return bool: True if IPv6, False if not (i.e. probably IPv4) """ return type(ip_address(ip)) == IPv4Address
7,099