content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def removeBots(gdf, bot_list): """ A Function for removing Twitter bots. Parameters ---------- gdf: <gpd.GeoDataFrame> A GeoDataFrame from which Twitter bots should be removed. bot_list: <list> Input either 'home_unique_days' or 'home_unique_weeks' ...
e938f46bcf5c87dfa81db96f127c88d948f061db
8,300
def getinput(prompt): """>> getinput <prompt> Get input, store it in '__input__'. """ local_dict = get_twill_glocals()[1] inp = input(prompt) local_dict['__input__'] = inp return inp
db26e8361518f1728edfb15c6417586f8c3ca73d
8,301
import os import torch def plot_qualitative_with_kde( named_trainer, dataset, named_trainer_compare=None, n_images=8, percentiles=None, # if None uses uniform linspace from n_images figsize=DFLT_FIGSIZE, title=None, seed=123, height_ratios=[1, 3], font_size=12, h_pad=-3, ...
f8b7c93c399c63df9cacc766da8fee99b6620ee8
8,302
import subprocess def get_git_doc_ref(): """Return the revision used for linking to source code on GitHub.""" global _head_ref if not _head_ref: try: branch = git_get_nearest_tracking_branch('.') _head_ref = _run_git(['rev-parse', branch]).strip() except subprocess...
cf4cbd6dcf1a95dc56e25ebf996e05abc35e4c86
8,303
def update_trails(force=False, offline=False): """ Update trails from feeds """ success = False trails = {} duplicates = {} try: if not os.path.isdir(USERS_DIR): os.makedirs(USERS_DIR, 0755) except Exception, ex: exit("[!] something went wrong during creatio...
2ff83a3681899d6dffa8bdcedcbb7e9839bbc919
8,304
def bq_to_rows(rows): """Reformat BigQuery's output to regular pnguin LOD data Reformat BigQuery's output format so we can put it into a DataFrame Args: rows (dict): A nested list of key-value tuples that need to be converted into a list of dicts Returns: list: A list of dictionaries ...
9ff842d1c41d7ebe5c822d4c07b2f26b5524b0fe
8,305
def network_config(session, args): """network config functions""" cmd = pluginlib.exists(args, 'cmd') if not isinstance(cmd, basestring): msg = "invalid command '%s'" % str(cmd) raise pluginlib.PluginError(msg) return if cmd not in ALLOWED_NETWORK_CMDS: msg = "Dom0 execut...
d2a551166e7d5c445f1cba6404a3e526f4e7ecdd
8,306
from DB import dbget from DB import dbput def persistent_property(name,default_value=0.0): """A propery object to be used inside a class""" def get(self): class_name = getattr(self,"name",self.__class__.__name__) if not "{name}" in name: if class_name: dbname = class_name+"."+name...
44ed6d8a20b4d84c8c4d27410ba28a17d37f7ef1
8,307
def album_id(items, sp_album): """Iterate through results to find correct Discogs album id.""" try: artist = sp_album['artists'][0].lower().replace(" ", "") except IndexError: artist = "" owners = -1 discogs_id = -1 similarity = 0 title = sp_album['name'].lower().replace(" "...
1c8f0f870c1a0c6c71de115ae6a0d15cf235af6f
8,308
def css_defaults(name, css_dict): """Находит первое значение по-умолчанию background -> #FFF color -> #FFF content -> "" """ cur = css_dict.get(name) or css_dict.get(name[1:-1]) if cur is None: return None default = cur.get('default') if default is not None: return de...
8418af5e27dfc85a3ec70dea2e7416595ee86a1f
8,309
def yn_zeros(n,nt): """Compute nt zeros of the Bessel function Yn(x). """ return jnyn_zeros(n,nt)[2]
384ebc8fec6109de36d3c17d265b53c01a2195b6
8,310
def get_chebi_parents(chebi_ent): """ Get parents of ChEBI entity :param chebi_ent: :return: """ if hasattr(chebi_ent, 'OntologyParents'): return [ent.chebiId for ent in chebi_ent.OntologyParents if (ent.type == 'is a')] else: return []
bfdf3cbfae45c07a9f5f97a85f1c64f680ac49fc
8,311
def average_saccades_time(saccades_times): """ :param saccades_times: a list of tuples with (start_time_inclusive, end_time_exclusive) :return: returns the average time of saccades """ return sum([saccade_time[1] - saccade_time[0] for saccade_time in saccades_times]) / len(saccades...
a22a5d89ddd4317fa10ed6f5d920f17560028514
8,312
from typing import Optional from typing import List from typing import Tuple import logging def solve_tsp_local_search( distance_matrix: np.ndarray, x0: Optional[List[int]] = None, perturbation_scheme: str = "two_opt", max_processing_time: Optional[float] = None, log_file: Optional[str] = None, ) ...
f1b77b7fb3d1b83d18a7f2ba99d4a266e98f8462
8,313
def split(self, split_size_or_sections, dim=0, copy=True): """Return the split chunks along the given dimension. Parameters ---------- split_size_or_sections : Union[int, Sequence[int] The number or size of chunks. dim : int, optional, default=0 The dimension to split. copy : bo...
cd6725af62fc0f5cde758e23add206a2ddb7c0af
8,314
def HighFlowSingleInletTwoCompartmentGadoxetateModel(xData2DArray, Ve: float, Kbh: float, Khe: float, dummyVariable): """This function contains the algorithm for calculating how concentration varies with time ...
18684058926b9362b7a6b495cf1f48fd8c3188e4
8,315
import struct import numpy def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize): """Read CZ_LSMINFO tag from file and return as dict.""" assert byteorder == '<' magic_number, structure_size = struct.unpack('<II', fh.read(8)) if magic_number not in (50350412, 67127628): raise ValueError...
1bcf4d22315503e2f21fcbacd6a0797fc2fd16a7
8,316
def mi_alignment( alignment, mi_calculator=mi, null_value=DEFAULT_NULL_VALUE, excludes=DEFAULT_EXCLUDES, exclude_handler=None, ): """Calc mi over all position pairs in an alignment alignment: the full alignment object mi_calculator: a function which calculated MI from two entropies and ...
f576b8c4df018bba787c7c46091e52b70badd9de
8,317
def Jaccard3d(a, b): """ This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array ...
a4452e523e484db50b99d36f9ee67c3508678ea6
8,318
def get_pod_obj(name, namespace=None): """ Returns the pod obj for the given pod Args: name (str): Name of the resources Returns: obj : A pod object """ ocp_obj = OCP(api_version='v1', kind=constants.POD, namespace=namespace) ocp_dict = ocp_obj.get(resource_name=name) p...
464aa15574ee65672f7963e6e5426753ff98ee72
8,319
import sys import subprocess def _input_password() -> str: """ Get password input by masking characters. Similar to getpass() but works with cygwin. """ sys.stdout.write("Password :\n") sys.stdout.flush() subprocess.check_call(["stty", "-echo"]) password = input() subprocess.check_...
8d3dbc3f6221f3a2558dab5617227b2f6e4940ca
8,320
import os def file_size(file_path): """Return the file size.""" if os.path.isfile(file_path): file_info = os.stat(file_path) return convert_bytes(file_info.st_size)
ed28923767f0a7e708d66cb06fba7ad8120b69d7
8,321
def median_rank(PESSI_SORT, OPTI_SORT, A): """ Calculates the median rank of each action. :param PESSI_SORT: Dictionary containing the actions classified according to the pessimistic procedure. :param OPTI_SORT: Dictionary containing the actions classified according to the optimistic procedure. :pa...
7f760847ae2a69edf07a593a6ebfb84dce4c4103
8,322
from typing import Optional import json def get_token( event: ApiGatewayEvent, _context: LambdaContext, node_api: Optional[NodeApi] = None ) -> dict: """Get token details given a token uid. *IMPORTANT: Any changes on the parameters should be reflected on the `cacheKeyParameters` for this meth...
7be9e80aef60ad7f5befa3f21b597541eb79c4d0
8,323
import re def update_dictionary_entries(old_entries, need_to_add): """ Expects dictionary of species entries and unique list of species (as SMILES) that need to be added Creates new entries for the species that need to be added Returns old and new entries """ list(set(need_to_add)) fo...
9182c42349b76a7e72c3c1c134cb347ed0bd2a2d
8,324
import optparse import os import sys def ParseOptions(): """Parses the options passed to the program. @return: Options and arguments """ parser = optparse.OptionParser(usage="%prog [--no-backup]", prog=os.path.basename(sys.argv[0])) parser.add_option(cli.DEBUG_OPT) parse...
f697bc76956b30fbe9836cd8ba4fce40d726968c
8,325
def four_rooms(dims, doorway=1.): """ Args: dims: [dimx, dimy] dimensions of rectangle doorway: size of doorway Returns: adjmat: adjacency matrix xy: xy coordinates of each state for plotting labels: empty [] """ half_x, half_y = (dims[0]*.5, dims[1]*.5) quarter_x,...
0744ab4b38ab0b5d0b96c53d45c88dc1e37f932e
8,326
def get_verse_url(verse: str) -> str: """Creates a URL for the verse text.""" node = CONNECTIONS[verse] volume = scripture_graph.VOLUMES_SHORT[node['volume']].lower() if volume == 'bom': volume = 'bofm' elif volume == 'd&c': volume = 'dc-testament' elif volume == 'pogp': ...
37ce47aa6e18e3f550e9adacb3bf16affb6154f8
8,327
from typing import cast from typing import List def get_ws_dependency_annotation(state: GlobalState) -> WSDependencyAnnotation: """ Returns the world state annotation :param state: A global state object """ annotations = cast( List[WSDependencyAnnotation], list(state.world_state.get_...
ba44455594c4a1f63dac5adec95b2efe6a4b2af6
8,328
def get_gin_confg_strs(): """ Obtain both the operative and inoperative config strs from gin. The operative configuration consists of all parameter values used by configurable functions that are actually called during execution of the current program, and inoperative configuration consists of all p...
9f9081aafa6a4a43be37edd4002ee17ac518f5d4
8,329
def L(x, c, gamma): """Return c-centered Lorentzian line shape at x with HWHM gamma""" return gamma / (np.pi * ((x - c) ** 2 + gamma ** 2))
853ba2c978a50f9f43915342caebed2e3d5ead8d
8,330
import socket import logging def request_data_from_weather_station(): """ Send a command to the weather station to get current values. Returns ------- bytes received data, 0 if error occurred """ sock = socket.create_connection((WEATHER_HOST, WEATHER_PORT), GRAPHITE_TIMEOUT) s...
0bf28c3cf5db1f14446aa9866b9854b435378439
8,331
def solution2(arr): """improved solution1 #TLE """ if len(arr) == 1: return arr[0] max_sum = float('-inf') l = len(arr) for i in range(l): local_sum = arr[i] local_min = arr[i] max_sum = max(max_sum, local_sum) for j in range(i + 1, l): local_sum...
835240bb4f70e5b6425a6ac0d2a4210e2c8a0ad0
8,332
def hillas_parameters_4(pix_x, pix_y, image, recalculate_pixels=True): """Compute Hillas parameters for a given shower image. As for hillas_parameters_3 (old Whipple Fortran code), but more Pythonized MP: Parameters calculated as Whipple Reynolds et al 1993 paper: http://adsabs.harvard.edu/abs/1993ApJ...
87fa302b6e6b1b81b66d8e8fb7cc4e34da1583d9
8,333
from typing import List from typing import Optional def create_intrusion_set( name: str, aliases: List[str], author: Identity, primary_motivation: Optional[str], secondary_motivations: List[str], external_references: List[ExternalReference], object_marking_refs: List[MarkingDefinition], ) ...
be8df574ac1be08c724620cf20495922cff5918e
8,334
from ..core import Tensor def broadcast_to(tensor, shape): """Broadcast an tensor to a new shape. Parameters ---------- tensor : array_like The tensor to broadcast. shape : tuple The shape of the desired array. Returns ------- broadcast : Tensor Raises ------...
3c738227f98d4ca8a6b1c0cc98cea769b697a987
8,335
def admin_required(handler_method): """Require that a user be an admin. To use it, decorate your method like this:: @admin_required def get(self): ... """ @wraps(handler_method) def check_admin(*args, **kwargs): """Perform the check.""" if current_user....
03cc9e9cd32ab0b239f45c70fffcd85108b0173c
8,336
import requests def get(path): """Get.""" verify() resp = requests.get(f"{URL}{path}", headers=auth) try: resp.raise_for_status() except requests.exceptions.HTTPError as e: error_msg(str(e)) return return resp.json()
c1661ac0e07ff467f15a429fe6fbf09d53a34ef9
8,337
def combine_dataframes(dfs: [pd.DataFrame]) -> pd.DataFrame: """ Receives a list of DataFrames and concatenates them. They must all have the same header. :param dfs: List of DataFrames :return: Single concatenated DataFrame """ df = pd.concat(dfs, sort=False) return df
b7c1cd94870638a3a975ea7c4f9c284cbd4ee0a9
8,338
import os def df_to_hdf5(df, key, dir_path): """ Save the DataFrame object as an HDF5 file. The file is stored in the directory specified and uses the key for the filename and 'h5' as the extension. :param df: DataFrame to save as a file :param key: ID for storage and retrieval :param dir_...
aaf7e2d9f64da6f53b2fc908cc59d9331172c614
8,339
def _bound_accumulated_rotations(robot_name, command_dicts): """ Checks axes whose rotations have been accumulated to ensure they've not exceeded the stated limits. If they have, this function attempts to slide the commands by +/- 360 degrees. If the limits are still exceeded, this function return...
68ca1357178563975af9a3baeb1ba89177993af4
8,340
def get_email_manager(config: CFG, session: Session): """ :return: EmailManager instance """ #  TODO: Find a way to import properly without cyclic import smtp_config = SmtpConfiguration( config.EMAIL__NOTIFICATION__SMTP__SERVER, config.EMAIL__NOTIFICATION__SMTP__PORT, config...
f5a7a3c934912e346b70ad12b475fd45d4d7069f
8,341
import numpy def _approx_sp(salt,pres): """Approximate TDl at SP. Approximate the temperature and liquid water density of sea-ice with the given salinity and pressure. :arg float salt: Salinity in kg/kg. :arg float pres: Pressure in Pa. :returns: Temperature and liquid water density ...
b45727ad6f08cead1eb32477c8691233c38e9387
8,342
def _get_connection_params(resource): """Extract connection and params from `resource`.""" args = resource.split(";") if len(args) > 1: return args[0], args[1:] else: return args[0], []
87cdb607027774d58d1c3bf97ac164c48c32395c
8,343
import subprocess def download_archive(url, out_path): """Downloads a file from the specified URL to the specified path on disk.""" return subprocess.call(['curl', url, '-o', out_path])
e3c59f542a8fa662169d74428ed98dbf79d3d705
8,344
from typing import Union import requests from typing import List from typing import Dict from typing import Any from typing import Callable from typing import cast import operator def listdata( resp: Union[requests.Response, List[Dict[str, Any]]], *keys: Union[str, Callable[[], bool]], sort: Union[bool, s...
878df7c56f97a3fe2c92499955bb760888673bbc
8,345
import os import yaml def create_chart_data(start_path, excluded_dashboards=excluded_dashboards): """Read chart names and SQL code from the repository. Args: start_path (str): "./dashboards" excluded_dashboards (list): list of dashboards to exclude from testing (e.g. WIP, Untitled, etc) ...
7c3de75b033f2467058fea2843bcc21a0488ab59
8,346
def get_current_pkg(): """ Returns: パッケージ名 (str): 常に大文字表記で返ってくる """ return eval_foreign_vm_copy("(send *package* :name)")
16c768dace7a4e88f7d7eb21aab58ce917f2ce43
8,347
def _normalise_trigger(value: float) -> float: """ Helper function used to normalise the controller trigger values into a common range. :param value: Value to be normalised :raises: ValueError :return: Normalised value """ return _normalise(value, _HARDWARE_TRIGGER_MIN, _HARDWARE_TRIGGER_MA...
d5653da9f625896865a3fd9601d3f2707cba6e8c
8,348
def full_process(s): """Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case""" if s is None: return "" #Here we weill force a return of "" if it is of None, empty, or not valid #Merged from validate_string try: ...
071ba938708f170b914576895f7cab1aa8cb1cc3
8,349
import math def ldexp(space, x, i): """ldexp(x, i) -> x * (2**i) """ return math2(space, math.ldexp, x, i)
ef083d77ff36acbc7d7dfede0772e9e8bf34b17a
8,350
def menu(): """ Print a menu with all the functionalities. Returns: The choice of the user. """ print "=" * 33 + "\nMENU\n" + "=" * 33 descriptions = ["Load host from external file", "Add a new host", "Print selected hosts", "C...
29bdce7c50cea7d9bbc5a27b71c803db91fe4eef
8,351
from typing import Optional from typing import Container from typing import List async def objects_get(bucket: Optional[str] = None, index: Index = Depends(Provide[Container.index]), buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Object]: """ search...
f6949922ac5c355469fbaf450758180ac422f33a
8,352
import json def thumbnail_create(request, repo_id): """create thumbnail from repo file list return thumbnail src """ content_type = 'application/json; charset=utf-8' result = {} repo = get_repo(repo_id) if not repo: err_msg = _(u"Library does not exist.") return HttpResp...
876f9af7d61336f0f91f0b7277943265fb6e7a35
8,353
import uvloop import asyncio def initialize_event_loop(): """Attempt to use uvloop.""" try: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass return asyncio.get_event_loop()
cba229f5330bc89a60607f9523d3727b6db30094
8,354
def _setup_pgops(multi_actions=False, normalise_entropy=False, sequence_length=4, batch_size=2, num_mvn_actions=3, num_discrete_actions=5): """Setup polices, actions, policy_vars and (optionally) entropy_scale_op.""" t = sequence_l...
5d6ddc58db39496fed3c99c214c1f835ee49f2ea
8,355
async def definition_delete(hub, ctx, name, **kwargs): """ .. versionadded:: 1.0.0 Delete a policy definition. :param name: The name of the policy definition to delete. CLI Example: .. code-block:: bash azurerm.resource.policy.definition_delete testpolicy """ result = False...
7f3e6b2b3b6bbcea590a042b923fd797a56840ee
8,356
import optparse def parse_options(argv): """Parses and checks the command-line options. Returns: A tuple containing the options structure and a list of categories to be traced. """ usage = 'Usage: %prog [options] [category1 [category2 ...]]' desc = 'Example: %prog -b 32768 -t 15 gfx input view sche...
df6910fb6600f8c4573eced74dfcd8bc6ec1a5ad
8,357
def get_data_for_file(folder, ports): """Parses the pcap files in the specified folder, and outputs data for the specified ports """ # Load private keys and port->provider mappings keys, providers, nodes = read_keys(os.path.join(folder, 'keys')) print 'Loading packets' # Load packets with op...
be81404b54231bde3444d3b3545cafa1c836c074
8,358
async def create_channel_in_db( context: 'Context', game_config: 'GameConfig', channel_id: str, finished: bool = False ) -> Channel: """Utility function to create a channel in the database :param context: The Discord Context. :param game_config: The GameConfig to use for extra info. :pa...
a2ea09b436c4eeabd37c0c8220d791d89db3912f
8,359
def retry(times, func, *args, **kwargs): """Try to execute multiple times function mitigating exceptions. :param times: Amount of attempts to execute function :param func: Function that should be executed :param args: *args that are passed to func :param kwargs: **kwargs that are passed to func ...
7e9fd482a70409d62ea108ddaa83440fcd2b024f
8,360
def _apply_prediction(G, func, ebunch=None): """Applies the given function to each edge in the specified iterable of edges. `G` is an instance of :class:`networkx.Graph`. `ebunch` is an iterable of pairs of nodes. If not specified, all non-edges in the graph `G` will be used. """ if ebunc...
5e046bf7608337f6ed046a71b8a3983f53109d46
8,361
def import_class(class_object): """ Import a class given a string with its name in the format module.module.classname """ d = class_object.rfind(".") class_name = class_object[d + 1:len(class_object)] m = __import__(class_object[0:d], globals(), locals(), [class_name]) return getattr(m, clas...
82df3ed7d646bd423ccefacc00493e917f13c430
8,362
def anonymous_fun_0_(empty_closure_0_): """ empty_closure_0_: () """ def anonymous_fun_1_(par_map_input_1_): """ par_map_input_1_: Double """ def anonymous_fun_2_(par_map_input_0_): """ par_map_input_0_: Double """ def anonymous_fun_3_(fused_input_0_): """ ...
2ea827153fadc359d056f4b981dbb5d3bf3711ee
8,363
def get_examples(mode='train'): """ dataset[0][0] examples """ examples = { 'train': ({'id': '0a25cb4bc1ab6f474c699884e04601e4', 'title': '', 'context': '第35集雪见缓缓张开眼睛,景天又惊又喜之际,长卿和紫萱的仙船驶至,见众人无恙,' '也十分高兴。众人登船,用尽合力把自身的真气和水分输给她。雪见终于醒过来了,但却一脸木然,全无反应。众人向常胤求助,却发现人世界竟没有雪见的身世纪录。长卿询问清微的身世,...
0b5fb45bcac847cd3f7e7b3e5b264e350c891211
8,364
from IPython.core.display import HTML def display_tables(tables, max_rows=10, datetime_fmt='%Y-%m-%d %H:%M:%S', row=True): """Display mutiple tables side by side on a Jupyter Notebook. Args: tables (dict[str, DataFrame]): ``dict`` containing table names and pandas DataFrames. max_...
904a900e97aab4809ea5057025a5a7a075429942
8,365
def get_visible_enemy_units(observation, as_list=False, as_dict=True): """ This function takes an observation and returns a list of the enemy units that are on screen and are visible. A unit is considered visible if is either visible (in the protos sense) or if it is snapshotted and finished. The definition...
e134892664e70427c67093812b3a79cc45c8f29c
8,366
def prepare_default_result_dict(key, done, nodes): """Prepares the default result `dict` using common values returned by any operation on the DHT. Returns: dict: with keys `(k, d, n)` for the key, done and nodes; `n` is a list of `dict` with keys `(i, a, x)` for id, address, and expirat...
420beb66352fee7b4d38f6b4cf628cbaa86a03df
8,367
def MatchScorer(match, mismatch): """Factory function that returns a score function set to match and mismatch. match and mismatch should both be numbers. Typically, match should be positive and mismatch should be negative. Resulting function has signature f(x,y) -> number. """ def scorer(x, y...
fe3829efc64cb4d9785e52b8af6949c147481902
8,368
import random def random_choice(context: RuntimeContext, *choices): """Template helper for random choices. Supports structures like this: random_choice: - a - b - <<c>> Or like this: random_choice: - choice: pick: A probability: 50% ...
cc74c4106e2263e4b46ef25ed5cb83839040bb5f
8,369
def _compute_paddings(height_pad_amt, width_pad_amt, patch_axes): """Convert the total pad amounts to the format needed by tf.pad().""" top_pad = height_pad_amt // 2 bottom_pad = height_pad_amt - top_pad left_pad = width_pad_amt // 2 right_pad = width_pad_amt - left_pad paddings = [[0, 0] for _ in range(4...
3a5154ba0fa6808bc6dc8e20fcb4203324762ba9
8,370
def tab_size(computer, name, value): """Compute the ``tab-size`` property.""" if isinstance(value, int): return value else: return length(computer, name, value)
f121cc308f4c88e021e240767ae03479a26a46f6
8,371
def match_complete(user_id=""): """Switch 'complete' to true in matches table for user, return tallies.""" print("match_complete", user_id) user = sm.get_user(user_id) # Note: 0/1 used for 'complete' b/c Booleans not allowed in SimpleObjects this_match, i = current_match_i(user) temp = this_match['complete'...
1af499c671f209ba8bc9333e372947c90b9a2b8c
8,372
def compute_range_map(flow, downsampling_factor=1, reduce_downsampling_bias=True, resize_output=True): """Count how often each coordinate is sampled. Counts are assigned to the integer coordinates around the sampled coordinates using weights from ...
fa73194435ae893dcd359f93f1488a6b654f8d31
8,373
from typing import List def get_wer(refs: List[str], hyps: List[str]): """ args: refs (list of str): reference texts hyps (list of str): hypothesis/prediction texts """ n_words, n_errors = 0, 0 for ref, hyp in zip(refs, hyps): ref, hyp = ref.split(), hyp.split() n_w...
fb142f4d048bffca1a1119e4a2e7c68e1effcbfc
8,374
def get_first(somelist, function): """ Returns the first item of somelist for which function(item) is True """ for item in somelist: if function(item): return item return None
81976910c46102d3b15803d215f3bf5a554f9beb
8,375
def np_cross(a, b): """ Simple numba compatible cross product of vectors """ return np.array([ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ])
0d19a1bfdf7bf5d6835203f61654edc8263b3bbd
8,376
import sys import locale def get_process_output(process, encoding=None): """Get the output from the process.""" output = process.communicate() returncode = process.returncode if not encoding: try: encoding = sys.stdout.encoding except Exception: encoding = loc...
84622c05e84627d0651d21194391c672fb111b6f
8,377
import tqdm from sys import stdout def dct_2d(pixel_blocks: np.ndarray, verbose: int = 0) -> np.ndarray: """ Does 8x8 2D DCT on an image represented by pixel blocks. :param pixel_blocks: A np.ndarray of shape AxBx8x8x3, where A = H/8, B = W/8. :param verbose: An int; if greater than 0...
00e6421d186635032fd4afc1fd932ee977c71c70
8,378
import itertools def remove_duplicates(llist): """ Removes any and all duplicate entries in the specified list. This function is intended to be used during dataset merging and therefore must be able to handle list-of-lists. :param llist: The list to prune. :return: A list of unique elements ...
cbdf1a4db99a7a5fac37f25776cc1387ed8c54e0
8,379
def images_in_bbox(bbox: dict, **filters) -> str: """ Gets a complete list of images with custom filter within a BBox :param bbox: Bounding box coordinates Format:: >>> { ... 'west': 'BOUNDARY_FROM_WEST', ... 'south': 'BOUNDARY_FROM_SOUTH', ...
317554d0f666753cdfc8a3657f7f0b92d5af141d
8,380
def find_start_time_from_afl(project_base_dir): """ Finds the start time of a project from afl directories. This time is taken from the fuzzer_stats entry of the first config iteration's fuzzer. """ try: first_main_dir = main_dirs_for_proj(project_base_dir)[0] except: #if fu...
f8f21b65e1901615e16953da48ac39008dcb240b
8,381
def filter_none_values(d, recursive=True): """ Returns a filtered copy of a dict, with all keys associated with 'None' values removed. adapted from: http://stackoverflow.com/q/20558699 adapted from: http://stackoverflow.com/a/20558778 :param d: a dict-like object. :param recursive: If True, pe...
2a25ae331c99196c6f6eed7d5fe055f27583b1d2
8,382
def nonseq(): """ Return non sequence """ return 1
7c8f4a616a6761153226d961be02f6cf5b0cc54a
8,383
import io def load_image(path, color_space = None, target_size = None): """Loads an image as an numpy array Arguments: path: Path to image file target_size: Either, None (default to original size) or tuple of ints '(image height, image width)' """ img = io.imread(path)...
882210dff5dfa46596562483966b4a72c37aa7a8
8,384
def kubernetes_node_label_to_dict(node_label): """Load Kubernetes node label to Python dict.""" if node_label: label_name, value = node_label.split("=") return {label_name: value} return {}
c856d4e6d1f2169f7028ce842edc881cbca4e783
8,385
def get_category_user_problem(cat_name, username): """ 获取直接在指定目录下的用户AC的题目、尚未AC的题目和尚未做过的题目的情况 :param cat_name: :param username: :return: """ cat = __Category.objects.filter(name=cat_name).first() user = __User.objects.filter(username=username).first() if user is None or cat is None: ...
96e78d527f5bd0002345973eb085e04246e936ae
8,386
import math def floatToJson(x): """Custom rule for converting non-finite numbers to JSON as quoted strings: ``"inf"``, ``"-inf"``, and ``"nan"``. This avoids Python's bad habit of putting literal ``Infinity``, ``-Infinity``, and ``NaN`` in the JSON (without quotes).""" if x in ("nan", "inf", "-inf"): ...
938700c100d9176f6d950aee9ddf8f90109bedcc
8,387
import os def get_datafiles(datadir, prefix = ""): """ Scan directory for all csv files prefix: used in recursive call """ datafiles = [] for fname in os.listdir(datadir): fpath = os.path.join(datadir, fname) datafile = os.path.join(prefix, fname) if os.path.isdir(fpa...
9d975985a7b16af75436f8941881982f8a39d5d7
8,388
import os def auto_delete_file_on_change(sender, instance, **kwargs): """ Deletes old file from filesystem when corresponding `MediaFile` object is updated with new file. """ if not instance.pk: return False try: old_file = sender.objects.get(pk=instance.pk).url_banner ...
fa65394c95f3312e694e006751a7833c8d989af5
8,389
import math def systematic_uncertainties(): """tabulates sources of uncertainty and sums them in quadrature""" result_m = [ 0.066, # [0.07-0.12] 0.066 ± 0.019 0.019, # [0.12-0.20] 0.019 ± 0.009 0.002, # [0.20-0.30] 0.002 ± 0.009 -0.006, # [0.30-0.4...
71941441b09a593ebc2a3e396d2b86684bc75cfe
8,390
def extract_metamap(json_, key): """ Task function to parse and extract concepts from json_ style dic, using the MetaMap binary. Input: - json_ : dic, json-style dictionary generated from the Parse object related to the specific type of input - key : str, string d...
543b1470f36ee85dde2c2447ecc204544ef8fd52
8,391
def get_testinfo_by_reference(ref_name, ref_type): """ get test content by reference name @params: ref_name: reference name, e.g. api_v1_Account_Login_POST($UserName, $Password) ref_type: "api" or "suite" """ function_meta = parse_function(ref_name) func_name = function_meta["func_na...
967b32149ae094d2ef86cc88b2131047b98b1f09
8,392
import logging def game_info(uuid: str) -> dict: """ return info about game by uuid :param uuid: :return: message """ logging.info(uuid) logging.info(games.keys()) if UUID(uuid) in games.keys(): select_game: Game = games.get(UUID(uuid)) return { "uuid": uuid...
15faaab2f256830a0f2537ada4c742f703a74783
8,393
def miller_rabin(n, a): """ Miller-Rabin Primality Test Returns true if n is a (probable) prime Returns false if n is a composite number """ s = 0 d = n - 1 while d % 2 == 0: s = s + 1 d = d >> 1 x = square_and_multiply(a, d, n) if x != 1 and x + 1 != n: f...
2de6b54c05d4052e5d2c8fd915a0a2814a7da28f
8,394
def luhn_sum_v1(num): """ First version of luhn_sum; uses a list which it modifies in-place. """ nums = [int(i) for i in reversed(str(num))] for i in xrange(1, len(nums), 2): nums[i] *= 2 return sum(sum(divmod(i, 10)) for i in nums)
c2ff96069710a2321d9871608d0d9bbaddc18d30
8,395
def get_rate_discounted_rate(item_code, customer, company, so_number = None): """ This function is use to get discounted rate and rate """ item_group = frappe.get_value("Item", item_code, 'item_group') # parent_item_group = frappe.get_value("Item Group", item_group, 'parent_item_group') count = frappe.db.sql(f""" ...
8560bf5846a0500941840d59fb79cd721196a7ca
8,396
from typing import Dict from typing import Any import os import logging import json def lambda_handler(event: Dict[str, Any], context: Dict[str, Any]) -> str: """ Lambda function to parse notification events and forward to Slack :param event: lambda expected event object :param context: lambda expect...
6b6251b42063a91605b98eb31810af410dbf2617
8,397
def sum_obs_np(A): """summation over axis 0 (obs) equivalent to np.sum(A, 0)""" return np.einsum("ij -> j", A) if A.ndim > 1 else np.sum(A)
c14abc00b2ea6fa64c32fe7ac10f0007cb4705e8
8,398
def _macos_command_line_infoplist_impl(ctx): """Implementation of the internal `macos_command_line_infoplist` rule. This rule is an internal implementation detail of `macos_command_line_application` and should not be used directly by clients. It merges Info.plists as would occur for a bundle but then p...
d70a47def85cff62fc21e907a9f0a246a9b1c192
8,399