content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def condense_colors(svg): """Condense colors by using hexadecimal abbreviations where possible. Consider using an abstract, general approach instead of hard-coding. """ svg = re.sub('#000000', '#000', svg) svg = re.sub('#ff0000', '#f00', svg) svg = re.sub('#00ff00', '#0f0', svg) ...
413f1d7c69a52384fc21ee6f8eda6f2a63833e66
3,642,254
import attr def install_pytest_confirmation(): """Ask if pytest should be installed""" return f'{fg(2)} Do you want to install pytest? {attr(0)}'
b81da35d4eb7e755f7780cf0b6da056096613549
3,642,255
def rgb(r=0, g=0, b=0, mode='RGB'): """ Convert **r**, **g**, **b** values to a `string`. :param r: red part :param g: green part :param b: blue part :param string mode: ``'RGB | %'`` :rtype: string ========= ============================================================= mode ...
563b8fe8273ce4534567687df01cebe79b9f58dc
3,642,257
def load_csv_translations(fname, pfx=''): """ Load translations from a tab-delimited file. Add prefix to the keys. Return a dictionary. """ translations = {} with open(fname, 'r', encoding='utf-8-sig') as fIn: for line in fIn: line = line.strip('\r\n ') if len(lin...
e8b4707fe5eeb0f0f4f4859bd9a5f2272387a022
3,642,258
def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4): """ Compute bleu and rouge scores. """ assert set(pred_dict.keys()) == set(ref_dict.keys()), \ "missing keys: {}".format(set(ref_dict.keys()) - set(pred_dict.keys())) scores = {} bleu_scores, _ = Bleu(bleu_order).compute_score(re...
b000f97208fc8254e28ebc85501912e568c7b2d7
3,642,259
from datetime import datetime def check_upload_details(study_id=None, patient_id=None): """ Get patient data upload details """ participant_set = Participant.objects.filter(patient_id=patient_id) if not participant_set.exists() or str(participant_set.values_list('study', flat=True).get()) != study_id: ...
6611e9235a6085635e19a9cad8e1920adb757a87
3,642,260
def crc32c_rev(name): """Compute the reversed CRC32C of the given function name""" value = 0 for char in name: value ^= ord(char) for _ in range(8): carry = value & 1 value = value >> 1 if carry: value ^= CRC32_REV_POLYNOM return value
0aea3d45c0efc136be56bac2ee44ba8e08945de3
3,642,261
def sils_cut(T,f,c,d,h): """solve_sils -- solve the lot sizing problem with cutting planes - start with a relaxed model - add cuts until there are no fractional setup variables Parameters: - T: number of periods - P: set of products - f[t]: set-up costs (on period t) ...
ca689370fe928b38cdd96cdd7b227699f0979a1c
3,642,262
def progressive_fixed_point(func, start, init_disc, final_disc, ratio=2): """Progressive fixed point calculation""" while init_disc <= final_disc * ratio: start = fixedpoint.fixed_point(func, start, disc=init_disc) init_disc *= ratio return start
d46d325bdc3ddb1c5627e231f9659e992a9a0748
3,642,263
import json async def create_new_game(redis: Redis = Depends(redis.wrapper.get)): """Create a new game with an unique ID.""" game = get_new_game() handle_score(game) game_dict = game_to_dict(game) game_id = token_urlsafe(32) await redis.set(game_id, json.dumps(game_dict)) return GameState(...
45de279daba553d4e722f64d0ccb921f90332112
3,642,264
def _write_reaction_lines(reactions, species_delimiter, reaction_delimiter, include_TS, stoich_format, act_method_name, ads_act_method, act_unit, float_format, column_delimiter, sden_operation, **kwargs): """Writ...
9787279dee81cd97922657739975c93fcbed8249
3,642,265
def refines_constraints(storage, constraints): """ Determines whether with the storage as basis for the substitution map there is a substitution that can be performed on the constraints, therefore refining them. :param storage: The storage basis for the substitution map :param constraints: The const...
de82087c41d95240ee9d15bd51810b7c5594ef0f
3,642,266
def dot_fp(x, y): """Dot products for consistent scalars, vectors, and matrices. Possible combinations for x, y: scal, scal scal, vec scal, mat vec, scal mat, scal vec, vec (same length) mat, vec (n_column of mat == length of vec) Warning: No broadca...
d1bf8bd32727973ebb65ead39921202bfd842973
3,642,267
def add_one(num: int) -> int: """Increment arg by one.""" return num + 1
72d8ff69fa5766e813f637f9796753ae51e493b9
3,642,268
def normalize(data, train_split): """ Get the standard score of the data. :param data: data set :param train_split: number of training samples :return: normalized data, mean, std """ mean = data[:train_split].mean(axis=0) std = data[:train_split].std(axis=0) return (data - mean) / std,...
cfc45ac5bd6ae7a30169253a1ae3ed64c1bd1118
3,642,269
def lemma(name_synsets): """ This function return lemma object given the name. .. note:: Support only English language (*eng*). :param str name_synsets: name of the synset :return: lemma object with the given name :rtype: :class:`Lemma` :Example: ...
84a9ae7dbb1679477257ff03557afa75f950a542
3,642,270
def export_cookies(domain, cookies, savelist=None, sp_domain=None): """ Export cookies used for remembered device/other non-session use as list of Cookie objects. Only looks in jar matching host name. Args: domain (str) - Domain to select cookies from cookies (requests.cookies.Requests...
7609ac6452ed49dae5cd66f280bbeb4b27b17034
3,642,271
from typing import Tuple from typing import OrderedDict def adaptive_crossover(parents: Tuple[AbstractSolution, AbstractSolution], variables_number: int, crossover_pattern: int) -> ChildrenValuesTyping: """ Adaptive crossover function. Crossover is performed ...
76446c9c35739dddd9bfb797379b44616c552bbd
3,642,272
def get_type_dict(kb_path, dstc2=False): """ Specifically, we augment the vocabulary with some special words, one for each of the KB entity types For each type, the corresponding type word is added to the candidate representation if a word is found that appears 1) as a KB entity of that type, ""...
cd35054505c429cc1ad17eabe1cafb1aa6b38a1f
3,642,273
def parse_time(duration: str, minimum: int = None, maximum: int = None, error_on_exceeded: bool = True) -> int: """Function that parses time in a NhNmNs format. Supports weeks, days, hours, minutes and seconds, positive and negative amounts and max values. Minimum and maximum values can be set (in seconds), and...
9878d744cd9cc60696d414a31ff121e384e261a9
3,642,274
def get_fragment_mz_dict(pep, fragments, mod=None): """ :param pep: :param fragments: :param mod: :return: """ mz_dict = dict() for each_fragment in fragments: frag_type, frag_num, frag_charge = rapid_kit.split_fragment_name(each_fragment) mz_dict[each_fragment] = calc_fr...
ffc79c35111548471a3a98f5999dee013975752d
3,642,276
def merge_dicts(iphonecontrollers, ipadcontrollers): """Add ipad controllers to the iphone controllers dict, but never overwrite a custom controller with None!""" all_controllers = iphonecontrollers.copy() for identifier, customclass in ipadcontrollers.items(): if all_controllers.get(identifier) is ...
10638e775d6578e2553ff5b2b47aff8a17051c7e
3,642,277
def perimRect(length,width): """ Compute perimiter of rectangle >>> perimRect(2,3) 10 >>> perimRect(4, 2.5) 13.0 >>> perimRect(3, 3) 12 >>> """ return 2*(length+width)
50fdd92430352f443d313d0931bab50ad5617622
3,642,278
def add_deprecated_species_alias(registry, ftype, alias_species, species, suffix): """ Add a deprecated species alias field. """ unit_system = registry.ds.unit_system if suffix == "fraction": my_units = "" else: my_units = unit_system[suffix] def _dep_field(field, data): ...
2782079c908227d11780f66fb2d809b69680a31a
3,642,281
def docker_client(): """ Return the current docker client in a manner that works with both the docker-py and docker modules. """ try: client = docker.from_env(version='auto', timeout=3600) except TypeError: # On older versions of docker-py (such as 1.9), version isn't a #...
7761299ea845577d67815df9fdd98dd74e828454
3,642,282
import typing import copy def bulk_generate_metadata(html_page: str, description: dict=None, enable_two_ravens_profiler=False ) -> typing.List[typing.List[dict]]: """ :param html_page: :param description: :param es_index...
333d4ce53eac5b7214d516a09c5070b718b7a165
3,642,283
def add_cals(): """ Add nutrients from products. """ if 'username' in session: user_obj = users_db.get(escape(session['username'])) calc = Calculator(user_obj.weight, user_obj.height, user_obj.age, user_obj.gender, user_obj.activity) food = request.form....
f052b1d314fa3005f7bcd74b5890dba049bb3827
3,642,284
def parse(q): """http://en.wikipedia.org/wiki/Shunting-yard_algorithm""" def _merge(output, scache, pos): if scache: s = " ".join(scache) output.append((s, TOKEN_VALUE, pos - len(s))) del scache[:] try: tokens = lex(q) except Exception as e: ...
484b240d1ec2cea3cf553bcbac5bef33efd1f74a
3,642,285
def CheckChangeOnUpload(input_api, output_api): """Presubmit checks for the change on upload. The following are the presubmit checks: * Check change has one and only one EOL. """ results = [] results.extend(_CommonChecks(input_api, output_api)) # Run on upload, not commit, since the presubmit bot apparen...
4791e348cfa7e4e1d25341bf44f8ddb8c8a84d4e
3,642,286
def compute_compression_rate(file: str, zip_archive) -> float: """Compute the compression rate of two files. More info: https://en.m.wikipedia.org/wiki/Data_compression_ratio :param file: the uncompressed file. :param zip_archive the same file but compressed. :returns the compre...
f92f81282b51da253b1f06ad63d72555917b8256
3,642,287
def set_idc_func_ex(name, fp=None, args=(), flags=0): """ Extends the IDC language by exposing a new IDC function that is backed up by a Python function This function also unregisters the IDC function if 'fp' was passed as None @param name: IDC function name to expose @param fp: Python callable tha...
fe3656d7e33285eecc79b497866529e81ff15e64
3,642,288
from typing import Dict def get_hidden_plugins() -> Dict[str, str]: """ Get the dictionary of hidden plugins and versions. :return: dict of hidden plugins and their versions """ hidden_plugins = get_cache('cache/hidden-plugins.json') if hidden_plugins: return hidden_plugins else: ...
bf4db552411576a4840b72e2e10aab25030d6191
3,642,289
import time def wait_for_re_doc(coll, key, timeout=180): """Fetch a doc with the RE API, waiting for it to become available with a 30s timeout.""" start_time = time.time() while True: print(f'Waiting for doc {coll}/{key}') results = re_client.get_doc(coll, key) if results['count'] ...
0aa70ddd010f2d60ef2340d17ddf94b8660d0f1c
3,642,290
def split_year_from_week(data: pd.DataFrame) -> pd.DataFrame: """ Because we have used the partition key as the NFL year, the year/week need to be put into the appropriate columns """ data[[Stats.YEAR, Stats.NFL_WEEK]] = data[Stats.YEAR].str.split("/", expand=True) data[Stats.NFL_WEEK] = data[Stats....
52e65d28b3169759e949725b17d159d319514a61
3,642,291
from .core import Array, from_array def normalize_index(idx, shape): """Normalize slicing indexes 1. Replaces ellipses with many full slices 2. Adds full slices to end of index 3. Checks bounding conditions 4. Replace multidimensional numpy arrays with dask arrays 5. Replaces numpy array...
63b98679ca435a238682d86124d6a60e81dd1f89
3,642,292
def relu(data): """Rectified linear unit. .. math:: out = max(x, 0) Parameters ---------- data : relay.Expr The input data Returns ------- result : relay.Expr The computed result. """ return _make.relu(data)
3c4602d68ca18a851ed6c24a35c348b1a97a2a4d
3,642,293
def levsim(args): """Returns the Levenshtein similarity between two terms.""" term_i, term_j, j = args return (MLEV_ALPHA * (1 - Levenshtein.distance(term_i, term_j) \ / max(len(term_i), len(term_j)))**MLEV_BETA, term_j, j)
5c4c70cbf0c172ac42ad26d15753a18e79fdd1f4
3,642,294
def retrieve_job_logs(job_id): """Retrieve job's logs. :param job_id: UUID which identifies the job. :returns: Job's logs. """ return JOB_DB[job_id].get('log')
b2759f3af8316272c4f4ef7f63939634a114c0c9
3,642,295
def _normalize_format(fmt): """Return normalized format string, is_compound format.""" if _is_string_or_bytes(fmt): return _compound_format(sorted( _factor_format(fmt.lower()))), ',' in fmt else: return _compound_format(sorted([_normalize_format(f)[0] for f in...
30094ec1b00205ae321a53f1bcba3ae250cd740d
3,642,297
def get_cevioai_version() -> str: """ CeVIO AIのバージョンを取得します。 Returns ------- str CeVIO AIのバージョン """ _check_cevioai_status() return _service_control.host_version
1186878664776d445402d04251bec140cda3390a
3,642,298
def handle_player_dead_keys(key): """ The set of keys for a dead player. Can only see the inventory and toggle fullscreen. """ key_char = chr(key.c) if key.vk == libtcod.KEY_CHAR else "" if key_char == 'i': return {'show_inventory': True} if key.vk == libtcod.KEY_ENTER and key.la...
35f6288e7e830c36b163cd762a3a53531bbee394
3,642,302
def safe_std(values): """Remove zero std values for ones.""" return np.array([val if val != 0.0 else 1.0 for val in values])
ab09a435393ea8025af966f4b464e088dce7a00b
3,642,303
def _munge_source_data(data_source=settings.NETDEVICES_SOURCE): """ Read the source data in the specified format, parse it, and return a :param data_source: Absolute path to source data file """ log.msg('LOADING FROM: ', data_source) kwargs = parse_url(data_source) path = kwargs.pop...
bda1261e3cf914402aa4e7b4e49f523088da1fe9
3,642,304
def create_app(settings_override=None): """ Create a flask application using the app factory pattern :return: Flask app """ app = Flask(__name__, instance_relative_config=True) app.config.from_object('config.settings') app.config.from_pyfile('settings.py', silent=True) if setting...
de3dbd009b67cfabd37e71063dc3d2b925b08cb6
3,642,305
def convex_hull(ps: Polygon) -> Polygon: """Andrew's algorithm""" def construct(limit, start, stop, step=1): for i in range(start, stop, step): while len(res) > limit and cross(res[-1] - res[-2], s_ps[i] - res[-1]) < 0: res.pop() res.append(s_ps[i]) assert l...
4cdf71cdb65e838f6ef2b4617237d483257364df
3,642,306
def get_api_file_url(file_id): """Get BaseSpace API file URL.""" api_url = get_api_url() return f'{api_url}/files/{file_id}'
eff39b6dc2470f4217b8190104b3efb7c532f995
3,642,307
def Tr(*content, **attrs): """ Wrapper for tr tag >>> Tr().render() '<tr></tr>' """ return KWElement('tr', *content, **attrs)
30b3cd48fb96a0d7d04f5deebe85f4de77d82126
3,642,308
import numpy def _read_storm_locations_one_time( top_tracking_dir_name, valid_time_unix_sec, desired_full_id_strings): """Reads storm locations at one time. K = number of storm objects desired :param top_tracking_dir_name: See documentation at top of file. :param valid_time_unix_sec: Valid t...
7867d2a36b71d0ab0c4d694e617cabe2aa960e92
3,642,309
def ja_il(il, instr): """ Returns llil expression to goto target of instruction :param il: llil function to generate expression with :param instr: instruction to pull jump target from :return: llil expression to goto target of instr """ label = valid_label(il, instr.ja_target) return il....
9eb18f9b709c960467d9c6a9d9cbed0d7619c5fe
3,642,310
def create_plot_durations_v_nrows(source, x_axis_type='log', x_range=(1, 10**5), y_axis_type='log', y_range=(0.001, 10**3)): """ Create a Bokeh plot (Figure) of do_query_dur and stream_to_file_dur versus num_rows. num_rows is the number of result rows from the query. P...
2c018a68d521ba7116086f4d9f2fb015c4f584d8
3,642,311
from auroraapi.text import Text import functools def listen_and_transcribe(length=0, silence_len=0.5): """ Listen with the given parameters, but simulaneously stream the audio to the Aurora API, transcribe, and return a Text object. This reduces latency if you already know you want to convert the speech to text. ...
2807b00fc760d4767c211ba168ac38dc793743aa
3,642,312
def load_test_dataframes(feature_folder, **kwargs): """ Convenience function for loading unlabeled test dataframes. Does not add a 'Preictal' column. :param feature_folder: The folder to load the feature data from. :param kwargs: keyword arguments to use for loading the features. :return: A DataFra...
69d503c61ec752ed640c9416f7d2292788389aee
3,642,313
import random def _match_grid(grid): """ given a grid, create the other side to obey: one p1 black must be a p2 green, tan, and black; and vice versa """ l = [""] * 25 color_dict = { "b": [i for i in range(25) if grid[i] == "b"], "t": [i for i in range(25) if grid[i] =...
83b2ee7ac92c5f5d085cd5da11fff7132449736e
3,642,314
def add_vary_callback_if_cookie(*varies): """Add vary: cookie header to all session responses. Prevent downstream web serves to accidentally cache session set-cookie reponses, potentially resulting to session leakage. """ def inner(request, response): vary = set(response.vary if response.va...
ee7949f8c6ba1c11784b2c460e3c9dd962473412
3,642,315
import re def fix_span(text_context, offsets, span): """ find start-end indices of the span in the text_context nearest to the existing token start-end indices :param text_context: (str) text to search for span in :param offsets: (List(Tuple[int, int]) list of begins and ends for each token in the tex...
0c4802c20fa138a6e011f550a58328eb54a487a5
3,642,316
def update_moira_lists( strategy, backend, user=None, **kwargs ): # pylint: disable=unused-argument """ Update a user's moira lists Args: strategy (social_django.strategy.DjangoStrategy): the strategy used to authenticate backend (social_core.backends.base.BaseAuth): the backend being ...
f21f481bbf0b12e76149a93fee3c5c4923407c29
3,642,317
def certificate_get_all_by_project(context, project_id): """Get all certificates for a project.""" return IMPL.certificate_get_all_by_project(context, project_id)
6e4c83ff75c229034ae843607d20ae211e094df9
3,642,318
def simple_list(li): """ takes in a list li returns a sorted list without doubles """ return sorted(set(li))
1e36f15cea4be4b403f0a9795a2924c08b2cb262
3,642,319
from typing import OrderedDict def create_model(gpu, arch = 'vgg16', input_size = 25088, hidden_layer_size = 512, output_size = 102): """Creates a neural network model. """ if arch in archs_dict: model = archs_dict[arch] else: print("You haven`t inserted a valid architecture. Check the...
39b8b58cfe97b5872a20f67fbeadff8b5d8e1b16
3,642,320
import json def write_json(object_list, metadata,num_frames, out_file = None): """ """ classes = ["person","bicycle","car","motorbike","NA","bus","train","truck"] # metadata = { # "camera_id": camera_id, # "start_time":start_time, # "num_frames":num_frames, # ...
8b224af4edbd31570a432a8c551e95cd7a002818
3,642,321
def get_infer_iterator(src_dataset, src_vocab_table, batch_size, eos, sos, src_max_len=None): """Get dataset for inference.""" # Totol number of examples in src_dataset # (3003 examples + 69 padding ...
81ebd9f9f7d17bf1046f3fd0fafcbc3cdbb53ef4
3,642,322
def get_num_hearts(image): """Returns the number of full and total hearts. Keyword arguements: image - image of hearts region """ # definitions: lower_full = np.array([0, 15, 70]) upper_full = np.array([30, 35, 250]) lower_empty = np.array([150, 160, 220]) upper_empty = np....
614d11546c5d458b5e9d485024da4bdb34688e24
3,642,323
import copy def _clean_root(tool_xml): """XSD assumes macros have been expanded, so remove them.""" clean_tool_xml = copy.deepcopy(tool_xml) to_remove = [] for macros_el in clean_tool_xml.getroot().findall("macros"): to_remove.append(macros_el) for macros_el in to_remove: clean_too...
9df0980265b26a2de1c88d2999f10cd5d1421e0b
3,642,324
import logging import traceback def page_not_found(e): """Return a custom 404 error.""" logging.error(':: A 404 was thrown a bad URL was requested ::') logging.error(traceback.format_exc()) return render_template('404.html'), 404
11a553ab9ce52b4b1ba12916887f636d02aaef8f
3,642,325
def find_prime_factors(num): """Return prime factors of num.""" validate_integers(num) zero_divisors_error(num) potential_factor = 2 prime_factors = set() while potential_factor <= num: if num % potential_factor == 0: prime_factors.add(potential_factor) num = num/...
fe15c75d19081ec5fa5cfdefa0c95e4bcd20c26d
3,642,326
from datetime import datetime def json_serial(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() elif isinstance(obj, (dict)): return obj raise TypeError("Type %s not serializable" % type(obj))
7da3adb9dde3315741b5dcad2fa276e9f0b582af
3,642,327
def ignore_exception(exception): """Check whether we can safely ignore this exception.""" if isinstance(exception, BadRequest): if 'Query is too old' in exception.message or \ exception.message.startswith('Have no rights to send a message') or \ exception.message.startswith('Messag...
3f0182fbe7cec2e5978c61c110d10ed039869fd7
3,642,333
def rmse_loss(prediction, ground_truth, weight_map=None): """ :param prediction: the current prediction of the ground truth. :param ground_truth: the measurement you are approximating with regression. :param weight_map: a weight map for the cost function. . :return: sqrt(mean(differences squared)) ...
aef45b5549151a3d6c026dd34ccd9b6aa2b6d695
3,642,334
def get_corrupted_simulation_docs(): """Returns iterable of simdocs without samples (when num_paticles >0) When num_particle<=0, no samples are created and the simulation is considered Finished anyway. These ignored simulations """ return db[DBCOLLECTIONS.SIMULATION].find({ 'procstatus.stat...
f23620d7ea09fd37790ceb682f15dc0183b17c9c
3,642,335
def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor: """ Parameters ---------- x : Tensor DESCRIPTION. downsample : bool DESCRIPTION. filters : int DESCRIPTION. kernel_size : int, optional DESCRIPTION. The defaul...
092c41b6508ccb52d545219e0d2e254c3430362a
3,642,336
def dehaze(img, level): """use Otsu to threshold https://scikit-image.org/docs/stable/auto_examples/segmentation/plot_multiotsu.html n.b. threshold used to mask image: dark values are zeroed, but result is NOT binary level: value 1..5 with larger values preserving more bright voxels level: d...
bdb6f55fd09986a2abac92728644777fae77f6ca
3,642,337
def matthews_correlation_coefficient(tp, tn, fp, fn): """Return Matthews correlation coefficient for values from a confusion matrix. Implementation is based on the definition from wikipedia: https://en.wikipedia.org/wiki/Matthews_correlation_coefficient """ numerator = (tp * tn) - (fp * fn) den...
2048fb05664b3fcab99e08c51eb11a222676df84
3,642,338
import re def run_analysis(apk_dir, md5_hash, package): """Run Dynamic File Analysis.""" analysis_result = {} logger.info('Dynamic File Analysis') domains = {} clipboard = [] # Collect Log data data = get_log_data(apk_dir, package) clip_tag = 'I/CLIPDUMP-INFO-LOG' clip_tag2 = 'I CL...
f5108c8e3a09799e451bc8182018acf1481615e4
3,642,340
from datetime import datetime import fastapi async def quotes( ticker: str, date: datetime.date, uow: UoW = fastapi.Depends(dependendies.get_uow), ) -> ListResponse[Ticker]: """Return the list of available tickers.""" with uow: results = uow.quotes.iterator({'ticker': ticker, 'date': date}) ...
4267815af0ec13bc617870ee16b7b452a66d7891
3,642,341
from typing import Tuple from typing import Union def delete_snapshot(client, data_args) -> Tuple[str, dict, Union[list, dict]]: """ Delete exsisting snapshot from the system. :type client: ``Client`` :param client: client which connects to api. :type data_args: ``dict`` :param da...
509298677120b61dd9aa050dbe40aacffff6d97c
3,642,342
from backend.models.prices import PriceDB def api_user_submissions(user_id): """Gets the price submissions for a user matching the user_id. Example Request: HTTP GET /api/v1/users/56cf848722e7c01d0466e533/submissions Example Response: { "success": "OK", "user_submissi...
498c91451896dde6d347492acad9573839c45e13
3,642,343
def get_pdf_info(pdf_path: str) -> PdfInfo: """Get meta information of a PDF file.""" info: PdfInfo = PdfInfo(path=pdf_path) keys = get_flat_cfg_file(path="~/.edapy/pdf_keys.csv") ignore_keys = get_flat_cfg_file(path="~/.edapy/pdf_ignore_keys.csv") for key in keys: info.user_attributes[key...
3f80d9d50261e6b7a9e1c90b504abcbeed2b214d
3,642,344
import json import zlib import base64 def convert_gz_json_type(value): """Provide an ArgumentParser type function to unmarshal a b64 gz JSON string. """ return json.loads(zlib.decompress(base64.b64decode(value)))
1cf0300f40c8367b9129f230a7fef0c9b89ba012
3,642,345
def get_tag(tag): """ Returns a tag object for the string passed to it If it does not appear in the database then return a new tag object If it does exisit in the data then return the database object """ tag = tag.lower() try: return Session.query(Tag).filter_by(name=unicode(tag)).on...
e11ae349fa4d436a6b7057bf0b5d8b74a7e0f4e4
3,642,346
def get_closest_area( lat: float, lng: float, locations: t.List[config.Area] ) -> t.Optional[config.Area]: """Return area if image taken within 50 km from center of area""" distances = [ (great_circle((area.lat, area.lng), (lat, lng)).km, area) for area in locations ] distance, closest_area ...
3deb96bc1863ed1d02699cff0a48edd9471bbade
3,642,348
def disable(request): """ Disable Pool Member Running Script """ try: auth = AuthSession(request.session) client = auth.get_clientFactory() id_server_pool = request.POST.get('id_server_pool') ids = request.POST.get('ids') if id_server_pool and ids: ...
9c56d891a86db3e9f999cb8f329630172ea9703e
3,642,349
def fastapi_native_middleware_factory(): """Create a FastAPI app that uses native-style middleware.""" app = FastAPI() # Exception handler for `/client_error_from_handled_exception` app.add_exception_handler(IndexError, client_induced_exception_handler) app.add_middleware(BaseHTTPMiddleware, dispa...
5c85df93f126443b19b10b58fc7cb57661fd3388
3,642,350
def _partial_dependence( pipeline, X, features, percentiles=(0.05, 0.95), grid_resolution=100, kind="average", custom_range=None, ): """Compute the partial dependence for features of X. Args: pipeline (PipelineBase): pipeline. X (pd.DataFrame): Holdout data f...
1b8ae5811b7e815805e95d1c4ccc2fb1127187a9
3,642,351
from typing import Union from typing import Tuple def nplog( a: np.ndarray, deriv: bool = False, eps: float = 1e-30, verbose: bool = False ) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: """$C^2$ extension of $\ln(a)$ below `eps` Args: a: a Numpy array deriv: if `True`, the first ...
cc2258b78aca58c71d61aa058b9de0d408165268
3,642,352
def _section_to_text(config_section: ConfigSection) -> str: """Convert a single config section to text""" return (f'[{config_section.name}]{LINE_SEP}' f'{LINE_SEP.join(_option_to_text(option) for option in config_section.options)}{LINE_SEP}')
ee5feed2f9453c9f3338997d5294bada22961f07
3,642,354
import tempfile def TempFileDecorator(func): """Populates self.tempfile with path to a temporary writeable file""" def f(self, *args, **kwargs): with tempfile.NamedTemporaryFile(dir=self.tempdir, delete=False) as f: self.tempfile = f.name return func(self, *args, **kwargs) f.__name__ = func.__nam...
d696a16cade0eee36fee9cba4c0d8b96fbcc79e4
3,642,355
import string import random def get_random_string(length: int) -> str: """ Returns a random string starting with a lower-case letter. Later parts can contain numbers, lower- and uppercase letters. Note: Random Seed should be set somewhere in the program! :param length: How long the required strin...
6cf20ce7d158ac158ffa49cac427c396cfd840db
3,642,356
import numpy def subset_by_month(prediction_dict, desired_month): """Subsets examples by month. :param prediction_dict: See doc for `write_file`. :param desired_month: Desired month (integer from 1...12). :return: prediction_dict: Same as input but with fewer examples. """ error_checking.ass...
4df4eca74bcb433e85a06a99b32877890909ba86
3,642,357
import time def build_dataset_mce(platform, dataset_name, columns): """ Creates MetadataChangeEvent for the dataset. """ actor, sys_time = "urn:li:corpuser:etl", int(time.time()) fields = [] for column in columns: fields.append({ "fieldPath": column["name"], "n...
22fab14fe4a6e9f01b24ca67dce40b5860aebbe2
3,642,358
def FindMissingReconstruction(X, track_i): """ Find the points that will be newly added Parameters ---------- X : ndarray of shape (F, 3) 3D points track_i : ndarray of shape (F, 2) 2D points of the newly registered image Returns ------- new_point : ndarray of shape...
36e0f0f2dbc6a68f20a349a92fc1c882d5d0b73a
3,642,360
def deserialize(iodata): """ Turn IOData back into a Python object of the appropriate kind. An object is deemed deserializable if 1) it is recorded in SERIALIZABLE_REGISTRY and has a `.deserialize` method 2) there exists a function `file_io_serializers.<typename>_deserialize` Parameters ---...
3eb21f34b1571626a40fc52bd2eae2a42ff7dbb4
3,642,361
from typing import Union from typing import Iterable from typing import Tuple from typing import Optional def business_day_offset(dates: DateOrDates, offsets: Union[int, Iterable[int]], roll: str= 'raise', calendars: Union[str, Tuple[str, ...]]=(), week_mask: Optional[str]=None) -> DateOrDates: """ Apply offs...
32769b604b8e671b8318b0a6e00cdb8331774870
3,642,362
def factorial(n): """ Return n! - the factorial of n. >>> factorial(1) 1 >>> factorial(0) 1 >>> factorial(3) 6 """ if n<=0: return 0 elif n==1: return 1 else: return n*factorial(n-1)
da5bc6f68375c7db03b7b2bdac1fec2b476ba563
3,642,363
from scipy.io import loadmat from scipy.interpolate import interp1d def _load_absorption(freqs): """Load molar extinction coefficients.""" # Data from https://omlc.org/spectra/hemoglobin/summary.html # The text was copied to a text file. The text before and # after the table was deleted. The the follo...
e31c5d46c5e2de81627834f51ddb79f6f1265e5a
3,642,364
import math def pw_sin_relaxation(b, x, w, x_pts, relaxation_side=RelaxationSide.BOTH, pw_repn='INC', safety_tol=1e-10): """ This function creates piecewise relaxations to relax "w=sin(x)" for -pi/2 <= x <= pi/2. Parameters ---------- b: pyo.Block x: pyomo.core.base.var.SimpleVar or pyomo.cor...
38c5d8a459f8c90aaa17a95f4000e4388e491f69
3,642,365
def doc_to_tokenlist_no_sents(doc): """ serializes a spacy DOC object into a python list with tokens grouped by sents :param doc: spacy DOC element :return: a list of of token objects/dicts """ result = [] for x in doc: token = {} if y.has_extension('tokenId'): parts[...
0879e49836910d1f3a9be93281158c1b64978d53
3,642,367
def _applychange(raw_text: Text, content_change: t.TextDocumentContentChangeEvent): """Apply changes in-place""" # Remove chars start = content_change.range.start range_length = content_change.range_length index = _find_position(raw_text, start) for _ in range(range_length): raw_text.pop...
9dddeb69a5830980721d747f743e5e516f2eba51
3,642,368
def get_engine(): """Return a SQLAlchemy engine.""" connection_dict = sqlalchemy.engine.url.make_url(FLAGS.sql_connection) engine_args = { "pool_recycle": FLAGS.sql_idle_timeout, "echo": False, } if "sqlite" in connection_dict.drivername: engine_args["poolclass"] = sqlalche...
f93bfe29b7cf96d32f250e4385d3d2a794a02ee0
3,642,369
def ccw(p0, p1, p2): """ Judge whether p0p2 vector is ccw to p0p1 vector. Return value map: \n 1: p0p2 is ccw to p0p1 (angle to x axis bigger) \n 0: p0p2 and p0p1 on a same line \n -1: p0p2 is cw to p0p1 (angle to x axis smaller) \n Args: p0: base point index 0 and 1 is...
46599e0df6c39346e4b61f6daeb140a8db6225a3
3,642,370
def get_ffmpeg_folder(): # type: () -> str """ Returns the path to the folder containing the ffmpeg executable :return: """ return 'C:/ffmpeg/bin'
4708eec64ff56b72f7b1b9cc7f5ee7916f6310bd
3,642,371