content
stringlengths
22
815k
id
int64
0
4.91M
def merged_stis_data(filename, extension=1): """Get spectrum data from all STIS spectral orders. If only filename is given, use SCI extension. Returns ------- wavs: numpy array, all wavelengths, sorted flux: all fluxes at these wavelengths errs: all errors at these wavelengths """ ...
5,287,000
def generate_tuples(parameters): """ :param parameters: :return: """ if len(parameters.keys()) % 2 != 0: parameters['dummy'] = [] keys = parameters.keys() max_0 = keys[0] max_1 = keys[1] for key in keys[1:]: if len(parameters[key]) >= len(parameters[max_0]): ...
5,287,001
def run_augment(*args, **kwargs): """Run augment routines.""" return estims_routine(**init_all(*args, routine='augment', **kwargs))
5,287,002
def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def remove_articles_ar(text): return re.sub('\sال^|ال', ' ', text) def white_space_fix(text): return ' '....
5,287,003
def check_prime(number): """ Checks if the given number is prime :param: number Number to evaluate for primality :rtype: bool True if the number is a prime, false otherwise """ for divisor in range(2, int(number**0.5) + 1): if number % divisor == 0: return False return Tr...
5,287,004
def hijack_log() -> StringIO: """Temporarily add a StringIO Output handler to the logger to retrieve log messages""" output = StringIO() stream = StreamHandler(output) formatter = Formatter('%(message)s') stream.setFormatter(formatter) LOGGER.addHandler(stream) yield output LOGGER.remove...
5,287,005
def is_higher_version( module_o_version: typing.Union[types.ModuleType, str, tuple[int, ...]], version: typing.Union[tuple[int, ...], str], /, *, sep: str = ".", keep_dev_version: bool = True, semver: bool = False, ) -> bool: """ MODULE_o_VERSION > VERSION Parameters -------...
5,287,006
async def test_form_invalid_game_name(hass: HomeAssistant) -> None: """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "fivem.fivem.FiveM.get_info_raw", return_value=_mock_fivem_inf...
5,287,007
def get_bot_and_update_from_args(args): """Find bot and update instance in the given args. Args: args(iterable): arguments to search for the bot and update. Returns: tuple. telegram.Bot. instance of bot that found in args. telegram.Upate. instance of update that found i...
5,287,008
def tally_date_handler(request: HttpRequest, enclosure_slug): """Called from tally page to change date tally""" # if it's a POST: pull out the date from the cleaned data then send it to "count" if request.method == "POST": form = TallyDateForm(request.POST) if form.is_valid(): t...
5,287,009
def parse_args(): """set and check parameters.""" parser = argparse.ArgumentParser(description="BRDNet process") parser.add_argument("--pipeline", type=str, default=None, help="SDK infer pipeline") parser.add_argument("--clean_image_path", type=str, default=None, help="root path of image without noise")...
5,287,010
def kldiv_normal(y, sigma): """ may be unstable because of often small length of y compared to the number of bins. """ delta = sigma/10 width = 10*sigma x = torch.arange(0, width, delta) x = torch.cat([-x.flip(0)[:-1], x]) p = (y.view(-1)-x.view(-1, 1)).div(delta).pow(2).mul(-0.5).ex...
5,287,011
def pngs_to_gif(): """ Creates gif for the von karman vortex street given the saved pngs """ # Create the frames frames = [] imgs = glob.glob(r"./figures/von_karman_vortex_shedding/all_png_parallel/*.png") regex = re.compile(r'\d+') numbers = [int(x) for img in imgs for x in regex.findal...
5,287,012
def calcDelta(r, x_e, n_ae): """ Calculate topocentric distance to the asteroid. Parameters ---------- r : float (1) Heliocentric/barycentric distance in arbitrary units. x_e : `~numpy.ndarray` (N, 3) Topocentric position vector in same units as r. n_ae : `~numpy.ndarray` (N...
5,287,013
def ParseModel(model): """Parses a model ID into a model resource object.""" return resources.REGISTRY.Parse( model, params={'projectsId': properties.VALUES.core.project.GetOrFail}, collection=MODELS_COLLECTION)
5,287,014
def verify_entity_type(entity_to_control_list: list, entity_type: str): """Verify intended entity type. Raise exception if the provided entity type is not expected. :type entity_to_control_list: ``list`` :param entity_to_control_list: Intended entity list to be verified. :type entity_type: ``str`` ...
5,287,015
def update_accordions(clicks): """create bot accordions""" acc_list = [] pair_count = 0 for i in tg_wrapper.helper.get_all_bot_list(): tg_wrapper.helper.read_data(i) state = "defaulted" if "botcontrol" in tg_wrapper.helper.data: state = tg_wrapper.helper.data["botcont...
5,287,016
def _app(ml_framework: str, *args, port: str = "8000"): """Transient app server for testing.""" process = subprocess.Popen( ["unionml", "serve", f"tests.integration.{ml_framework}_app.fastapi_app:app", "--port", port, *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) if l...
5,287,017
def is_bootstrap_started(): """Checks to see if bootstrap has started. Returns: True if the bootstrap has started, else False. """ return config_model.Config.get('bootstrap_started')
5,287,018
def get_feature(feature, first_stage): """FPN, C4, C5""" cfg = load_yml(feature_yml) key = f'{feature}-{first_stage}' return cfg.get(key, None)
5,287,019
def plotRatePSD(include=['eachPop', 'allCells'], timeRange=None, binSize=5, minFreq=1, maxFreq=100, transformMethod='morlet', stepFreq=1, NFFT=256, noverlap=128, smooth=0, norm=False, overlay=True, popColors=None, ylim=None, figSize=(10,8), fontSize=12, lineWidth=1.5, saveData=None, saveFig=None, showFig=True): """...
5,287,020
def recreate_dir(path): """ Recreate directory :param path: :return: """ if os.path.exists(path): shutil.rmtree(path) os.makedirs(path, mode=0o777)
5,287,021
def _evaluate_airy_function_at_point(x, y, z, wavelength, numerical_aperture, refractive_index): """ Evaluates the Airy point spread function at a point. Args: x: Float, x coordinate, in meters. y: Float, y coordinate, in meters. z: Float, z coordinate, in meters. wavelength...
5,287,022
def ge_in_wall_dimmer_switch_state_fixture(): """Load the ge in-wall dimmer switch node state fixture data.""" return json.loads(load_fixture("zwave_js/ge_in_wall_dimmer_switch_state.json"))
5,287,023
def synthetic_regression_5k_features(dataset_dir): """ Synthetic regression generator from sklearn http://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_regression.html TaskType:regression NumberOfFeatures:5000 NumberOfInstances:100K """ return datasets.make_regression(...
5,287,024
def genify(options_list, gen): """ Choose position from interval of discrete parameters based on gen value :param options_list: List of discrete values :param gen: DNA gen value :return: """ # Probability steps for projecting to given gen prob_step = 1 / len(options_list) for i in range(len(options_list)): ...
5,287,025
def to_int(value): """Return the absolute value.""" try: return int(float(value)) except (ValueError, TypeError): try: return int(float(value.replace(',','').replace('/','.').replace('\\','.'))) except Exception: return 0
5,287,026
def read_openssh_public_key(key_file): """ Convert an openssl formatted key into a pkcs#1 formatted key as used by our rsa library """ with open(os.path.expanduser(key_file), 'r') as file_handle: keydata = base64.b64decode(file_handle.read().split(None)[1]) parts = [] while keydata:...
5,287,027
def _writen(fd: int, data: bytes) -> None: """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:]
5,287,028
def getCharsSegments(rows, bounds): """ Gets the char segments of text row images acording to chars bounds. rows and bounds are list of the same matching sizes. Parameters ---------- rows(list) : The list of segmented text row images bounds(list) : Bounds matching chars iamges sizes in a t...
5,287,029
def make_lsgst_experiment_list(opLabelSrc, prepStrs, effectStrs, germList, maxLengthList, fidPairs=None, truncScheme="whole germ powers", keepFraction=1, keepSeed=None, includeLGST=True): """ Create a list of all the op...
5,287,030
def download_records(url: str, page_size: int, output_dir: Path, max_workers): """download catalogue records from the legacy SASDI Uses the legacy SASDI CSW interface to retrieve existing catalogue records with the csw:Record typename. """ with httpx.Client() as client: try: t...
5,287,031
def getArrDiffs(dataSet): """ Compares each successive number in a size n numpy array to its predecessor, generating a list of differences, returning a size (n - 1) numpy array. to a list. :param dataSet: A numpy array of numbers :return: An array containing the differences from the imput array....
5,287,032
def _decide_indices_order(indices): """ arrange indices such the first entry in list has smallest index, the second has the second smallest index """ indices = list(np.roll(indices, -np.argwhere(indices == np.min(indices))[0][0])) second_entry, last_entry = indices[1], indices[-1] if second_ent...
5,287,033
def figsize(*args, **kwargs): """ Set theme_figsize(...) as global plotnine.options + mpl.rcParams: - https://plotnine.readthedocs.io/en/stable/generated/plotnine.themes.theme.html - http://matplotlib.org/users/customizing.html Can be used either as a global mutation (`figsize(...)`) or a context m...
5,287,034
def new_compoent(): """add a new compoent to the system""" mycontext[2] = {} code_loc = "liblind/com2.nexe" mycontext[2][PROGRAM] = code_loc mycontext[2][CMD_LINE] = [] setup_dispatcher(2) setup_filetable(2) setup_component_communication(2) nacl = safelyexecutenativecode(code_loc, []) if nacl !...
5,287,035
def percent(mylist, item): """Return the percentage of an item of a list. :param mylist: (list) list of elements :param item: (any) an element of the list (or not!) :returns: percentage (float) of item in mylist """ return 100.0 * freq(mylist, item)
5,287,036
def raise_alpaca_if(n, m): """If non-zero Alpaca error, raise the appropriate Alpaca exception Parameters: n: Error number from JSON response m: Message text for exception Returns: Nothing if n==0, raises if n != 0 Note: * If an unassigned error code in the range 0x400...
5,287,037
def setup(bot) -> None: """ Bind this cog to the bot """ bot.add_cog(Confessions(bot))
5,287,038
def load_cat_to_name(json_path): """Load Label Name from JSON file.""" with open(json_path, 'r') as f: cat_to_name = json.load(f) return cat_to_name
5,287,039
def dtc(messages): """ converts a frame of 2-byte DTCs into a list of DTCs """ codes = [] d = [] for message in messages: d += message.data # look at data in pairs of bytes # looping through ENDING indices to avoid odd (invalid) code lengths for n in range(1, len(d), 2): # ...
5,287,040
def id_overlap_count(input_ids: ListColumn, matching_ids: ListColumn): """ Returns the number of overlaps between two lists of ids Parameters --------- input_ids: First list of ids matching_ids: Second list of ids Examples ------- >>> import torcharrow as ta >>> from torcharrow...
5,287,041
def run_training(): """Train MNIST for a number of steps.""" # Get the sets of images and labels for training, validation, and # test on IndianPines. dataset = HoustonDataset.Houston() train_img = dataset.get_patches(PATCH_SIZE, Train=True, PCA=False, LiDAR=False) test_img = dataset.get_...
5,287,042
def BLVGG(input_tensor, first_filter, hidden_filter, first_dilation, num_classes): """ Build the baseline VGG model :param input_tensor: input tensor :param first_filter: number of first filters :param hidden_filter: number of hidden filters :param first_dilation: number of first dilati...
5,287,043
def get_plot(request): """Return a PNG plot of the requested PBS Daily QA data.""" # Get the primary key for the test instance and obtain the filenames pk = get_value_from_request(request, 'id', 0) tests = models.TestInstance.objects.filter( test_list_instance_id=pk ).values('string_value',...
5,287,044
def _mined_attributes_required() -> bool: """Returns True if mined attributes will be required for this batch. Returns: True if mined attributes will be required for the optimizers being run in this batch, false otherwise. """ for optimizer_parameter in _OPTIMIZERS_THAT_USE_MINED_ATTRIBUTES: if _ex...
5,287,045
def multi_blend(arrays, colors, alphas=None, modes=None, input_max=1, color_max=1): """Composite one or more one-channel images atop one another, colorizing each. The arrays will be blended in reverse order: arrays[0] will be the base and arrays[-1] will be the top image. Parameters: arrays: l...
5,287,046
def plot_3d(df, target_variable): """ 3d plot of data frame columns :param df: pandas.DataFrame :param target_variable: pandas.Series :return: None """ unique_labels = target_variable.unique() ordinal_encoding = [np.where(unique_labels == label)[0][0] for label in...
5,287,047
def user_albums_query(user_id: str, page_number: int) -> dict: """ Build User albums query. :param user_id: User id :param page_number: page number :return: Query """ return { "id": 8, "operationName": "AlbumList", "query": "query AlbumList($input: AlbumListInput!) {album {list(input: $input) ...
5,287,048
def _consts(fn: typing.Callable) -> tuple: """ Returns a tuple of the function's constants excluding the docstring. """ return tuple(x for x in fn.__code__.co_consts if x != fn.__doc__)
5,287,049
def test_plotter_save_defaults(file_regression): """ Test adding of custom parameters """ import tempfile p = Plotter(TEST_DICT) p.set_defaults(continue_on_error=True, **{'B': 0, 'A': {'test3': 'extra'}, 'D': 'not a key'}) with tempfile.NamedTemporaryFile('r') as file: p.save_defa...
5,287,050
def suite(): """ This method must be included at the end of all sub-test modules. To use in other modules, copy this entire method to the new module. :return: (unittest.TestSuite) Test suite for this sub-test """ tests = inspect.getmembers(sys.modules[__name__], inspect.isclass) loader = uni...
5,287,051
def x_y_to_name(x, y) -> str: """ Make name form x, y coords Args: x: x coordinate y: y cooridante Returns: name made from x and y """ return f"{x},{y}"
5,287,052
def database(): """ Get all raw database details.""" data = db.DB().db_get() return data
5,287,053
def read_vasp_xml(filename='vasprun.xml', index=-1): """Parse vasprun.xml file. Reads unit cell, atom positions, energies, forces, and constraints from vasprun.xml file """ import numpy as np import xml.etree.ElementTree as ET from ase import Atoms from ase.constraints import FixAtoms,...
5,287,054
def indice_PM10(fila, columna): """Cálculo del índice de calidad del aire para el PM10 (usando datos de micro gramo sobre metro cúbico). Las operaciones que se realizan aquí son una normalización para que cada contaminante se mida de acuerdo al índice de calidad del aire. Esta función se ocupa de calcular ...
5,287,055
def sigmoid_cross_entropy_balanced_back(logits, label, name='cross_entropy_loss'): """ Implements Equation [2] in https://arxiv.org/pdf/1504.06375.pdf Compute edge pixels for each training sample and set as pos_weights to tf.nn.weighted_cross_entropy_with_logits """ y = tf.cast(label, tf.float32...
5,287,056
def infer_table_schema_type_from_rdf_term(term_type, term_datatype): """Map an RDF literal type to Table Schema field type :param term_type: type from RDF term :param term_datatype: datatype from RDF term """ if (term_type == 'literal' and term_datatype is not None): return _RDF...
5,287,057
def _is_relative_length_valid(acro: str, full: str) -> bool: """ Check whether the relative length of acronym to full form are within reasonable bounds. A full form can be up to 20 times longer than the acronym and the acronym has to be at most 60% of the full form. According to analysis of `acro_...
5,287,058
def _driz_cr(sciImage, virtual_outputs, paramDict): """mask blemishes in dithered data by comparison of an image with a model image and the derivative of the model image. - ``sciImage`` is an imageObject which contains the science data - ``blotImage`` is inferred from the ``sciImage`` object here which...
5,287,059
def _lvl_error(level): """Get the lng/lat error for the hilbert curve with the given level On every level, the error of the hilbert curve is halved, e.g. - level 0 has lng error of +-180 (only one coding point is available: (0, 0)) - on level 1, there are 4 coding points: (-90, -45), (90, -45), (-90, 4...
5,287,060
def make_lowshelf( frequency: int, samplerate: int, gain_db: float, q_factor: float = 1 / sqrt(2) ) -> IIRFilter: """ Creates a low-shelf filter >>> filter = make_lowshelf(1000, 48000, 6) >>> filter.a_coeffs + filter.b_coeffs # doctest: +NORMALIZE_WHITESPACE [3.0409336710888786, -5.60887099222...
5,287,061
def pixelplt( array, xmin, xmax, ymin, ymax, step, vmin, vmax, title, xlabel, ylabel, vlabel, cmap, fig_name, ): """Pixel plot, reimplementation in Python of GSLIB pixelplt with Matplotlib methods. :param array: ndarray :param xmin: x axis minimum...
5,287,062
def test_ncclient_help_call(): """ Test dir method call ret should look like:: nrp1: ---------- ceos1: ---------- help: Module: nornir_salt Task plugin: ncclient_call Pl...
5,287,063
def prepare_wikidata_completion(qid=None, pid=None, is_category=False): """ Get the subject's label, Wikipedia article, and get property's label to construct the question :param qid: Entity Id starts with Q :param pid: Property Id starts with P :param is_category: flag indicates if qid is a cate...
5,287,064
def _kron_1d(a, b): """This function is for internal use. Returns a⊗b for 1d array. """ nb = b.size d = np.repeat(a, nb).reshape(-1, nb) d *= b return d.reshape(-1)
5,287,065
def micromanager_metadata_to_coords(summary, n_times=None, z_centered=True): """ Given the 'Summary' dict from micromanager, parse the information into coords for a corresponding DataArray. Parameters ---------- summary : dict Micromanager metadata dictionary. n_times : int ...
5,287,066
def create_tarfile(files, tar_path): """Create a tar file based on the list of files passed""" with tarfile.open(tar_path, "w:gz") as tar: for f in files: tar.add(f)
5,287,067
def problem1(limit, mod1, mod2): """Problem 1""" result = 0 for cur in range(0, limit): if cur % mod1 == 0 or cur % mod2 == 0: result += cur return result
5,287,068
def load_all_plugins(): """None""" pass
5,287,069
def arrayuniqify(X, retainorder=False): """ Very fast uniqify routine for numpy arrays. **Parameters** **X** : numpy array Determine the unique elements of this numpy array. **retainorder** : Boolean, optional Whether or not to return in...
5,287,070
def test_ill_conditioned_matrix( A: np.ndarray, A_eigh: Tuple[np.ndarray, np.ndarray], L: np.ndarray, method_kwargs: Dict[str, Any], ): """Tests whether the algorithm still works if the downdate blows up the condition number of the updated matrix.""" spectrum, Q = A_eigh # Generate adve...
5,287,071
def atmDensPoly6th(ht, dens_co): """ Compute the atmosphere density using a 6th order polynomial. This is used in the ablation simulation for faster execution. Arguments: ht: [float] Height above sea level (m). dens_co: [list] Coeffs of the 6th order polynomial. Return: a...
5,287,072
def create_multiple_images(sqla, n): """Commit `n` new images (up to len(valid_paths) to the database. Return their IDs.""" image_schema = ImageSchema() new_images = [] for i in range(n): if (i < num_valid_images): valid_images = image_schema.load(image_object_factory(sqla)) ...
5,287,073
def test_row_roundtrip_small(): """Test row_roundtrip.""" og_sample = np.asarray( np.random.normal(size=(3)), dtype=np.float64, order='F' ) sample = og_sample.copy() out = carma.row_roundtrip(sample) assert np.allclose(og_sample, out)
5,287,074
def render_product(context, product): """ Render a product snippet as you would see in a browsing display. This templatetag looks for different templates depending on the UPC and product class of the passed product. This allows alternative templates to be used for different product classes. ...
5,287,075
def filter_exitrons(exitrons, reads, bamfile, genome, db, skip_realign, mapq=50, pso_min=0.01, ao_min=2, cluster_purity=0, jitter=10): """ Parameters ---------- exitrons : list list of unfiltered exitrons from exitron_caller. reads : dict Each intron is a key, and the value is list o...
5,287,076
def test_non_manifest(monkeypatch, pack_workbench, exopy_qtbot): """Test handling a non PluginManifest in the list of manifests. """ patch_pkg(monkeypatch, [FalseEntryPoint(name='test', manifests=[Manifest1, object]), FalseEntryPoint(n...
5,287,077
def get_bias_initializer(name: str, dtype=jnp.float32) -> WeightInitializer: """Get a bias initializer.""" validate_bias_initializer(name) return INITIALIZER_CONSTRUCTORS[name](dtype=dtype)
5,287,078
def raw_fashion_train_images_file(): """ Train images of MNSIT. :return: filepath :rtype: str """ return data_file('fashion/train-images-idx3-ubyte', GZIP_EXT)
5,287,079
def comment_staticman(github_token, ci_data): """Sequence of functions to get data from github for staticman comment and then write the comment to github """ return sequence( pr_url, requests_get(github_token), lambda x: x.json(), get("body"), archieml.loads, ...
5,287,080
def get_file_name() -> str: """ Creates a unique file name for datastore by appending timestamp to the file name :return: """ import uuid uniq_append_string = uuid.uuid4().hex return "LOCAL_STORAGE_{}".format(uniq_append_string)
5,287,081
def _check_shift_reduce_conflicts(shifts, reductions): """ Check for conflicts between a shift table and a reduce table """ for item_set_shifts, item_set_reductions in zip(shifts, reductions): if set.intersection(set(item_set_shifts), set(item_set_reductions)): raise ShiftReduceConfl...
5,287,082
def requires_auth(function): """ :param function: :return: the validity of a request """ @wraps(function) def decorated(*args, **kwargs): p_access = False auth_token = False if not auth_token: auth_token = request.header.get('Authorization') if not aut...
5,287,083
def xyxy2xywh(box2d): """ input : [n, 4] [x1, y1, x2, y2] return : [n, 4] [x, y, w, h] compatible with both pytorch and numpy a faster dedicated numpy implementation can be found at lib/fast_util/bbox2d.py """ center_x = 0.5 * (box2d[:, 0] + box2d[:, 2]) center_y = 0....
5,287,084
def auth_npubs_retrieve_insert(auth_id, year, conn): """Retrieve an author's publication count until a given year, and insert.""" from sosia.processing.querying import base_query q = f"AU-ID({auth_id}) AND PUBYEAR BEF {year+1}" npubs = base_query("docs", q, size_only=True) tp = (auth_id, year, npub...
5,287,085
def back_url(request): """后台通知地址 :param request: :return: """ return HttpResponse("Hello back_url")
5,287,086
def test_substance_display_name_populated(client, admin_user, substance_factory): """ This test verifies that when a Substance is created and the display_name is not set to null, the result should not be modified and should be equal to that of the factory""" client.force_authenticate(user=admin_user) su...
5,287,087
def SignedCharCast(value): """Explicitly cast a value to type 'signed char'.""" shift = ConstInt(24) return RShift(LShift(value, shift), shift)
5,287,088
def get_nested_plot_frame(obj, key_map, cached=False): """Extracts a single frame from a nested object. Replaces any HoloMap or DynamicMap in the nested data structure, with the item corresponding to the supplied key. Args: obj: Nested Dimensioned object key_map: Dictionary mapping bet...
5,287,089
def __str_to_hash(string_to_hash: str, errors: str = 'ignore') -> str: """ Encodes the given string and generates a hash from it. """ string_hash = string_to_hash.encode(encoding="utf-8", errors=errors) return hashlib.md5(string_hash).hexdigest()
5,287,090
def zeros(shape, dtype, force_cpu=False): """ The OP creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0. Its :attr:`stop_gradient` will be set to True to stop gradient computation. Parameters: shape (tuple|list): Shape of output tensor. dtype (np.dtype|co...
5,287,091
def get_editors(ref_string): """ returns list of editors, which can appear anywhere in the reference :param ref_string: :return: """ if isinstance(ref_string, unicode): ref_string = unidecode.unidecode(ref_string) lead_match = LEADING_INIT_AUTHORS_PAT.search(ref_string) trail_m...
5,287,092
def extract_ta_features(stock_df): """Compute features using TA's technical indicators.""" initial_len = len(stock_df) stock_df = ta.add_trend_ta(stock_df, high="High", low="Low", close="Close") stock_df = ta.add_momentum_ta( stock_df, high="High", low="Low", close="Close", volume="Volume" ...
5,287,093
def user_pk_to_url_str(user): """ This should return a string. """ User = get_user_model() if (hasattr(models, 'UUIDField') and issubclass( type(User._meta.pk), models.UUIDField)): if isinstance(user.pk, six.string_types): return user.pk return user.pk.hex ...
5,287,094
def _get_coords(xedges, yedges): """Get coordinates given the edges of the histogram.""" global XBUFFER, YBUFFER if XBUFFER is None: xcenters = (xedges[:-1] + xedges[1:]) / 2 ycenters = (yedges[:-1] + yedges[1:]) / 2 X, Y = np.meshgrid(xcenters, ycenters) XBUFFER = X ...
5,287,095
def log_internal_error(out=sys.stderr, etype=None, evalue=None, tb=None): """Print internal error message (output defaults to stderr).""" print(os.linesep, file=out) print("""********** Oops, I did it again. ************* You have found an internal error in %(app)s. Please write a bug report at %(url)s and...
5,287,096
async def delete_metadata_obj(app, obj_id, notify=True, root_id=None, bucket=None): """ Delete the given object """ meta_cache = app['meta_cache'] dirty_ids = app["dirty_ids"] log.info(f"delete_meta_data_obj: {obj_id} notify: {notify}") if isValidDomain(obj_id): bucket = getBucketForDomain(o...
5,287,097
def get_information_from_certificate(certificate): """ Extract user information from a client certificate :param certificate: The certificate :return: """ if not certificate: return None, None # open certificate cert_chain = X509CertChain() try: cert_chain.parsePemLi...
5,287,098
def dump_cwa(fn): """WFOs.""" pgconn = get_dbconn("postgis", user="nobody") df = read_postgis( """ SELECT wfo, ST_Multi(ST_Buffer(ST_Simplify(the_geom, 0.01), 0)) as geom, ST_x(ST_Centroid(the_geom)) as lon, ST_Y(ST_Centroid(the_geom)) as lat, region from cwa...
5,287,099