content
stringlengths
22
815k
id
int64
0
4.91M
def process_addr(): """Process the bridge IP address/hostname.""" server_addr = request.form.get('server_addr') session['server_addr'] = server_addr try: leap_response = get_ca_cert(server_addr) session['leap_version'] = leap_response['Body'] \ ['PingRe...
10,900
def get_bkk_list(request): """板块课(通识选修课)""" myconfig = Config.objects.all().first() year = (myconfig.nChoose)[0:4] term = (myconfig.nChoose)[4:] if term == "1": term = "3" elif term == "2": term = "12" if myconfig.apichange: data = { 'xh':request.POST.get(...
10,901
def mkmonth(year, month, dates, groups): """Make an array of data for the year and month given. """ cal = calendar.monthcalendar(int(year), month) for row in cal: for index in range(len(row)): day = row[index] if day == 0: row[index] = None el...
10,902
def test_scoring_card(): """## Scoring card Each scoring card will have a victory point, and resources required. You will need to provide enough resources in order to obtain the scoring card. """ r = ScoringCard("YYYBBB (3)") assert r.victory_point == 3 assert r.target == Resource("BBB...
10,903
def test_is_interface_physical(): # pylint: disable=C0121 """ Test is_interface_physical """ assert is_interface_physical("GigabitEthernet0/0/2") is True assert is_interface_physical("GigabitEthernet0/0/2.890") is False assert is_interface_physical("GigabitEthernet0/0/2.1") is False asse...
10,904
def is_extension(step_str): """Return true if step_str is an extension or Any. Args: step_str: the string to evaluate Returns: True if step_str is an extension Raises: ValueError: if step_str is not a valid step. """ if not is_valid_step(step_str): raise ValueError('Not a valid step in a p...
10,905
def create_file(path: Union[str, Path]) -> None: """ Creates an empty file at the given location. Args: path (Union[str, Path]): Path where the file should be created. """ _path = _get_path(path) _path.touch()
10,906
def diff_list(first, second): """ Get difference of lists. """ second = set(second) return [item for item in first if item not in second]
10,907
def run(arguments=None): """This function is the main entrypoint for ale. It takes an optional argument which if passed makes the parser read those arguments instead of argv from the command line. This function parses the contents of the given config file and passes these options to the functions which...
10,908
def validate_dissolution_statement_type(filing_json, legal_type) -> Optional[list]: """Validate dissolution statement type of the filing.""" msg = [] dissolution_stmt_type_path = '/filing/dissolution/dissolutionStatementType' dissolution_stmt_type = get_str(filing_json, dissolution_stmt_type_path) ...
10,909
def parse_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser( usage='%(prog)s [options] <target path> <image> [image] ...') parser.add_argument( '-c', '--captions', dest='captions', action='store_true', default=False, help='read ima...
10,910
def weave(left: List[int], right: List[int]) -> List[List[int]]: """ Gives all possible combinations of left and right keeping the original order on left and right """ if not left or not right: return [left] if left else [right] left_result: List[List[int]] = weave_helper(left, right) right_result: List[List[i...
10,911
def test_rgb_to_hsl_part_18(): """Test rgb to hsl color function""" # assert rgb_to_hsl(0, 0, 0) == (300, 100, 0) assert rgb_to_hsl(51, 0, 51) == (300, 100, 10) assert rgb_to_hsl(102, 0, 102) == (300, 100, 20) assert rgb_to_hsl(153, 0, 153) == (300, 100, 30) assert rgb_to_hsl(204, 0, 204) == (30...
10,912
def compute_rel_attn_value(p_attn, rel_mat, emb, ignore_zero=True): """ Compute a part of *attention weight application* and *query-value product* in generalized RPE. (See eq. (10) - (11) in the MuseBERT paper.) Specifically, - We use distributive law on eq. (11). The function computes the ...
10,913
def check_input(args): """Checks whether to read from stdin/file and validates user input/options. """ # Defaults option = None fh = sys.stdin # file handle if not len(args): # Reading from pipe with default option if sys.stdin.isatty(): sys.stderr.write(__doc__) ...
10,914
def mock_real_galaxy(): """Mock real galaxy.""" dm = np.loadtxt(TEST_DATA_REAL_PATH / "dark.dat") s = np.loadtxt(TEST_DATA_REAL_PATH / "star.dat") g = np.loadtxt(TEST_DATA_REAL_PATH / "gas_.dat") gal = core.Galaxy( m_s=s[:, 0] * 1e10 * u.M_sun, x_s=s[:, 1] * u.kpc, y_s=s[:, 2...
10,915
def lend(request): """ Lend view. It receives the data from the lend form, process and validates it, and reloads the page if everything is OK Args: - request (HttpRequest): the request Returns: """ logged_user = get_logged_user(request) if logged_user is not None and logged_user.user_r...
10,916
def test_all_current_members(): """all_current_members works as expected """ r = niaopendata.all_current_members() _check_valid_list_response(r)
10,917
def main(): """ Spit out a string regardless of input """ args = getArguments().parse_args() if len(sys.argv) == 2: stronk.generate_random_keys( args.keyAmount, args.keyLength) elif len(sys.argv) >= 3: stronk.generate_random_keys( args.keyAmount, args.keyLength, a...
10,918
def deprecated() -> None: """Run the command and print a deprecated notice.""" LOG.warning("c2cwsgiutils_coverage_report.py is deprecated; use c2cwsgiutils-coverage-report instead") return main()
10,919
def build_syscall_Linux(syscall, arg_list, arch_bits, constraint=None, assertion = None, clmax=SYSCALL_LMAX, optimizeLen=False): """ arch_bits = 32 or 64 :) """ # Check args if( syscall.nb_args() != len(arg_list)): error("Error. Expected {} arguments, got {}".format(len(syscall.arg_types), ...
10,920
def gamma(x): """Diffusion error (normalized)""" CFL = x[0] kh = x[1] return ( 1. / (-2) * ( 4. * CFL ** 2 / 3 - 7. * CFL / 3 + (-23. * CFL ** 2 / 12 + 35 * CFL / 12) * np.cos(kh) + (2. * CFL ** 2 / 3 - 2 * CFL / 3) * np.cos(2 * kh)...
10,921
def copylabel(original_name): """create names/labels with the sequence (Copy), (Copy 2), (Copy 3), etc.""" copylabel = pgettext_lazy("this is a copy", "Copy") copy_re = f"\\({copylabel}( [0-9]*)?\\)" match = re.search(copy_re, original_name) if match is None: label = f"{original_name} ({copy...
10,922
def load_opts_from_mrjob_confs(runner_alias, conf_paths=None): """Load a list of dictionaries representing the options in a given list of mrjob config files for a specific runner. Returns ``[(path, values), ...]``. If a path is not found, use ``(None, {})`` as its value. If *conf_paths* is ``None``...
10,923
def clut8_rgb888(i): """Reference CLUT for wasp-os. Technically speaking this is not a CLUT because the we lookup the colours algorithmically to avoid the cost of a genuine CLUT. The palette is designed to be fairly easy to generate algorithmically. The palette includes all 216 web-safe colours to...
10,924
def test_retry_change(settings): """ Attempts to change retry property """ with pytest.raises(DeadlinksSettingsChange): settings.retry = 8 with pytest.raises(AttributeError): del settings.retry
10,925
def test_wf_st_6(plugin): """ workflow with two tasks, outer splitter and combiner for the workflow""" wf = Workflow(name="wf_st_6", input_spec=["x", "y"]) wf.add(multiply(name="mult", x=wf.lzin.x, y=wf.lzin.y)) wf.add(add2(name="add2", x=wf.mult.lzout.out)) wf.split(["x", "y"], x=[1, 2, 3], y=[11,...
10,926
def assert_table_headers(id_or_elem, headers): """Assert the headers of a table. The headers are the `<th>` tags. :argument id_or_elem: The identifier of the element, or its element object. :argument headers: A sequence of the expected headers. :raise: AssertionError if the element doesn't exist, ...
10,927
def get_file_from_rcsb(pdb_id,data_type='pdb'): """ (file_name) -> file_path fetch pdb or structure factor file for pdb_id from the RCSB website Args: file_name: a pdb file name data_type (str): 'pdb' -> pdb 'xray' -> structure factor Returns: a file path for the pdb file_name """ ...
10,928
def write_conll_prediction_file( out_file: str, examples: List[Example], y_preds: List[TAG_SEQUENCE]) -> None: """Writes a text output with predictions for a collection of Examples in CoNLL evaluation format, one token per line: TOKEN GOLD-TAG PRED-TAG Distinct example outputs ...
10,929
def parse_events(fobj): """Parse a trace-events file into {event_num: (name, arg1, ...)}.""" def get_argnames(args): """Extract argument names from a parameter list.""" return tuple(arg.split()[-1].lstrip('*') for arg in args.split(',')) events = {dropped_event_id: ('dropped', 'count')} ...
10,930
def enu2ECEF(phi, lam, x, y, z, t=0.0): """ Convert ENU local coordinates (East, North, Up) to Earth centered - Earth fixed (ECEF) Cartesian, correcting for Earth rotation if needed. ENU coordinates can be transformed to ECEF by two rotations: 1. A clockwise rotation over east-axis...
10,931
def _load_container_by_name(container_name, version=None): """ Try and find a container in a variety of methods. Returns the container or raises a KeyError if it could not be found """ for meth in (database.load_container, # From the labware database _load_weird_container): # honest...
10,932
def get_login(discord_id): """Get login info for a specific user.""" discord_id_str = str(discord_id) logins = get_all_logins() if discord_id_str in logins: return logins[discord_id_str] return None
10,933
def labels(repo): """Setup the RadiaSoft labels for ``repo``. Will add "radiasoft/" to the name if it is missing. Args: repo (str): will add https://github.com/radiasoft if missing """ r = _repo_arg(repo) for x in ('inprogress', 'c5def5'), ('1', 'b60205'), ('2', 'fbca04'): try:...
10,934
def to_json_dict(json_data): """Given a dictionary or JSON string; return a dictionary. :param json_data: json_data(dict, str): Input JSON object. :return: A Python dictionary/OrderedDict with the contents of the JSON object. :raises TypeError: If the input object is not a dictionary or string. """...
10,935
def get_keypoints(): """Get the COCO keypoints and their left/right flip coorespondence map.""" # Keypoints are not available in the COCO json for the test split, so we # provide them here. keypoints = [ 'nose', 'neck', 'right_shoulder', 'right_elbow', 'right_wris...
10,936
def has_mtu_mismatch(iface: CoreInterface) -> bool: """ Helper to detect MTU mismatch and add the appropriate OSPF mtu-ignore command. This is needed when e.g. a node is linked via a GreTap device. """ if iface.mtu != DEFAULT_MTU: return True if not iface.net: return False ...
10,937
def phrase_boxes_alignment(flatten_boxes, ori_phrases_boxes): """ align the bounding boxes with corresponding phrases. """ phrases_boxes = list() ori_pb_boxes_count = list() for ph_boxes in ori_phrases_boxes: ori_pb_boxes_count.append(len(ph_boxes)) strat_point = 0 for pb_boxes_num in ...
10,938
def editor(initial_contents=None, filename=None, editor=None): """ Open a text editor, user edits, return results ARGUMENTS initial_contents If not None, this string is written to the file before the editor is opened. filename If not None, the name of the file to edit. ...
10,939
def dismiss_notification(request): """ Dismisses a notification ### Response * Status code 200 (When the notification is successsfully dismissed) { "success": <boolean: true> } * `success` - Whether the dismissal request succeeded or not * Status code...
10,940
def remove_objects(*, objects: tuple = ()) -> None: """ Removes files or folders. >>> from snakypy.helpers.os import remove_objects >>> remove_objects(objects=("/tmp/folder", "/tmp/file.txt")) Args: objects (tuple): It must receive the path of the object, folders or files. ...
10,941
def writeTreeStructure(skillList, path: str, **args) -> None: """Output a file with a tree structure definition.""" data = [{ 'define': 'tree', 'tree': skillList.buildTree() }] dumpJsonFile(data, path, **args)
10,942
def switchToCameraCenter(cameraName, editor): """ Additional wrapper layer around switchToCamera. This function switches to the current camera and also toggles the view mode to be 'center' """ pass
10,943
def log_at_level(logger, message_level, verbose_level, msg): """ writes to log if message_level > verbose level Returns anything written in case we might want to drop down and output at a lower log level """ if message_level <= verbose_level: logger.info(msg) return True retu...
10,944
def datafile(tmp_path_factory): """Make a temp HDF5 Ocat details file within 60 arcmin of 3c273 for obsids before 2021-Nov that persists for the testing session.""" datafile = str(tmp_path_factory.mktemp('ocat') / 'target_table.h5') update_ocat_local(datafile, target_name='3c273', resolve_name=True, rad...
10,945
def _collect_scalars(values): """Given a list containing scalars (float or int) collect scalars into a single prefactor. Input list is modified.""" prefactor = 1.0 for i in range(len(values)-1, -1, -1): if isinstance(values[i], (int, float)): prefactor *= values.pop(i) return p...
10,946
def register_handler(pid): """ Registers the given Elixir process as the handler for this library. This function must be called first - and the client module must define a function with the same prototype which simply calls this function. """ global _msg_handling_pid _msg_handling_p...
10,947
def reduce(p): """ This recipe does a quick reduction of GMOS nod and shuffle data. The data is left in its 2D form, and only a sky correction is done. The seeing from the spectra cross-section is measured when possible. Parameters ---------- p : PrimitivesBASE object A primitive se...
10,948
def create_output_directory(validated_cfg: ValidatedConfig) -> Path: """ Creates a top level download directory if it does not already exist, and returns the Path to the download directory. """ download_path = validated_cfg.output_directory / f"{validated_cfg.version}" download_path.mkdir(parent...
10,949
def presentation_logistique(regression,sig=False): """ Mise en forme des résultats de régression logistique Paramètres ---------- regression: modèle de régression de statsmodel sig: optionnel, booléen Retours ------- DataFrame : tableau de la régression logistique """ # Pa...
10,950
def __check_count_freq(count_freq, flink_window_type): """ 校验窗口配置项:统计频率 :param count_freq: 统计频率 :param flink_window_type: 窗口类型 """ # 校验统计频率(单位:s) if flink_window_type in [TUMBLING, SLIDING, ACCUMULATE] and count_freq not in [ 30, 60, 180, 300, 600, ...
10,951
def test_L1DecayRegularizer(): """ test L1DecayRegularizer :return: """ main_program = fluid.Program() startup_program = fluid.Program() with fluid.unique_name.guard(): with fluid.program_guard( main_program=main_program, startup_program=startup_program): ...
10,952
def handle_colname_collisions(df: pd.DataFrame, mapper: dict, protected_cols: list) -> (pd.DataFrame, dict, dict): """ Description ----------- Identify mapper columns that match protected column names. When found, update the mapper and dataframe, and keep a dict of these changes to return to the...
10,953
def process_file(filename): """Read a file from disk and parse it into a structured dict.""" try: with codecs.open(filename, encoding='utf-8', mode='r') as f: file_contents = f.read() except IOError as e: log.info('Unable to index file: %s, error :%s', filename, e) return...
10,954
def revive(grid: Grid, coord: Point) -> Grid: """Generates a set of all cells which can be revived near coord""" revives = set() for offset in NEIGHBOR_OFFSETS: possible_revive = addpos(coord, offset) if possible_revive in grid: continue active_count = live_around(grid, possible_revive) if active_count == ...
10,955
def test_icons() -> None: """Test `icons` command.""" run( COMMAND_LINES["icons"], b"INFO Icons are written to out/icons_by_name and out/icons_by_id.\n" b"INFO Icon grid is written to out/icon_grid.svg.\n" b"INFO Icon grid is written to doc/grid.svg.\n", ) assert (Path("...
10,956
def test_verify_returns_permissions_on_active_collections_only(token, testapp): """Get user details and token expiry.""" inactive_collection = CollectionFactory(is_active=False) permission1 = PermissionFactory(user=token.user, collection=inactive_collection, registrant=Tr...
10,957
def extract_dated_images(filename, output, start_time=None, end_time=None, interval=None, ocr=False): """ Read a video, check metadata to understand real time and then extract images into dated files """ if start_time: vi = ManualTimes(filename, real_start_time=start_time, real_interval=interv...
10,958
def process_table_creation_surplus(region, exchanges_list): """Add docstring.""" ar = dict() ar["@type"] = "Process" ar["allocationFactors"] = "" ar["defaultAllocationMethod"] = "" ar["exchanges"] = exchanges_list ar["location"] = location(region) ar["parameters"] = "" ar["p...
10,959
def upload_event(): """ Expect a well formatted event data packet (list of events) Verify the access token in the request Verify the packet if verified then send to event hub else return a failure message """ # authenticate the access token with okta api call # get user id from okta ...
10,960
def makepath_coupled(model_hybrid,T,h,ode_method,sample_rate): """ Compute paths of coupled exact-hybrid model using CHV ode_method. """ voxel = 0 # make copy of model with exact dynamics model_exact = copy.deepcopy(model_hybrid) for e in model_exact.events: e.hybridType = SLOW # setup ...
10,961
def _django_setup_unittest(request, _django_cursor_wrapper): """Setup a django unittest, internal to pytest-django.""" if django_settings_is_configured() and is_django_unittest(request): request.getfuncargvalue('_django_test_environment') request.getfuncargvalue('_django_db_setup') _dja...
10,962
def commands(): """Manage your blobs.""" pass
10,963
def process_image_keypoints(img, keypoints, input_res=224): """Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the boundi...
10,964
def update_output( list_of_contents, list_of_names, list_of_dates, initiate_pipeline_n_clicks, clear_pipeline_n_clicks, append_uploads_n_clicks, refresh_uploads_n_clicks, clear_uploads_n_clicks, memory, user_login_n_clicks, session_data, workflow, initiate_pipeline_ti...
10,965
def _load_outputs(dict_: Dict) -> Iterable[Union[HtmlOutput, EbookConvertOutput]]: """Translates a dictionary into a list of output objects. The dictionary is assumed to have the following structure:: { 'outputs': [{ 'path': 'some', 'new': 'text' }, { 'path: '...', ...
10,966
def _async_friendly_contextmanager(func): """ Equivalent to @contextmanager, except the resulting (non-async) context manager works correctly as a decorator on async functions. """ @wraps(func) def helper(*args, **kwargs): return _AsyncFriendlyGeneratorContextManager(func, args, kwargs) ...
10,967
def all_inputs(n): """ returns an iterator for all {-1,1}-vectors of length `n`. """ return itertools.product((-1, +1), repeat=n)
10,968
def brightness(df: pd.DataFrame, gain: float = 1.5) -> pd.DataFrame: """ Enhance image brightness. Parameters ---------- df The dataset as a dataframe. Returns ------- df A new dataframe with follwing changes: * 'filename', overwrited with new brightened image ...
10,969
def generate_winner_list(winners): """ Takes a list of winners, and combines them into a string. """ return ", ".join(winner.name for winner in winners)
10,970
def test_get_alias_name_2(): """Test alias from empty meta extraction""" meta = { } assert get_alias_names(meta) is None
10,971
def infer_chords_for_sequence(quantized_sequence, chords_per_bar=None, key_change_prob=0.001, chord_change_prob=0.5, chord_pitch_out_of_key_prob=0.01, chord_note_concentr...
10,972
def stampify_url(): """The stampified version of the URL passed in args.""" url = request.args.get('url') max_pages = request.args.get('max_pages') enable_animations = bool(request.args.get('animations') == 'on') if not max_pages: max_pages = DEFAULT_MAX_PAGES _stampifier = Stampifier...
10,973
def pleasant_lgr_stand_alone_parent(pleasant_lgr_test_cfg_path, tmpdir): """Stand-alone version of lgr parent model for comparing with LGR results. """ # Edit the configuration file before the file paths within it are converted to absolute # (model.load_cfg converts the file paths) cfg = load(pleasa...
10,974
def twitter_channel(): """ RESTful CRUD controller for Twitter channels - appears in the administration menu Only 1 of these normally in existence @ToDo: Don't enforce """ #try: # import tweepy #except: # session.error = T("tweepy module not available w...
10,975
def init_time(p, **kwargs): """Initialize time data.""" time_data = { 'times': [p['parse']], 'slots': p['slots'], } time_data.update(**kwargs) return time_data
10,976
def welcome(): """ The code that executes at launch. It guides the user through menus and starts other functions from the other folders based on the users choices. """ clear() print(msg) print(Style.RESET_ALL) print("\n") print("Welcome!") input("Press ENTER key to begin!") c...
10,977
def bsplslib_D0(*args): """ :param U: :type U: float :param V: :type V: float :param UIndex: :type UIndex: int :param VIndex: :type VIndex: int :param Poles: :type Poles: TColgp_Array2OfPnt :param Weights: :type Weights: TColStd_Array2OfReal & :param UKnots: :ty...
10,978
def b_cross(self) -> tuple: """ Solve cross one piece at a time. Returns ------- tuple of (list of str, dict of {'CROSS': int}) Moves to solve cross, statistics (move count in ETM). Notes ----- The cube is rotated so that the white centre is facing down. The f...
10,979
def get_db(): """Creates a 'SQLAlchemy' instance. Creates a 'SQLAlchemy' instance and store it to 'flask.g.db'. Before this function is called, Flask's application context must be exist. Returns: a 'SQLAlchemy' instance. """ if 'db' not in g: current_app.logger.debug('construc...
10,980
def dsm_nifti(image, spatial_radius=0.01, dist_metric='correlation', dist_params=dict(), y=None, n_folds=1, roi_mask=None, brain_mask=None, n_jobs=1, verbose=False): """Generate DSMs in a searchlight pattern on Nibabel Nifty-like images. DSMs are computed using a patch surrounding e...
10,981
def generate_probes(filename_input, filename_results, options, conf=None, problem=None, probes=None, labels=None, probe_hooks=None): """ Generate probe figures and data files. """ if conf is None: required, other = get_standard_keywords() conf = Pr...
10,982
def retain_groundtruth(tensor_dict, valid_indices): """Retains groundtruth by valid indices. Args: tensor_dict: a dictionary of following groundtruth tensors - fields.InputDataFields.groundtruth_boxes fields.InputDataFields.groundtruth_classes fields.InputDataFields.groundtruth_confidences ...
10,983
def next_higher_number(some_integer_input): """ Given an integer, this function returns the next higher number which has the exact same set of digits. If no higher number exists, return the the integer provided as input. For instance: >>> next_higher_number(123) 132 >>> next_higher_nu...
10,984
def test_url_call_succeeds_with_200(monkeypatch): """ Test the function will return once the HTTP Response is 200 OK. """ # Setup the mocks. response = MagicMock(spec=urllib.request.addinfourl) response.getcode.return_value = 200 mock_urlopen = MagicMock(return_value=response) # Pat...
10,985
def cluster_list_node(realm, id): """ this function add a cluster node """ cluster = Cluster(ES) account = Account(ES) account_email = json.loads(request.cookies.get('account'))["email"] if account.is_active_realm_member(account_email, realm): return Response(json.dumps(cluster.list_nodes(r...
10,986
def validate_code(code): """ Ensure that the code provided follows python_variable_naming_syntax. """ regex = "^[a-z_][a-z0-9_]+$" if not re.search(regex, code): raise ValidationError("code must be in 'python_variable_naming_syntax'")
10,987
def compute_features_for_audio_file(audio_file): """ Parameters ---------- audio_file: str Path to the audio file. Returns ------- features: dict Dictionary of audio features. """ # Load Audio logging.info("Loading audio file %s" % os.path.basename(audio_file)) audio, sr = librosa.load(audio_file, sr=ms...
10,988
def complete_json(input_data, ref_keys='minimal', input_root=None, output_fname=None, output_root=None): """ Parameters ---------- input_data : str or os.PathLike or list-of-dict Filepath to JSON with data or list of dictionaries with information about annotations r...
10,989
def BuildSystem(input_dir, info_dict, block_list=None): """Build the (sparse) system image and return the name of a temp file containing it.""" return CreateImage(input_dir, info_dict, "system", block_list=block_list)
10,990
def add_upgrades(ws, cols, lnth): """ """ for col in cols: cell = "{}1".format(col) ws[cell] = "='New_4G_Sites'!{}".format(cell) for col in cols[:2]: for i in range(2, lnth): cell = "{}{}".format(col, i) ws[cell] = "='New_4G_Sites'!{}".format(cel...
10,991
def vae_loss(recon_x, x, mu, logvar, reduction="mean"): """ Effects ------- Reconstruction + KL divergence losses summed over all elements and batch See Appendix B from VAE paper: Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014 https://arxiv.org/abs/1312.6114 """ BC...
10,992
def assert_balance(from_channel, balance, locked): """ Assert the from_channel overall token values. """ assert balance >= 0 assert locked >= 0 distributable = balance - locked channel_distributable = channel.get_distributable( from_channel.our_state, from_channel.partner_state, ...
10,993
def test_driver_update_fails_with_invalid_id(): """ Tests updating a record fails if the record id is not found. """ with sqlite3.connect("index.sq3") as conn: driver = SQLAlchemyIndexDriver("sqlite:///index.sq3") did = str(uuid.uuid4()) baseid = str(uuid.uuid4()) rev =...
10,994
def Or(*args): """Defines the three valued ``Or`` behaviour for a 2-tuple of three valued logic values""" def reduce_or(cmp_intervala, cmp_intervalb): if cmp_intervala[0] is True or cmp_intervalb[0] is True: first = True elif cmp_intervala[0] is None or cmp_intervalb[0] is...
10,995
def create_task(): """Create a new task""" data = request.get_json() # In advanced solution, a generic validation should be done if (TaskValidator._validate_title(data)): TaskPersistence.create(title=data['title']) return {'success': True, 'message': 'Task has been saved'} # Simple...
10,996
def test_is_python_version_newer_than_3_6(): """Test to check python version is 3.7 or later""" assert util.is_python_version_newer_than_3_6() is not None
10,997
def move(timeout=10): """Send mouse X & Y reported data from the Pinnacle touch controller until there's no input for a period of ``timeout`` seconds.""" if mouse is None: raise OSError("mouse HID device not available.") start = time.monotonic() while time.monotonic() - start < timeout: ...
10,998
def get_socket_with_reuseaddr() -> socket.socket: """Returns a new socket with `SO_REUSEADDR` option on, so an address can be reused immediately, without waiting for TIME_WAIT socket state to finish. On Windows, `SO_EXCLUSIVEADDRUSE` is used instead. This is because `SO_REUSEADDR` o...
10,999