content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def gas_3parallel(method="nikuradse"): """ :param method: Which results should be loaded: nikuradse or prandtl-colebrook :type method: str, default "nikuradse" :return: net - STANET network converted to a pandapipes network :rtype: pandapipesNet :Example: >>> pandapipes.net...
b06b11bc346e430252901fe8fec19402e1e6aff9
3,630,700
def get_coordinates(df, year: str): """ Add column to the given DataFrame which contains coordinates of all films filmed at given year. """ df = df[df["Year"] == year] coordinates = [] geolocator = Nominatim(user_agent="main.py") for i in range(120): df_location = df.iloc[i, 2] ...
ed08cddf7c8a0333dc6cfca4e4c70703bff029f0
3,630,701
from pathlib import Path import json def get_partyname_wordlist( json_path: Path, filter_full_name: t.List = [], name_keys: t.List = ["full_name", "label", "short_name", "other_names"], lowercase: bool = False, add_spaces: bool = False, ): """Create a set of all possible and abreviatoions of p...
ed10da9f689af8f56cc2fc4eeb899764a5512646
3,630,702
def ceil_even(x): """ Return the smallest even integer not less than x. x can be integer or float. """ return round_even(x+1)
098f1fb847aa36f288f6b43030627ab5570117a6
3,630,703
def dict_to_PI(d, classes): """ Convert a dictionary to a PresentationInfo, using a pre-fetched dictionary of CssClass objects """ if d['prestype'] == 'command': return PresentationInfo(prestype=d['prestype'], name=d['name']) else: c = classes.get(d['name']) if c is None:...
620b0d21bc199046bf5dc05be0cba7269f340bbb
3,630,704
import typing def no_batch_embed(sentence: str) -> typing.List[float]: """Returns a list with the numbers of the vector into which the model embedded the string.""" return model.encode(sentence).tolist()
1351c4e3fc69ea261a149f864545c2c9275e78a5
3,630,705
def make_video(video_images_files, name, fps=30): """Given list of image files, create video""" # create video print('\nCreating video...') clip = ImageSequenceClip(video_images_files, fps) # write video clip.write_videofile(name) return clip
54037289258c5bfd5f682d6f75a442158949b228
3,630,706
def find_internal_gaps(seq): """ Accepts a string and returns the positions of all of the gaps in the sequence which are flanked by nt bases :param seq: str :return: list of [start,end] of all of the internal gaps """ gaps = find_gaps(seq) seq_len = len(seq) -1 internal_gaps = [] iu...
a890eba3dff6c8be186c6be1a2477daf658a65e6
3,630,707
def test_loop(model, ins, batch_size=None, verbose=0, steps=None): """Abstract method to loop over some data in batches. Arguments: model: Model instance that is being evaluated in Eager mode. ins: list of tensors to be fed to `f`. batch_size: integer batch size or `None`. verbose: verbosit...
9bed19f31eabdad791091bd68196e90d422a65e1
3,630,708
def find_bands(bands, target_avg, target_range, min_shows): """ Searches dictionary of bands with band name as keys and competition scores as values for bands that are within the range of the target average and have performed the minimum number of shows. Returns a list of bands that meet the search ...
1b2b93f0a1d4236ad62102205606eff8afb3802a
3,630,709
def get_named_targets(): """ Return a list of named target date ranges """ return ["std_train", "std_val", "std_test", "std_ens", "std_all", \ "std_future", "std_contest_fri", "std_contest", "std_contest_daily", "std_contest_eval", \ "std_contest_eval_daily", "std_paper", "std_paper_daily"]
23a15efff1facc5028e980d659ca6d2f61cdddf0
3,630,710
import scipy def create_edge_linestrings(G_, remove_redundant=True, verbose=False): """ Ensure all edges have the 'geometry' tag, use shapely linestrings. Notes ----- If identical edges exist, remove extras. Arguments --------- G_ : networkx graph Input networkx graph, with e...
478459007538c8d250b1d6f518300d9476866df4
3,630,711
def get_licenses(service_instance, license_manager=None): """ Returns the licenses on a specific instance. service_instance The Service Instance Object from which to obrain the licenses. license_manager The License Manager object of the service instance. If not provided it will...
f0c4f7fdc2418f09e7c7e319b8ec670f98db9ca3
3,630,712
def is_installed(request, project_id=None): """Check whether the extension {{ cookiecutter.project_name }} is installed.""" return JsonResponse({'is_installed': True, 'msg': '{{ cookiecutter.project_name }} is installed'})
ab25af53719e832d5f97b1f8757d630f6d4fec40
3,630,713
import os def predict(model, data, out_fname = None): """ Description: ----------- This function is used to predict the EV values for a given dataframe Parameters: ----------- model: The model to be finetuned (tf.keras.models.Model) data: The dataframe to be predicted (pandas.DataFra...
5207523a3247f8bfbc816cf53e122c3924266846
3,630,714
def line_order(line): """Recursive search for the line's hydrological level. Parameters ---------- line: a Centerline instance Returns ------- The line's order """ if len(line.inflows) == 0: return 0 else: levels = [line_order(s) for s in line.inflows] ...
d2342477abc9d53fbbe02c5c426b518ee59ca732
3,630,715
def get_data_colums(epoch): """Return the data columns of a given epoch :param epoch: given epoch in a numpy array, already readed from .csv """ ID = epoch[:,0]; RA = epoch[:,1]; RA_err = epoch[:,2]; Dec = epoch[:,3]; Dec_err = epoch[:,4]; Flux = epoch[:,5]; Flux_err = epoch[:,...
ba497f0aacf8356b80c8c433af05716b90519665
3,630,716
def reset_columns_DataFrame(df, new_columns=None): """ Rename *all* columns in a dataframe (and return a copy). Possible new_columns values: - None: df.columns = list(df.columns) - List: df.columns = new_columns - callable: df.columns = [new_columns(x) for x in df.columns] - str && df.shap...
7251ec76dcf828ad1ebc4bf96dfc19a2059f37f5
3,630,717
def bin_position(max_val): """returns position features using some symbols. Concatenate them at the end of sentences to represent sentence lengths in terms of one of the three buckets. """ symbol_map = {0: " `", 1: " _", 2: " @"} if max_val <= 3: return [symbol_map[i] for i in range(max_val)...
2c6caf100c07d56211ba8f8bfcef103dd623c6f5
3,630,718
def norm(g,scale=True): """normalises a network on the last axis, scale decides if there is a learnable multiplicative factor""" g.X=BatchNormalization(axis=-1,scale=scale)(g.X) return g
ef9a26e93b870a3d2cfd85aed3cf24d8129b464a
3,630,719
def makeEvent(rawEvent, time = 0): """Create a midi event from a raw event received from the sequencer. """ eventData = rawEvent.data if rawEvent.type == SSE.NOTEON: result = NoteOn(time, eventData.note.channel, eventData.note.note, eventData.note.velocity ...
5b7a24dfecfb5f0e1531e799dd0e77d9bb548360
3,630,720
def rule2(n): """2sqrt""" k = map(lambda x:x*2,rule1(n)) return k
7ea1b5e06be20ab4832e68536e210d8baf036925
3,630,721
def charge_sublayers(ich): """ Parse the InChI string for the formula sublayer. :param ich: InChI string :type ich: str :rtype: dict[str: str] """ return automol.convert.inchi.charge_sublayers(ich)
6532fc0ab5bd5b8a1e97ec5297a8394f67a6066d
3,630,722
import os def f_split_path(fpath, normpath=True): """ Splits path into a list of its component folders Args: normpath: call os.path.normpath to remove redundant '/' and up-level references like ".." """ if normpath: fpath = os.path.normpath(fpath) allparts = [] ...
0a0fafe2263cb77727609053866f7c1b95fa12d0
3,630,723
import os def get_path(*args): """ utility method""" return os.path.join(THIS_DIR, 'primitives_data', *args)
5d274e81a3b6bd621ff54ce841f26a978406928d
3,630,724
import requests def mixcloud_profile(): """ Display the authorized user's profile """ # Note: We would normally do this but Mixcloud requires specific parameters #client_id = current_app.config['CONFIG']['accounts']['mixcloud']['client_id'] #mixcloud_session = OAuth2Session(client_id, token=session['...
18f0f29b31e0becb04fd2a6bb59763298f246668
3,630,725
def search_metas(metas, criteria, keywords): """ Note: storage may contain message from others """ msgs = [] for meta in metas: if not satisfy_criteria(criteria, meta): continue if keywords == None or len(keywords) == 0: msgs.append(meta) continue ...
6bdf1593b2591ab0bc1a028ae854e19858614cda
3,630,726
import logging def count_large_cargos(b): """Gather number of large cargos in each planet.""" def find_planets(): return sln.finds(sln.find(b, By.ID, 'planetList'), By.CLASS_NAME, 'planetlink') num_planets = len(find_planets()) logging.info('Found {} planets'.format(num_planets)) ...
31b462da2a54be6979b6b7861709caa27af5e37b
3,630,727
def get_project(service, project_id): """Build service object and return the result of calling the API 'get' function for the projects resource.""" operation = service.projects().get(projectId=project_id).execute() return operation
9c512fbf2476039524e67178ada36fd15ebe8cee
3,630,728
def parse(src: str): """ Compila string de entrada e retorna a S-expression equivalente. """ return parser.parse(src)
4ffcc39b63839c5668b3ea435064249f60dbf222
3,630,729
import ast from typing import Tuple from typing import List from typing import Set def get_parser_init_and_actions(source: ast.Module) -> \ Tuple[List[ast.AST], str, Set[str]]: """ Function used to extract necessary imports, parser and argument creation function calls Parameters --------...
0a8920d69f51a7a379ee8415efcd277d3adcdc48
3,630,730
from pathlib import Path from typing import Dict def write_json_to_file(filepath: Path, jsonstr: Dict[str, str], indent: int = 4, eof_line=True): """Dosyaya JSON yazar. Dosya bulunamazsa ekrana raporlar hata fırlatmaz Arguments: filepath {Path} -- Okunacak dosyanın yolu jsonstr {Dict[str,...
59fdf74661350811c0fcd685d5949c37376e53d7
3,630,731
import os def get_version(): """ str: The package version. """ global_vars = {} # Compile and execute the individual file to prevent # the package from being automatically loaded. source = read(os.path.join("test_python_package", "__version__.py")) code = compile(source, "version.py", "exec"...
2f2769927e050dab348ff421aa541066184f322d
3,630,732
def aTimesFiltered(data, filterFunction, microBin=False): """ Filter a list of arrivalTimes =========================================================================== Input Meaning --------------------------------------------------------------------------- data Object with ...
b71a08c8431fc2c7cb8bca6c075d798ebea48db4
3,630,733
import select def get_publication_group(project, group_id): """ Get all data for a single publication group """ connection = db_engine.connect() groups = get_table("publication_group") statement = select([groups]).where(groups.c.id == int_or_none(group_id)) rows = connection.execute(statem...
f17c54800d8f4e84e7433a23a7d222e4d3d67bbf
3,630,734
import traceback import six def format_traceback(exc_info, encoding='utf-8'): """ Returns the exception's traceback in a nice format. """ ec, ev, tb = exc_info # Skip test runner traceback levels while tb and _is_relevant_tb_level(tb): tb = tb.tb_next # Our exception object may h...
c962b11bf629908b7575e6cf25ffebeb2b5956ec
3,630,735
import os def creatadata(datadir=None,exprmatrix=None,expermatrix_filename="matrix.mtx",is_mtx=True,cell_info=None,cell_info_filename="barcodes.tsv",gene_info=None,gene_info_filename="genes.tsv",project_name=None): """ Construct a anndata object Construct a anndata from data in memory or files on dis...
b0b64920032836fe0c79de1827afa166c4a5d59c
3,630,736
def test_declarative_region_modifier_zoom_in(): """Test that '+' suffix on area string properly decreases extent of map.""" data = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False)) contour = ContourPlot() contour.data = data contour.field = 'Temperature' contour.level = 700 *...
6d68ec6a15cc451226379f65cef69820f2169de7
3,630,737
def get_report(path): """ Downloads the MVP report. :param path: :return: """ return flask.send_from_directory(Parameters.TMP_DIR, path)
f6f9cc18c901b3ac89769f7bfb758ff538699269
3,630,738
def qbinomial(n, k, q = 2): """ Calculate q-binomial coefficient """ c = 1 for j in range(k): c *= q**n - q**j for j in range(k): c //= q**k - q**j return c
43c167aa506bd9ee6b87163d10da5b02e297e067
3,630,739
def _igraph_from_nxgraph(graph): """ Helper function that converts a networkx graph object into an igraph graph object. """ nodes = graph.nodes(data=True) new_igraph = igraph.Graph() for node in nodes: new_igraph.add_vertex(name=str(node[0]), species=node[1]["specie"], coords=node[1]["co...
04525dbdda343fdc1b572639eea0f4e5933ffb39
3,630,740
def _tiramisu_parameters(preset_model='tiramisu-67'): """Returns Tiramisu parameters based on the chosen model.""" if preset_model == 'tiramisu-56': parameters = { 'filters_first_conv': 48, 'pool': 5, 'growth_rate': 12, 'layers_per_block': 4 } ...
74e2dadf2a6af864b3f9dfec6241bf71833676f8
3,630,741
import time import requests import json def send_msg(request): """ 发送消息 :param request: :return: """ to_user = request.GET.get('toUser') msg = request.GET.get('msg') url = 'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsg?lang=zh_CN&pass_ticket=%s' %(TICKET_DICT['pass_ticket'],) ...
a028f37567e6fca6dc5e4b7c9e1ce826a184a5e1
3,630,742
import os import stat def get_type(path, follow=True, name_pri=100): """Returns type of file indicated by path. path : pathname to check (need not exist) follow : when reading file, follow symbolic links name_pri : Priority to do name matches. 100=override magic This t...
45a20cc179d569f5c993e9b90de393f210ab524d
3,630,743
import os def ELA(impath, Quality=90, Multiplier=15, Flatten=True): """ Main driver for ELA algorithm. Args: impath: Path to image to be transformed. Quality (optional, default=90): the quality in which to recompress the image. (0-100 integer). Multiplier (optional, default=15): v...
dced44b4db1ef25bd914b2609a0e7eb9dd07d8b9
3,630,744
import yaml def create_deployment_for_compin(compin: ManagedCompin, assessment: bool = False) -> str: """ Creates a Kubernetes deployment YAML descriptor for a provided compin. The compin's deployment template is enhanced in the following ways: (1) A node selector is added in order to ensure that...
90bb543a0c384b188f8284f4688a98d7e443d0c2
3,630,745
import requests def titles_request() -> 'Response': """Request titles. https://wiki.anidb.net/w/API#Anime_Titles """ return requests.get(_TITLES)
41aebc83511d440a91e5be0c866702260536dccc
3,630,746
def get_jds(text): """Given a text (string), returns a list of the Journal Descriptors contained""" scores = jdi.GetJdiScoresByTextMesh(text, InputFilterOption(LegalWordsOption.DEFAULT_JDI)) output_filter_option = OutputFilterOption() output_filter_option.SetOutputNum(3) result = OutputFilter.Proc...
9b508adfce00ba49a6b3fd303c98cb0056d62863
3,630,747
from pathlib import Path import subprocess def rpsbproc(results): """Convert raw rpsblast results into CD-Search results using rpsbproc. Note that since rpsbproc is reliant upon data files that generally are installed in the same directory as the executable (and synthaser makes no provisions for them ...
d3fbc8bc6456ed340db58f3809552c13e03a2c1b
3,630,748
def replacespecial(string, char_replacement=replacements): """Return unicode string with special characters replaced""" return "".join(c if c not in char_replacement else char_replacement[c] for c in string)
67d3e397ab35392a242cab48e1ad628b19d1a488
3,630,749
def parse_orcid_response(response): """ This safely digs into the ORCID user summary response and returns consistent dict representation independent of the user's visibility settings. """ return { "orcid": get_nested_key(response, "orcid-identifier", "path"), "email": get_nested_key...
5fdbc6307b7146c0454e824d18269314e7d89569
3,630,750
def discrete_metropolis_hastings(P, n_samples = 10000, n_iterations = 10000, stepsize = None): """ Perform a random walk in the discrete distribution P (array) """ #ensure normality n = np.sum(P) Px = interp1d(np.linspace(0,1,len(P)), P/n) x = np.random.uniform(0,1,n_samples) ...
3167ac2e03763693ea70bec7fee9071074331515
3,630,751
def vat(x, logits, model, v, eps, xi=1e-6): """ Generate an adeversarial perturbation. Args: x: tensor, batch of labeled input images of shape [batch, height, width, channels] logits: tensor, holding model outputs of input model: tf.keras model v: ...
6e8c50018e9b49e38d32c92acc3ae5fcce4654c0
3,630,752
def bond_yield(price, face_value, years_to_maturity, coupon=0): """ """ return (face_value / price) ** (1 / years_to_maturity) - 1
4c4a90f0fb29564acdad05138ca17932da39eb61
3,630,753
import ctypes def getTime(type_of_clock): """ Arg: type_of_clock...int case '1': CLOCK_REALTIME; case '2': CLOCK_MONOTONIC; case '3': CLOCK_MONOTONIC_COARSE; case '4': CLOCK_MONOTONIC_RAW; case '5': CLOCK_BOOTTIME; default: CLOCK_REALTIME; Return: ...
7fee5476bf967ca5fa74abfa4722a8ad2570a975
3,630,754
def ar_gain(alpha): """ Calculate ratio between the standard deviation of the noise term in an AR(1) process and the resultant standard deviation of the AR(1) process. :param alpha: Parameter of AR(1) :return: Ratio between std of noise term and std of AR(1) """ return np.sqrt((1 + alpha) / ...
966b2ade2aa0a70d71df2c9ee1567271bb988f07
3,630,755
import csv def fetch_data_2014(): """For import data year 2014 from excel""" static = open("airtraffict.csv", newline="") data = csv.reader(static) static = [run for run in data] static_2014 = [] for run in static: if run[3] == "2014": static_2014.append(run) return sta...
bd31335f2f4344330ca0c390d33891d2c8b7b843
3,630,756
from typing import Counter def classifyChord(chordPosition): """ :param chordPosition:所有音符的位置,所有音符都是在不同弦上,并且各位置的距离是限制在人类手掌范围内的。 例如:([6, 5], [5, 7], [4, 7], [3, 5], [2, 5]),表示6弦5品,5弦7品,4弦7品,3弦5品,2弦5品 :return:和弦类型,是一个列表,用来表示所有非空弦音,从低品到高品对应的个数。 例如:输入([6, 5], [5, 7], [4, 7], [3, 5], [2, 5]),返回[[5,3],...
1c9af3737f2e4ba2437a457e74f37fbbe1ff0406
3,630,757
def clean_columns(data): """ Removes : EventId, KaggleSet, KaggleWeight Cast labels to float. """ data = data.drop(["DER_mass_MMC", "EventId", "KaggleSet", "KaggleWeight",], axis=1) label_to_float(data) # Works inplace return data
073b41bfeaf9a3236698b04b74a621efffa135cf
3,630,758
def update_active_boxes(cur_boxes, active_boxes=None): """ Args: cur_boxes: active_boxes: Returns: """ if active_boxes is None: active_boxes = cur_boxes else: active_boxes[0] = min(active_boxes[0], cur_boxes[0]) active_boxes[1] = min(active_boxes[1], cu...
dfa1c9b32b9af9c6c9a1fb321f907dad51f9cca0
3,630,759
def get_user_request(): """Return the user's json.""" assert namespace_manager.get_namespace() == '' person = get_person() values = person.to_dict() return flask.jsonify(objects=[values])
be8d8a36ce096d6ac74cad3c62cdaaeb0ad2e326
3,630,760
def paginate_data(counted, limit, offset): """ Custom pagination function. :param counted: :param limit: :param offset: :return: {} """ total_pages = ceil(counted / int(limit)) current_page = find_page(total_pages, limit, offset) if not current_page: return None bas...
b34f55efac09c277b0ffabffa5012b29087f8cde
3,630,761
import torch def ones(shape, dtype=None): """Wrapper of `torch.ones`. Parameters ---------- shape : tuple of ints Shape of output tensor. dtype : data-type, optional Data type of output tensor, by default None """ return torch.ones(shape, dtype=dtype)
a234936baa16c8efdc63e903d8455895ab7f2f0c
3,630,762
def parse_catalog(catalog): """parses an atom feed thinking that it is OPDS compliant""" author = None title = None links = [] entries = [] updated = None for child in catalog: if child.tag == LINK_ELEM: links.append(parse_link(child)) elif child.tag == ENTRY_EL...
1a6b0b6d8b94f916f37f976cfa6feb7e4c7d6178
3,630,763
def get_queue(shares): """Transform category sizes to block queue optimally catsizes = [cs1, cs2, cs3, cs4] - blocks numbers of each color category """ # Defining catsizes matching the MSE-limit # amount = 1 # starting amount # lim = 0.03 # MSE-limit # while True: # error = 0 ...
acb8bd7372a2338b36c77c03776af45fc2727d89
3,630,764
def view_post(request, slug): """View post view""" post = get_object_or_404(Post, slug=slug) if not post.published: raise Http404 ret_dict = { 'post': post, } ret_dict = __append_common_vars(request, ret_dict) return render(request, 'blog/view_post.html', ret_dict)
5d777e6664555172a159b11ee3e6796a2767401a
3,630,765
def relhum(temperature, mixing_ratio, pressure): """This function calculates the relative humidity given temperature, mixing ratio, and pressure. "Improved Magnus' Form Approx. of Saturation Vapor pressure" Oleg A. Alduchov and Robert E. Eskridge http://www.osti.gov/scitech/servlets/purl/548871/ ...
3db1b72a96ac76fce041b8c5462d77ab5f0db9bb
3,630,766
def submit(year, day, part, session=None, input_file=None): """ Puzzle decorator used to submit a solution to advent_of_code server and provide result. If input_file is not present then it tries to download file and cache it for submiting solution else it require to be provided with input_file path whic...
f90b52eaa5e1ee78f257f33fd8454380e57dd71e
3,630,767
def mse(y, y_pred): """ Computes mean squared error. Parameters ---------- y: np.ndarray (1d array) Target variable of regression problems. Number of elements is the number of data samples. y_pred: np.ndarray (1d array) Predicted values for the given target va...
87c13131be28f92d3b9d75192d2e0e0d651979cc
3,630,768
from django.db import transaction from django.db import transaction def update_items(item_seq, batch_len=500, dry_run=True, start_batch=0, end_batch=None, ignore_errors=False, verbosity=1): """Given a sequence (queryset, generator, tuple, list) of dicts run the _update method on them and do bulk_update""" st...
c734f097db2ef8d5ff620cfd6386d53db4ed4543
3,630,769
def hue_weight(image, neighbor_filter, sigma_I = 0.05): """ Calculate likelihood of pixels in image by their metric in hue. Args: image: tensor [B, H, W, C] neighbor_filter: is tensor list: [rows, cols, vals]. where rows, and cols are pixel in image, ...
976a93ee7a5a83280485e1cd693b2cf10e67421a
3,630,770
def build_blueprint_with_loan_actions(app): """.""" blueprint = Blueprint( 'invenio_circulation', __name__, url_prefix='', ) create_error_handlers(blueprint) endpoints = app.config.get('CIRCULATION_REST_ENDPOINTS', []) pid_type = 'loan_pid' options = endpoints.get(pi...
0081a7795bbcab334c6a56991ebd3727e3799d5b
3,630,771
def featurize_and_to_numpy(featurizer, X_train, y_train, X_test, y_test): """ Featurize the given datasets, and convert to numpy arrays. """ featurizer.fit(X_train) X_train_feats = featurizer.transform(X_train) X_test_feats = featurizer.transform(X_test) X_train_np = X_train_feats.astype(np...
71e325e79770e4d049760e7701b98e8628b1c91f
3,630,772
def noise_per_box_v2_(boxes, valid_mask, loc_noises, rot_noises, global_rot_noises): """add noise for each box and check collision to make sure noisy bboxes do not collide with other boxes loc_noises and rot_noises are some noisy candidates, first successful noisy bbox candidate is cho...
68e75778dd6da7b1cbe4d1dfbf83b60034d43f61
3,630,773
def calculate_cornea_center_wcs(u1_wcs, u2_wcs, o_wcs, l1_wcs, l2_wcs, R, initial_solution): """ Estimates cornea center using equation 3.11: min ||c1(kq1) - c2(kq2)|| The cornea center should have the same coordinates, however, in the presents of the noise it is not always the case. Thus, the task...
67f153fbe39baf3b435f7fe11b2b2da611f08aab
3,630,774
def luminosity(S_obs, z, D_L=0, alpha=0): """Get radio luminosity with error. Default is LDR2. See https://www.fxsolver.com/browse/formulas/Radio+luminosity. """ if D_L == 0: D_L, _ = get_dl_and_kpc_per_asec(z=z) return (S_obs * 4 * np.pi * (D_L ** 2)) / (1 + z) ** (1 + alpha)
276c73e1575b67c918884bfc1f9a55feb3844a58
3,630,775
def add_categories_to(gifid, category_id): """ REST-like endpoint to add a category to a bookmarked gif :returns: Customized output from GIPHY :rtype: json """ user = ( models.database.session.query(models.users.User) .filter( models.users.User.token == flask.request...
8444400fb198b1d2630b2097bc77e19a347e32ef
3,630,776
import numpy def vtk_image_to_array(vtk_image) : """ Create an ``numpy.ndarray`` matching the contents and type of given image. If the number of scalars components in the image is greater than 1, then the ndarray will be 4D, otherwise it will be 3D. """ exporter = vtkImageExport() ...
e7640b69f7489d434da20a117ef46253198f7a7e
3,630,777
def delete_network_acl(acl_id): """Delete a network ACL.""" client = get_client("ec2") params = {} params["NetworkAclId"] = acl_id return client.delete_network_acl(**params)
87fca1c7dcd258e5ffcce638d9d74a3a50fbd0e9
3,630,778
def catalog_sections(context, slug=None, level=3, **kwargs): """ Отображает иерерхический список категорий каталога. Для каждой категории отображается количество содержащегося в ней товара. Пример использования:: {% catalog_sections 'section_slug' 2 class='catalog-class' %} :param context...
2c75a83aebbb494549443d08c8d0c6b054a20804
3,630,779
def get_scrapable_links( args, base_url, links_found, context, context_printed, rdf=False ): """Filters out anchor tags without href attribute, internal links and mailto scheme links Args: base_url (string): URL on which the license page will be displayed links_found (list): List of all...
ad078463ff146ea649250201f5cd625e277dc5d8
3,630,780
def AccuracyTestNMax(): """[summary] Test the accuracy using n-max random points """ plgs = getTestPolygons() pnt = Point(0, 0) # Calculate D using polygon partitioning method print("---------D---------------") for i in range(len(plgs)): print(DistCalc.DistCalcPART(pnt, plgs[i]))...
0f2fa1bf2990eafdf484123d4463056884a77cff
3,630,781
import pandas def read_source_MCI(csv_path: str | None = "volume_sum_icv_site.csv"): """ :param csv_path: str :return: Train and test dataset of independent variables X and dependent variable y """ MRI_source_df = pandas.read_csv(csv_path) X_df = MRI_source_df.iloc[:, 2:-2] del X_df['age...
3433f70d9da17a8eedfa9b3a7f047e4efb324dd0
3,630,782
import os def get_exp_logger(sess, log_folder): """Gets a TensorBoard logger.""" with tf.name_scope('Summary'): writer = tf.summary.FileWriter(os.path.join(log_folder), sess.graph) class ExperimentLogger(): def log(self, niter, name, value): summary = tf.Summary() ...
fe80f2db4f175e2ad4cc053fb5b29d0a54ea5772
3,630,783
import random def rollDie(): """returns a random int between 1 and 6""" return random.choice([1, 2, 3, 4, 5, 6])
27a3d3586fe313d78a5aea6dab8d10c58e76df56
3,630,784
def calc_ari(A, B): """ Adjusted Rand Index""" A = {v: k for k, s in A.items() for v in s} B = {v: k for k, s in B.items() for v in s} df = pd.DataFrame({'A': A, 'B': B}).dropna() A = df['A'].to_list() B = df['B'].to_list() return adjusted_rand_score(A, B)
8904c6232e47428364f97c26d55492890dff6cc0
3,630,785
def encode_adj(adj, max_prev_node=10, is_full=False): """ :param adj: n*n, rows means time step, while columns are input dimension :param max_degree: we want to keep row number, but truncate column numbers :return: """ if is_full: max_prev_node = adj.shape[0] - 1 # pick up lower tr...
8c2f21705b3b1aeff64a1b02c0519e51bb101d65
3,630,786
def get_datasource_content_choices(model_name): """Get a list (suitable for use with forms.ChoiceField, etc.) of valid datasource content choices.""" return sorted( [(entry.content_identifier, entry.name) for entry in registry["datasource_contents"].get(model_name, [])] )
3ce217f606e013e35189ffcdabff46c37060bf19
3,630,787
def setFDKToolsPath(toolName): """ On Mac, add std FDK path to sys.environ PATH. On all, check if tool is available. """ toolPath = 0 if sys.platform == "darwin": paths = os.environ["PATH"] if "FDK/Tools/osx" not in paths: home = os.environ["HOME"] fdkPath = ":%s/bin/FDK/Tools/osx" % (home) os.environ...
229f79954f5488f7bae067a5ad39a83d5b2fe527
3,630,788
import os import builtins def datasplit(datastream,split_param=None,split_value=0.2): """ Very flexible function for splitting the dataset into train-test or train-test-validation dataset. If datastream contains field `filename` - all splitting is performed based on the filename (directories are ommited t...
3554f795728edd7d4cc6b2595771811fc20897d7
3,630,789
def upd_p_fdtd_srl_2D_slope(p, p1, p2, fsrc, fsrc2, Nb, c, rho, Ts, dx, Cn, A, B, C, x_in_idx, y_in_idx, x_edges_idx, y_edges_idx, x_corners_idx, y_corners_idx, slope_start): """ This FDTD update is designed for case 5: slope. ...
bb536af34d655b741ee84c0649adfb2dd76eed4e
3,630,790
from datetime import datetime import calendar def PlistValueToPlainValue(plist): """Takes the plist contents generated by binplist and returns a plain dict. binplist uses rich types to express some of the plist types. We need to convert them to types that RDFValueArray will be able to transport. Args: p...
4e78b5c85dce44846d27e7ca8b3ea2bceeeba5eb
3,630,791
def columns_not_to_edit(): """ Defines column names that shouldn't be edited. """ ## Occasionally unchanging things like NIGHT or TILEID have been missing in the headers, so we won't restrict ## that even though it typically shouldn't be edited if the data is there return ['EXPID', 'CAMWORD', 'O...
430430c121d784727808b8e7c98d96bd846dc65f
3,630,792
def cat_dog(s): """Solution of problem at http://codingbat.com/prob/p164876 >>> cat_dog('catdog') True >>> cat_dog('catcat') False >>> cat_dog('1cat1cadodog') True """ last_3_chars = deque(maxlen=3) cat = deque('cat') dog = deque('dog') count = 0 for c in s: ...
dacc2b2e7fc6e19980afff0c010a9d64bf45e163
3,630,793
def CanCreateGroup(perms): """Return True if the given user may create a user group. Args: perms: Permissionset for the current user. Returns: True if the user should be allowed to create a group. """ # "ANYONE" means anyone who has the needed perm. if (settings.group_creation_restriction == ...
b4149315cef8086042b30be4334a426cf15927d6
3,630,794
def quad_corner_diff(hull_poly, bquad_poly, region_size=0.9): """ Returns the difference between areas in the corners of a rounded corner and the aproximating sharp corner quadrilateral. region_size (param) determines the region around the corner where the comparison is done. """ bquad_corne...
1190b4ff43632c072c220b5bdfae29c239e8662f
3,630,795
def _context_deleteserver(ip, port, server_name, config=None, disabled=None): """Delete a server context. """ if config is None or ('_isdirty' in config and config['_isdirty']): config = loadconfig(APACHECONF, True) scontext = _context_getserver(ip, port, server_name, config=config, disabled=dis...
cf41b61c4d8296373a4f4df4f1764485ec221466
3,630,796
def CreateStyleFromConfig(style_config): """Create a style dict from the given config. Arguments: style_config: either a style name or a file name. The file is expected to contain settings. It can have a special BASED_ON_STYLE setting naming the style which it derives from. If no such setting is fo...
42c36df604b26cdad9f8b0571863bfbfd92c9df9
3,630,797
def build_weighted_matrix(corpus, tokenizing_func=basic_tokenizer, mincount=300, vocab_size=None, window_size=10, weighting_function=lambda x: 1 / (x + 1)): """Builds a count matrix based on a co-occurrence window of `window_size` elements before and `window_size` elements after the focal wo...
d21b220c7697fb59ed2a4590bd54d9bbb0331758
3,630,798
def checksum_data_16bit(data): """Calculate 16 bit checksum (really just summing up shorts) over a chunk.""" return reduce(lambda r, x: (r + x) & 0xFFFF, map(lambda (x, y): (ord(y) << 8) | ord(x), zip(*[iter(data)] * 2)), 0)
4d453e5a02eb3359e5aa30442230604f45d6d27b
3,630,799