content
stringlengths
22
815k
id
int64
0
4.91M
def unit_parameters(_bb_spine_db_export: dict, _grid_name: str, _node_name: str, _unit_name: str, _time_index, _alternative='Base', _eff_level=1, _p_unit=False, _node_name_if_output=None, _node_name_if_input=None ): """ :param _bb_spine_db_export:...
7,800
def read_from_file(file_path): """ Read a file and return a list with all the lines in the file """ file_in_list = [] with open(file_path, 'r') as f: for line in f.readlines(): file_in_list.append(line) return file_in_list
7,801
def count(predicate, iterable): """ Iterate over iterable, pass the value to the predicate predicate and return the number of times the predicate returns value considered True. @param predicate: Predicate function. @param iterable: Iterable containing the elements to count. @return: The number o...
7,802
def get_object_from_path(path): """ :param path: dot seperated path. Assumes last item is the object and first part is module path(str) - example: cls = get_object_from_path("a.module.somewhere.MyClass") you can create a path like this: class_path = "{0}.{1}".format...
7,803
def _get_collection_memcache_key(collection_id, version=None): """Returns a memcache key for the collection. Args: collection_id: str. ID of the collection. version: int. Schema version of the collection. Returns: str. The memcache key of the collection. """ if version: ...
7,804
def test_landsat_id_pre_invalid(): """Raises error on invalid pre-collection.""" scene = "L0300342017083LGN00" with pytest.raises(InvalidLandsatSceneId): landsat8._landsat_parse_scene_id(scene)
7,805
def test_kubeadm_binary_which(host): """ Tests the output to confirm kubeadm's binary location. """ assert host.check_output('which kubeadm') == PACKAGE_BINARY
7,806
def biKmeans(dataSet, k, distMeas=calcEuclideanDistance): """ 二分K-均值算法 :param dataSet: :param k: :param distMeas: :return: """ m = np.shape(dataSet)[0] clusterAssment = np.mat(np.zeros((m, 2))) centroid0 = np.mean(dataSet, axis=0).tolist()[0] centList = [centroid0] # create...
7,807
def get(directory): """Prepare df and gdf with solar atlas tiled data.""" files_list = glob.glob(os.path.join(directory, "*", "*.csv")) data = [] for file in files_list: logging.info(file) tiles = pd.read_csv(file, header=None) tiles.columns = ["tilename", "minx", "maxx", "miny",...
7,808
def cleanup(args, repo): """Clean up undeployed pods.""" if args.keep < 0: raise ValueError('negative keep: %d' % args.keep) def _is_enabled_or_started(pod): for instance in pod.iter_instances(): if scripts.systemctl_is_enabled(instance.unit_name): return True ...
7,809
def optimizer_builder( config: Dict): """ Instantiate an optimizer. :param config: :return: """ # --- argument checking if not isinstance(config, dict): raise ValueError("config must be a dictionary") # --- read configuration decay_rate = config["decay_rate"] de...
7,810
def convertfile(filename, orig=1): """Convert the filename given from using Numeric to using NumPy Copies the file to filename.orig and then over-writes the file with the updated code """ fid = open(filename) filestr = fid.read() fid.close() filestr, changed = fromstr(filestr) if ch...
7,811
def psi(z: float, a: float, b: float) -> float: """Penalty function with uniformly bounded derivative (Eq. 20) Args: z: Relative distance a: Cohesion strength b: Separation strength """ c = np.abs(a - b) / (2 * np.sqrt(a * b)) return ((a + b) / 2) * (np.sqrt(1 + (z + c) ** 2)...
7,812
def caselessSort(alist): """Return a sorted copy of a list. If there are only strings in the list, it will not consider case. """ try: return sorted(alist, key=lambda a: (a.lower(), a)) except TypeError: return sorted(alist)
7,813
def EnableRing(serialPort): """ Enable the ISU to listen for SBD Ring Alerts. When SBD Ring Alert indication is enabled, the 9602 asserts the RI line and issues the unsolicited result code SBDRING when an SBD Ring Alert is received. """ ...
7,814
def verify_image(filename_or_obj, format, resolution): """ Verify that the image in filename_or_obj has the specified format and resolution. """ width, height = resolution if format in RAW_FORMATS: size1 = ( math.ceil(width / 16) * 16 * math.ceil(height / ...
7,815
def render(template, **context): """Render the given template. :param template: The template file name or string to render. :param **context: Context keyword-arguments. """ class Undefined(BaseUndefined): def _fail_with_undefined_error(self, *args, **kwargs): try: ...
7,816
def read(pth, format=None, encoding=None, cols=None, **kwargs): """Returns the contents of a file into a string or format-dependent data type (with special handling for json and csv files). The format will either be inferred from the file extension or can be set explicitly using the `format` arg. Text ...
7,817
def audio(src: str) -> str: """ Insert audio tag The tag is currently not supported by Nuance, please use `audio_player` kit: docs/use_kits_and_actions.md :param src: :return: """ return f'<audio src="{src}"/>'
7,818
def read(*rnames): """ Read content of a file. We assume the file to be in utf8 """ return open(os.path.join(os.path.dirname(__file__), *rnames), encoding="utf8", mode="r").read()
7,819
def PerpendicularDistanceToFinish(point_b_angle: float, point_b: gps_pb2.Point) -> float: """ cos(B) = Adjacent / Hypotenuse https://www.mathsisfun.com/algebra/trig-finding-side-right-triangle.html """ return math.cos(math.radians(point_b_angle)) * point_b.start_finish_dista...
7,820
def get_revolut_stocks() -> List[str]: """ Gets all tickers offered on Revolut trading platform. Returns: list(str) """ import requests req = requests.get("https://globefunder.com/revolut-stocks-list/") tickers = list(pd.read_html(req.content)[0]["Symbol"]) tickers = [ticker.re...
7,821
def move_recipes_by_condition(path, directory_name, condition): """ Moves the recipes that satisfy conditon to a new directory called directory_name """ os.mkdir(directory_name) recipe_list = list_recipes_by_condition(path, condition) for recipe in recipe_list: shutil.move(recipe, os.getcwd(...
7,822
def response_text(response_class): """ Return the UTF-8 encoding of the API response. :param response_class: class to cast the response to :return: Text of the response casted to the specified class """ def _inner(f): @wraps(f) def wrapper(obj, *args, **kwargs): res...
7,823
def create_rankings( a: Dataset, b: Dataset, n_samples: int = 100, unravel: bool = False, **kwargs: int ) -> Tuple[ndarray, ndarray]: """ Sample a dataset 'a' with 'n' negative samples given interactions in dataset 'a' and 'b'. Practically, this function allows you to generate evaluation data as de...
7,824
def make_even(x): """Make number divisible by 2""" if x % 2 != 0: x -= 1 return x
7,825
def get_num_vehicles(session, query_filters): """Gets the total number of annotations.""" # pylint: disable-msg=E1101 num_vehicles_query = session.query( func.count(Vehicle.id)) \ .join(Photo) \ .filter(Photo.test == True) \ # pylint: enable-msg=E1101 for query_filter i...
7,826
def create_python_src_file(basedir, daystr, sample_count): """Creates a skeleton python file.""" filename = '' if sample_count == 1: filename = '../input/sample.txt' else: filename = '../input/sample1.txt' with open(os.path.join(basedir, 'src', daystr + '.py'), 'w') as file: message = ( "imp...
7,827
def task_status_edit(request, status_id, response_format='html'): """TaskStatus edit""" status = get_object_or_404(TaskStatus, pk=status_id) if not request.user.profile.has_permission(status, mode='w'): return user_denied(request, message="You don't have access to this Task Status") if request...
7,828
def is_windows_system(): """ | ##@函数目的: 获取系统是否为Windows | ##@参数说明:True or False | ##@返回值: | ##@函数逻辑: | ##@开发人:jhuang | ##@时间: """ return 'Windows' in platform.system()
7,829
def seepage_from_unitary(U): """ Calculates leakage by summing over all in and output states in the computational subspace. L1 = 1- sum_i sum_j abs(|<phi_i|U|phi_j>|)**2 """ sump = 0 for i in range(2): for j in range(2): bra_i = qtp.tensor(qtp.ket([i], dim=[2]), ...
7,830
def auto_get(*args): """ auto_get(type, lowEA, highEA) -> ea_t Retrieve an address from queues regarding their priority. Returns 'BADADDR' if no addresses not lower than 'lowEA' and less than 'highEA' are found in the queues. Otherwise *type will have queue type. @param type (C++: atype_t *) @para...
7,831
def isLineForUser(someLine=None, username=None): """determins if a raw output line is for a user""" doesMatch = False try: doesMatch = utils.isLineForMatch(someLine, username) except Exception as matchErr: logs.log(str(type(matchErr)), "Error") logs.log(str(matchErr), "Error") logs.log(str((matchErr.args)),...
7,832
def get_view_class(callback): """ Try to get the class from given callback """ if hasattr(callback, 'view_class'): return callback.view_class if hasattr(callback, 'cls'): return callback.cls # TODO: Below code seems to not do anything.. mod = importlib.import_module(callback....
7,833
def create_multipart_upload(s3_obj, bucketname, object_key): """ Initiates Multipart Upload Args: s3_obj (obj): MCG or OBC object bucketname (str): Name of the bucket on which multipart upload to be initiated on object_key (str): Unique object Identifier Returns: str : M...
7,834
def test_dispatcher_config_needed_problem(): """Command needs a config, which is not there.""" class MyCommand(BaseCommand): help_msg = "some help" name = 'cmdname' needs_config = True def run(self, parsed_args): pass groups = [('test-group', 'title', [MyCommand...
7,835
def cn(DB): """Return the cursor and connection object.""" conn = sqlite3.connect(DB) c = conn.cursor() return (c,conn)
7,836
def _build_category_tree(slug, reference=None, items=None): """ Builds a recursive tree with category relations as children. """ if items is None: items = [] for key in reference: category = reference[key] if category["parent"] == slug: children = _build_catego...
7,837
def test_parse_config(): """Test noded.conf parsing.""" config = noded.parse_config("conf/noded.conf") assert config.get("defaults", "redis_host") == "localhost" assert config.getint("defaults", "redis_port") == 6379 assert config.getint("defaults", "redis_db") == 0 assert config.getint("default...
7,838
def partially_matched_crossover(random, mom, dad, args): """Return the offspring of partially matched crossover on the candidates. This function performs partially matched crossover (PMX). This type of crossover assumes that candidates are composed of discrete values that are permutations of a given se...
7,839
def add(eq, sign): """Adds a character to the "equation" list, consisting of two numbers and an operation sign between them""" print(sign, end=" ") add_more(eq, sign) print(eq) if len(eq) > 3: count(eq) print(eq)
7,840
def regex_trim(input, regex, replace=''): """ Trims or replaces the regex match in an input string. input (string): the input string to search for matches regex (string): regex to match replace (string - optional): a string to replace any matches with. Defaults to trimming the match. """ return re.sub(regex, re...
7,841
def test_d2scan(): """ Test ``d2scan`` scan (1D step scan) along two axes with ZP motors. """ print("Running scan ..") uid, = RE(d2scan([sclr1,zebra,merlin1,xspress3],10,zpssx,-1,1,zpssy,-1,1,0.1)) print("Scan is completed") print("Filling the table ...") _ = db[uid].table(fill=True) ...
7,842
def getENVIframeDir(strPathScene, sSubDir=None): """ Return directory containing envi frames frame bsqs in this dir are named FR_yyyy.mm.dd_X.bsq Optional subdirectory name sSubDir. workaround for non standard directory organization. """ strWild = strPathScene + r'SEQhdr\ENVI_FR*' ...
7,843
def LoadAllSuitesOfProject(project_name): """Loads all of the suites of a project.""" project_key = db.Key.from_path(bite_project.BiteProject.kind(), project_name) return BiteSuite.all().ancestor(project_key)
7,844
def debug(line: str = None, cell: str = None, local_ns = None): """Toggle debugging mode for the current cell."""
7,845
def calc_temps(start_date, end_date): """TMIN, TAVG, and TMAX for a list of dates. Args: start_date (string): A date string in the format %Y-%m-%d end_date (string): A date string in the format %Y-%m-%d Returns: TMIN, TAVG, and TMAX """ return session.query...
7,846
def __check_rse_usage(rse: RseData, greedy: bool = False, logger: "Callable[..., Any]" = logging.log) -> 'Tuple[int, bool]': """ Internal method to check RSE usage and limits. :param rse_name: The RSE name. :param rse_id: The RSE id. :param greedy: If True, needed_free_space will be set to 1T...
7,847
def train_model(ad, rsrc_loc, algo='IR', log_dir=None): """ Train a CellO model based on the genes of an input dataset. Parameters ---------- ad : AnnData object Expression matrix of n cells by m genes algo : String The name of the algorithm used to train the model. 'IR' ...
7,848
def ps_roi_max_align_2d( x, rois, roi_indices, outsize, spatial_scale, group_size, sampling_ratio=None ): """Position Sensitive Region of Interest (ROI) Max align function. This function computes position sensitive max value of input spatial patch with the given region of interests. Each RO...
7,849
def received_date_date(soup): """ Find the received date in human readable form """ return utils.date_text(history_date(soup, date_type="received"))
7,850
def show_avail_tasks() -> None: """ Print the available and callable tasks (FabSim3 APIs or plugins tasks) """ avail_task_dict = {} for task_name, task_obj in env.avail_tasks.items(): if not hasattr(task_obj, "task_type"): continue if hasattr(task_obj, "plugin_name"): ...
7,851
def create_observation_from_inat_data(inaturalist_data): """Creates an observation in our local database according to the data from iNaturalist API. :returns: the observation (instance of Nest or Individual) created. Raises: TaxonMatchError """ observation_time = dateparser.parse(inaturali...
7,852
def get_cert_sha256_by_openssl(certraw: str) -> str: """calc the sha1 of a certificate, return openssl result str""" res: str = None tmpname = None try: tmpname = tmppath / f"{uuid.uuid1()}.crt" while tmpname.exists(): tmpname = tmppath / f"{uuid.uuid1()}.crt" tmpname...
7,853
def analytic_pi(x, c, w, h): """Analytic response function for an even pair of Lorentz distributions. Correspond to .. math:: \\Pi(x) = \\int_{-\infty}^{\\infty} \\frac{\\omega^2}{\\omega^2+x^2}\sigma()_{i} where :math:`\\sigma(\\omega)` is :func:`~even_lorentzian`. Args: x...
7,854
def run(canvas): """ This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None """ canvas = np.array(canvas) next_gen_canvas = np.array(create...
7,855
def initialize_vocabulary(vocabulary_path): """Initialize vocabulary from file. We assume the vocabulary is stored one-item-per-line, so a file: dog cat will result in a vocabulary {"dog": 0, "cat": 1}, and this function will also return the reversed-vocabulary ["dog", "cat"]. Args: vocabulary_p...
7,856
def ravel_space(space): """ Convert the space into a Discrete space. """ dims = _nested_dim_helper(space) return Discrete(dims[0])
7,857
def _add_col(dataframe, metadata, col_limits, families, weights, random_state): """Add a new column to the end of the dataframe by sampling a distribution from ``families`` according to the column limits and distribution weights and sampling the required number of values from that distribution.""" nrow...
7,858
def read_and_decrypt_mylogin_cnf(f): """Read and decrypt the contents of .mylogin.cnf. This decryption algorithm mimics the code in MySQL's mysql_config_editor.cc. The login key is 20-bytes of random non-printable ASCII. It is written to the actual login path file. It is used to generate the r...
7,859
def list_files(tag=None, inst_id=None, data_path=None, format_str=None, supported_tags=None, file_cadence=dt.timedelta(days=1), two_digit_year_break=None, delimiter=None, file_type=None): """Return a Pandas Series of every file for chosen Instrument data. Parameters ----------...
7,860
def is_on_top(bb1, bb2): """ For obj 1 to be on top of obj 2: - obj1 must be above obj 2 - the bottom of obj 1 must be close to the top of obj 2 """ bb1_min, _ = bb1 _, bb2_max = bb2 x1,y1,z1 = bb1_min x2,y2,z2 = bb2_max return z1 < z2 + ONTOP_EPSILON and is_above(bb1, ...
7,861
def main_menu(args): """ Display main menu """ # Main menu prompts selection contains function choice = qust.select('Public Building Manager - Main Menu', choices=load_main_entires(), style=st).ask() # Call funtion of menu entry if choice: choice(args)
7,862
def finishing(): """ Finish the deployment, clean up server(s). """
7,863
def prepare_definitions(defs, prefix=None): """ prepares definitions from a dictionary With a provided dictionary of definitions in key-value pairs and builds them into an definition list. For example, if a dictionary contains a key ``foo`` with a value ``bar``, the returns definitions will be a li...
7,864
def load_training_data(mapsize=512, grfized=False, exclude_fid=False, dense_grid=False, random_split=False, from_files=False): """Load data for different training scenarios.""" if not grfized and (not dense_grid) and (not random_split): # the default data ...
7,865
def concat_features(args, feature_dim_name='feature'): """Concatenate Xs along a set of feature dimensions Parameters ---------- args : iterable list of tuples of the form (dims, DataArray) where dims is a tuple of dimensions that will be considered feature dimensions Returns ------- ...
7,866
def _inspect_mixin( self, geoctx=None, format="pyarrow", file=None, timeout=30, client=None, **params ): """ Quickly compute this proxy object using a low-latency, lower-reliability backend. Inspect is meant for getting simple computations out of Workflows, primarily for interactive use. It's quick...
7,867
def list_dvs(service_instance): """ Returns a list of distributed virtual switches associated with a given service instance. service_instance The Service Instance Object from which to obtain distributed virtual switches. """ return utils_common.list_objects(service_instance, vim.Distributed...
7,868
def setup(app): """Call methods during builder initiated.""" app.connect("builder-inited", build_mapping_tables)
7,869
def generate(env): """Add Builders and construction variables for LaTeX to an Environment.""" env.AppendUnique(LATEXSUFFIXES=SCons.Tool.LaTeXSuffixes) import dvi dvi.generate(env) import pdf pdf.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.ltx', LaTeXAuxAction) bld...
7,870
def gdb_cli_args(request: FixtureRequest) -> Optional[str]: """ Enable parametrization for the same cli option """ return getattr(request, 'param', None) or request.config.getoption('gdb_cli_args', None)
7,871
def coerce_rfc_3339_date(input_date): """This function returns true if its argument is a valid RFC 3339 date.""" if input_date: return datetime.datetime.strptime(input_date, "%Y-%m-%dT%H:%M:%SZ") return False
7,872
def extract_job_url(job): """ parse the job data and extract the str for the URL of the job posted params: job str: html str representation from bs4 returns: url str: relative URL path of the job ad """ return job.a["href"]
7,873
def test_upsert_page(mocker): """Base case: page doesn't already exist""" confluence = mocker.Mock(spec=Confluence) parent_page_mock = mocker.Mock() parent_page_mock.id = mocker.sentinel.parent_page_id confluence.get_page.side_effect = [None, parent_page_mock] page = Page( space=mocker...
7,874
def commit(experiment_name, time): """ Try to commit repo exactly as it is when starting the experiment for reproducibility. """ try: sh.git.commit('-a', m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time), allow_empty=True ...
7,875
def weighted_loss(class_weights): """ Create a weighted loss function. Penalise the misclassification of classes more with the higher usage """ weight_values = list(class_weights.values()) def weighted_binary_crossentropy(y_true, y_pred): # add another dimension to compute dot product ...
7,876
def delete_cluster(resource_root, name): """ Delete a cluster by name @param resource_root: The root Resource object. @param name: Cluster name @return: The deleted ApiCluster object """ resp = resource_root.delete("%s/%s" % (CLUSTERS_PATH, name)) return ApiCluster.from_json_dict(resp, resource_root)
7,877
def reload_plugin(name): """Reloads the MIBI plug-in 'name'.""" reload('mibi.plugin.' + name)
7,878
def mk_test(x, alpha = 0.05): """This perform the MK (Mann-Kendall) test to check if there is any trend present in data or not Args: x: a vector of data alpha: significance level Returns: trend: tells the trend (increasing, decreasing or no trend) h: True (if...
7,879
def convert_event_to_boxes(event: Event) -> List[EventBox]: """Takes in an event and converts this into a list of boxes that when combined completely cover the time allocated to this event. Usually, this list will contain a single EventBox as many events start and end on the same day, but any events split a...
7,880
def limit_bone(bone, x, y, z, ik=True): """ bone: PoseBone x: (float, float) y: (float, float) z: (float, float) ik: bool """ # Bone Constraints limit = bone.constraints.new(type='LIMIT_ROTATION') limit.use_limit_x = True limit.use_limit_y = True limi...
7,881
def _reduce_consecutive_layers(conv_defs, start_id, end_id, multiplier=0.5): """Reduce the outputs of consecutive layers with multiplier. Args: conv_defs: Mobilenet conv_defs. start_id: 0-based index of the starting conv_def to be reduced. end_id: 0-based index of the last conv_def to be reduced. m...
7,882
def ajax_save_content(request): """ Save front end edited content """ site = get_current_site(request) content_name = request.POST['content_name'] cms_content = CmsContent.objects.get(site=site, name=content_name) cms_content.content = request.POST['content'] cms_content.save() return HttpRe...
7,883
def add_regional_group_costs(ws, data_sheet): """ """ ws.sheet_properties.tabColor = "92D050" ##Color white ws.sheet_view.showGridLines = False #Set blue and red border strips set_cell_color(ws, 'A1:AZ1', "004C97") set_cell_color(ws, 'A2:AZ2', "C00000") ws = bar_chart(ws, "Estima...
7,884
def normal(loc=0.0, scale=1.0, size=(1,1), sparsity=1.0): """ Draw random samples from a normal (Gaussian) distribution. Parameters ---------- loc: Mean ("centre") of the distribution. scale: Standard deviation (spread or "width") of the distribution. size: Output shape (only tuple ...
7,885
def random_data(num): """ will return json random float, hex, int and a random password {0: { 'float': 186.66541583209647, 'hex': '43435c553c722359e386804f6b28d2c2ee3754456c38f5e7e68f', 'int': 851482763158959204, 'password': '5AJ]-02X0J' ...
7,886
def test_local_branch_exists(mock_repo): """ GIVEN GitRepo is initialized with a path and repo WHEN branch.exists is called with a valid branch and None remote THEN True is returned """ repo = GitRepo(repo=mock_repo) mock_repo.branches = ["master", "test"] assert repo.branch.exists("tes...
7,887
def denied(request): """Authentication failed and user was denied.""" return render(request, 'djangosaml2/denied.html')
7,888
def getFontCoverage(f, glyphCache=None): """ Calculate a weighted average of all glyph coverages. Use frequencies of multiple languages to average out language specific bias. So it does not use all the glyphs, just the A-Z, a-z for the languages we have fequencies for. """ total = []...
7,889
def monday_of_week(year, week): """ Returns a datetime for the monday of the given week of the given year. """ str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w') date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon, day=str_time.tm_mda...
7,890
def preview_image(instance, sender, *args, **kwargs): """Updates book previews if the rating has changed""" if not ENABLE_PREVIEW_IMAGES or sender not in (Review, ReviewRating): return changed_fields = instance.field_tracker.changed() if len(changed_fields) > 0: edition = instance.book...
7,891
def object_meta(metadata: Metadata) -> Mapping[str, Any]: """ Return a minimal representation of an ObjectMeta with the supplied information. Spec: https://github.com/argoproj/argo-workflows/blob/v3.0.4/docs/fields.md#objectmeta """ meta: Dict[str, Any] = {} if metadata.generate_name_from_pref...
7,892
def assert_equal(actual: Literal["statespace"], desired: Literal["statespace"]): """ usage.statsmodels: 1 """ ...
7,893
def clear_cmd(): """ Utility function that clear the shell """ try: os.system('clear') except: pass try: os.system('cls') except: pass
7,894
def vectorize_timing(n_targets): """ Calculate the rise time of ``n_targets`` targets, return the run time in seconds. """ from time import time vega_coord = SkyCoord(279.23473479*u.degree, 38.78368896*u.degree) vega = FixedTarget(name="Vega", coord=vega_coord) target_list = n_targets*[v...
7,895
def print_stats(fromdir): """Print collected statistics.""" # Include statistics from subprocesses. for statfile in glob.glob('%s/*.dump' % fromdir): with open(statfile) as f: statblob = f.read() statdata = json.loads(statblob) for num, stat in enumerate([amqp_stats, lay...
7,896
def get_game(name, all=False): """ Get the game information for a particular game. For response object structure, see: https://dev.twitch.tv/docs/v5/reference/search/#search-games May throw exceptions on network/Twitch error. """ search_opts = { 'query': name, 'type': 'suggest', 'live': 'false', } head...
7,897
def compute_correlation_prob_class_target(candidates_per_query_target): """This function computes the overall correlation between the probability of being in the positive class and the value of the target column """ probs_per_query_target = [] gains_per_query_target = [] for key in candidates_per_query_tar...
7,898
def get(sql: str): """ execute select SQL and return unique result. select count(1) form meters or select lass(ts) from meters where tag = 'xxx' :return: only value """ result = _query(sql) try: value = result.next() except StopIteration: return None ...
7,899