content
stringlengths
22
815k
id
int64
0
4.91M
def investigateTreesAndAlignments(d, srcSIndex, tgtSIndex): """ Return the parse trees and word alignments for this pair of source sentence and target sentence indices """ src = d.sentence(srcSIndex) tgt = d.highlight(tgtSIndex) # get matchList, and trim so it is only leaf nodes ma...
79,700
def build_faces(structure, template, vertex_list, target, fill_uncompleted='border'): """ Creates the faces :param structure: row[]: column[]; cell[]: vertex: int - inner mesh structure :param template: RFTemplate - template :param vertex_list: VertexData[] - created vertex :param target: RFTarg...
79,701
async def test_get_node_callq(ready_inventory): """Test the get function returning the dictionary allowing to send command query """ nodes = ready_inventory.nodes node_callq = ready_inventory.get_node_callq() # Check if all the nodes are in the node_callq assert len(node_callq) == len(nodes)...
79,702
def read(filename, include_fourcc=False): """Reads a LAB container and returns all stored files. :param filename: Path to the LAB to read :return: List of LAB entry tuples [(str, bytes), ..., ] where the tuple represents (name, data) of the entry """ # Utility function for reading null-terminated n...
79,703
def gf_sub_const(f, a, p): """Returns f - a where f in GF(p)[x] and a in GF(p). """ if not f: a = -a % p else: a = (f[-1] - a) % p if len(f) > 1: return f[:-1] + [a] if not a: return [] else: return [a]
79,704
def replace_jax_res_net_block_vars_to_tf( jax_initial_vars: NestedMap) -> NestedMap: """Replaces the JAX ResNetBlock vars to TF compatible vars. Args: jax_initial_vars: JAX ResNetBlock vars. Returns: tf_initial_vars which is TF compatible with ResNetBlock. """ tf_initial_vars = jax_initial_vars....
79,705
def install_transproteomic_pipeline(env): """ """ ## version should be of form X.X.X-codename default_version = "4.6.1-occupy" version = env.get("tool_version", default_version) version_parts = re.match("(\d\.\d)\.(\d)-(.*)", version) major_version = version_parts.group(1) revision = ver...
79,706
def edges( graph: BELGraph, *, examples: bool = True, minimum: Optional[int] = None, file: Optional[TextIO] = None, **kwargs, ) -> None: """Print a summary of the edges in the graph.""" print(edges_str(graph=graph, examples=examples, minimum=minimum, **kwargs), file=file)
79,707
def run(xconfig): """ Implements --ssonly mode """ global monjer, config config = xconfig # Check input filename if not config.run['infile']: failwith(ER.OPT_MISSING, "option infile required (-i/--infile)") else: if not os.path.exists(config.run['infile']): f...
79,708
def assemble_SHCNN_blocks(inputs, config, dropout_prob, hw, mw, lw, hw2, mw2, lw2, h2m, m2l): """ Definition of all the layers according to config :param inputs: dictionary of inputs with keys [points, neighbors, pools, upsamples, features, batches, labels] :param config: :param dropout_prob: :r...
79,709
def sample_with_temperature(logits, sampling_temp, keep_topk, keep_topp): """Select next tokens randomly from the top k possible next tokens. Samples from a categorical distribution over the ``keep_topk`` words using the category probabilities ``logits / sampling_temp``. Args: logits (FloatTen...
79,710
def get_mask_from_lengths(lengths): """Constructs binary mask from a 1D torch tensor of input lengths Args: lengths (torch.tensor): 1D tensor Returns: mask (torch.tensor): num_sequences x max_length x 1 binary tensor """ max_len = torch.max(lengths).item() ids = torch.arange(0, ...
79,711
def get_resp(url): """Get webpage response as an lxml.html.HtmlElement object.""" try: headers = {'User-Agent': random.choice(USER_AGENTS)} try: request = requests.get(url, headers=headers, proxies=get_proxies()) except MissingSchema: url = add_protocol(url) ...
79,712
def fixed_ro_bci_edge_small_angle(ascentlat, lat_fixed_ro_ann=None, burg_num=None, ross_num=None, delta_v=None, height=HEIGHT_TROPO, grav=GRAV_EARTH, rot_rate=ROT_RATE_EARTH, radius=RAD_EARTH): """Small-angle solut...
79,713
def veclength(vec): """Returns the length of the given vector(s). Multiple vectors may be passed in, with a shape of ``(n, 3)``. """ vec = np.array(vec, copy=False).reshape(-1, 3) return np.sqrt(np.einsum('ij,ij->i', vec, vec))
79,714
def get_guardian(day: date, holiday_list: List[List[date]]) -> str: """Get the guardian for a day, according to the holidays.""" if is_father_day(day): return "B" if is_mother_day(day): return "L" if day_is_holiday(day, holiday_list): return get_guardian_holidays(day, holiday_lis...
79,715
def check_gpu(): """ Log error and exit when set use_gpu=true in paddlepaddle cpu ver sion. """ logger = logging.getLogger(__name__) err = "Config use_gpu cannot be set as true while you are " \ "using paddlepaddle cpu version ! \nPlease try: \n" \ "\t1. Instal...
79,716
def add_two_polynomials(polynomial_1: list, polynomial_2: list) -> list: """ This function expects two `polynomials` and returns a `polynomial` that contains their `sum`. :param polynomial_1: First polynomial :param polynomial_2: Second polynomial :return: A polynomial representing the sum of t...
79,717
def timeout_timer(item, timeout): """Dump stack of threads and call os._exit() This disables the capturemanager and dumps stdout and stderr. Then the stacks are dumped and os._exit(1) is called. """ if SUPPRESS_TIMEOUT: return try: capman = item.config.pluginmanager.getplugin('c...
79,718
def mediane(x, y=None): """ Computes the median """ if (isinstance(x, np.ndarray)): x = torch.from_numpy(x) if (isinstance(y, np.ndarray)): y = torch.from_numpy(y) dxx = distances(x) if y == None: return dxx.median() dyy = distances(y) dxy = distances(x,...
79,719
def train_loop(model, epochs, loss_fn, train_dl, valid_dl, use_gpu=False, lr=0.01): """ Loop between training and validation cycles through n epochs :param model: pytorch model :param epochs: number of epochs :param loss_fn: loss function :param train_dl: pytorch dataloder on top of MatchDataset...
79,720
def update_values(player, state_history, winner=False): """ Updates values. """ player.values[state_history[-1]] = -1 if winner: player.values[state_history[-1]] = 1 for state in state_history: if state not in player.values: player.values[state] = 0 ...
79,721
def ListFilesAndDirs(store, pattern, callback): """List all subdirectories and files in a directory. Not recursive. Returns (subdirs, files).""" result = yield gen.Task(ListAllCommonPrefixes, store, '/', prefix=PrefixFromPattern(pattern)) callback(result)
79,722
def ajax_required(fn): """ Placed on a view, this decorator will raise :class:`django.http.Http404` if the incoming request is not an HTTP POST or if the header `HTTP_X_REQUESTED_WITH` is not set. """ @functools.wraps(fn) def wrapper(request, *args, **kwargs): if request.method != "...
79,723
def read_images(data_packs: List[matchzoo.DataPack], fat_pth_file: str, max_len_images: int, side, image_dim: int = 2048) -> Tuple[torch.Tensor, Dict, Dict]: """ - Prune the the maximum number of images per query or per doc based on `max_len_images` - Read tensors from the giant pth file. ...
79,724
def find_song(json_data, filename, source, lyrics, rename, info, link, art, artist_art, preview): """Actually do things with the data found.""" # How many errors errors = 0 # Fill song data song_data = SongData() # Get stuff from the rest of the sources, first source will be first in dictionary...
79,725
def mmd_gaussian(samples1, samples2, sigma=10.0): """ MMD constraint with Gaussian Kernel support matching in BEAR This code was stolen from: https://github.com/aviralkumar2907/BEAR/blob/master/algos.py sigma is set to 10.0 for hopper, cheetah and 20 for walker/ant """ # Batch x num_samples x n...
79,726
def import_fbx(path): """ imports the fbx from each lamp """ newpath = os.path.dirname(path) + '/' os.chdir(newpath) hou.hipFile.importFBX('scene.fbx')
79,727
def DefaultKeyWriter(key_name): """This key writer rewrites keys as lower camel case. Expects that the input is formed by '_' delimited words. Args: key_name: Name of the key to serialize. Returns: Key name in lower camel-cased form. """ return ToLowerCamelCase(key_name)
79,728
def test_sign_file_entitlements(dummy_command, tmp_path): """Entitlements can be included in a signing call.""" # Sign the file with an adhoc identity dummy_command.sign_file( tmp_path / "random.file", identity="Sekrit identity (DEADBEEF)", entitlements=tmp_path / "macOS" / "app" / "...
79,729
def get_server_info( chains: List[Chain], chain_names: List[str] ) -> List[Dict[str, Any]]: """ Get the server info for a set of chains. Args: chains: A list of the chains to search. chain_names: The names of the chains. Returns: The server info of the node(s) in the chain(...
79,730
def get_random_orthonormal_vector(base_vector: ParameterVector) -> ParameterVector: """Helper function to generate a random orthogonal vector with respect to a provided base vector.""" random_vector = np.random.normal(size=base_vector.shape) new_vector = ( random_vector - np.dot(random_v...
79,731
def PUtilVisCompare (in1UV, in2UV, err): """ Compares the visibilites in *in1UV* with those in *in2UV*. * return: RMS ( real, imaginary differences / amplitude of *inUV2* ) * in1UV = Numerator Python UV object. Possible infoList parameter printRat scalar float if given and >0.0 then tell a...
79,732
def plot_experiment_mean_and_std(values, ax, color_mapping=None): """ Plot the mean and std of n experiment with m steps. :param values: dict maping an agent name to An n x m numpy array describing the cumulative reward of n experiments of a single agent """ m = next(iter(values....
79,733
def execcmd(msg: bytes, listen: bool): """ 构建发送特定api方法,使用udp,默认地址 localhost、4038port 传参msg即为api指令,listen确定是否监听套接字返回值 """ myopt = opts("localhost", CORE_API_PORT, socket.SOCK_DGRAM) sock = socket.socket(socket.AF_INET, myopt.protocol) sock.setblocking(True) try: sock.connect((myop...
79,734
def detect_mandrel_edge(): """This function detects whether the the beginning or the end of pipe is in the frame""" ap = argparse.ArgumentParser() ap.add_argument("-f", "--frames", help="path to frames") args = vars(ap.parse_args()) frame_name = [] for (dirpath, dirnames, filenames) in walk(args...
79,735
def normalize(vec: DSList): """ Normalize the input vector. :param vec: DSList :return: DSList """ norm_ = norm(vec) return smul(1/norm_, vec)
79,736
def name_asm_file(module_path): """ A decorator to put on top of tests which create asm, obj, and exe files. Usually, you should pass `__file__` in as the module path. EX: @name_asm_file(__file__) def test_my_feature(): ... """ base_name = os.path.basename(os.path.spl...
79,737
def distro_name_errors(distro_name): """Returns a list of errors in the distro name. Empty list means distro name is valid.""" errors = [] if len(distro_name) == 0: errors.append( "distro name cannot be zero length") if distro_name.startswith(defaults['catalog_prev_distro_pref...
79,738
def prime_def(num): """ Поиск максимального простого делителея числа :param num: :return: """ from math import sqrt prime_set = set(range(1, num + 1)) #print(prime_set) for i in range (2, int(sqrt(num))): if i in prime_set: prime_set -= set(range(2*i, num + 1, i))...
79,739
def test_instantiate_array_w_sapm_temperature_parameters(system_def): """Regression test for gh #129 """ sapm_temp_example = {"a": -3.47, "b": -0.0594, "deltaT": 3} arrd = deepcopy(system_def.inverters[0].arrays[0].dict()) arrd["name"] = "PVWatts temperature params" arrd["temperature_model_paramete...
79,740
def dict_from_two_lists(keys: list, values: list): """Creates a dictionary from a list of keys and a list of values. Examples: >>> keys = ('bztar', 'gztar', 'tar', 'xztar', 'zip')\n >>> values = ('.tbz2', '.tgz', '.tar', '.txz', '.zip')\n >>> newdict = dict_from_two_lists(keys, values)\...
79,741
def unzip_all_bots(ld: LeagueDir): """ Unzip all zip files in the bot directory """ for root, dirs, files in os.walk(ld.bots, topdown=True): dirs[:] = [d for d in dirs] for file in files: if ".zip" in file: path = os.path.join(root, file) with ...
79,742
def hashable_index(tuple_idx): """Return an hashable representation of a tuple of slice object We add this because the slice object in python is not hashable. Parameters ---------- tuple_idx : tuple A tuple of slice/int objects Returns ------- ret : tuple A hashable re...
79,743
def add_new_entry(): """ Add IP details for the current user in Airtable :return: True """ table.create(build_data_new()) return True
79,744
def pfcwd(): """Show details of the pfc watchdog """ pass
79,745
def open_clean_bands(band_path, crop_extent, valid_range=None): """Open and mask a single landsat band using a pixel_qa layer. Parameters ----------- band_path : string A path to the array to be opened crop_extent : GeoDataFrame A shapefile ...
79,746
def encode_single_dataframe(dataframe: pd.DataFrame, f, types: dict=None, column_order: list=None, bigendian: bool=False, properties: dict=None): """ :param dataframe: A pandas dataframe to encode :param f: A file-like object to write the encoded data to :param columns: A dic...
79,747
def rms_combine(signals, weights = None, days = 1024, max_leverage = 5, join = 'outer', method = 'ffill'): """ >>> dt1 = drange(2000,2020, '1b') >>> sig1 = pd.DataFrame(ewmxo(np.random.normal(0,1,(len(dt1),10)), 18, 54, vol = 30) , dt1) >>> sig2 = pd.DataFrame(ewmxo(np.random.normal(0,1,(len(dt1),10)), ...
79,748
def get_output_type(name: str) -> OutputType: """Fetches a previously registered OutputType by name""" if name in OUTPUT_TYPES: return OUTPUT_TYPES[name] else: raise ValueError('The output type %s is unknown' % name)
79,749
def export_metadata( program_title="version", usrdata=None, matched_psms=0, unmatched_psms=0, usrfile="file", taxon_totals=dict(), outname=None, outpath=".", **kwargs, ): """Update iSPEC database with some metadata information""" print("{} | Exporting metadata".format(time.ct...
79,750
def list_tags_for_resources(ResourceType=None, ResourceIds=None): """ Lists tags for up to 10 health checks or hosted zones. For information about using tags for cost allocation, see Using Cost Allocation Tags in the AWS Billing and Cost Management User Guide . See also: AWS API Documentation ...
79,751
def test_transform_pre_history(multitrend_df: pd.DataFrame, pre_multitrend_df: pd.DataFrame): """Check that transform works correctly in case of fully unseen pre history data.""" bs = _OneSegmentChangePointsTrendTransform( in_column="target", change_point_model=Binseg(), detrend_model=LinearRegression()...
79,752
def prepare_for_parsing(multinet): """ Compute layout for a hairball visualization Args: param1 (obj): multilayer object Returns: tuple: (names, prepared network) """ layers = defaultdict(list) for node in multinet.nodes(data=True): try: layers[node[0...
79,753
def peek(nbytes=0) -> typing.Generator[_Action, Buffer, bytes]: """Read output without consuming it. Read but **does not** consume data from the protocol input. This is a *non-blocking* primitive, if less data than requested is available, less data is returned. It is meant to be used in combination wi...
79,754
def load_dataset(dataset='single_person'): """ Load train- and testset from subfolder 'dataset'. Download dataset: https://www.kaggle.com/ahmetfurkandemr/mask-datasets-v1/data and: https://www.kaggle.com/shreyashwaghe/medical-mask-dataset Run png_to_hdf5.py :param dataset: dataset to load :r...
79,755
def get_func_prototype_from_man(func): """ Parse "man func" output and return the function prototype. :param func: function name :returns the function prototype as a string. If not found, returns empty string. """ if func in g_prototype_db: return g_prototype_db[func] man_output = ge...
79,756
def defaultOutput(message, player=None): """ An example output function. Can be overridden by the caller. """ if player == None: print message else: print player + ": " + message
79,757
def train_gcn( dgl_tuple: Tuple[List[DGLHeteroGraph], dict], params: Dict[str, Any] ) -> Model: """ Trains a GCN model """ epochs: int = params["epochs"] hidden_features: int = params["hidden_features"] out_features: int = params["out_features"] G = dgl_tuple[0][0] input_shape: int =...
79,758
def lfsr(state, taps): """Linear-feedback shift register.""" while True: newbit = reduce(lambda x, y: x ^ state[y], taps, 0) oldbit, state = state[0], state[1:] + [newbit] yield oldbit, state
79,759
def main(): """ Create PowerMaxGatherFacts object and perform action on it based on user input from playbook """ obj = PowerMaxGatherFacts() obj.perform_module_operation()
79,760
def check_tied_units( all_t2_units: List[T2Compute], first_pass_config: Union[FirstPassConfig, dict[str,Any]] ) -> None: """ :raises: ValueError if tied t2 units are present in t2_units but the requred t2 units are not present in t2_compute """ tied_units: List[T2Compute] = [] for el in all_t2_units: ...
79,761
def get_sas_generator_host() -> str: """ Gets env variable for SAS generator url :retrurn sas url """ # TODO handle KeyError return os.environ['SAS_GENERATOR_HOST']
79,762
def create_procgen_env(config, instance_seed, instance): """ Creates a procgen environment and applies recommended wrappers. """ procgen_args = {k[8:]: v for k, v in vars(config).items() if k.startswith('procgen_')} procgen_args['start_level'] += 300_000*instance env = gym.make(f'procgen:procgen-{config...
79,763
def dedupe(items: list, only_neighbors: bool = False) -> list: """ Deduplicate a list while keeping order If only_neighbors is True, dedupe will only check neighboring values """ ret = [] for item in items: if (only_neighbors and ret and ret[-1] != item) or item not in ret: ...
79,764
def process_night_lights(country): """ Clip the nightlights layer to the chosen country boundary and place in desired country folder. Parameters ---------- country : string Three digit ISO country code. """ iso3 = country['iso3'] folder = os.path.join(DATA_INTERMEDIATE, is...
79,765
def major7( base: Union[int, str, Tone, Note], duration: Union[Tuple[int, int], Signature, None] = None, velocity: Optional[float] = None ) -> Tuple[Note, Note, Note, Note]: """ Generates Major Seventh chord. If note is provided as the first argument, duration and velocity of this n...
79,766
def gaussian_kernel1d( kernel_size: int, sigma: float, device: torch.device, dtype: torch.dtype ): """1D Gaussian kernel.""" khalf = (kernel_size - 1) / 2.0 x = torch.linspace(-khalf, khalf, steps=kernel_size, dtype=dtype, device=device) pdf = torch.exp(-0.5 * (x / sigma).pow(2)) return pdf / pd...
79,767
def interrupt() -> int: """interrupt hparams """ return 2
79,768
def fmtquant(quant, *args, **kwargs): """Give python Quantity object (or UncertainQuantity) and any arguments that fmtuncert takes. Additional arguments: units: Set True to append units (will make parentheses around values). Formats as tex formula if `tex=True` is set. ...
79,769
def remove_claims(claim_id, summary=None, revision=None, mediawiki_api_url=None, login=None, allow_anonymous=False, user_agent=None): """ Delete an item :param claim_id: One GUID or several (pipe-separated) GUIDs identifying the claims to be removed. All claims must belong to the same entity. :type ...
79,770
def preprocess(): """ Data preprocessing @return: """ (X_train, y_train), (X_test, y_test) = cifar10.load_data() num_train, img_channels, img_rows, img_cols = X_train.shape num_test, _, _, _ = X_test.shape num_classes = len(np.unique(y_train)) X_train = X_train.astype('float32') / ...
79,771
def encrypt_file(filepath): """Encrypt file contents to base64. :param filepath: the path of the file. """ try: # if it starts with ~ # os.path.expanduser with open(filepath) as inf: file_contents = inf.read() return file_contents.encode('base64') exce...
79,772
def flex_add_argument(f): """Make the add_argument accept (and ignore) the widget option.""" def f_decorated(*args, **kwargs): kwargs.pop('widget', None) return f(*args, **kwargs) return f_decorated
79,773
async def healthcheck_handler(_): """Demonstrates a simple healthcheck example. """ data = {"status": "ok"} return healthcheck_response(data)
79,774
def readMember(request, id=id): """メンバー読取""" template = loader.get_template('webapp1/members/read.html') # ------------------------- # 1 # 1. host1/webapp1/templates/webapp1/members/read.html を取得 # -----------...
79,775
def GQSignal_fetch_bootstrap_singal_day(start, end, frequence='day', market_type=QA.MARKET_TYPE.STOCK_CN, portfolio='myportfolio', ...
79,776
def param(name, *args, **kwargs): """ A wrapper for `tf.Variable` which enables parameter sharing in models. Creates and returns theano shared variables similarly to `tf.Variable`, except if you try to create a param with the same name as a previously-created one, `param(...)` will just retur...
79,777
def parse_args(): """ Obtain the simulation options from the input arguments Return a tuple with the following elements: * config_file: Relative location of the simulation configuration file * show_plot: If true, plots shall be generated after the simulation * from_file: If true, the output of ...
79,778
def Bulk_emails(): """批次寄信""" users = [ {"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"}, {"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"}, {"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"}, {"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"}, {"name": "xxxxxxxxxx", "email": "xxxxxxxxxx"...
79,779
def run(): """ Run game. """ words = load_words(WORDFILE) wrangler = provided.WordWrangler(words, remove_duplicates, intersect, merge_sort, gen_all_strings) provided.run_game(wrangler)
79,780
def model2(): """Build a convnet with dropout and batch normalisation.""" input = layers.Input(shape=input_shape[1:], dtype=np.float) x = layers.Conv1D(10, 5, activation='relu', name='CONV_1')(input) x = layers.Conv1D(10, 5, activation='relu', name='CONV_2')(x) x = layers.BatchNormalization()(x) ...
79,781
def test31(): """ Use find_by_name to find all containers """ assert isinstance(p, Pod) results = p.find_by_name('containers') assert len(results) == 2
79,782
def test_mesh_convergence(): """ Check mesh convergence as elements get smaller. """ # Columns of the dataframe columns = ['ratio', 'elapsed', 'current-left', 'current-center', 'number-of-elements', 'voltage-input', 'losses'] # Ratios of the mesh size ratios = [4,3,2.5,2,1.75,1.5,1.3,1.2,1....
79,783
def in_subnet(cidr, addrs=None): """ Returns True if host is within specified subnet, otherwise False """ for address in addrs: if ip_in_subnet(address, cidr): return True return False
79,784
def constant_time_compare(val1: AnyStr, val2: AnyStr) -> bool: """Return True if the two strings are equal, False otherwise.""" return secrets.compare_digest( encoding.force_bytes(val1), encoding.force_bytes(val2) )
79,785
def saveFinalImage(): """save the resulting file in a file in the .ppm format""" file = self.askFileSave(types=[('PPM files', '.ppm')]) outline.save(outline.finalImage, file)
79,786
def balance_command(update: Update, context: CallbackContext) -> None: """Send the current balances of the account.""" get_balances()
79,787
def get_warehouse_stocks(code, start_date=None, end_date=None): """ 获取期货某品种的注册仓单数据 :param code: 合约代码,如CU1903 :param start_date: 开始日期,必须指定 :param end_date: 结束日期,默认为策略当天日期的前一天 :return: -pandas DataFrame on_warrant 注册仓单量 market 期货品种对应交易所 """
79,788
def make_company_node(c: dict) -> Node: """Create new Company node for dict """ all_attributes = c.get('all_attributes', {}) return Node('Company', name=c['name'], company_number=c['company_number'], federal_state=all_attributes.get('federal_state'), ...
79,789
def problem_reciprocal_exponential(x): """Return recrprocal exponential function.""" return np.exp(-x)
79,790
def get_cached_latest_versions(versions=None): """ Get the latest versions from a cached file""" import datetime from azure.cli.core._session import VERSIONS if not versions: versions = _get_local_versions() if VERSIONS[_VERSION_UPDATE_TIME]: version_update_time = datetime.datetime...
79,791
def default_session_fixture(request): """Logging disabled when running tests.""" logging.disable(logging.CRITICAL)
79,792
def get_time(raw_time): """ Get treated time value from the raw provided time. # 2020/09/05T05:21:48z # 2020-09-05T05:21:48z # dtr = dt.replace("/","-")[:-1] :param raw_time: <string> :return treated_time: <datetime> """ treated_time = raw_time.replace("/", "-") return treate...
79,793
def update_table(contents, filename, last_modified): """ This is the first function called when the dashboard opens Takes in data from upload or uses default Creates pkl file of DF to be accessed Also takes in values from filters Need to adjust this so if the user uploads a new file it recogniz...
79,794
def write_to_config(config, config_path='/config', resources=None): """Write the config to main lovelace file.""" config_file = os.path.join(config_path, LOVELACE_FILE) with open(config_file, 'w') as outfile: outfile.write(DISCLAIMER) if resources is not None: yaml.dump(resou...
79,795
def noise_floor(nf=1, bandwidth=1, noise_temp=290): """ Calculate noise floor of a receiver. :param nf: Noise figure in dB :param bandwidth: bandwidth in Hz :param noise_temp: noise temperature in Kelvin """ return ( 10 * math.log10(KBOLTZMAN * noise_temp * 1000) + nf + 10 * math.lo...
79,796
def decrypt_generator(filename, key): """Stream decrypted file with given key. The given key must be the same that was returned by encrypt_file_inline. :param filename: The name of the file to decrypt. :type filename: str :param key: The key used to decrypt the file. :type key: str :re...
79,797
def get_round_from_jitemid(jitemid, cursor): """Take a jitemid, return a round.""" round_jitemid_mapping = { (0, 'br negative one') } # if jitemid is a key in the dictionary: # return the value # otherwise just return "UNKNOWN ROUND" return round
79,798
def safe_urlsplit(url): """This is a hack to prevent the regular urlsplit from splitting around question marks. A question mark (?) in a URL typically indicates the start of a querystring, and the standard library's urlparse function handles the querystring separately. Unfortunately, question marks can...
79,799