content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests from bs4 import BeautifulSoup def get_the_content(url, date): """ 컴퓨터 공학과 홈페이지 내용들 가져오기. """ ret = [] res = requests.get(url) soup = BeautifulSoup(res.content, "html.parser") update = soup.select('div.total-wrap > span') ret.append("오늘 업데이트 된 게시글 : " + update[1].text) fi...
2f25ca0a877ad8e801992d1ddc2b92c558dc7851
3,611,497
def MergeBaseClass(cls, base): """Merge a base class into a subclass. Arguments: cls: The subclass to merge values into. pytd.Class. base: The superclass whose values will be merged. pytd.Class. Returns: a pytd.Class of the two merged classes. """ bases = tuple(b for b in cls.bases if b != base)...
713801316e2c6dde799b9c57b7e2e513d1bc6352
3,611,498
def chart_data_to_df(func): """获取df""" @wraps(func) def inner(self, *args, **kwargs): if self.df.empty: columns = ["datetime", "open", "high", "low", "close", "volume"].extend(self.extend_field) self.df = pd.DataFrame(self.list_dict, columns=columns) return func(self,...
6164835b9943cfc6711202aa46baa48558da83cf
3,611,499
def choose_pivot_first(_: list[int], left: int, __: int) -> int: """Choose first element as pivot""" return left
931c7a182feda076213ec85f2d7909e7ff2e87cb
3,611,501
def __virtual__(): """ Check dependencies """ if has_depends is False: msg = "jks unavailable: {0} execution module cant be loaded ".format( __virtualname__ ) return False, msg return __virtualname__
db75a200406c918f0de16d3d4fce761c35bb26c4
3,611,502
from typing import Union import pathlib def limit( limit_results: fit.LimitResults, *, figure_folder: Union[str, pathlib.Path] = "figures", close_figure: bool = True, save_figure: bool = True, ) -> mpl.figure.Figure: """Visualizes observed and expected CLs values as a function of the POI. ...
62b441785b2c903752e2b171f325d0c671dbcb09
3,611,503
def retag_from_strings(string_tag) : """ Returns only the final node tag """ valure = string_tag.rfind('+') if valure!= -1 : tag_recal =string_tag [valure+1:] else : tag_recal = string_tag return tag_recal
5bef884498efb19eb354bb6119450c9c25a19e1c
3,611,505
def voronoi(obj, tol=0.0, bounds=None): """ Computes a Voronoi diagram. *obj* is a :class:`Geometry <geoscript.geom.Geometry>` or a ``list`` of geometries. *tol* is the snapping tolerance used to improved the robustness of the *bounds* is an optional :class:`Bounds <geoscript.geom.Bounds>` used to c...
0c77b6840f5ebb19ed6c95ea643794fb87adf692
3,611,506
def get_base_model(model_name, weights_path, weight_decay=1e-4): """ Define base model used in transfer learning. """ if not weights_path: weights_path = 'imagenet' if model_name == 'VGG16': base_model = VGG16(weights=weights_path, include_top=False) elif model_name == 'VGG19...
b52d35302de63727ec8ae1675fc6779d18e324c5
3,611,507
def _select_config(conf, root_node: str, child_node: str, selection: str): """ Extract the list of step objects corresponding to the list of names provided. Parameters ---------- conf step configuration object root_node : str node to sta...
595653fd9d03b50f78560da77f0a507ed962d441
3,611,508
from typing import Tuple def check_still_complete( segments_in: Tuple["BaseSegment", ...], matched_segments: Tuple["BaseSegment", ...], unmatched_segments: Tuple["BaseSegment", ...], ) -> bool: """Check that the segments in are the same as the segments out.""" initial_str = join_segments_raw(segme...
8e793a896f7ce85cc6d0ed43caf0e8afd180b710
3,611,509
def reinforce_loss(disc_logits, gen_logprobs, gamma, decay): """The REINFORCE loss. Args: disc_logits: float tensor, shape [batch_size, sequence_length]. gen_logprobs: float32 tensor, shape [batch_size, sequence_length] gamma: a float, discount factor for cumulative reward. decay: a float, ...
bf5b88541feb9086f98220bb78576ffcea1428c0
3,611,510
def test_mnemonic_colors(all_terms): """Make sure color shortcuts work.""" @as_subprocess def child(kind): def color(t, num): return t.number_of_colors and unicode_parm('setaf', num) or '' def on_color(t, num): return t.number_of_colors and unicode_parm('setab', num)...
e1c68fb19e08597e5aec94f8a6fb97acfd18c56d
3,611,511
def static(path): """Jinja2 filter version of staticfiles. Hopefully.""" return staticfiles_storage.url(path)
d92f54137dc5ee51bb422fd0f3d429154a6d3c69
3,611,512
def custom_after_log(resource_name, logger, log_level): """After call strategy that logs to some logger the finished attempt.""" def log_it(retry_state): log_message = f"Finished call to `{resource_name}` after " \ f"{retry_state.seconds_since_start:0.3f}(s), this was " \ ...
faaffb83e0da9afd87b939380d1808450624c61d
3,611,513
import urllib import logging def SubmitIntermoduleRequest(module, path, data=None, deadline=None): """Helper method for making calls from one GAE module to another. Args: module: GAE module name, as found in the corresponding .yaml file. path: The path portion of the intermodule URL. data: Optional ...
588918c161a0dc2d7b845452cdf1de3f533c18de
3,611,514
from snakemake.io import temp def processed_file(suffix, directory='process', magnification='10X', temp_tags=tuple()): """Format output file pattern, for example: processed_file('aligned.tif') => 'process/10X_{well}_Tile-{tile}.aligned.tif' """ file_pattern = f'{directory}/{magnification}_{{well}}_Til...
c4e7b5fc1faa5d29afbf889e874548fd1a8e3b4c
3,611,515
import pathlib def get_summit_config_path(config_dir_name=".summit"): """Returns the path to the summit config directory""" home = pathlib.Path.home() return home / config_dir_name
af89240c29b440d52e41676c07cd97fa642d288d
3,611,518
def merge_coco_results(existing_coco_results, new_coco_results, image_id_offset): """ Merges the two given coco result dicts into one. :param existing_coco_results: A dict describing the first coco results. :param new_coco_results: A dict describing the second coco results. :return: A dict containing t...
78b8efe19b3f540b6b0943cacc7207a746232faf
3,611,519
def process_regex(regex): """ This function parse a regex string into a dictionary of fields and regexes Format: <field1> -> <regex1> <field2 -> <regex2> etc.""" res_dict = {} lines = regex.split("\n") for l in lines: tok = l.split("->") if len(tok) != 2: ...
ad8fb6cc1d2713de53442ce9c9defbe2a45da0a5
3,611,520
def sum_xalpha_j(samples, alpha): """Get F(x1,x2,..)= (1*x1**alpha+2*x2**alpha+...) = sum j x_j^alpha Args: samples (array_like): [N_samples, N_x] array of samples alpha (float): power of x Returns: feature (array_like): [N_samples, 1] feature grad_feature (array_like): [...
c814498f58a1958aafcbbf9416fad10ee79f339e
3,611,521
from re import T def rgb2gray(img: T.Tensor): """ Converts a batch of RGB images to gray. :param img: a batch of RGB image tensors. :return: a batch of gray images. """ if len(img.shape) != 4: raise ValueError('Input images must have four dimensions, not %d' % len(img...
deafe384ffca2e02c5e56d05b573381f6b774557
3,611,523
def get_object_for_editing(request, uid, target_klass=None): """ Return the specified instance by uid for editing. If a target_klass is provided, uid will be checked for consistency. If the request has no logged-in user, a 401 Response will be returned. If the item is not found, a 404 Response will...
8fee58f0ffc206ecf5775f26beb88567134fc7d8
3,611,524
def before_request(): """Updates session with values coming from the query string if present. If credentials are invalid, set error flag, for error wrapper to redirect to settings page. """ update_session_for('editorial_features', coercion=lambda x: x == 'enabled') if is_changing_credentials()...
0aa25a3be214da77df2db8075ad95379854786f5
3,611,525
def get_price_including_tax(soup): """ Analyze "soup" to extract price with tax. Args: soup -- bs4.BeautifulSoup from http request of book url. Return: price with tax """ table = soup.table cell = table.find_all("td") price_including_tax = cell[3].text return price_includ...
e59672a873377ee42348573a8ea54409771a844d
3,611,526
from ._coo import COO def broadcast_to(x, shape): """ Performs the equivalent of :obj:`numpy.broadcast_to` for :obj:`COO`. Note that this function returns a new array instead of a view. Parameters ---------- shape : tuple[int] The shape to broadcast the data to. Returns -----...
81e72532c70f4aa0dd055db1ca748f9cae28e44d
3,611,527
from datetime import datetime import math def get_julian_datetime(date): """ Convert a datetime object into julian float. Args: date: datetime-object of date in question Returns: float - Julian calculated datetime. Raises: TypeError : Incorrect parameter type ValueError: ...
4195b9d05d6696df1f2b6f3dd45dfa10fb88a460
3,611,528
def invoke(kind, topology=None, inputs=None, schemas=None, params=None): """ Invoke an SPL operator with an arbitrary number of input ports and arbitrary number of output ports. """ if topology is None: topology = inputs.topology # Add operator invocation op = topology.graph.addOp...
3aa5d93e1dc612b3956dc33fadc1b9889eed5972
3,611,529
import logging def create_table(dynamodb, table_name, partition_key, sort_key={}, rcu=15, wcu=5): """ Purpose: Create an DynamoDB Table by name Args: dynamodb (DynamoDB Resource Object): DynamoDB Object owning the Table table_name (String): Name of table to return partition...
192a6a0d643d6bf6604d91517bc37a76cf61a9bd
3,611,532
def _equal(a, b, rtol, atol): """Returns True if a == b. a and b are both strings, floats or numpy arrays.""" # python 2/3 compatibility: convert raw bytes to string a = fix_string(a) b = fix_string(b) if isinstance(a, str): return a == b return np.allclose(a, b, rtol=rtol, atol=atol)
af33d92f02571c52155a6cb4a1f6aac69010996a
3,611,533
def is_rm_textfile(filename): """Returns True if the given filename is a known remarkable-specific textfile.""" if filename.endswith('.json'): return True if filename.endswith('.content'): return True if filename.endswith('.pagedata'): return True if filename.endswith('.bookm...
fd2d05fb1900d432c63d9b2bad0b802e5e00c601
3,611,534
import requests def get_postcode_data_GCR(postal_code): """request data from geocoder.ca""" URL = "https://geocoder.ca" PARAMS = {'postal': postal_code, 'geoit': "XML"} resp = requests.get(url = URL, params = PARAMS) resp = resp.content.decode() root = ET.fro...
289e877c740be5496aa54e778e7986d58b08bbcf
3,611,535
def get_piis_for_date(query_str, year=None, loaded_after=None): """Search ScienceDirect through the API for articles and return PIIs. Parameters ---------- query_str : str The query string to search with. year : Optional[str] The year to constrain the search to. loaded_after : O...
77436c17ebd811247cbf286efa474dbd4310c280
3,611,537
def postDailyStandUp(): """ Post in slack the daily standup for all users in a specific channel """ team_meet_up = services.datastore().retrive_daily_team_meetup() msg = prepare_standup_message(team_meet_up) slack.post_with_attachment(msg, config["channel"]) return "ok"
ba48242a250b4f1d369c6e0456586aeba7431325
3,611,538
def get_sandbox(report=MAIN_REPORT): """ Retrieves the current sandbox instance attached to this report. Typically, this is used to retrieve the sandbox without running the students' code. Args: report (:py:class:`pedal.core.report.Report`): The report with the sandbox instance....
6da242496a7205e24aa88ade2c8de1dddac3427c
3,611,539
from re import T def sheva_na_after_long_vowel(last_vowel, prev, guess): """`sheva` after long vowel is `sheva-na` Source: [Simanim] 3.1.3 > `sheva` after a long vowel without an accent is a `sheva-na`. Source: [HaMillon] 2.16.3 > `sheva` after a long vowel is `sheva-na`. """ if ( ...
5200ff6056cb14779a95c90cae27707a2a5889b2
3,611,540
def testGameMap(): """ ***TEST CASES*** """ # testing item adj/name collision testsword = Weapon("elvish sword", "A blade of Elvish make.", 2, weight=2) testsword2 = Weapon("rusty elvish sword", "A discarded old blade of Elvish steel.", 2) testsword3 = Weapon("sword elvish rusty", "A mix of adjectiv...
f9dd269cda17172820b808790cc7a9f1b7428938
3,611,541
def conv1x1BN(in_planes, out_planes, stride=1, groups=1, dilation=1, require_relu=False): """1x1 convolution with padding followed by batch-normalization""" if require_relu is True: return cm.ConvBNReLU(in_planes=in_planes, out_planes=out_planes, ...
809dfeb07030d386146f4366b4e6be930832e2ed
3,611,542
from mage import endpoint def mutate(q): """ Perform a raw mutation. Args: q (str): The mutation to run Example: >>> import mage >>> mage.connect() >>> mage.mutate("createAssessment(input: {type: EXTERNAL, name: "test", assessmentClientId: "12345"}) {id}) """ ...
ded80ffefaa47ee9cb13c946feacc914a626487c
3,611,543
async def get_recipe_summary( start=0, limit=9999, session: Session = Depends(generate_session), user: bool = Depends(is_logged_in) ): """ Returns key the recipe summary data for recipes in the database. You can perform slice operations to set the skip/end amounts for recipes. All recipes are sorted by ...
3406dc5c6e3e71ed090482915b0335916938215f
3,611,545
from .data.predictive_models import latest_model_outputs from .data.manual_overrides import get_currently_overridden_reaches def compose_tweet() -> str: """Generates the message that gets tweeted out. This function does not actually send the Tweet out; this function is separated from the function that sen...
af22a43c4f38ce54f5950384cc2f08088c21517e
3,611,547
def calc_grad_norms(model): """Computes a gradient clipping coefficient based on gradient norm.""" norms = [] for p in model.parameters(): if p.grad is None: continue modulenorm = p.grad.data.norm() norms += [modulenorm] return norms
6a35dafa04182716c0de1ffd5edc969118c8f078
3,611,548
def load_filtered_data(detector): """ Load a filtered dataset and the corresponding mask. :param detector: an instance of the class Detector :return: the data and the mask array """ root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( initialdir=detector.datad...
36f0cff7ef85335117ef061d864fa205065d311a
3,611,549
def put_user(user_id): """update a user""" user = storage.get("User", user_id) if user is None: abort(404) if not request.get_json(): return make_response(jsonify({'error': 'Not a JSON'}), 400) for attr, val in request.get_json().items(): if attr not in ['id', 'email', 'creat...
226c18d8f3ea417d85259ae1af755dfab715caf0
3,611,550
def force_gd1(pot,ro,vo): """Return the force at GD-1""" # Just use R=12.5 kpc, Z= 6.675 kpc, phi=0 R1= 12.5 Z1= 6.675 p1= 0. return (potential.evaluateRforces(pot,R1/ro,Z1/ro,phi=p1, use_physical=True,ro=ro,vo=vo), potential.evaluatezforces(pot,...
3fe5deb850b4d1e039131fda746e9ccc8889b3aa
3,611,551
def count(self): """自定义一个count函数,替代Paginator内的count函数""" sql, params = self.object_list.query.sql_with_params() sql = sql % params cache_key = md5(sql.encode('utf-8')).hexdigest() # 先去redis内取 rows = cache.get(cache_key) # 如果取不到,再去数据库内查询 if not rows: rows = self.object_list.count(...
62d52efb0d179b5921509d60de7c4b5340444b67
3,611,552
def potentialAxi(R,pot,vc=1.,ro=1.): """ NAME: potentialAxi PURPOSE: return the potential INPUT: R - Galactocentric radius (/ro) pot - potential vc - circular velocity ro - reference radius OUTPUT: Phi(R) HISTORY: 2010-11-30 - Written - Bov...
05f693a3e3151739c75e5386adcad51b0d40484a
3,611,553
def convert_hcc_hg(rsun, b0, l0, x, y, z=None): """Convert Heliocentric-Cartesian (HCC) to Heliographic coordinates (HG) (given in degrees).""" if z is None: z = np.sqrt(rsun**2 - x**2 - y**2) # z[z < 0] = np.NAN b0 = np.deg2rad(b0) l0 = np.deg2rad(l0) cosb = np.cos(b0) sinb = ...
4c3fde8c97d891ce1b4e433b97a93f1dd74f1c06
3,611,554
from typing import List from typing import Any from typing import Dict def create_filter_dict(filter_type: str, filter_by: str, filter_value: List[Any], operator: str) -> Dict[str, Any]: """Creates a dictionary with the filter for the list-incidents request. :param filter_type: The filter type. :param fi...
31c1a86c9fdfb193669e99cb1425bea9c89bf367
3,611,555
import time def simulate_qubit_pairs_3D_lattice(cbrt_n, m): """ Simulates a set of qubits in a 3D lattice grid of shape cbrt_n x cbrt_n x cbrt_n. Performs six seperate rounds when applying gates to ensure that the depth of the circuit is accurate Runs the simulation a total of m times and returns ...
5e96c20927b3daa02d189f8e5ee3268aa8767a91
3,611,556
def _fofactory(tag, attribs): """ Factory to create each element with the fo: namespace. """ return ElementTree.Element(_foname(tag), attribs)
3fe149f72c7d58f514cbc3967bccc94cb79451d8
3,611,557
import copy def calMultiRegression(bt,sf,of,leadingTime,ty1,ty2,py1,py2,predictors,fstType,pError,sError,oError,bError,countE): """ calculate multiple regression bt: best track data ty1: year1 ty2: year2 predictors: predictors fstType: fst variable type pError:...
1c49a2d9929d47e8deb0671f0f6ed3d3b1ac819a
3,611,558
def compute_Omegas(M_omega, lambdas, method='lbfgs', n_epoch=1000, lr=1.): """Compute Omegas directly from M_omega""" Ws = compute_Ws(M_omega, lambdas, method=method, n_epoch=n_epoch, lr=lr) Omegas = Omegas_from_Ws(Ws, M_omega, lambdas) return Omegas
278c6188345a2f0ad8d79dbf72bb1bd36c1493c8
3,611,559
def ensemble_transfer_matrix(NAtoms, kd, g1d, gprime, gm, Delta1, Deltap, Omega): """ NAtoms: The number of atoms kd: The product of the wavevector k of the input quantum field (and also approximately the wavevector of the classical drive) and the dis...
0ae6d59c62131edc13d51920b4fd4bf44bcf82e5
3,611,560
def graph_model(fgraph, *model_args, **model_kwargs): """Create a PyMC3 model from a Theano graph with `RandomVariable` nodes. """ model = pm.Model(*model_args, **model_kwargs) nodes = [n for n in fgraph.toposort() if isinstance(n.op, RandomVariable)] rv_replacements = {} for n...
494f4115642d25ed61f9d4d825e87d72af638ddb
3,611,561
def synthesis2(model, text, CONFIG, use_cuda, ap, speaker_embeddings=None, style_wav=None, truncated=False, enable_eos_bos_chars=False, #pylint: disable=unused-argument do_trim_silence=False, ...
8fb215b0209e789b3a8c77189e600c7e6f201b03
3,611,562
def get_resource_name(prefix, project_name): """Get a name that can be used for GCE resources.""" # https://cloud.google.com/compute/docs/reference/latest/instanceGroupManagers max_name_length = 58 project_name = project_name.lower().replace('_', '-') name = prefix + '-' + project_name return name[:max_nam...
7779f71e00063b32566f05d4cb0d8daef81043c0
3,611,563
def imresize(img, size, return_scale=False, interpolation='bilinear'): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple): Target (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, a...
161c4336135cc965905262cb993903e318800f19
3,611,564
def do_test(template_str, context_dict=None, autoescape=True, lang_code="en-us"): """ Use django's templating engine to render a template against a context Arguments: :param template_str: The template to render :param context_dict: The context to render the template against ...
b56b44772ed0a32da6a4ca837b073b870841434a
3,611,565
from pathlib import Path from typing import Dict def get_punctuality_list_for_buses(buses_coordinates: pd.DataFrame, stops_coordinates: pd.DataFrame, api_key: str = None, path: Path = None, ...
bdf5bc77566ff5782699e621037ff9ab15fc2a85
3,611,566
def pytest_collection(session: _pytest.main.Session): """ See :func:`_pytest.hookspec.pytest_collection_modifyitems` for documentation. Also see the "`Writing Plugins <https://docs.pytest.org/en/latest/writing_plugins.html>`_" guide. """ if is_nait_mode(): f = pytest.File(py.path.local(_...
d830f33147892a41e1c46c257b72a1f9a086c7fb
3,611,567
def rpc_schema_exists(schema): """ test that an event-machine schema exists """ return eventstore(schema).storage.db.schema_exists()
7a69dd1be356173730cacb6dda788fc4cb79cda6
3,611,568
def find_beat(v): """ find the beat of a vector format midi using the autocorrelation function """ # binary vector for testing autocorrelation v2 = [0 if x[0] == -1 else 1 for x in v] result = [] # no need to check more than 24*4 = 96 # i.e. 4 quarter notes of standard midi for lag i...
b408afced09779eb69b40ae54d1fd2c2cfcf1906
3,611,569
import configparser def dd_status(img_size: int) -> float: """ function to read the output file of dd and convert it to a percent completion :param img_size: size of the image :return: percent completion of dd """ config = configparser.ConfigParser() config.read(get_config()) con ...
00739b6a35e4cfd5227ee8fef6ba498a37a3fd39
3,611,570
def get_config_var(name): """Return the value of a single variable using the dictionary returned by 'get_config_vars()'. Equivalent to get_config_vars().get(name) """ return get_config_vars().get(name)
5df1f05f70ae2a88640b02f1cd274fdf79a4fabe
3,611,571
def interpolate_line2d(xs, ys=None, interpol=3, window=3, verbose=3): """interpolate 2D vector. Description ----------- Smoothing a 2d vector can be challanging if the data is low sampled. This function contains two steps. First interpolation of the input line followed by a convolution. Parame...
be747fb52620e17aa415628c3fb7e3adb1e25ebe
3,611,572
import torch def _generate_anchors(base_size, scales, aspect_ratios): """Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, base_size - 1, base_size - 1) window. """ anchor = np.array([1, 1, base_size, base_size], dtype=np.float) - 1 anchors = _ratio_e...
a932ecfacac98d874435ff560375fd4509eefe66
3,611,573
from pathlib import Path def matplotBandGaps(x1, y1, x2, y2, xlabel, ylabel, filename, title=None, addOLS = True, first=False): """ A function used to plot band gaps. ... Args ---------- x : list (dim:N) A list containing numeric values with np.nan as non-entries y : list (dim:N) ...
4a30c5b99cb64ced48459e454d695c6ce0d75bf1
3,611,574
import threading def _front_operate( callback, work_pool, transmission_pool, utility_pool, termination_action, operation_id, name, payload, complete, timeout, subscription, trace_id): """Constructs objects necessary for front-side operation management. Args: callback: A callable that accepts pack...
222aad67b31e4927d3702598c56ea8c857da2f7d
3,611,575
def handle_RepeatFirstError(exc, source): """Handles situation where ``repeat`` was uses wrongly as it did not appear as the first keyword of a given statement. """ _ = gettext_lang.lang params = exc.args[0] linenumber = params["linenumber"] begin = linenumber - 1 end = linenumber + 1...
de0bde1af1ca097f9117e2e06d1898b8a056212f
3,611,576
from typing import Iterable def gradient_point(point: float, gradient: Iterable[str] = REDGREENGRADIENT) -> str: """Get color at a point on color gradient.""" if point < -1 or point > 1: raise ValueError("Point must fall on range [-1, 1]") elif len(gradient) != 3: raise ValueError("Gradient must be an iterable...
53a04df449626c428cc1f11a818e539dce74cb74
3,611,577
def transform(query, schema, origin=None): """ transform Args: query(dict): query schema(dict): schema origin(list): logical form Returns: parse result Rsises: NULL """ preprocess_schema(schema) if origin is None: lf = query['predicted_rule_tokens'] else: ...
2004d0e3cbdae61ad05ca74c51daf8de45862b9e
3,611,578
def read_line_from_file(file): """Reads one line from a file and returns it as string.""" with open(file, "r") as f: result = f.readline() return result
3f3da3642e7931469e853c977aef67cd1024bbe5
3,611,579
def _bidirectional_pred_succ(G, source, target, ignore_nodes=None, ignore_edges=None, force_edges=None): """Bidirectional shortest path helper. Returns (pred,succ,w) where pred is a dictionary of predecessors from w to the source, and succ is a dictionary of success...
0e8caf06e22bd5dbceb52d50f09664f656847567
3,611,580
def subset_partition(lst): """ Finds the two subsets that partition the lst in such a way that the sum of elements in both subsets are equal pre: lst should be a list of numbers ( can be float or int) post: returns the two subsets with equal sum """ if sum(lst) % 2 != 0: r...
ed24ad12c08265aa56c3b3bf51c430c616f98c7b
3,611,581
from typing import Union from typing import List from typing import Dict from typing import Optional from typing import OrderedDict def plot_task_completion_rates( completion_rates: Union[List[float], Dict[str, List[float]]], bins: Union[list, range] = None, ax: Optional[Axes] = None ) -> Axes...
0e82ef33aae854d9d1b710cefe28b44a9caec40e
3,611,582
import struct def deflate_long(n, add_sign_padding=True): """turns a long-int into a normalized byte string (adapted from Crypto.Util.number)""" # after much testing, this algorithm was deemed to be the fastest s = bytes() n = long(n) while (n != 0) and (n != -1): s = struct.pack('>I', n &...
8d70b4b733ece9ea66d5cd4e84eb8e04ba14b6a9
3,611,584
def get_todays_image(session: Session = Depends(generate_session), group_name: str = "Home"): """ Returns the image for todays meal-plan. """ group_in_db: GroupInDB = db.groups.get(session, group_name, "name") recipe = get_todays_meal(session, group_in_db) if recipe: recipe_image = ima...
c280c4089203131ccfdd3d7d4cdb8dd0ba6cc8ce
3,611,585
def plot_imgs( img_list, row_title=None, cmap='viridis', show_axis=False, tight_layout=True, figsize=(10, 6) ): """Plot a series of cropped images. Parameters ---------- img_list : str A list of images to be plotted. row_title : str, optional Y-axis la...
b3ddc2cf9b77c386c77cfe710625f4ae5a957fa3
3,611,586
def sdO(data): """ This is the evolutionary definition of the sdB phase, which is defined as a core He burning phase where the star looks spectroscopically as an sdO star. This is defined as Teff higher than 40000 K. If the star does not have a core He burning phase as defined by HeCoreBurning, this fu...
6c7f0d74d019c8149e1675a6cc0e8c0d5fcdb986
3,611,587
def get_ecf_club(database, key): """Return ECFrefDBrecordECFclub instance for dbrecord[key].""" c = database.get_primary_record(filespec.ECFCLUB_FILE_DEF, key) cr = ECFrefDBrecordECFclub() cr.load_record(c) return cr
becb7e4ad34ba0421acadde28e01c80754598c72
3,611,588
def find_known_node(node): """ Iterate through the config_dict to find to which key the given <node> might corresponds too. Returns: (str or None): config_dict key if match found else None """ for known_node, node_data in config_dict.items(): if node_data["check"](n...
3317444e8fadfd59a518541f3543cace78e9c8dd
3,611,589
import pandas as pd import numpy as np from datetime import datetime import json from fhirclient.models import clinicalprofile, fhirreference, identifier, codeableconcept, fhirdate, quantity def writeLabProfile(labs_counts, labs_frequencyPerYear, labs_fractionOfSubjects,labs_units, labs_names, lab...
1d7ef5d01514136be01cbf64fcc62e2714393dbc
3,611,590
def makeDicts(): """make a dict out of a live packet capture w/ the data we want""" listOfDicts = [] for pkt in capture.sniff_continuously(packet_count=50): listOfDicts.append({"source": pkt["ip"].src, "destination":pkt["ip"].dst, "protocol":pkt.highest_layer}) return listOfDicts
d4a0f940672cc309ce633541696eb09f60ee3eff
3,611,591
def create_sub_graph_by_node_capacity(dump_path=LIGHTNING_GRAPH_DUMP_PATH, k=64, highest_capacity_offset=0): """ Creates a sub graph with at most k nodes, selecting nodes by their total capacities. :param dump_path: The path to the JSON describing the lightning graph dump. :param k: The maximal number ...
61f5af0551c33bac03f27be7b271d47430a106d6
3,611,592
def parsething(thing): """I figure out what 'foobar baz in quux quum is not documented' means, and return: the name of the foobar, and the kind of the foobar. """ if thing.startswith("Compound "): tp, name = "type", thing.split()[1] else: m = THING_RE.match(thing) if not m...
eb86de61812983a1605c50b36c6150fb477e4737
3,611,593
from typing import Dict from datetime import datetime from contextlib import suppress import copy def process(business: Business, # pylint: disable=too-many-branches filing: Dict, filing_rec: Filing, filing_meta: FilingMeta): # pylint: disable=too-many-branches """Process the...
a437ca7056bd51627f9d3b86c0239212fb052983
3,611,594
def from_rotation_around_x(angle): """Get the rotation matrix for rotation around X. Args: angle: rank N tensor of shape [..., 1]. Returns: rank N+1 tensor of shape [..., 3, 3] containing rotation matrices. Raises: ValueError: if the shape of angle is invalid. """ angle = tf.convert_to_tensor...
1d25b9a06e20e9045b6d5d48baf7f7986a67545e
3,611,595
def direct_field_search(queryset, field_names, search_string, as_of_date=None): """Takes a queryset and a list of field names that the search string can act on.""" # Split the string in case of first name, surname e.t.c search_strings = tokenize_search_string(search_string) q_filter = Q() for se...
8f8f98fb2ad8ba2584040546d5e7b23e000ffed4
3,611,597
def get_all_triplets(labels: ndarray) -> ndarray: """Select all possible triplets of (anchor, positive, negative) from batch""" triplets = [] pos_pairs, neg_pairs = get_all_pairs(labels) for pos in pos_pairs: for neg in neg_pairs: if pos[0] == neg[0]: triplets.append(...
3e48fefc94f16eb1aa2b298e6bad569a47833312
3,611,598
def get_start() -> dict: """Получение start при запуске бота.""" start = client.start() if start: return start sleep_delay() return get_start()
2470e56182485e2efee91a8fa0d3e387467e70a6
3,611,599
def _get_block_timestamp_from_web3( web3: Web3, block_number: int, ) -> int: """ Gets the timestamp of a block from the blockchain. will raise an exception if the block is not found. """ return web3.eth.getBlock(block_number).timestamp
dd0210c1250c0c3d955e3965b35dab700ad817a4
3,611,600
def round_float(value, precision=1): """ Returns the float as a string, rounded to the specified precision and with trailing zeroes (and . if no decimals) removed. """ return str(round(value, precision)).rstrip("0").rstrip(".")
afa167709c73b2c536a795c0e38975e212311210
3,611,601
def get_etcd_client(): """ Gets the Etcd Client instance using host and port defined in TOTEM_ETCD_SETTINGS :return: Instance of etcd.Client :rtype: etcd.Client """ return etcd.Client(host=TOTEM_ETCD_SETTINGS['host'], port=TOTEM_ETCD_SETTINGS['port'])
aa25a0610d44cc84d85e149ecd9b0c948b8aa9f1
3,611,603
def _widen_hsv_color_range(color_range, proportion): """Widens range by proportion new lower bound = old - (old * proportion / 2) new upper bound = old + (old * proportion / 2) """ new_range = [[None, None, None], [None, None, None]] max_values = [180, 255, 255] # h, s ,v for i in range(3): ...
f4a1f9867cbe34b92ee8d157c6a277780712c587
3,611,604
from datetime import datetime def date(candidate: str) -> datetime.date: """Converts ECMWF-format date strings into a `datetime.date`. Accepted absolute date formats: - YYYY-MM-DD - YYYYMMDD - YYYY-DDD, where DDD refers to the day of the year For example: - 2021-10-31 - 19700101 ...
9cbe50172a70d68e0ac2fdc33ed0716e27333dda
3,611,606
def test_game(game,team): """Broken out so we can test for all kinds of variations once we build the variation list.""" return (team.lower() in [game["competitions"][0]["competitors"][0]["team"]["location"].lower(), game["competitions"][0]["competitors"][1]["team"]["location"].lower(), game["competitions"][0]["co...
7e35d434415ba5cb94fd02f119bd59f5f98898fb
3,611,607
def calculate_parse_metrics(gold_corpus, annotated_corpus): """Calculate POS/UAS/LAS accuracy based on gold and annotated sentences.""" check.Eq(len(gold_corpus), len(annotated_corpus), 'Corpora are not aligned') num_tokens = 0 num_correct_pos = 0 num_correct_uas = 0 num_correct_las = 0 for ...
bd51d29a2debd4553d1e3f80e0b6dfb813602efb
3,611,608
import numpy def ifftn(x1, s=None, axes=None, norm=None): """ Compute the N-dimensional inverse discrete Fourier Transform. Multi-dimensional arrays computed as batch of 1-D arrays Limitations ----------- Parameter ``norm`` is unsupported. Parameter ``x1`` supports ``dpnp.int32``, ``dpnp...
3582a38d713230c4125464163feaf8c2511c2a27
3,611,609
import re def get_summary(icalendar_text: str): """Get the first SUMMARY: line from an iCalendar text. Do not care about the line being continued. """ match = re.search(SUMMARY_PATTERN, icalendar_text) return match[1]
34b75d9e6614075fcafb900b0d8f05fd5714d3e8
3,611,610