content
stringlengths
22
815k
id
int64
0
4.91M
def fetch_last_posts(conn) -> list: """Fetch tooted posts from db""" cur = conn.cursor() cur.execute("select postid from posts") last_posts = cur.fetchall() return [e[0] for e in last_posts]
30,800
def update_click_map(selectedData, date, hoverData, inputData): """ click to select a airport to find the detail information :param selectedData: :param date: :param hoverData: :return: """ timestamp = pd.to_datetime(date) if date else 0 fig = px.scatter_geo( airports_info, ...
30,801
def configure_blueprints(app: Flask): """ Configure blueprints. """ app.register_blueprint({{cookiecutter.blueprint_name}})
30,802
def EncoderText(model_name, vocab_size, word_dim, embed_size, num_layers, use_bi_gru=False, text_norm=True, dropout=0.0): """A wrapper to text encoders. Chooses between an different encoders that uses precomputed image features. """ model_name = model_name.lower() EncoderMap = { 'scan': Enco...
30,803
def feat_extract(pretrained=False, **kwargs): """Constructs a ResNet-Mini-Imagenet model""" model_urls = { 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 'resnet52': 'https://do...
30,804
def compose_all( mirror: Union[str, Path], branch_pattern: str = "android-*", work_dir: Optional[Path] = None, force: bool = False, ) -> Path: """Iterates through all the branches in AOSP and create the source maps. This methods: - list all the existing branches and filter those matchin...
30,805
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ n = len(input_list) heap_sort(input_list) decimal_value = 1 n1 = 0 ...
30,806
def _partial_ema_scov_update(s:dict, x:[float], r:float=None, target=None): """ Update recency weighted estimate of scov-like matrix by treating quadrants individually """ assert len(x)==s['n_dim'] # If target is not supplied we maintain a mean that switches from emp to ema if target is None: ...
30,807
def test_scalar_zero(py_c_vec: PyCVec): """Check zero behaviour with division ops.""" Vec, Angle, Matrix, parse_vec_str = py_c_vec for x, y, z in iter_vec(VALID_NUMS): vec = Vec(x, y, z) assert_vec(0 / vec, 0, 0, 0) assert_vec(0 // vec, 0, 0, 0) assert_vec(0 % vec, 0, 0, 0) ...
30,808
def refresh_rates(config, path="rates.json"): """Fetch and save the newest rates Arguments: config {currency.config} -- Config object Keyword Arguments: path {str} -- path or filename of Rates JSON to be saved (default: {"rates.json"}) Returns: dict -- fe...
30,809
def add_all_files(root_dir: str = 'data/') -> List[Path]: """Recursively iterates over a directory and returns all files with paths Args: root_dir: the starting directory to search from Returns: List of all files found, with paths relative to the root_dir """ root_path = Path(root_...
30,810
def migrate_component_indicators_data(apps, schema_editor): """ Adds the Indicator object from Component.indicator to the many-to-many relationship in Component.indicators """ Component = apps.get_model('goals', 'Component') for component in Component.objects.select_related('indicator')...
30,811
def _get_chrome_options(): """ Returns the chrome options for the following arguments """ chrome_options = Options() # Standard options chrome_options.add_argument("--disable-infobars") chrome_options.add_argument('--ignore-certificate-errors') # chrome_options.add_argument('--no-sandbo...
30,812
def add_document(dbname, colname, doc, url=cc.URL_KRB, krbheaders=cc.KRBHEADERS) : """Adds document to database collection. """ resp = post(url+dbname+'/'+colname+'/', headers=krbheaders, json=doc) logger.debug('add_document: %s\n to %s/%s resp: %s' % (str(doc), dbname, colname, resp.text)) return ...
30,813
def legendre(n, monic=0): """Returns the nth order Legendre polynomial, P_n(x), orthogonal over [-1,1] with weight function 1. """ if n < 0: raise ValueError("n must be nonnegative.") if n==0: n1 = n+1 else: n1 = n x,w,mu0 = p_roots(n1,mu=1) if n==0: x,w = [],[] hn = 2.0/(2*...
30,814
def cal_sort_key(cal): """ Sort key for the list of calendars: primary calendar first, then other selected calendars, then unselected calendars. (" " sorts before "X", and tuples are compared piecewise) """ if cal["selected"]: selected_key = " " else: selected_key =...
30,815
def test_env_dtm_formats(fmts, inp, exp): """ If $DTM_FORMATS is set, its value should be added at the beginning of the default parseable input formats. """ pytest.dbgfunc() with tbx.envset(DTM_FORMATS=fmts): a = dt(inp) assert a() == exp
30,816
def get_data_loader(): """Safely downloads data. Returns training/validation set dataloader.""" mnist_transforms = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.1307, ), (0.3081, ))]) # We add FileLock here because multiple workers will want to # download data, an...
30,817
def preview_game_num(): """retorna el numero de la ultima partida jugada""" df = pd.read_csv('./data/stats.csv', encoding="utf8") x = sorted(df["Partida"],reverse=True)[0] return x
30,818
def ensure_is_dir(d, clear_dir=False): """ If the directory doesn't exist, use os.makedirs Parameters ---------- d: str the directory we want to create clear_dir: bool (optional) if True clean the directory if it exists """ if not os.path.exists(d): os.makedirs(d) ...
30,819
def XCO( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "4.46", **kwargs ) -> Graph: """Return XC...
30,820
async def test_wikidata_search_does_not_rank_aliases_high_enough(best_match_id, mock_aioresponse): """ Matches on aliases are not ranked high enough by the default search profile. """ assert ( await best_match_id('GER', typ='Q6256') == 'Q183')
30,821
def test_setURL_valid_URL_but_no_settings(caplog): """Test setURL""" iface = MagicMock(autospec=SerialInterface) url = "https://www.meshtastic.org/d/#" with pytest.raises(SystemExit) as pytest_wrapped_e: anode = Node(iface, 'bar', noProto=True) anode.radioConfig = 'baz' anode.set...
30,822
def rasterize_layer_by_ref_raster(src_vector, ref_raster, use_attribute, all_touched=False, no_data_value=0): """Rasterize vector data. Get the cell value in defined grid of ref_raster from its overlapped polygon. Parameters ---------- src_vector: Geopandas.GeoDataFrame Which vector data to...
30,823
def wraplatex(text, width=WIDTH): """ Wrap the text, for LaTeX, using ``textwrap`` module, and ``width``.""" return "$\n$".join(wrap(text, width=width))
30,824
def test_simple_sql(engine_testaccount): """ Simple SQL by SQLAlchemy """ result = engine_testaccount.execute('show databases') rows = [row for row in result] assert len(rows) >= 0, 'show database results'
30,825
def register(request): """ Render and process a basic registration form. """ ctx = {} if request.user.is_authenticated(): if "next" in request.GET: return redirect(request.GET.get("next", 'control:index')) return redirect('control:index') if request.method == 'POST': ...
30,826
def green_agg(robots: List[gs.Robot]) -> np.ndarray: """ This is a dummy aggregator function (for demonstration) that just saves the value of each robot's green color channel """ out_arr = np.zeros([len(robots)]) for i, r in enumerate(robots): out_arr[i] = r._color[1] return out_arr
30,827
def tcp_port_open_locally(port): """ Returns True if the given TCP port is open on the local machine """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(("127.0.0.1", port)) return result == 0
30,828
def wrap(text, width=80): """ Wraps a string at a fixed width. Arguments --------- text : str Text to be wrapped width : int Line width Returns ------- str Wrapped string """ return "\n".join( [text[i:i + width] for i in range(0, len(text), w...
30,829
def parallel_vector(R, alt, max_alt=1e5): """ Generates a viewing and tangent vectors parallel to the surface of a sphere """ if not hasattr(alt, '__len__'): alt = np.array([alt]) viewer = np.zeros(shape=(3, len(alt))) tangent = np.zeros_like(viewer) viewer[0] = -(R+max_alt*2) ...
30,830
def load_datasets(parser, args): """Loads the specified dataset from commandline arguments Returns: train_dataset, validation_dataset """ args = parser.parse_args() dataset_kwargs = { "root": Path(args.train_dir), } source_augmentations = Compose( [globals()["_aug...
30,831
def stock_total_deal_money(): """ 总成交量 :return: """ df = stock_zh_index_spot() # 深证成指:sz399001,上证指数:sh00001 ds = df[(df['代码'] == 'sz399001') | (df['代码'] == 'sh000001')] return ds['成交额'].sum() / 100000000
30,832
def reboot(WorkspaceId): """Reboot a specific AWS Workspace instance.""" client = aws() console.log( Panel('Attemptng reboot of workspaceId: ' + WorkspaceId, title='INFO', style=info_fmt)) response = client.reboot_workspaces(RebootWorkspaceRequests=[ { ...
30,833
def _ls(dir=None, project=None, all=False, appendType=False, dereference=False, directoryOnly=False): """ Lists file(s) in specified MDSS directory. :type dir: :obj:`str` :param dir: MDSS directory path for which files are listed. :type project: :obj:`str` :param project: NCI project identi...
30,834
def print_subs(valid_subs:list): """ Words of length 2 ab ac ca Words of length 3 cab """ max_len = -1 for sub in valid_subs: if len(sub) > max_len: max_len = len(sub) output = [[] for _ in range(max_len)] for sub in valid_subs: output[len(sub)-1].append(sub...
30,835
def uploadMetadata(doi, current, delta, forceUpload=False, datacenter=None): """ Uploads citation metadata for the resource identified by an existing scheme-less DOI identifier (e.g., "10.5060/FOO") to DataCite. This same function can be used to overwrite previously-uploaded metadata. 'current' and 'delta'...
30,836
def one_away(string_1: str, string_2: str)-> bool: """DP, classic edit distance funny move, we calculate the LCS and then substract from the len() of the biggest string in O(n*m) """ if string_1 == string_2: return False @lru_cache(maxsize=1024) def dp(s_1, s_2, distance=0): """standard ...
30,837
async def reset_alarm_panel(hass, cluster, entity_id): """Reset the state of the alarm panel.""" cluster.client_command.reset_mock() await hass.services.async_call( ALARM_DOMAIN, "alarm_disarm", {ATTR_ENTITY_ID: entity_id, "code": "4321"}, blocking=True, ) await hass....
30,838
def test(net, loss_normalizer): """ Tests the Neural Network using IdProbNet on the test set. Args: net -- (IdProbNet instance) loss_normalizer -- (Torch.Tensor) value to be divided from the loss Returns: 3-tuple -- (Execution Time, End loss value, Model's predictio...
30,839
def scale_from_matrix(matrix): """Return scaling factor, origin and direction from scaling matrix. """ M = jnp.array(matrix, dtype=jnp.float64, copy=False) M33 = M[:3, :3] factor = jnp.trace(M33) - 2.0 try: # direction: unit eigenvector corresponding to eigenvalue factor w, V = jnp.linalg.eig(M33) ...
30,840
def get_fort44_info(NDX, NDY, NATM, NMOL, NION, NSTRA, NCL, NPLS, NSTS, NLIM): """Collection of labels and dimensions for all fort.44 variables, as collected in the SOLPS-ITER 2020 manual. """ fort44_info = { "dab2": [r"Atom density ($m^{-3}$)", (NDX, NDY, NATM)], "tab2": [r"Atom tempe...
30,841
def lens2memnamegen_first50(nmems): """Generate the member names for LENS2 simulations Input: nmems = number of members Output: memstr(nmems) = an array containing nmems strings corresponding to the member names """ memstr=[] for imem in range(0,nmems,1): if (imem < 10)...
30,842
def initialize_settings(tool_name, source_path, dest_file_name=None): """ Creates settings directory and copies or merges the source to there. In case source already exists, merge is done. Destination file name is the source_path's file name unless dest_file_name is given. """ settings_dir = os...
30,843
def preprocess_output(fp_hdf_out, raw_timestamps, output, output_timestamps, average_window=1000, dataset_name='aligned'): """ Base file for preprocessing outputs (handles M-D case as of March2020). For more complex cases use specialized functions (see for example preprocess_output in util.tetrode module) ...
30,844
def landing_pg(): """Landing page.""" landing = st.sidebar.selectbox("Welcome", ["Home", "Interactive"]) if landing == "Home": landing_src() else: interactive()
30,845
def test_list_boolean_length_nistxml_sv_iv_list_boolean_length_1_4(mode, save_output, output_format): """ Type list/boolean is restricted by facet length with value 5. """ assert_bindings( schema="nistData/list/boolean/Schema+Instance/NISTSchema-SV-IV-list-boolean-length-1.xsd", instance...
30,846
def get_stopword_list(filename=stopword_filepath): """ Get a list of stopword from a file """ with open(filename, 'r', encoding=encoding) as f: stoplist = [line for line in f.read().splitlines()] return stoplist
30,847
def annotate(d, text='', filename='notes.txt'): """Create a file FILENAME in the directory D with contents TEXT.""" f = open(os.path.join(d, filename), 'w') f.write(text) f.close()
30,848
def test_create_file_obj_deleted(new_dataset): """Test for the case where this file only exists in ancestor commits""" hexsha = new_dataset.repo.repo.head.commit new_dataset.remove('dataset_description.json') tree = new_dataset.repo.repo.commit(hexsha).tree assert create_file_obj( new_datase...
30,849
def append_composite_tensor(target, to_append): """Helper function to append composite tensors to each other in the 0 axis. In order to support batching within a fit/evaluate/predict call, we need to be able to aggregate within a CompositeTensor. Unfortunately, the CT API currently does not make this easy...
30,850
def check_index(ind, dimension): """Check validity of index for a given dimension Examples -------- >>> check_index(3, 5) >>> check_index(5, 5) Traceback (most recent call last): ... IndexError: Index is not smaller than dimension 5 >= 5 >>> check_index(6, 5) Traceback (most rece...
30,851
def to_text(value): """Convert an opcode to text. *value*, an ``int`` the opcode value, Raises ``dns.opcode.UnknownOpcode`` if the opcode is unknown. Returns a ``str``. """ return Opcode.to_text(value)
30,852
def prompt_merge(target_path, additional_uris, additional_specs, path_change_message=None, merge_strategy='KillAppend', confirmed=False, confirm=False, show_advanced=True, show_verbosi...
30,853
def _demo_mm_inputs(input_shape, num_classes): """Create a superset of inputs needed to run test or train batches. Args: input_shape (tuple): input batch dimensions num_classes (int): number of semantic classes """ (N, C, H, W) = input_shape rng = np.random.R...
30,854
def clean_vm(root): """Remove vagrant VM from specified path""" v = vagrant.Vagrant(root=root) print(" - Cleanig VM ", root) try: v.destroy() except Exception as err: print(err) try: os.remove(root + "/Vagrantfile") except FileNotFoundError: pass
30,855
def get_ephemeral_port(sock_family=socket.AF_INET, sock_type=socket.SOCK_STREAM): """Return an ostensibly available ephemeral port number.""" # We expect that the operating system is polite enough to not hand out the # same ephemeral port before we can explicitly bind it a second time. s = socket.socket...
30,856
def iterMergesort(list_of_lists, key=None): # Based on http://code.activestate.com/recipes/511509-n-way-merge-sort/ # from Mike Klaas """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key})...
30,857
def main(): """ Let this thing fly """ args = get_args() # connect this thing si = vmware_lib.connect(args.host, args.user, args.password, args.port, args.insecure) content = si.RetrieveContent() vm_object = None if args.template_folder: folder = vmware_lib.get_obj(content...
30,858
def tear_down(): """ tear down test environment """ # destroy test database from django.db import connection connection.creation.destroy_test_db("not_needed") # teardown environment from django.test.utils import teardown_test_environment teardown_test_environment()
30,859
def IR_guess_model(spectrum: ConvSpectrum, peak_args: Optional[dict] = None) -> tuple[Model, dict]: """ Guess a fit for the IR spectrum based on its peaks. :param spectrum: the ConvSpectrum to be fit :param peak_args: arguments for finding peaks :return: Model, parameters """ min_intensity,...
30,860
def virus_monte_carlo(initial_infected, population, k): """ Generates a list of points to which some is infected at a given value k starting with initial_infected infected. There is no mechanism to stop the infection from reaching the entire population. :param initial_infected: The amount of people...
30,861
def threadsafe_generator(f): """ A decorator that takes a generator function and makes it thread-safe. """ def g(*a, **kw): return threadsafe_iter(f(*a, **kw)) return g
30,862
def test_heirarchical_data(heirarchical_data_structure, settings_number_of_columns_5): """Testing that heirarchical data can be handled by VMC (even though this is NOT recommended""" instance = EvenVMCView() rows = instance.process_entries(heirarchical_data_structure) for row in range(len(rows) - 1): ...
30,863
def lastmsg(self): """ Return last logged message if **_lastmsg** attribute is available. Returns: last massage or empty str """ return getattr(self, '_last_message', '')
30,864
def _callback_on_all_dict_keys(dt, callback_fn): """ Callback callback_fn on all dictionary keys recursively """ result = {} for (key, val) in dt.items(): if type(val) == dict: val = _callback_on_all_dict_keys(val, callback_fn) result[callback_fn(key)] = val return re...
30,865
def ovb_partial_r2_bound(model=None, treatment=None, r2dxj_x=None, r2yxj_dx=None, benchmark_covariates=None, kd=1, ky=None): """ Provide a Pandas DataFrame with the bounds on the strength of the unobserved confounder. Adjusted estimates, standard errors and t-values (among other qu...
30,866
def top_ngrams(df, n=2, ngrams=10): """ * Not generalizable in this form * * This works well, but is very inefficient and should be optimized or rewritten * Takes a preposcessed, tokenized column and create a large list. Returns most frequent ngrams Arguments: df = name of DataFrame wit...
30,867
def install_openvpn(instance, arg, verbose=True): """ """ install(instance, {"module":"openvpn"}, verbose=True) generate_dh_key(instance, {"dh_name":"openvpn", "key_size":"2048"}) server_conf = open("simulation/workstations/"+instance.name+"/server_openvpn.conf", "w") server_conf.write("port 1...
30,868
def filter_params(module: Module, train_bn: bool = True) -> Generator: """Yields the trainable parameters of a given module. Args: module: A given module train_bn: If True, leave the BatchNorm layers in training mode Returns: Generator """ children = list(module.children())...
30,869
def rossoporn_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]: """Read the html for rossoporn.com""" #Parses the html of the site soup = soupify(driver) dir_name = soup.find("div", class_="content_right").find("h1").text dir_name = clean_dir_name(dir_name) images = soup.find_all("...
30,870
def pid_from_context(_, context, **kwargs): """Get PID from marshmallow context.""" pid = (context or {}).get('pid') return pid.pid_value if pid else missing
30,871
def score_text(text, tokenizer, preset_model, finetuned_model): """ Uses rule-based rankings. Higher is better, but different features have different scales. Args: text (str/ List[str]): one story to rank. tokenizer (Pytroch tokenizer): GPT2 Byte Tokenizer. preset_model (Pytorch model)...
30,872
def get_bot_list(swarming_server, dimensions, dead_only): """Returns a list of swarming bots.""" cmd = [ sys.executable, 'swarming.py', 'bots', '--swarming', swarming_server, '--bare', ] for k, v in sorted(dimensions.iteritems()): cmd.extend(('--dimension', k, v)) if dead_only: cmd.append(...
30,873
def running_on_kaggle() -> bool: """Detect if the current environment is running on Kaggle. Returns: bool: True if the current environment is on Kaggle, False otherwise. """ return os.environ.get("KAGGLE_KERNEL_RUN_TYPE") == "Interactive"
30,874
def _get_picture_from_attachments(path): """Get picture bytes from telegram server""" url = 'https://api.telegram.org/file/bot' + API_TOKEN + '/' + path pic_path = './photos/pic.jpg' curl_command = f'curl {url} > {pic_path}' data = subprocess.run(curl_command, shell=True) if data.returncode !...
30,875
def parse_cards(account_page_content): """ Parse card metadata and product balances from /ClipperCard/dashboard.jsf """ begin = account_page_content.index(b'<!--YOUR CLIPPER CARDS-->') end = account_page_content.index(b'<!--END YOUR CLIPPER CARDS-->') card_soup = bs4.BeautifulSoup(account_page_c...
30,876
def __setitem__(x, key, value, /): """ Note: __setitem__ is a method of the array object. """ pass
30,877
def interaction_time_data_string(logs, title): """ times = utils.valid_values_for_enum((models.LogEntry.TIME_CHOICES)) contexts_map = dict(models.LogEntry.TIME_CHOICES) counts = {contexts_map[k]: v for k, v in _counts_by_getter(logs, lambda l: l.time_of_day).items() }...
30,878
def main() -> None: """ Load the data from a csv file and insert it into a MongoDB database. """ import json with open("script_constants.json", "r") as file: constants = json.load(file) pokemon_data_filename = constants["Pokemon_data_filename"] pokemon = extract_data_from_csv(pokemo...
30,879
def _label_boost(boost_form, label): """Returns the label boost. Args: boost_form: Either NDCG or PRECISION. label: The example label. Returns: A list of per list weight. """ boost = { 'NDCG': math.pow(2.0, label) - 1.0, 'PRECISION': 1.0 if label >= 1.0 else 0.0, } return boost[b...
30,880
def iterate_orthologous_lexical_matches(prefix) -> Iterable[MappingTuple]: """Generate orthologous relations between lexical matches from different species.""" names = pyobo.get_id_name_mapping(prefix) species = pyobo.get_id_species_mapping(prefix) provenance = get_script_url(__file__) count = 0 ...
30,881
def has_matching_ts_templates(reactant, bond_rearr): """ See if there are any templates suitable to get a TS guess from a template Arguments: reactant (autode.complex.ReactantComplex): bond_rearr (autode.bond_rearrangement.BondRearrangement): Returns: bool: """ mol_gra...
30,882
def get_commands(xml: objectify.ObjectifiedElement): """ Returns an action and the room from the xml string. :param xml: :return: """ return xml.body.attrib["action"]
30,883
def compression_point(w_db, slope = 1, compression = 1, extrapolation_point = None, axis = -1): """Return input referred compression point""" interpol_line = calc_extrapolation_line(w_db, slope, extrapolation_point, axis) return cross(interp...
30,884
def main(): """ calculates a hilbert pseudocurve of p iterations. Scale the pseudocurve to match the desired image. Move along the curve and sample image and to get average color at each segment Output gcode corresponding the coordinates and scaled Z levels. If no image is given, a flat hilbert...
30,885
def pattern_remove_incomplete_region_or_spatial_path( perception_graph: PerceptionGraphPattern ) -> PerceptionGraphPattern: """ Helper function to return a `PerceptionGraphPattern` verifying that region and spatial path perceptions contain a reference object. """ graph = perception_graph.copy_as...
30,886
def test_multiplication(): """test multiplication (f*g) for both value and derivative""" assert f_5.get()[0] == f.get()[0] * g.get()[0] assert f_5.get()[1] == f.get()[0] * g.get()[1] + f.get()[1] * g.get()[0] """test multiplication (g*f) for both value and derivative""" assert f_6.get()[0] == g.get(...
30,887
def other_shifted_bottleneck_distance(A, B, fudge=default_fudge, analysis=False): """Compute the shifted bottleneck distance between two diagrams, A and B (multisets)""" A = pu.SaneCounter(A) B = pu.SaneCounter(B) if not A and not B: return 0 radius = fudge(upper_bound_on_radius(A, B)) e...
30,888
def getCountdown(c): """ Parse into a Friendly Readable format for Humans """ days = c.days c = c.total_seconds() hours = round(c//3600) minutes = round(c // 60 - hours * 60) seconds = round(c - hours * 3600 - minutes * 60) return days, hours, minutes, seconds
30,889
def from_aiida_type(x): """Turn Aiida types into their corresponding native Python types.""" raise TypeError(f"Do not know how to convert {type(x)} to native Python type")
30,890
def fromPSK(valstr): """A special version of fromStr that assumes the user is trying to set a PSK. In that case we also allow "none", "default" or "random" (to have python generate one), or simpleN """ if valstr == "random": return genPSK256() elif valstr == "none": return bytes([0])...
30,891
def init_app(_): """Initializes backend"""
30,892
def get_subpackages(name): """Return subpackages of package *name*""" splist = [] for dirpath, _dirnames, _filenames in os.walk(name): if osp.isfile(osp.join(dirpath, "__init__.py")): splist.append(".".join(dirpath.split(os.sep))) return splist
30,893
def list_hierarchy(class_name, bases): """ Creates a list of the class hierarchy Args: ----- class_name: name of the current class bases: list/tuple of bases for the current class """ class_list = [Uri(class_name)] for base in bases: if base.__name__ not in IGNORE_C...
30,894
def output_mesh(mesh, config): """Outputs mesh in formats specified in config. :param mesh MeshInfo: tetrahedral mesh. :param config Config: configuration for mesh build. """ if not config.output_format: return logger.info('Outputting mesh in formats: {}' .format(', '.join(config...
30,895
def move_mouse_to_specific_location(x_coordinate, y_coordinate): """Moves the mouse to a specific point""" LOGGER.debug("Moving mouse to (%d,%d)", x_coordinate, y_coordinate) pyautogui.moveTo(x_coordinate, y_coordinate) return Promise.resolve((x_coordinate, y_coordinate))
30,896
def rss(): """Return ps -o rss (resident) memory in kB.""" return float(mem("rss")) / 1024
30,897
def load_pickle_file(filename): """Read a pickle file, return a generator""" with open(filename, "rb") as f: while True: try: yield pickle.load(f) except EOFError: break
30,898
def compare_words( word1_features, word2_features, count=10, exclude=set(), similarity_degree=0.5, separate=False, min_feature_value=0.3 ): """ Сравнение двух слов на основе списка похожих (или вообще каких-либо фич слова). Возвращает 3 списка: характерные для первог...
30,899