content
stringlengths
22
815k
id
int64
0
4.91M
def download_url(url, output_folder=None, overwrite=False, verbose=False): """ Download file from given url :param url: URL to download file from :param str output_folder: Output folder (Default: current directory) :param bool overwrite: Overwrite output file if it already exists :param bool ve...
5,306,800
def calc_U_slip_quasisteady(eps, E, x, mu): """ Slip velocity (quasi-steady limit) """ u_slip_quasisteady = -eps*E**2*x/(2*mu) return u_slip_quasisteady
5,306,801
def split(nsentences, cv): """ :param nsentences: :param cv: :return: """ index = np.arange(nsentences) for i in range(0, cv): lower = np.floor((i/cv) * nsentences) upper = np.floor(((i + 1)/cv) * nsentences) test_range = np.arange(lower, upper, dtype=np.int16) ...
5,306,802
def momentum(df, column='close', n=20, add_col=False, return_struct='numpy'): """ Momentum Parameters ---------- df : Pandas DataFrame A Dataframe containing the columns open/high/low/close/volume with the index being a date. open/high/low/close should all be floats. volume ...
5,306,803
async def test_create_new_credential(manager, provider): """Test that we create a new credential.""" credentials = await provider.async_get_or_create_credentials( {"username": "good-user", "password": "good-pass"} ) assert credentials.is_new is True user = await manager.async_get_or_create_...
5,306,804
def get_version() -> Optional[str]: """Returns the current version of strops. Requires a symlink install or to run strops directly from the repository. """ commit = None try: git_dir = path.join(ROOT_DIR, ".git") if path.exists(git_dir): commit = ( check_...
5,306,805
def mock_cloud_fixture(opp): """Fixture for cloud component.""" opp.loop.run_until_complete(mock_cloud(opp)) return mock_cloud_prefs(opp)
5,306,806
def get_distinct_project_attributes(attribute, path=PROJECT_HOME): """Get distinct values of the named attribute. .. versionadded:: 0.16.0-d :param attribute: The name of the attribute. :type attribute: str :param path: The path to where projects are stored. :type path: str :rtype: Order...
5,306,807
def scale_y_reverse(name=None, breaks=None, labels=None, limits=None, expand=None, na_value=None): """ Continuous position scales (y) where trans='reverse' Parameters ---------- name : string The name of the scale - used as the axis label or the legend title. If None, the default, the name ...
5,306,808
def run(): """Run command.""" from mne.commands.utils import get_optparser, _add_verbose_flag parser = get_optparser(__file__) subjects_dir = mne.get_config('SUBJECTS_DIR') parser.add_option('-o', '--overwrite', dest='overwrite', action='store_true', hel...
5,306,809
def get_sequence_of_considered_visits(max_num_considered_actions, num_simulations): """Returns a sequence of visit counts considered by Sequential Halving. Sequential Halving is a "pure exploration" algorithm for bandits, introduced in "Almost Optimal Exploration in Multi-Ar...
5,306,810
def check_proof_of_work(header: Header) -> bool: """ Validates the Proof of Work constraints. Parameters ---------- header : Header of interest. Returns ------- check : `bool` True if Proof of Work constraints are satisfied, False otherwise. """ # TODO: Implemen...
5,306,811
def reader_function(path): """Take a path or list of paths and return a list of LayerData tuples. Readers are expected to return data as a list of tuples, where each tuple is (data, [add_kwargs, [layer_type]]), "add_kwargs" and "layer_type" are both optional. Parameters ---------- path : s...
5,306,812
def select_object(): """Select a random image from the PDS Planetary Rings Node.""" # First randomly select a field fields = set(META['FIELD']) field = random.sample(fields, 1)[0] # Having selected a field, select a random number from that mission max_field = META['MAX_NUM'][META['FIELD'] == field] idx = random....
5,306,813
def load_all_vocabs_details_from_github(): """Uses the GitHub API via the Python client to get all the vocab details from the files in the vocabularies/ folder :return: a dict of vocabularies' details """ print('Loading all vocabs from GitHub') print("Vocabs to be uploaded:") gh = Github(co...
5,306,814
def two_node_diff(a): """Calculate and return diffs over two nodes instead of one.""" N = len(a) return a[2:] - a[:(N-2)]
5,306,815
def get_hue_sample_num(gamut_boundary_lut_name=mcfl.BT709_BOUNDARY): """ shape[0]: luminance sample shape[1]: hue sample """ return np.load(gamut_boundary_lut_name).shape[1]
5,306,816
def Quit(): """ Hotkey function that stops hotkey manager's event loop. :return: None. """ # Stop hotkey manager's event loop hotkey_manager_get().eloop_stop()
5,306,817
def make_savedir(parent_dir='./'): """ make directory to save results Params ---------- parent_dir : str parent directory to save results """ if parent_dir[-1] != '/': parent_dir += '/' import datetime import os orig_dirname = datetime.datetime.now().strftime('%...
5,306,818
def _get_timeout(payload_len): """Conservatively assume min 5 seconds or 3 seconds per 1MB.""" return max(3 * payload_len / 1024 / 1024, 5)
5,306,819
def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size, normalize_digits=True): """ Create vocabulary file (if it does not exist yet) from data file. Data file is assumed to contain one sentence per line. Each sentence is tokenized and digits are normalized (if norm...
5,306,820
def add_member(data): """Adds the newly signed up user to the member Table""" # ToDo: Get Project Details from user during signup. Current system assumes user has no project preference. try: CheckConnection() with Connection.cursor() as cursor: name = str(data["name"]) ...
5,306,821
def check_img(img, input_dir): """ Checks whether the img complies with API`s restrictions. Parameters ---------- img : str Image name. input_dir : str Path to the dir with the image to check. Returns ------- Error message if image does not comply with A...
5,306,822
def add_vec_mod2(v, w): """ Mod 2 addition separately on each components of v and w :params list/str v, w: bit-strings (or list representations) to be added mod 2 :return str: component-wise mod 2 sum of the input strings/lists """ if len(v) != len(w): raise AssertionError("Input length...
5,306,823
def sokal_sneath3( x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None ) -> float: """Sokal-Sneath similarity (v3) Sneath, P. H., & Sokal, R. R. (1973). Numerical taxonomy. The principles and practice of numerical classification. Args: x (BinaryFeatureVecto...
5,306,824
def deactivate(name, path, user): """ Deactivate a wordpress plugin name Wordpress plugin name path path to wordpress install location user user to run the command as CLI Example: .. code-block:: bash salt '*' wordpress.deactivate HyperDB /var/www/html a...
5,306,825
def _average_gradients(tower_grads, catname=None): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over...
5,306,826
def _validate_int( setting, value, option_parser, config_parser=None, config_section=None ) -> int: """Validate an integer setting.""" return int(value)
5,306,827
def wait_for(predicate, timeout, fail_func=None, period=0.001): """Wait for predicate to turn true, or fail this test""" # from distributed.utils_test deadline = time() + timeout while not predicate(): sleep(period) if time() > deadline: # pragma: no cover if fail_func is no...
5,306,828
def get_best_name(phenomena): """ Create a best_name field which takes the best name as defined by the preference order :param phenomena: phenomena attributes in form [{"name":"standard_name","value":"time"},{"name":"---","value":"---"},{}...] :return: best_name(string) """ preference_order = ["...
5,306,829
def GetFqdn(): """Get the desired FQDN via flags.""" return FLAGS.glazier_spec_fqdn
5,306,830
def get_global_evidence(a): """ PyMultiNest's Analyzer has a get_stats() method, but it's a bit too sluggish if all we want is to get the global evidence out. This is a hack around the issue. """ stats_file = open(a.stats_file) lines = stats_file.readlines() stats = {} a._read_error_...
5,306,831
def load_data(database_filepath): """Loads data from database and returns label and features dataframe""" engine = db.create_engine('sqlite:///{}'.format(database_filepath)) conn = engine.connect() df = pd.read_sql_table('messages', con=conn) X = df['message'] Y = df.iloc[:, 4:] return X, Y...
5,306,832
def test_get_process_raises_api_error(cbcsdk_mock): """Test of getting process through a WatchlistAlert""" # mock the alert request cbcsdk_mock.mock_request("GET", "/appservices/v6/orgs/test/alerts/6b2348cb-87c1-4076-bc8e-7c717e8af608", GET_ALERT_TYPE_WATCHLIST_INVALID) # mo...
5,306,833
def merge_scalar_results(results, scalar_fields): """ Collect all scalar results in a (hierarchical) dataframe. """ return pd.DataFrame( [[getattr(res, k) for k in scalar_fields] for res in results], columns=scalar_fields, ).set_index("case")
5,306,834
def omega_KMid(r): """ Keplerian angular velocity """ return (const.G*M/((r*u.AU)**3))**0.5
5,306,835
def buildRecorderDicts(energyInterval, powerInterval, voltageInterval, energyPowerMeter, triplexGroup, recordMode, query_buffer_limit): """Helper function to construct dictionaries to be used by individuals to add recorders to their own models. Note that th...
5,306,836
def rooms_n2(): """ Two rooms side by side """ rm1 = Room('rm1', 1e3, [[0,0], [5,0], [5,5], [0,5]]) rm2 = Room('rm2', 2e3, [[5,0], [10,0], [10,5], [5,5]]) rooms = [rm1, rm2] return rooms
5,306,837
def get_env(env_var_name): """ If present, returns environment variable value, if not - raises 'ImproperlyConfigured' """ env = environ.Env() environ.Env.read_env() return env(env_var_name)
5,306,838
def vis_cmd(mappings, fname, display, non_neighbors): """Visualizes a mapping.""" for mapping in mappings: fname = sketch_to_pdf(mapping, fname, non_neighbors) if display: click.launch(fname) yield mapping
5,306,839
def remove_property(key): """Removes a property with given key. Alias for: :meth:`~neptune.experiments.Experiment.remove_property` """ get_experiment().remove_property(key)
5,306,840
def test_flatten_list(): """Test the success scenario of the function flatten_list.""" assert(r.flatten_list([[1, 2], [3, 4]]) == [1, 2, 3, 4])
5,306,841
def writeDataIntoCsvFile(filePath, filteredStatDict): """ Write data into a csv file args : - filePath (str): outputfile's full path - filteredStatDict (dict): data to write into the output csv file """ import csv totalOccur = sum(occur for word, occur in filter...
5,306,842
def sub(arg1, arg2): """ Function that subtracts two arguments. """ return arg1 - arg2
5,306,843
def query_for_data(driver): """Grab all relevant data on a jobs page. Return: ------ job_titles: list job_locations: list posting_companies: list dates: list hrefs: list """ job_titles = driver.find_elements_by_xpath( "//span[@itemprop='tit...
5,306,844
def set_msglevels(mock_msg): """Set mock Msg() class message levels""" mock_msg.ERR = 0 mock_msg.MSG = 1 mock_msg.WAR = 2 mock_msg.INF = 3 mock_msg.VER = 4 mock_msg.DBG = 5 mock_msg.DEF = mock_msg.INF
5,306,845
def users_json(): """ Return the all the users data in json format """ users = session.query(User).all() return jsonify(users=[user.serialize for user in users])
5,306,846
def get_image_info(filepath): """ Gets an image's information. """ image = Image.open(filepath) info = { 'width': image.size[0], 'height': image.size[1], } metadata = get_image_exif(image) # camera camera = None if EXIF_MODEL in metadata: camera = metada...
5,306,847
def listAll(): """ Load listAll page """ old_stdout = sys.stdout sys.stdout = open('file.txt', 'w') i_d = wmc.repository.list() sys.stdout.close() sys.stdout = old_stdout fl = open('file.txt','r') i_d = fl.read() fl.close() msg = Markup(i_d) return render_template('li...
5,306,848
def split_line(line: str) -> typing.Tuple[str, str]: """ Separates the raw line string into two strings: (1) the command and (2) the argument(s) string :param line: :return: """ index = line.find(' ') if index == -1: return line.lower(), '' return line[:index].lower(), lin...
5,306,849
def naep_aggregate(input_df): """ :param input_df: :return: """ # Treat years as strings input_df['YEAR'] = input_df['YEAR'].astype('str') # input_df.drop_duplicates(inplace=True) # PRIMARY_KEY, STATE, and YEAR will be the same staging_df = pd.DataFrame() staging_df['PRIMARY_KE...
5,306,850
def matrix_transpose(mat: List[List]) -> List[List]: """ >>> matrix_transpose([[1, 2], [3, 4], [5, 6]]) [[1, 3, 5], [2, 4, 6]] """ if len(mat) == 0: raise ValueError("Matrix is empty") return [[mat[j][i] for j in range(len(mat))] for i in range(len(mat[0]))]
5,306,851
def test_decode_simple_list(): """ >>> decode('a;b;c') [('', 'a'), ('', 'b'), ('', 'c')] >>> decode('a;b;c;') [('', 'a'), ('', 'b'), ('', 'c')] """
5,306,852
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]: """ Returns a valid NHS number, as an ``int``, given the first 9 digits. The particular purpose is to make NHS numbers that *look* fake (rather than truly random NHS numbers which might accidentally be real). For examp...
5,306,853
def ios_application(name, apple_library = apple_library, infoplists_by_build_setting = {}, **kwargs): """ Builds and packages an iOS application. Args: name: The name of the iOS application. apple_library: The macro used to package sources into a library. infoplists_by_build_setting...
5,306,854
def passthrough_rest_object(source_url): """ Passes through a non-CORS locked down JSON object from the origin request. """ if request.method == 'GET': reqUrl = request.args.get('url','') req = requests.get(reqUrl) if req.status_code == 200: return req.content els...
5,306,855
def randint(low, high, shape, device=None): """Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive). Parameters ---------- low Lowest integer to be drawn from the distribution. high One above the highest integer to be drawn fr...
5,306,856
def construct_formula(label, rel_cols, label_side="l"): """ Constructs a generic formula string from column names and a label name. label ~ Col1+Col2+...+ColN :param label: Label or class which should be regressed for. (case/control, treatment/untreated etc.) :param rel_cols: Relevant columns for t...
5,306,857
def run_footprinting(data_file, pwm_idx, bam_files, out_dir, prefix, label_indices="", signal_matching_key="ATAC_SIGNALS.NORM"): """for a given motif, run footprinting and plots """ if label_indices != "": label_indices = "--labels_indices {}".format(label_indices) label_ind...
5,306,858
def shell_context(): # pragma: no cover """ Make shell context. :return: A dictionary of objects for use in shell context. :rtype: dict """ return {'DB': DB, 'IMBUser': IMBUser, 'Visit': Visit}
5,306,859
def start_new_session(self): """Starts a new session to be used to send requests and returns it.""" session = requests.Session() session.auth = (self._api_key, '') # pylint: disable=protected-access session.headers['User-Agent'] = config.constants.USER_AGENT session.proxies = PROXIES return ses...
5,306,860
def test_cutadapt_fq(expected_fixture, tmp_dir, sample): """ Test ``cutadapt`` FASTQ files for equality. See :py:func:`riboviz.fastq.equal_fastq`. :param expected_fixture: Expected data directory :type expected_fixture: str or unicode :param tmp_dir: Temporary directory, from configuration file...
5,306,861
def EvaluateMetricsAndPlots( # pylint: disable=invalid-name extracts: beam.pvalue.PCollection, eval_shared_model: types.EvalSharedModel, desired_batch_size: Optional[int] = None, metrics_key: Text = constants.METRICS_KEY, plots_key: Text = constants.PLOTS_KEY, compute_confidence_intervals: Opti...
5,306,862
def _find_first_common_next_vertex_in_edges__impl( g: Graph, es: List[Set[Union[Edge, None]]], map_of_visited: [List[Dict[int, int]]], allow_open_branches: bool, allow_loops: bool, vs_to_not_visit: List[int] = None, allow_loop_edges=True ) -> Union[None, List[Edge]]: """ :param g: Graph :par...
5,306,863
def catch_errors(exception=None, catch_generic=True, **kwargs): """ A decorator to preprocess an API class method, and catch a specific error. """ if exception is None: exception = RestApiException def decorator(func): @wraps(func) def wrapper(self, *args, **kwargs): ...
5,306,864
def set_alpha(n_points): """Set an alpha value for plotting that is scaled by the number of points. Parameters ---------- n_points : int Number of points that will be in the plot. Returns ------- alpha : float Value for alpha to use for plotting. """ for key, val i...
5,306,865
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the HomematicIP alrm control panel from a config entry.""" home = hass.data[HMIPC_DOMAIN][config_entry.data[HMIPC_HAPID]].home devices = [] for group in home.groups: if isinstance(group, AsyncSecurityZoneGroup): ...
5,306,866
def sendStart(sP): """this function will send 2 values: the x and y coordinates of the startpoint of the maze""" sPX, sPY = sP xpins = [gpio2] sendData([sPX], xpins, True) ypins = [gpio2, gpio1] sendData([sPY], ypins, True)
5,306,867
def test_indirect_inputs(client): """Test defining indirect inputs.""" path_1 = "/some/absolute/path" path_2 = "relative/path" path_3 = "a/path with white-spaces/" input_1 = Input(path_1) with Project() as project: input_2 = Input(path_2) input_3 = Input(path_3) assert Path(p...
5,306,868
def identify_days(year_string, date_list): """ The function takes a single integer number (4 digits) and returns all itEms of a list that have this number at the very beginning. :year_string: a string that is equivalent to a four digit integer :date_list: a list of dates or anything else, but we ar...
5,306,869
async def yükle(ctx, extension): """İstenilen,komut dosyalarını yükler.""" bot.load_extension(f'cogs.{extension}') await ctx.send(f'Komutlar başarıyla yüklendi {ctx.author}')
5,306,870
def test_center_gaussian(): """ Test the centering algorithm with Gaussian weighting """ ngau = 10 npix = 200 # Make a Gaussian comb with some random subpixel offsets xi = np.arange(ngau,npix,npix//ngau, dtype=float) xt = xi + np.round(np.random.normal(scale=1., size=xi.size), decimals=...
5,306,871
def run_build(command, *args, **kwargs): """ Run and report build command execution :param command: array of tokens :return: exit code of the process """ environment = kwargs.get('env', os.environ) logging.debug('run build %s, in environment: %s', command, environment) exit_code = subproces...
5,306,872
def split_nvr_epoch(nvre: str): """Split nvre to N-V-R and E. This function is backported from `kobo.rpmlib.split_nvr_epoch`. @param nvre: E:N-V-R or N-V-R:E string @type nvre: str @return: (N-V-R, E) @rtype: (str, str) """ if ":" in nvre: if nvre.count(":") != 1: ...
5,306,873
def findMergeNode(head1, head2): """ Go forward the lists every time till the end, and then jumps to the beginning of the opposite list, and so on. Advance each of the pointers by 1 every time, until they meet. The number of nodes traveled from head1 -> tail1 -> head2 -> intersection point and ...
5,306,874
def encode_pool_list(pool, normalize_by=None): """ Return a matrix X of `len(shape) * reduce(mul, shape)` columns and `pool.n` rows, encoding the payoffs of all the games in 'pool', and a vector Y, with `pool.n` rows, of integer "labels" representing which action was played for each example. The la...
5,306,875
def set_weights(): """Set weights for each digit in NHS number""" weights = [10, 9, 8, 7, 6, 5, 4, 3, 2] return np.array(weights)
5,306,876
def expand_and_broadcast(s1: Shape, s2: Shape): """Expand two shapes to make them of equal rank and then broadcast. Args: s1 (:class:`lab.shape.Shape`): First shape. s2 (:class:`lab.shape.Shape`): Second shape. Returns: :class:`lab.shape.Shape`: Expanded and broadcasted shape. ...
5,306,877
def BuildFactoryZip(buildroot, board, archive_dir, factory_shim_dir, version=None): """Build factory_image.zip in archive_dir. Args: buildroot: Root directory where build occurs. board: Board name of build target. archive_d...
5,306,878
def get_distribution_strategy(distribution_strategy="mirrored", tpu_address=None, **kwargs): """Returns a DistributionStrategy for running the model. Args: distribution_strategy: a string specifying which distribution strategy to use. Accepted v...
5,306,879
async def augment_chat( request_data: TextData, user: str = Path(default="default", description="user for which the chats needs to be log"), current_user: User = Depends(Authentication.get_current_user_and_bot) ): """ Fetches a bot response for a given text/query for user on path paramet...
5,306,880
def test_bpp_notifications(preauth_asgi_browser): """Sprawdz, czy notyfikacje dochodza. Wymaga uruchomionego staging-server. """ s = "test notyfikacji 123 456" assert preauth_asgi_browser.is_text_not_present(s) call_command( "send_notification", preauth_asgi_browser.authorized_us...
5,306,881
def py_mb_convert(file_location, file_extension): """ Convert files from one format to another with PyMOAB. Input: ______ file_location: str User supplied file location. file_extension: str User supplied file format to convert to, including '.' Returns: ____...
5,306,882
def _compress_image(buffer, compression="JPEG"): """ Compress array to specified format. >>> _compress_image(np.array([[0]]), 'JPEG') '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofH\ h0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/wAALCAABAAEBAREA/8QAHwAAAQUBAQEB\ AQEAAAAAAAAAA...
5,306,883
async def edit_bot(request: Request, user_id: int, bot_id: int, bot: BotMeta): """ Edits a bot, the owner here must be the owner editing the bot. Due to backward compatibility, this will return a 202 and not a 200 on success """ bot_dict = bot.dict() bot_dict["bot_id"] = bot_id bot_dict["use...
5,306,884
def sigfig(x, n): """ Produces x values to "n" significant figures From : https://stackoverflow.com/a/55599055 :param x: numpy array, the values to round :param n: int, the number of significant figures required :return: """ if isinstance(x, np.ndarray): xin = np.array(x) ...
5,306,885
def calc_SingleValueDiff(comp, opt, mtype='mean', ef=True): """ Computes a single value difference of the actual PALC results. Called by :any:`optimize_PALC` and :any:`diff_on_ls`. Parameters ---------- comp : list or 1D-array Computed PALC results in optimization region. opt : list...
5,306,886
def resnet_v1(input_shape, depth, num_classes=10, activation='relu'): """ResNet Version 1 Model builder [a] Stacks of 2 x (3 x 3) Conv2D-BN-ReLU Last ReLU is after the shortcut connection. At the beginning of each stage, the feature map size is halved (downsampled) by a convolutional layer with str...
5,306,887
def get_gains_check(speakers, position, sx, sy, sz): """call get_gains, and check that the return is normalised and positive""" g = get_gains(speakers, position, sx, sy, sz) assert np.all(g >= 0) npt.assert_allclose(np.linalg.norm(g), 1) return g
5,306,888
def test_opencv(): """ This function is workaround to test if correct OpenCV Library version has already been installed on the machine or not. Returns True if previously not installed. """ try: # import OpenCV Binaries import cv2 # check whether OpenCV Binaries are 3.x+ if parse_version(cv2.__v...
5,306,889
def test_asana_error_handler(caplog): """ Tests the `@asana_error_handler` decorator. """ caplog.set_level(logging.ERROR) def gen_text(text1, text2, text3): return f'{text1} | {text2} | {text3}' dec_gen_text = aclient.asana_error_handler(gen_text) assert dec_gen_text('one', text3='...
5,306,890
def test_to_json_two_pieces(): """test_to_json_with_a_board_with_two_pieces""" king = King() rook = Rook() board = Board(3, 4) board.put(king, 1, 1) board.put(rook, 2, 2) res = json.loads(board.to_json()) expected = json.loads('{"m": 4, "pieces": {"(2, 2)": "R", "(1, 1)": "K"}, "n": 3}')...
5,306,891
def finish_animation(sensehat): """Finish animation. Args: sensehat (SenseHat): """ x = (255, 255, 0) w = (255, 255, 255) o = (0, 0, 0) icon = [ o, o, x, x, x, x, o, o, o, x, x, x, x, x, x, o, x, x, w, x, x, w, x, x, x, x, x, x, x, x, x, x, x,...
5,306,892
def expandvars_dict(settings: dict) -> dict: """Expand all environment variables in a settings dictionary. ref: http://stackoverflow.com/a/16446566 :returns: Dictionary with settings """ return {key: _expandvars(value) for key, value in settings.items()}
5,306,893
def token_required(func): """ [x] - deprecated """ @functools.wraps(func) async def wrapper(self, text_data: str, *args, **kwargs): scope = getattr(self, "scope") user = AnonymousUser() if "user" in scope: user = scope["user"] # print('request dec id: ',...
5,306,894
def execute( method, max_retries, retry_interval, use_retry=True, *args, **kwargs ): """Execute HTTP request with retry support. Args: method (string): HTTP verb. use_retry (bool): If True, will use retry configuration (default: True). max_retries (in...
5,306,895
def stacked_sectors(df): """ Takes dataframe and sorts table fields by sector Parameters ---------- **df** : 'pd.df' Dataframe to be sorted by sector. Returns ------- **output** : 'pd.df' Dataframe of the table that was imported and split by sector """ ...
5,306,896
def stringify(num): """long int -> 20-character string""" str = hex(num)[2:] if str[-1] == 'L': str = str[:-1] if len(str) % 2 != 0: str = '0' + str str = str.decode('hex') return (20 - len(str)) *'\x00' + str
5,306,897
def load_object_lists(category=None): """ load object pathes according to the given category Args: category:a iterable object contains the category which we want render Returns: generator of gnerators of obj file pathes """ # type checking # not empty ...
5,306,898
def replace_esp_example_includes(line, source_path): """Updates any includes for local example files.""" # Because the export process moves the example source and header files out of # their default locations into the top-level 'main' folder in the ESP-IDF # project, we have to update any include references to ...
5,306,899