content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def exp_map(x, r, tangent_point=None): """ Let \(\mathcal{M}\) be a CCM of radius `r`, and \(T_{p}\mathcal{M}\) the tangent plane of the CCM at point \(p\) (`tangent_point`). This function maps a point `x` on the tangent plane to the CCM, using the Riemannian exponential map. :param x: np.array,...
798ee0a7016e84a454d2786b9a58c9bce23b8f62
42,955
def count_media_packages(distribution_artefacts): """ Count media packages in nested list. :param distribution_artefacts: Nested list containing distribution artefacts mapped to media packages and tenants :type distribution_artefacts: dict :return: Amount of media packages :rtype: int """ ...
715fb6e1fc1791051265a21021884a201ff08485
42,956
def get_eos_df(df,order,volpp_name='volpp',epp_name='Epp',with_error=False): """ obtain eos_df for df Args: df (pd.DataFrame): raw data, must have columns [volpp,epp] order (int): polynomial order, must be one of 1,2,3 """ data = [] snamel = df.sname.unique() for sname in snamel: sel = df.sname...
81a2859490edadde316f5e6649145e78b89a0193
42,957
def value_at_risk_1d_nb(returns, cutoff=0.05): """See `empyrical.value_at_risk`.""" returns = returns[~np.isnan(returns)] if len(returns) < 1: return np.nan return np.percentile(returns, 100 * cutoff)
86ab8bf763a79f868a57f5d0fcfe913d5e1fa151
42,958
def read_last_processed(): """Read last processed build number.""" with open("last_processed", "r") as fin: return int(fin.readline())
4362696222c0469c0150632650f07feb0f1a3273
42,959
def best_model_from_trials(trials): """Extract and return the best model object from trails.""" valid_trial_list = [trial for trial in trials if STATUS_OK == trial['result']['status']] losses = [float(trial['result']['loss']) for trial in valid_trial_list] index_having_minimum_lo...
f5e6e2ce339d418614510cb5645b9e8eff0e7a11
42,961
def get_region_keys(options): """ Extract the region name and credentials, from the options. :param options: options returned from OptionParser().parse_args() :type options: optparse.Values :rtype: k.aws.config.RegionAwsCreds """ region_name = options.region if not region_name: region_name = DEFAULT_REGION_...
a19fecefe11bef8cdc2242595c0bd6d92c4b63c4
42,962
def dirac(t, n, freq, pulse_delay): """ :param t: time sequence (s). :type t: list of floats :param n: time iteration index :type n: int :param freq: frequency of the sinusoid (Hz) :type freq: float :param pulse_delay: number of iteration for the delay of the signal defined in the i...
280234938eed8818666368d66b815ccb967b6dbb
42,963
import pickle import time def video_classify(video_name): """ extract_feature """ logger.info('predict ... ') logger.info(video_name) imgs_path = video_name.replace(".mp4", "").replace("mp4", "frames") pcm_path = video_name.replace(".mp4", ".pcm").replace("mp4", "pcm") # step 1: extra...
68276bcff8dd7d15c645a9d9daa2515486865785
42,964
def make_mag_column_names(instrument, filters): """ Given as input the instrument name and the list of filters needed, this routine generates the list of output header values for the Mirage input file. Parameters ---------- instrument : str 'NIRCam', 'NIRISS', or 'Guider" filte...
e003b1afb3ea2dccc4d7a29971779821e0d67361
42,965
def update(request, tid): """Update a PAF.""" return render(request, 'transaction/update.html', {})
24bac9561c0cad412218191d49eb1dbf5895279f
42,966
def get_student_sessions(): """ This api returns the student's sessions within a time frame. """ student_id = request.json.get('student_id', None) start_time = request.json.get('start_time', None) end_time = request.json.get('end_time', None) start_time_utc = datetime_string_to_utc(start_ti...
7cd360eb77bc91af69598dceb733aebb6d059671
42,967
import platform def get_macos_version(): """returns a tuple with the (major,minor,revision) numbers""" # OS X Yosemite return 10.10, so we will be happy with len(...) == 2, then add 0 for last number try: mac_ver = tuple(int(n) for n in platform.mac_ver()[0].split('.')) assert 2 <= len(mac...
982ae4be358fbfbda02a8b184f51c7f097353a58
42,968
def RunModel(num_parameters, num_training_samples): """ Creates a logistic regression model of size num_parameters by initializing the parameters randomly. Generates ground truth for the model and adds the specified amount of noise to the labels. Then uses gradient decent to train the model and determines the...
6df51d24091589d78199da9212d01cef7ed35ea7
42,969
import torch def DeterminePeople(tensor, classes): """ Input: Tensor of all objects detected on screen Output: Tensor of only 'people' detected on screen """ PersonIndexes = [] #Index of 'person' in tensor CurrentIndex = 0 for t in tensor: cls = int(t[-1]) ObjectDetected = "{0...
37f0875fe4fbb5e636e5f63795b5634072fb80a7
42,970
def get_query_date_index(timeframe="today 5-y"): """Queries Google trends to have a valid index for query results that returned an empty dataframe Args: timeframe (string): Returns: pd.Series: date index of Google trend's interest_over_time() """ # init pytrends with query that ALW...
a23b08f56348d5f6b9d9812b9934bb72bd0b33dc
42,971
def _l2t_section(label, include_section, include_marker): """Helper function converting section labels to text. Assumes _l2t_subterp, _l2t_interp, and _l2t_appendix failed""" if include_marker: marker = u'§ ' else: marker = '' if include_section: # Regulation Text with secti...
01052effeba4f00fb1024d91c954aa6031153973
42,972
def extract_scores_from_outlist_file(outlist): """ :param outlist: :return: """ scores = {'SEED': [], 'FULL': [], 'OTHER': []} outlist_fp = open(outlist, 'r') for line in outlist_fp: if line[0] != '#': line = [x for x in line.strip().split(' ') if x!=''] s...
cdaf7dca6784e6b7c5d9afd31b207d651824371e
42,973
def init_services(service_definitions, client_get, client_authn_factory=None): """ Initiates a set of services :param service_definitions: A dictionary containing service definitions :param client_get: A function that returns different things from the base entity. :param client_authn_factory: A lis...
9e2184e2e0fd755a44c8bdcd74b979793ea36945
42,974
def get_clients(units=None, cacert=None): """Create a list of clients, one per vault server. :param units: List of IP addresses of vault endpoints :type units: [str, str, ...] :param cacert: Path to CA cert used for vaults api cert. :type cacert: str :returns: List of CharmVaultClients :rty...
b324e54e4468b5d518f3beeba8d916bb50a36509
42,977
def var_to_np(var): """Convenience function to transform `torch.Tensor` to numpy array. Should work both for CPU and GPU.""" return var.cpu().data.numpy()
5c68a839f4d9c4dfbcf3ec7d695ebacf402470ae
42,978
def is_aaai_url(url): """determines whether the server from url @param url : parsed url """ return 'aaai.org' in url.netloc
36a5a71de9c40ad287e44f064aa85053ed13eef9
42,979
import ssl import ctypes def ModExp(a, b, c): """Uses openssl, if available, to do a^b mod c where a,b,c are longs.""" if not _FOUND_SSL: return pow(a, b, c) # convert arbitrary long args to bytes bytes_a = number.LongToBytes(a) bytes_b = number.LongToBytes(b) bytes_c = number.LongToBytes(c) # conv...
2cb6c47b33a0ede55df72cce2e6d960f80bd00bc
42,980
def get_words_label(words_data: list) -> list: """ 得到当前数据集下的词汇表 :param words_data: 读取到的词语数据 :return: 词汇表 """ # 使用 set 去重 words_label = set({}) for words in words_data: words_label.update(words[1]) res = list(words_label) res.sort() return res
d9ce0701c3c1baff1067d5c96a7730dc42b027f9
42,982
def home(request): """ Controller for the app home page. """ # Get the options for the GLDAS Variables variables = gldas_variables() variable_opts = [] for key in sorted(variables.keys()): variable_opts.append((key, variables[key])) del variables date_opts = available_dates()...
45a4d19c90f0b91c79b72da9e930144408a10992
42,983
import json def add_identifier(request): """ Create an Actor Identifier. Should be an AJAX POST. :param request: Django request. :type request: :class:`django.http.HttpRequest` :returns: :class:`django.http.HttpResponseRedirect` """ if request.method == "POST" and request.is_ajax(): ...
e366c33c1960fe0e505cf427ce4a1c4a42bd6760
42,984
def alias_(expression, alias, table=False, dialect=None, quoted=None, **opts): """ Create an Alias expression. Expample: >>> alias_('foo', 'bar').sql() 'foo AS bar' Args: expression (str or Expression): the SQL code strings to parse. If an Expression instance is pass...
2f82256913d610c28ba500773717679e8cbaff8e
42,986
async def async_attach_trigger(hass, config, action, automation_info): """Listen for state changes based on configuration.""" device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(config[CONF_DEVICE_ID]) trigger = (config[CONF_TYPE], config[CONF_SU...
a2b9ee295d648c689f9f6e8d6e55f9d568cd940e
42,987
import functools def forward_errors(func): """ Transforms ``func`` in order to forward any ``grpc.RPCError`` returned by the upstream grpc as the result of the current grpc call. """ @functools.wraps(func) def wrapper(self, request, context, *args, **kwargs): try: return f...
4c33fa2ac5ec0241a5c783de78da7dcb7d9690b9
42,988
import decimal def add_graph_data(graph, dataset, value, cluster=None, horiz_value=None, pval=None, val_min=None, val_max=None): """Add a graph datapoint. Return the newly created GraphData object on success. Raise a LoaderException on error, or if the provided arguments are not valid for the graph. """ if ...
0a3e6be86174433de140cad4d2a2e5870e8a1acf
42,989
def run_sim(systems, trades, edge=0.1, pnl=0.01): """ 模拟多个参数组合的资金曲线,策略的胜率从-edge ~ edge :param systems: 参数数量 :param trades: 交易次数 :param edge: 最优参数的额外胜率 :param pnl: 每次交易盈亏百分比的标准差 :return: 实际最优参数的排名,回测结果最好参数的实际edge """ # 参数1~N的盈利笔数 win_rate_list = 0.5 + np.linspace(-1 * edge, edge,...
67db3b4c9ce90c9316049eb9246c443cc904b2a3
42,990
def verify_ldp_database_session( device, interface=None, expected_interface=None, label_type='input', local_label=None, max_time=60, check_interval=10, ): """Verifies ldp session exists Args: device (obj): device object interface (str): Interface to use in show comma...
4173d56992468542e2d56ffb5be9a97ea341891a
42,991
def get_exptype_counts(exposures, calibs, width=300, height=300, min_border_left=50, min_border_right=50): """ Generate a horizontal bar plot showing the counts for each type of exposure grouped by whether they have FLAVOR='science' or PROGRAM='calib' ARGS: exposures : a table of exposures whic...
ed1378b9749ce188b70933768c54078a270db613
42,993
def map(**kwargs): """Returns a dictionary of the given keyword arguments mapped to their values from the environment. """ d = {} e = lower_dict(environ.copy()) for k, v in kwargs.iteritems(): d[k] = e.get(v) return d
4bd95e2575fa6262c5635fbf805c4dbe1272b01c
42,994
def login_ui(): """ Login to OpenShift Console return: driver (Selenium WebDriver) """ logger.info("Get URL of OCP console") console_url = config.UI_SELENIUM.get("url") browser = config.UI_SELENIUM.get("browser_type") if browser == "chrome": logger.info("chrome browser...
280278c3db9eac33c6f49f85c58c8cd4388f8591
42,996
def hover_over(spell: str, stopcast: bool = False, dismount: bool = True, ) -> str: """ Hover over target. """ macro = f'#showtooltip {spell}\n' if stopcast: macro += '/stopcast\n' if dismount: macro += '/dismount\n' macro += f'/use [@mous...
74586c97b971cbfab169c1777b6c82921015e8ba
42,997
def read_story_file(filename): """read story file, return three lists, one of titles, one of keywords, one of stories""" title_list, kw_list, story_list = [], [], [] with open(filename, 'r') as infile: for line in infile: title, rest = line.strip().split('<EOT>') kw, story = ...
f354618f57eef3f8c842f2802044bc0fea0666f7
42,998
def rotate_points(points, width=600, height=300): """180 degree rotation of points of bbox Parameters ---------- points: list or array Coordinates of top-left, top-right, bottom-left and bottom-right points width, height: int Width/height of perspective transformed module image Return...
ca15ebb21d9c34ba69049831395ce48de44c70a7
42,999
def inSkipTokens(start, end, skip_tokens: list) -> bool: """ Check if start and end index(python) is in one of skip tokens """ for token in skip_tokens: if start >= token[0] and end <= token[1]: return True return False
a51124471eb9f1c3be84f132fc4cce3dad6ef336
43,000
def comp(a,b,av=None,bv=None,domatch=True,out=None) : """ VSCATTER comparison of two different data sets """ if domatch : i1,i2=match.match(a['APOGEE_ID'],b['APOGEE_ID']) gd = np.where(a['NVISITS'][i1] == b['NVISITS'][i2])[0] a=a[i1[gd]] b=b[i2[gd]] fig = vscat(a) vs...
265834ad57d4eae8e2ef4278e56bba593f1af62c
43,001
def create_canvas_obj(stroke_width, drawing_mode, realtime_update, background_image, key, height, width): """ Creating a canvas object in Streamlit with the parameters specified by the user. """ canvas_result = st_canvas( fill_color="rgba(255, 165, 0, 0)", stroke_width=stroke_width, ...
c0bc8b5f82b0fc6f4f2624923de8e8b93e77fa5e
43,002
import time def get_observed_entity_list(): # noqa: E501 """get observed entity list get observed entity list # noqa: E501 :param timestamp: the time that cared :type timestamp: int :rtype: EntitiesResponse """ timestamp = time.time() entities = [] # obtain tcp_link entities ...
2ff032fd62a825d673a513ce7789ae4ed7055713
43,003
def datetime_to_time_str(dattim): """ Converts datetime to a string containing only the time. @rtype : str """ return dattim.strftime(TIME_STR_FORMAT)
a93e124a9ebcf531e5dca1c0816a3a0e6ddf1dfa
43,004
from typing import List from typing import Union def nest_tokens(tokens: List[Token]) -> List[Union[Token, NestedTokens]]: """Convert the token stream to a list of tokens and nested tokens. ``NestedTokens`` contain the open and close tokens and a list of children of all tokens in between (recursively nes...
14e6c803a7ce3c9ce50f47ea69dfd6b7d6e09db6
43,005
def is_restricted(fname): """ Is the filename restricted - not to be downloaded by non question editors? """ if fname in ('datfile.txt', 'datfile.dat', 'qtemplate.html', 'marker.py', 'results.py'): return True if fname.startswith("_"): return True if fname.en...
5da7491791aed0364c685a30854c8d9d268eeb5c
43,007
def getBlock(lines, row): """ Parameters ---------- lines row Returns ------- """ block = [] for i in range(row, len(lines)): if lines[i][0] == 'END': return i, block else: if lines[i][0] != '#': block.append(lines[i])
7c8f8e45084eb9ff92d7c68fc03bf285d98ab2d7
43,008
def serve_suggestions(request): """Returns a list of nodes matching the given query""" # Retrieving the query query = request.GET.get("q") if query: # connecting to mongodb with the credentials defined above client = pymongo.MongoClient(f"mongodb://{USERNAME}:{PASSWORD}@{HOSTNAME}") ...
8e9625da706b0ba0906be8fa0f78e452b0386a88
43,009
from pathlib import Path import tomli def get_project_name() -> str: """Find project name, which is prefix for info distributions. Returns: str: the name of package specified in pyproject.toml Raises: EnvironmentError: if file pyproject.toml is not found. """ pyproject_path = sea...
500c549ba799ef845687c5704abd9f8753366e8c
43,010
import math def gcj02_to_wgs84(lng, lat): """ GCJ02(火星坐标系)转GPS84 :param lng:火星坐标系的经度 :param lat:火星坐标系纬度 :return: """ if not in_hz(lng, lat): return lng, lat dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * ...
1fd96b505d9651ed3ad386094d115eb046113d41
43,012
def get_related_sets(node): """Return objectSets that are relationships for a look for `node`. Filters out based on: - id attribute is NOT `pyblish.avalon.container` - shapes and deformer shapes (alembic creates meshShapeDeformed) - set name ends with any from a predefined list - set in not in ...
a901ce6ce367faa01691e6e0131bdcba1e399205
43,013
import re def get_geoinfo(location: str) -> dict: """ Infer geographical ISO information from location :param location: geo location of the person :return: dictionary with ISO geo-information """ mapping = get_country_mapping() if location: search = re.search(r'\((.*?)\)', location...
74f55d45286ac3170282d63383af7a8e473c2381
43,015
def Hl_operator(omega): """ implements Hl operator in eq 20 """ omega_norm = np.linalg.norm(omega) term1 = (1/2)*np.eye(3) if (omega_norm < 1.0e-5): return term1 term2 = np.nan_to_num((omega_norm - np.sin(omega_norm)) / (omega_norm**3)) * skew(omega) term3 = np.nan_to_num(...
839ff879c45a2551e02ad4c95e59207bddf8dab1
43,016
def get_world_inverse_matrix(mobj): """ Returns world inverts matrix of the given Maya object :param mobj: MObject, Maya object we want to retrieve world inverse matrix of :return: MMatrix """ inverse_matrix_plug = api.DependencyNode(mobj).find_plug('worldInverseMatrix', want_networked_plug=Fal...
3be1fdc05c04eaf8ebfd5e1f757900ec2fd496b6
43,017
def sum_of_even_valued_fibonacci_numbers() -> int: """Sum of even valued Fibonacci numbers. The values of the Fibonacci sequence should not exceed four millions. Returns: int: returned sum. """ return sum(get_even_fibonacci_sequence())
1405bb172f82638c7da56b74491ded54e660e8ae
43,018
from typing import Dict from typing import Any def get_event_dict(event: Event) -> Dict[str, Any]: """Get event dict.""" final_event_dict = {} event_dict = event.__dict__.copy() final_event_dict["point"] = event.point.__dict__.copy() final_event_dict["is_site"] = event.is_site final_event_dict...
f75cbdba563fd428b7b13367e155b98cd35c6711
43,019
from datetime import datetime def get_customer_lifetime(df_cust, ref_date, start_date): """ Takes in a customer dataframe and returns the customer lifetime based on a reference date. Parameters: ----------- df_cust : dataframe Customer dataframe ref_date : str ...
8cc20bee96ec61b71e24b9e0e17dd4d5f034cc1f
43,020
def helicsFederateIsAsyncOperationCompleted(fed: 'helics_federate') -> "helics_bool": """ check if the current Asynchronous operation has completed Parameters ---------- * `fed` : the federate to operate on Returns ------- 0 if not completed, 1 if completed """ retur...
282e4831e84212be5eec0dd48968d852e04fbe27
43,021
def svn_fs_change_node_prop(*args): """ svn_fs_change_node_prop(svn_fs_root_t root, char path, char name, svn_string_t value, apr_pool_t pool) -> svn_error_t """ return _fs.svn_fs_change_node_prop(*args)
87c8cd35189257e75c65eea23e6abdb969e283ea
43,022
def macaulay_duration(cashflows, discount_rate): """ Computes the Macaulay Duration of a sequence of cash flows """ discounted_flows = discount(cashflows.index, discount_rate)*cashflows weights = discounted_flows/discounted_flows.sum() return np.average(cashflows.index, weights=weights.squeeze()...
eee20c900ad7b2f65a34ab1d10a1bf73e87cef9f
43,023
def precheck(context): """ calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_' (e.g. "precheck_ami_id") Checking function should return True if OK, or raise RuntimeError w/ message if not Args: context: a populated EFVersionContext object Returns: True if the p...
c4bb435dc40d9504f710d9c4df4ca11163e037c8
43,024
from pathlib import Path async def print_text(req: Request, request: PrintTextRequest) -> ResponsePayload: """Print a text""" config = Config() database = Database() print_id = database.generate_print_id() username = req.state.user_info["username"] printer = Printer() _print_header(config...
9ca8d3e2e2664aac01cc55456a58520a65a265eb
43,025
def catch_index_error(what, otherwise): """ runs callable 'what' and catches IndexErrors, returning 'otherwise' if one occurred :param what: callable :param otherwise: alternate result in case of IndexError :return: result of 'what' or 'otherwise' in case of IndexError """ try: retur...
9138dcea8464f98fcf84edc4d0991cafe9ebd97c
43,026
def alert(alertID=1): """ Serves an individual alert investigation report for the given alert ID. """ pageState = "{ type: 'alert', dataID: '" + alertID + "' }" return render_template( 'technical/index.html', content=g.config['TECHNICAL_CONFIG'], page=pageState, langa...
86ef70d5fbfa45d4a0f84598bb07347f2bc6b6de
43,027
def decode_data_sequence(data): """Read encapsulated data and return a list of strings. Parameters ---------- data : str String of encapsulated data, typically dataset.PixelData Returns ------- list of bytes All fragments in a list of byte strings """ # Convert data...
ed98e459741cbf741a48f40a0a484c248222886f
43,028
def LF_CG_DISTANCE_SHORT(c): """ This LF is designed to make sure that the compound mention and the gene mention aren't right next to each other. """ return -1 if len(list(get_between_tokens(c))) <= 2 else 0
920a0db568e82f6f841f57ea682b3bfd42a1d9da
43,029
def generate_motions(p, u, a, d, plane_center, bbox, radius=500, n=32): """Generate random robot motions that point sensor at plane Generate n motions that keep the sensor at position p and orientation u pointing at the plane given by a[0] + a[1] + a[2] + d = 0 Args: p: 3D position of sensor o...
5962464cdf33dab9fb1a5d2609ade533e04b95a6
43,030
from datetime import datetime def timesince(dt, default="just now"): """ Returns string representing "time since" e.g. 3 days ago, 5 hours ago etc. """ now = datetime.utcnow() diff = now - dt periods = ( (diff.days / 365, "year", "years"), (diff.days / 30, "month", "m...
3b4ecbd30f7769c746e1b7485f8c84ff626d13e5
43,031
def group_zero_one_loss(y_true, y_pred, group_membership, *, normalize=True, sample_weight=None): """A wrapper around the :any:`sklearn.metrics.zero_one_loss` routine. The arguments remain the same, with `group_membership` added. However, the only positional a...
4f7b664185587bb2852c255f6a8ae791fca0be2f
43,033
from typing import Union def build_from_dataframe(data: pd.DataFrame, tz: Union[str, list]=None, unit: Union[str, list]=None, name: Union[str, list]=None, type: Union[str, list]=None ) -> list:...
ae43ef4b198e52df1db07fb9a5207ac0d8479835
43,035
def unauthorized(): """Redirect unauthorized users to Login page.""" flash("You must be logged in to view that page.") return redirect(url_for("auth.login"))
a2f4d45c3f2ab215ba350759102022de849804d6
43,036
def shape(parameter): """ Get the shape of a ``Parameter``. Parameters ---------- parameter: Parameter ``Parameter`` object to get the shape of Returns ------- tuple: shape of the ``Parameter`` object """ return parameter.shape
ceb2b9a6199d980386b306ff329b797dc1815a29
43,037
def readFlatWFS(fn,interp=None): """ Load in data from WFS measurement of flat mirror. Assumes that data was processed using processHAS, and loaded into a .fits file. Scale to microns, strip NaNs. If rotate is set to an array of angles, the rotation angle which minimizes the number of NaNs i...
f3f0872cc071f23c7c68c8cb503a209167968e27
43,038
def filter_specials(letter): """Filter based on dict SPECIAL""" return SPECIAL[letter] if letter in SPECIAL else letter
ef152930615c2eb9158de30ebfa2be773b900e90
43,039
from typing import Union from typing import Sequence def mape_score( y_true: Union[Sequence[float], np.ndarray, pd.Series], y_pred: Union[Sequence[float], np.ndarray, pd.Series], ) -> float: """Calculates the Mean Absolute Percentage Error, a common metric used for Time Series Problems Parameters ...
baa87b285e81eb26323547d0e9d5ea7c5eff8dcd
43,040
import inspect import tempfile import scipy def EKOI(x,n=INFO, small=True,dir=tempDir, sz=500., label=""): """ output x variable name, create an image based on x value and output a string which cause emacs to display the image """ r = "" frame = inspect.currentframe() ff = inspect.getouterfram...
df3fae3335f6003ca276ae69661650fdd7f3be35
43,042
def get_fusion_major_courses(fusion_major_soup): """ :param related_major_soup: SoupParser.soup_jar['융합전공'] :return: ["빅데이터융합", ...] """ lecture_dropdown = fusion_major_soup.find_all('div', {'style': 'height:10em;overflow-y:scroll;'})[1] ret = [] for i in lecture_dropdown.find_all(...
ec053466955547140e458e0d17e8935d81e3da1c
43,043
def setup(hass, base_config): """Start Tentalux platform.""" config = base_config.get(DOMAIN) host = config[CONF_HOST] port = config[CONF_PORT] name = 'tentalux' controller = TentaluxController(host, port) controller.connect() devs = {'light': [], 'scene': [], 'camera': []} # One l...
2d1a26560a2b2ef03b8ecbd74e8fd2dcdd8db278
43,044
def position_split(position_source, position_cible): """Prend les arguments positions_sources et position_cible et sépare la lettre et le chiffre. Les chiffres sont transformé en entier dans l'objectif d'appliquer des opérations mathématiques. La lettre est transformé en index dans l'objectif d'apli...
51216b32614a6d9dd41216b445b9cc3036abf8f3
43,046
def shannon_entropy(mag, magerr): """Shannon entropy (Shannon et al. 1949) is used as a metric to quantify the amount of information carried by a signal. The procedure employed here follows that outlined by (D. Mislis et al. 2015). The probability of each point is given by a Cumulative Distribution Fun...
67628d332a2a0c028d39f3e074968ed5fb9c597f
43,048
def _item_attributes_match(crypto_config, plaintext_item, encrypted_item): # type: (CryptoConfig, Dict, Dict) -> Bool """Determines whether the unencrypted values in the plaintext items attributes are the same as those in the encrypted item. Essentially this uses brute force to cover when we don't know the ...
3b1520b05c043e0f3aaec40746646e9297dc4136
43,050
import json def get_all_years(): """ All years report """ return json.dumps(query_for_date(4))
97af82b3116ef18dfa90073b8ca096790d3d519a
43,052
def generate_title_label_pred(tweets_dict): """Generate predicted cluster labels for data points based on title similarity""" global tfidf_titles # Get the list of sample_num number of titles from the dict corpus title_list = corpus_list(tweets_dict, 0, sample_num) # Taking stems and synonyms into account for stri...
7c9d419acd001992df8ad764c55c39697c77f875
43,053
def underline_code( source: str, location: SourceLocation, end_location: SourceLocation, padding: int = 1, ) -> str: """Underline code.""" pos, lineno, colno = location end_pos, end_lineno, end_colno = end_location view_begin = pos view_end = end_pos for _ in range(padding + 1)...
de50934cf8cb692366ea87fe45d4774aee6a3715
43,054
def generateTruth(samples): """ generates truth data is sample infected :param samples: samples to generate truth for :return: truth """ truth = [{'SampleID': sample['SampleID'], 'Truth': decision(sample['CurrentProb'])} for sample in samples] return tru...
8ca0cf4ccdafe97769ab4f8f7a1dc90d9b5b4d37
43,055
def aggregate_single_eval( # noqa: C901 result_dict: dict, all_seeds_for_run: list, eval_name: str ) -> dict: """Mean over seeds of single config run.""" new_results_dict = {} data_temp = result_dict[all_seeds_for_run[0]] # Get all main data source keys ("meta", "stats", "time") data_sources = ...
17edc40ff26dfceecbb85f21dc97ffa52abe6973
43,056
def information(file_name): """ adds information extension, if missing :param file_name: name of file :type file_name: str :returns: file with extension added :rtype: str """ return _add_extension(file_name, Extension.INFORMATION)
125fe007c33e00aceee50e159ce41f494d4ffddc
43,057
from typing import Union from typing import Optional def restrict_chat_member(token: str, chat_id: Union[int, str], user_id: int, permissions: ChatPermissions, until_date: Optional[int] = None ...
ce2069c63fea420593b79d3c72298e346f7d8ac6
43,058
def access_message(user_profile, message_id): # type: (UserProfile, int) -> Tuple[Message, UserMessage] """You can access a message by ID in our APIs that either: (1) You received or have previously accessed via starring (aka have a UserMessage row for). (2) Was sent to a public stream in your r...
f120077e133a09ef94be2ae7ae3aeff2fb4778da
43,059
def transfer_continue_pinyin_to_hanzi(param, model='dag'): """ 全拼音按音节切分后转汉字 :param param: :param model: :return: """ try: if param.strip() == '': raise Exception('invalid param') if is_chinese(param): return param else: pinyin = con...
49e2716bda2c65f2159f0b39b07bbd326353f79a
43,060
def del_clipboard(): """Delete a clipboard entry""" id = int(request.form.get("id")) cb.delete(id) return ""
71511b9e403b280ffa14d1861c1eaf7c97240b1d
43,062
from typing import Optional from typing import Dict from typing import Callable from typing import Any from typing import List def to_list( mapping: Optional[Dict[Key, Val]], key_transform: Callable[[Key], Any] = str_if_bytes, val_transform: Callable[[Val], Any] = to_redis_type, ) -> List: """Flattens...
c04c351858281d1807ea5e388bb4466217f71d29
43,063
def check_down_diagonal(board): """ Checks to see if one of the players got all the spaces in the diagonal going from top-left corner to bottom-right corner. If so, it returns the symbol for that player. If not, it returns None. """ symbol = board[0][0] for row in range(1, SIZE): if board[...
7cf37de563288482fa6608efa7cb2151ea352ed4
43,064
def get_bbf_file(data_file_name): """Return information from file in bbf/bbf/data/... Do NOT call on import time -- that would make flamedisx unusable to non-XENON folks! """ ensure_repo('XENON1T/bbf.git', BBF_PATH) return fd.get_resource(f'{BBF_PATH}/bbf/data/{data_file_name}')
6be27a840bc73b6290f958a13536aa770b6d6af2
43,065
def load( phonopy_yaml=None, # phonopy.yaml-like must be the first argument. supercell_matrix=None, primitive_matrix=None, is_nac=True, calculator=None, unitcell=None, supercell=None, nac_params=None, unitcell_filename=None, supercell_filename=None, born_filename=None, f...
53197ded23e46c38410acab530301036969f6c92
43,066
def vote(): """ allows the governance contract to approve or deny a new value if governance approves, the num_votes counter increases by 1 if governance rejects, the reporter's ALGO stake is sent to the governance contract solidity equivalent: slashMiner() Args: 0) will always be equal...
2020c77b0d765164da81c9b54f28121ed640649f
43,068
def load_w2v_instance(file_path): """ Load a word2vec instance given its file path. :param file_path: File path where the instance is located. :return: Word2vec instance. """ return w2v.Word2Vec.load(file_path)
8399e084e10c31954caef9c6a601a35394a357da
43,069
import requests def get_streets_with_postal_codes_by_city(city_name, way_type=None): """ :param city_name: name of city in English :return: """ query_template_path = core_path() / 'osm' / 'templates' / 'get_streets_with_postal_codes_by_city_name.txt' with query_template_path.open(...
3e88baa1337f00667b0d51ac93d8386cef801712
43,070
def get_maj_answer(votes_per_answer): """ :param votes_per_answer: dictionary with {'1': int, '2': int}, where the ints add up to NBR_ANNOTATORS :return: the majority answers, i.e., number of votes at least half that of the number of annotators; raises error if the answers are tied """ if (len(...
87baeafd2ff39c4aa0ea970f501d1c195ffadecd
43,071
def find_subsequence(sequence, query): """ Find a subsequence in a sequence. Parameters ---------- sequence : Sequence The sequence to find the subsequence in. query : Sequence The potential subsequence. Its alphabet must extend the `sequence` alphabet. Retu...
c21e37866df09ac71b7af7a1d33a4a82b168ce17
43,072
def get_retention_period(instance): """ Finds "Backup" tag in list of tags or returns default period (7 days) :param instance: dict Dictionary output with instance details from describe_instances call :return: Retention period for that instance """ for tag in instance["Tags"]: if tag["Ke...
4f122f91ecdae5cead86a8f1703d7c9d19111e16
43,073