content
stringlengths
22
815k
id
int64
0
4.91M
def test_typecheck() -> None: """ Typechecks LabGraph using mypy. Assumes that the test is running from a PEX (if not, the test skips). """ mypy_ini_path = get_resource_tempfile(__name__, "mypy.ini") mypy_args = ["--config-file", mypy_ini_path] zip_path: Optional[str] = None try: ...
63,900
def calculateExtents(values): """ Calculate the maximum and minimum for each coordinate x, y, and z Return the max's and min's as: [x_min, x_max, y_min, y_max, z_min, z_max] """ x_min = 0; x_max = 1 y_min = 0; y_max = 1 z_min = 0; z_max = 2 if values: initial_value = values[...
63,901
def list_domain(config: dict[str, ...]) -> None: """List blacklisted domains""" if is_root(): logger.warning("Please do not run this command as 'root'") sys.exit(1) if len(config["BL_DOMAINS"]) == 0: click.echo("No blacklisted domains found") sys.exit(0) click.echo("All b...
63,902
def split_data_train_dev_test(df): """ Creating sets for model building and testing. Steps: 1. Training set (70%) - for building the model 2. Development set a.k.a. hold-out set (15%) - for optimizing model parameters 3. Test set (15%) - For testing the performance of the tuned model """ # ...
63,903
def start_simulate(pid): """Function for starting Circle-Map simulate""" print("\nRunning Circle-Map Simulate\n") sp.call("mkdir temp_files_%s" % pid, shell=True) return(pid)
63,904
def _prep_inputs_(X, y, theta, penalty=None, center=None): """Internal use function to simplify variable transformations for regression. This function is used on the inputs to ensure they are the proper shapes Parameters ---------- X : ndarray y : ndarray theta : ndarray penalty : ndarr...
63,905
def place_order(order='buy', price=0.0, currency='krw', coin_amount=0.0, order_type='limit'): """Place an order. :param order: ``buy`` | ``sell`` :param price: Price per BTC :param currency: KRW by default. I wouldn't assume Korbit supports any other currency at the...
63,906
def shuffle_isis(spiketrain, n=1, decimals=None): """ Generates surrogates of a neo.SpikeTrain object by inter-spike-interval (ISI) shuffling. The surrogates are obtained by randomly sorting the ISIs of the given input :attr:`spiketrain`. This generates independent `SpikeTrain` object(s) with s...
63,907
def is_installed(name): """ Check if a CRUX package is installed. """ with settings(hide("running", "stdout", "stderr", "warnings"), warn_only=True): res = run("prt-get listinst {}".format(name)) return res.succeeded
63,908
def test_analyze_crash_attribute(config): """The attribute checker crashes.""" FakeChecker = create_fake_checker( check_type=CheckType.attribute, name="name", text="text", url="url" ) def raises(*a): raise ValueError FakeChecker.run = raises with patch("charmcraft.linters.CHEC...
63,909
def parse_conf_node(env: BuildEnvironment, text: str, node: addnodes.desc_signature) -> str: """ Parse the content of a :rst:dir:`conf` directive. :param env: The Sphinx build environment. :param text: The content of the directive. :param node: The docutils node class. """ args = text.split('^') name = args[0...
63,910
def are_postgres_migrations_uptodate() -> bool: """ Check that all migrations that the running version of the code knows about have been applied. Returns `True` if so, `False` otherwise """ try: executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) plan = executor.migratio...
63,911
def step_lr(lr_max, epoch, num_epochs): """Step Scheduler""" ratio = epoch/float(num_epochs) if ratio < 0.3: return lr_max elif ratio < 0.6: return lr_max*0.2 elif ratio <0.8: return lr_max*0.2*0.2 else: return lr_max*0.2*0.2*0.2
63,912
def test_list_string_enumeration_nistxml_sv_iv_list_string_enumeration_1_5(mode, save_output, output_format): """ Type list/string is restricted by facet enumeration. """ assert_bindings( schema="nistData/list/string/Schema+Instance/NISTSchema-SV-IV-list-string-enumeration-1.xsd", instan...
63,913
def test_generate_from_file_name(tmp_path: Path) -> None: """Test generating from file names for input and output""" test_case_path = _get_test_case_path("basic") result_path = tmp_path / "result_with_another_name.html" generate_from_filename(test_case_path, str(result_path.resolve()), False, False, Fa...
63,914
def set_home(home): """ Set Home """ # This module should be refactored into object to avoid the anti-pattern global statement global CONFIG_PATH, CACHE_PATH, SHARE_PATH CONFIG_PATH = os.path.join(home, "config") CACHE_PATH = os.path.join(home, "cache") SHARE_PATH = os.path.join(home, "share")
63,915
def insertion_sort_counting(A): """ Instrumented Insertion Sort to return #swaps, #compares. """ N = len(A) num_swap = num_compare = 0 for i in range(N): for j in range(i, 0, -1): num_compare += 1 if A[j - 1] <= A[j]: break num_swap += ...
63,916
def add_statement(statement, state): """Add searched statement to found issues.""" stmt_text = statement.serialize_skip(' ') name = statement.var(0).value() if name in state: state[name].append((stmt_text, statement.config.path)) else: state[name] = [(stmt_text, statement.config.pat...
63,917
def update_constellation(constellation_name): """ Updates the constellation via the cloud interface. This is an operation applied to a running constellation to ugrade the software """ proc = multiprocessing.current_process().name log("update '%s' from proc '%s'" % (constellation_name, proc))...
63,918
def dir_basename_from_pid(pid,j): """ Mapping article id from metadata to its location in the arxiv S3 tarbals. Returns dir/basename without extention and without full qualified path. It also ignores version because there is no version in the tarbals. I understand they have the updated version in the tarball...
63,919
def heat_capacity(T, E, S): """ This function calculates the heat capacity by taking in the temperature 'T', energy 'E', and entropy 'S' as NumPy arrays. The number 'Num' is also necessary to complete the heat capacity calculation. """ C = np.zeros_like(T) for i in range...
63,920
def test_all_search_terms(): """Assert correct list created.""" assert sorted(expected_terms) == sorted(s.search_terms)
63,921
def _print_exception_string(exc, first=0): """ Obtain and print a stacktrace and exception info. :param exc: The exception that has been raised :type exc: :py:class:`Exception` :param first: The first index of the exception traceback to show :type first: uint """ stack = traceback.extra...
63,922
def train_default_classifier(): """ Train a classifier using the entire training dataset """ train = traindata.get_training_data_all() train = util_ensemble_code.add_nac(train, 50) geoloc_cls_default = GeoLocClassifier() geoloc_cls_default.train_classifier(train) if not ppclassifier.save_classif...
63,923
def retrieve_penalties_from_event_data(period_events): """ Retrieves penalty information from game event data. """ penalties_dict = dict() for period in period_events: events = period_events[period] for event in events: if event['type'] != 'penalty': cont...
63,924
def create_folder_old(cluster_indices, yhat): """ :param cluster_indices: function that returns numpy array of list of indices where the specified label = actual label (yhat) :param yhat: numpy array of class labels :return: list of list of indices by label """ folders = [cluster_indices(-1, yha...
63,925
def seconds_to_hours( move_data, label_time=constants.TIME_TO_PREV, new_label=None, inplace=True ): """ Convert values, in seconds, in label_distance column to hours. Parameters ---------- move_data : pymove.core.MoveDataFrameAbstract subclass. The input trajectory data label_time ...
63,926
def numba_hist(samples, bins, range): """ Wrapper to optimise numpy's histogram function with numba. """ return np.histogram(samples, bins, range)
63,927
def prepare_product_terms(session_context, product_dict, attributes=None, reprocessing_product=False, batch_processing=False): """ Processes the terms (cleans stop-words, stems, counts, persists DF's and TFIDF's) of all TEXT-type attributes of the given product. :param ses...
63,928
def ortools_wrapper_count_solutions(model,var_array): """ ortools_wrapper((model,var_array,print_solution=print_solution,num_sols=0) This is a simple wrapper for just counting the solutions of a model. Parameters: - model : the model - var_array: the array of arrays of the decision vari...
63,929
def pytest_sessionstart(session): """ called after the ``Session`` object has been created and before performing collection and entering the run test loop. :param _pytest.main.Session session: the pytest session object """ # Let PyTest do its own thing yield if session.config.getoption("--s...
63,930
def fv_match(form_name, regex, value): """>> fv_match <formname> <field regex> <value> Set value of *all* form fields with a name that matches the given regular expression. (Unlike 'formvalue' or 'fv', this will not complain about multiple matches!) """ form = browser.form(form_name) i...
63,931
def load_data_mnist_without_cfg(batch_size, resize=None, root=os.path.join( '~', '.pytorch', 'datasets', 'mnist'), use_normalize=True): """Download the MNIST dataset and then load into memory.""" root = os.path.expanduser(root) transformer = [] if resize: transformer += [transforms.Resize(re...
63,932
def find_manhattan_distance(): """ Двигаемся из точки (0,0) в соответствие со списком инструкция: Nx - двигаться на North на x клеток Sx - двигаться на South на x клеток Ex - двигаться на East на x клеток Wx - двигаться на West на x клеток Lx - сменить направление взгляда на x градусов влево...
63,933
def _extract_local_archive(working_dir, cleanup_functions, env_name, local_archive): """Helper internal function for extracting a zipfile and ensure that a cleanup is queued. Parameters ---------- working_dir : str cleanup_functions : List[() -> NoneType] env_name : str local_archive : str ...
63,934
def padded_chunks(l, n): """Yield successive n-sized chunks from l.""" tl = n out = [] for i in range(0, len(l), n): if i + n > len(l): tl = n - (len(l) - i) out.append(np.pad(np.array(l[i:]), ((0, tl), (0, 0)), 'constant')) else: out.append(n...
63,935
def _get_arguments(): """Build argument parser.""" parser = argparse.ArgumentParser(description='This starts a measure calculation.') parser.add_argument( '-s', '--state', help=""" State to extract data from. """, required=True, type=str) args ...
63,936
def print_json(obj: Union[Dict[Any, Any], List[Any]]) -> None: """Display a dictionary or a list with indent.""" print(json.dumps(obj, default=str, indent=4))
63,937
def fix_extension(filename_end): """Processes ending section of filename to get extension Args: filename_end (str): starting section of filename Returns: str: file extension """ return_value = filename_end pattern_string = r".*\.(\w{3})$" pattern = re.compile( patte...
63,938
def setup_seed(seed): """ set up random seed :param seed: :return: """ torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) np.random.seed(seed) random.seed(seed) # torch.backends.cudnn.deterministic = True
63,939
def rhombus_area(diagonal_1, diagonal_2): """Returns the area of a rhombus""" # You have to code here # REMEMBER: Tests first!!! return (diagonal_1 * diagonal_2) / 2
63,940
def aes_decrypt(ciphertext, password): """ This runs a command equivilent to: echo $ciphertext | openssl enc -aes-256-cbc -a -A -d -k $password to produce plaintext. """ p0 = Popen(["1", ciphertext], shell=False, stdout=PIPE, executable="echo") p1 = Popen(["1", "enc", "-aes-256-cbc", "...
63,941
def on_gateway_state_event(_client: Client, event: GatewayStateEvent): """On Gateway state event callback.""" logger.info('''Gateway state received: serial: %s version: %s connected devices: %s''', event.gateway_serial, event.gateway_app_version, ...
63,942
def MaybeWriteOutputFile(filename, data): """Write a file from a test if allowed.""" if 'TEST_UNDECLARED_OUTPUTS_DIR' not in os.environ: logging.error('Not allowed to write from the test.') return output_dir = os.environ['TEST_UNDECLARED_OUTPUTS_DIR'] filepath = os.path.join(output_dir, os.path.basena...
63,943
def unicode_dict(_dict): """ Make sure keys and values of dict is unicode. """ r = {} for k, v in iteritems(_dict): r[unicode_string(k)] = unicode_obj(v) return r
63,944
def local_server(): """Local Orchestrate API server. Initializes a local instance of gRPC servicer serving the Orchestarte API. Yields: None. """ log.info('Starting local server') log.info('ORCHESTRATE_PROJECT : %s', os.environ['ORCHESTRATE_PROJECT']) log.info('ORCHESTRATE_API_HOST: %s', os.environ[...
63,945
def main(): """Run experiments""" # Compute datasets datasets = list(map( lambda d: str(SNAP_DATA_DIR / (d + SNAP_DATA_EXT)), preprocessed )) # Log logger.info('Starting CPLEX Experiment') # Generate experiments experiments = product(PREPROCESSING_TIMEOUTS, datasets) ...
63,946
def first(column, ignore_nulls=False): """ Returns the first value in a group. The function by default returns the first values it sees. It will return the first non-null value it sees when ``ignore_nulls`` is set to true. If all values are null, then null is returned. """ return _with_expr(exp...
63,947
def test_init(logger): """ Tests initialization. """ packet = layers.packet.Packet(IP(src="127.0.0.1", dst="127.0.0.1")/TCP(sport=2222, dport=3333, seq=100, ack=100, flags="S")) trigger = actions.trigger.Trigger(None, None, None) trigger.is_applicable(packet, logger) actions.trigger.FIXED_T...
63,948
def group_configurations_detail_handler(request, course_key_string, group_configuration_id, group_id=None): """ JSON API endpoint for manipulating a group configuration via its internal ID. Used by the Backbone application. POST or PUT json: update group configuration based on provided informat...
63,949
def geodetic2geocentric(h, lat, lon, ellipsoid=None, **kwargs): """Convert from geodetic to geocentric coordinates. The geodetic coordinates refer to the reference ellipsoid specified by input ellipsoid. See module docstring for a defintion of the geocentric coordinate system. Parameters: ...
63,950
def test_conditional_shared_limits(): """Test that conditional shared limits work.""" app = Flask(__name__) limiter = Limiter(app, key_func=get_remote_address) @app.route("/limited") @limiter.shared_limit("1 per day", "test_scope") def limited_route(): return "passed" @app.route("/...
63,951
def cross_layer_equalization_auto(): """ perform auto cross layer equalization """ # load a model tf.keras.backend.clear_session() _ = ResNet50(weights='imagenet', input_shape=(224, 224, 3)) sess = tf.compat.v1.keras.backend.get_session() # get starting op name to invoke api for cle input_...
63,952
def _profile_is_configured(profile): """ Check if given profile is already configured. Args: profile (str): Profile to check. Returns: bool: Whether the profile was already configured or not. """ exit_code, _ = awscli(f"configure list --profile {profile}") return not exit_code
63,953
def test_SEPASammlerExportView_1(browser): """Testing SEPASammler Energieabschlag 1 XML export.""" from sw.allotmentclub import SEPASammler, SEPASammlerEntry, BookingKind from sw.allotmentclub import Member import datetime import lxml.etree kind = BookingKind.find_or_create( title='Energ...
63,954
def update_input_image_permissions( sender, instance, action, reverse, model, pk_set, **_ ): """ Assign or remove view_image permissions for the algorithms editors and creators when inputs/outputs are added/removed to/from the algorithm jobs. Handles reverse relations and clearing. """ if ac...
63,955
def is_equidistant(energy, tol=1e-08): """Returns True only when energy is equidistant.""" spacings = np.unique(np.diff(energy)) for spacing in spacings[1:]: if not np.isclose(spacing, spacings[0], atol=tol): return False return True
63,956
def test_logger_configured_with_yaml_file(fs): """Test fails if YAMLConfig cannot be instantiated from Yaml file""" fs.create_dir(os.path.expanduser("~")) fs.create_file("logging.yaml", contents=config_yaml) YAMLConfig.from_file("logging.yaml") logger = logging.getLogger("test_logger") for handl...
63,957
def acf(x,l): """ Auto correlation function of a given vector x with a maximum lag of length l. """ import numpy as np return np.array([1]+[np.corrcoef(x[:-i], x[i:])[0,1] \ for i in range(1, l)])
63,958
def rstdmf_divisions( paths_to_restore, restore_path, disk_space_margin: int = 100 * GiB, disk_refresh_time: int = 60, rstdmf_size_limit: int = 10 * GiB, rstdmf_file_limit: int = 24, max_size_on_disk: int = 0, verbose: bool = False, preserve_order: bool = True, ): """Securely mak...
63,959
def match_tenses(paths): """Match tenses from Spacy Doc objects. French verses have already been parsed into Spacy Doc objects. We can apply a Matcher along with some custom-written rules to match verb tenses of interest. We do that here. """ # load the parsed Spacy Docs, linked by verse...
63,960
def gDawson(n): """Return the G-value of a single Dawson game""" if n == 0: return 0 if n == 1: return 1 successors_g = [] for next_state in successors(n): if len(next_state) == 1: successors_g.append(gDawson(next_state[0])) else: successors_g....
63,961
def test_get_volunteers_wrong_method(client, method): """/volunteers only supports POST, try it with others""" call = getattr(client, method) response = call("/api/volunteers") # Should return HTTP 405 "Method Not Allowed" assert response.status_code == 405
63,962
def preprocess_data( exec_time_data: pd.DataFrame, neuro_bins: arrays.IntervalArray | pd.IntervalIndex, impair_bins: arrays.IntervalArray | pd.IntervalIndex, duration_bins: arrays.IntervalArray | pd.IntervalIndex, transition_fade_distance: Optional[int] = None, ) -> pd.DataFrame: """ Process...
63,963
def calc_stats(geojson, request, geostore_id): """Given an input geojson and (optionally) some params (period, agg_by, etc), calculate the # of alerts in an AOI""" geom = shape(geojson['features'][0]['geometry']) geom_area_ha = tile_geometry.calc_area(geom, proj='aea') # check if it's too big t...
63,964
def test_resourceclass_view(initialized_sm, test_resources): """ Get a view registered for a resource type """ # Get the request service services = initialized_sm.services request_service: RequestService = services['request'] request = request_service.make_request(resourceid='news/first') # Re...
63,965
def CaptureFrame(event, tile_id = 1, layer = 1): """Creating frame to modify tiles in area""" global x1, y1 #TODO #is lisbox selected? if __main__.lb_Tiles.get(ACTIVE) != "": tile = __main__.lb_Tiles.get(ACTIVE) category = __main__.category.get() if tile_id != 0: ...
63,966
def repo(folder): """a git repo The folder is initialized as a git repo. The two files in the folder are committed. """ repo = git.Repo.init(folder) repo.git.add(A=True) repo.index.commit('initial commit') yield repo
63,967
def op_name(graph, tfobj_or_name): """ Get the name of a tf.Operation :param graph: tf.Graph, a TensorFlow Graph object :param tfobj_or_name: either a tf.Tensor, tf.Operation or a name to either """ graph = validated_graph(graph) return get_op(graph, tfobj_or_name).name
63,968
def check_conflict(tracks): """Check if there are 2 tracks in the same frame""" conflict_idx = [] for i in range(len(tracks)): for j in range(len(tracks)): temp_dets = np.concatenate([tracks[i].dump(), tracks[j].dump()], axis=0) if i!=j and not debug_frame(temp_dets): ...
63,969
def save_pbobject_as_json(pb_object, save_path): """ Save protobuf (pb2) object to JSON file with our standard indent, key ordering, and other settings. Any calls to save protobuf objects to JSON in this repository should be through this function. Parameters ---------- pb_object: pb2 objec...
63,970
def parse_map_align_stdout(stdout): """Parse the stdout of map_align and extract the alignment of residues. Parameters ---------- stdout : str Standard output created with map_align Returns ------ dict A dictionary where aligned residue numbers in map_b are the keys and resi...
63,971
def diff_dicts(new, origin): """Only compare the first layer, return a the dict that represent add, remove, modify changes from new to origin NOTE: If one of the two dicts comes from another, eg. from .copy(), # make sure new and origin are totally different from each other, that means, the result ...
63,972
def move_to_answer(request, post, **kwargs): """ Move this post to be an answer """ parent = post.root ptype = Post.ANSWER msg = "dragged post to answer" return move(request=request, parent=parent, source=post, ptype=ptype, msg...
63,973
def kgen_lang_plugin_registered(plugin, manager): """ a new kgen_lang plugin got registered. :param plugin: the plugin module or instance :param _kgen_lang.config.KGenLangPluginManager manager: kgen_lang plugin manager .. note:: This hook is incompatible with ``hookwrapper=True``. """
63,974
def read_feed(feed_url): """ Generates an events list based on a calendar URL :param feed_url: valid URL for an iCalendar feed :returns: list of icalendar Events """ response = requests.get(feed_url) cal = Calendar.from_ical(response.content) return get_events(cal)
63,975
def generate_Promo2SinceNWeeks(all_data: pd.DataFrame, drop=True): """Generate (inplace) a feature 'Promo2SinceNWeeks' which counts the weeks (in integer) since when a Promo2 started. Fills missing values with -1000. Creates a new boolean column 'Promo2SinceNWeeks_missing' highlighting the missing value...
63,976
def nonmatsubara_exponents(coup_strength, cav_broad, cav_freq, beta): """ Get the exponentials for the correlation function for non-matsubara terms for the underdamped Brownian motion spectral density . (t>=0) Parameters ---------- coup_strength: float The coupling strength parameter. ...
63,977
def test_ipu_cpu_match(recompute_checkpoint, embedding_serialization): """ Test that the BERT model ran on IPU approximately matches that same model ran on the CPU. """ import warnings warnings.filterwarnings("ignore", category=torch.jit.TracerWarning) # Config args = """ --config u...
63,978
def run_generate(): """Entrance is here.""" parser = argparse.ArgumentParser() parser.add_argument("model_name", type=str, help="like facebook/bart-large-cnn,t5-base, etc.") parser.add_argument("input_path", type=str, help="like cnn_dm/test.source") pa...
63,979
async def main() -> NoReturn: """Example executor""" _login: str = os.getenv('LOGIN') _password: str = os.getenv('PASSWORD') async with strava_connector(_login, _password, filters={'date': datetime.datetime(year=2021, month=9, day=18)}) as strava_obj: activities:...
63,980
def get_branch_index_sub_divide(sub_divisions, edge_index, edge_degree, box_size=None, edge_x=None, edge_y=None, edge_z=None, phi=None, theta=None, edge_phi=None, edge_theta=None, branch_cutting_frequency=1000, mode='Euclidean', two_dimension=True): ""...
63,981
def get_approved_anime_posts(conn, mal_id) -> dict: """ Get reddit posts for some anime, that were manually checked and approved. """ with conn: with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cursor: query = """select mar.post_id, mar.sub_name, mar.source_link, mar.vi...
63,982
def get_default_look_in_description(schema_node: SchemaNode) -> str: """Filter. Get the default value of a JSON Schema property. If not set, look for it in the description.""" default_value = get_default(schema_node) if default_value: return default_value description = schema_node.keywords.get(...
63,983
def deserialize_date(data_type, data, model_finder): """Deserializes data into a python date Expected input value in format YYYY-MM-DD as per https://tools.ietf.org/html/rfc3339#section-5.6 standard Raise ValueError if the input is well formatted but not a valid date. Return None if the...
63,984
def sort(seq): """Cocktail sort implementation""" # [5,3,6,1,8,7,2] length = len(seq) left, right = 0, length - 1 while left <= right: for i in range(left, right): if seq[i] > seq[i+1]: seq[i], seq[i+1] = seq[i+1], seq[i] right -= 1 for i in range(right, left, -1): if seq[i-1] > seq...
63,985
def tsunami_forecast_render(): """ Renders the tsunami forecast index. """ return render_template("tsunami_forecast.html")
63,986
def get_tensor_n_elements(tensor): """Return the number of elements in a tensor.""" if isinstance(tensor, numpy.ndarray): return tensor.size if torch_available(): if isinstance(tensor, torch.Tensor): return torch.numel(tensor) raise ValueError("Unsupported tensor type. " ...
63,987
def task( fn: Callable = None, **task_init_kwargs: Any ) -> Union[ "prefect.tasks.core.function.FunctionTask", Callable[[Callable], "prefect.tasks.core.function.FunctionTask"], ]: """ A decorator for creating Tasks from functions. Args: - fn (Callable): the decorated function - ...
63,988
async def started_message(message: Message): """ Start command text, it is received by the user when he first writes to the bot """ await message.edit_text( text=( "Hi, I am a bot, able to send " "you <b>any photo by the selected category.</b>...
63,989
def test_require_single_existing_key(): """ When given a single existing key, require() throws no exceptions """ # 'version' is one of the default values, so we know it'll be there require('version')
63,990
def setup(client: commands.Bot) -> None: """ Cog's setup function. """ client.add_cog(TravelBuddies(client))
63,991
def ads(x, adsParameter): """ ADS function """ p = adsParameter exp1 = 1 + math.exp(-1 * (x - p.C + p.D / 2) / p.E) exp2 = 1 + math.exp(-1 * (x - p.C - p.D / 2) / p.F) dx = p.A + p.B / exp1 * (1 - 1 / exp2) return dx / p.DMAX
63,992
def sendNewReviewNotification(to_user, review, reviewed_name, redirect_url): """Sends out a notification to alert the user of a new Review. Args: to_user: The user who should receive a notification review: The review which triggers this notification reviewed_name: Name of the entity reviewed redire...
63,993
def label_diversity_norm(label): """ label差异性均值 :param label: :return: """ return label_diversity(label) / label_set_num(label)
63,994
def last_common_ancestor(taxonomies): """Compute last common ancestor""" lca = list() if len(taxonomies) > 1: zipped = zip(*taxonomies) for level in zipped: if len(set(level)) > 1: level = "*" else: level = level[0] lca.appe...
63,995
def get_resource_share(id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetResourceShareResult: """ Resource Type definition for AWS::RAM::ResourceShare """ __args__ = dict() __args__['id'] = id if opts is None: opts = pulumi.Invok...
63,996
def ip_to_ascii(ip_address): """ Converts the quad IP format to an integer representation. """ return struct.unpack('!L', socket.inet_aton(ip_address))[0]
63,997
def nck(nval, kval): """from https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python""" # https://en.wikipedia.org/wiki/Binomial_coefficient""" # Computes the binomial coefficient n choose k""" kval = min(kval, nval-kval) numer = reduce(op.mul, range(nval, nval-kval, -1), ...
63,998
def accumulate(results, gt, weights = None, exclude_keys = []) : """ Take results from evaluate_objects and ground truth and compile a simple data structure containing correct, total and nb_correlations """ # Get default weights if weights == None : weights = { a : { o : 1 for o in t.keys()...
63,999