content
stringlengths
22
815k
id
int64
0
4.91M
def _make_relative_path(base_path, full_path): """ Strip out the base_path from full_path and make it relative. """ flask.current_app.logger.debug( 'got base_path: %s and full_path: %s' % (base_path, full_path)) if base_path in full_path: # Get the common prefix common_prefix...
5,346,900
def md5_hash_file(fh): """Return the md5 hash of the given file-object""" md5 = hashlib.md5() while True: data = fh.read(8192) if not data: break md5.update(data) return md5.hexdigest()
5,346,901
def rule(request): """Administration rule content""" if request.user.is_authenticated(): return helpers.render_page('rule.html', show_descriptions=True) else: return redirect('ahmia.views_admin.login')
5,346,902
def get_tenant_info(schema_name): """ get_tenant_info return the first tenant object by schema_name """ with schema_context(schema_name): return Pharmacy.objects.filter(schema_name=schema_name).first()
5,346,903
def get_lr(curr_epoch, hparams, iteration=None): """Returns the learning rate during training based on the current epoch.""" assert iteration is not None batches_per_epoch = int(hparams.train_size / hparams.batch_size) if 'svhn' in hparams.dataset and 'wrn' in hparams.model_name: lr = step_lr(hp...
5,346,904
def delete_map(): """ Delete all maps Returns ------- (response, status_code): (dict, int) The response is a dictionary with the keys -> status, message and result. The status is a bool that says if the operation was successful. The messag...
5,346,905
def test_building_scenarioloop_scenarios(mocker): """ Test building Scenarios from a Scenario Loop """ # given scenario_loop = ScenarioLoop(1, 'Scenario Loop', 'Iterations', 'I am a Scenario Loop', 'foo.feature', 1, parent=None, tags=None, preconditions=None, backgro...
5,346,906
def delete_page(shortname): """Delete page from the database.""" # Check page existency if get_page(shortname) is None: abort(404) if shortname is None: flash("No parameters for page deletion!") return redirect(url_for("admin")) else: query_db("DELETE FROM pages WHER...
5,346,907
def has_property(name, match=None): """Matches if object has a property with a given name whose value satisfies a given matcher. :param name: The name of the property. :param match: Optional matcher to satisfy. This matcher determines if the evaluated object has a property with a given name. I...
5,346,908
def gain_stability_task(run, det_name, fe55_files): """ This task fits the Fe55 clusters to the cluster data from each frame sequence and writes a pickle file with the gains as a function of sequence number and MJD-OBS. Parameters ---------- run: str Run number. det_name: str ...
5,346,909
def get_datetime(timestamp): """Parse several representations of time into a datetime object""" if isinstance(timestamp, datetime.datetime): # Timestamp is already a datetime object. return timestamp elif isinstance(timestamp, (int, float)): try: # Handle Unix timestamps....
5,346,910
def conda_installed_files(prefix, exclude_self_build=False): """ Return the set of files which have been installed (using conda) into a given prefix. """ res = set() for dist in install.linked(prefix): meta = install.is_linked(prefix, dist) if exclude_self_build and 'file_hash' i...
5,346,911
def computeStarsItembased(corated, target_bid, model): """ corated - {bid: star, ...} """ if corated == None: return None corated.pop(target_bid, None) bid_cor = list(corated.keys()) collect = [] for b in bid_cor: pair = None if b < target_bid: pair = ...
5,346,912
def print_json_errors(res): """ from a dimcli.DslDataset object, print out an errors summary """ if "errors" in res.json.keys(): if "query" in res.json["errors"]: print(res.json["errors"]["query"]["header"].strip("\n")) for key in res.json["errors"]["query"]["details"]: ...
5,346,913
def main(): """ This script will create a new fabric at the site specified in the param provided. """ # logging, debug level, to file {application_run.log} logging.basicConfig( filename='application_run.log', level=logging.DEBUG, format='%(asctime)s.%(msecs)03d %(levelname)s...
5,346,914
def beacon(config): """ Monitor the memory usage of the minion Specify thresholds for percent used and only emit a beacon if it is exceeded. .. code-block:: yaml beacons: memusage: - percent: 63% """ ret = [] _config = {} list(map(_config.update, con...
5,346,915
def copy_params(config_file, new_dir): """ copy config_file to new location """ name = os.path.basename(config_file) new_dir = os.path.join(new_dir, 'params', name) shutil.copyfile(config_file, new_dir)
5,346,916
def dump_bdb(db_dump_name, repo_path, dump_dir): """Dump all the known BDB tables in the repository at REPO_PATH into a single text file in DUMP_DIR. Omit any "next-key" records.""" dump_file = dump_dir + "/all.bdb" file = open(dump_file, 'w') for table in ['revisions', 'transactions', 'changes', 'copies', '...
5,346,917
def write_config(data, path): """ Takes a dict data and writes it in json format to path. Args: data (dict[str: dict[str: str]]): The data to be written to path path: (PosxPath): Path to the file data will be written to """ with open(path, "w+") as file: json.dump(data, ind...
5,346,918
def get_surrounding_points(search_values, point_set): """ #for each value p[i] in search_values, returns a pair of surrounding points from point_set the surrounding points are a tuplet of the form (lb[i], ub[i]) where - lb[i] < p[i] < ub[i] if p[i] is not in point_set, and p[i] is within range - lb[...
5,346,919
def _scriptable_get(obj, name): """ The getter for a scriptable trait. """ global _outermost_call saved_outermost = _outermost_call _outermost_call = False try: result = getattr(obj, '_' + name, None) if result is None: result = obj.trait(name).default finally: ...
5,346,920
def Iq(q, intercept, slope): """ :param q: Input q-value :param intercept: Intrecept in linear model :param slope: Slope in linear model :return: Calculated Intensity """ inten = intercept + slope*q return inten
5,346,921
def read_sph(input_file_name, mode='p'): """ Read a SPHERE audio file :param input_file_name: name of the file to read :param mode: specifies the following (\* =default) .. note:: - Scaling: - 's' Auto scale to make data peak = +-1 (use with caution if read...
5,346,922
def test_bulk_disable(): """ Test for disable all the given workers in the specific load balancer """ with patch.object(modjk, "_do_http", return_value={"worker.result.type": "OK"}): assert modjk.bulk_disable(["node1", "node2", "node3"], "loadbalancer1")
5,346,923
def unpack(path, catalog_name): """ Place a catalog configuration file in the user configuration area. Parameters ---------- path: Path Path to output from pack catalog_name: Str A unique name for the catalog Returns ------- config_path: Path Location of new...
5,346,924
def psi4ToStrain(mp_psi4, f0): """ Convert the input mp_psi4 data to the strain of the gravitational wave mp_psi4 = Weyl scalar result from simulation f0 = cutoff frequency return = strain (h) of the gravitational wave """ #TODO: Check for uniform spacing in time t0 = mp_psi4[:, 0] list_len = len(t0) comple...
5,346,925
def get_optimizer(library, solver): """Constructs Optimizer given and optimization library and optimization solver specification""" options = { 'maxiter': 100 } if library == 'scipy': optimizer = optimize.ScipyOptimizer(method=solver, options=options) elif library == 'ipopt': ...
5,346,926
def use_profile(profile_name): """Make Yolo use an AWS CLI named profile.""" client.YoloClient().use_profile(profile_name)
5,346,927
def _cast_query(query, col): """ ALlow different query types (e.g. numerical, list, str) """ query = query.strip() if col in {"t", "d"}: return query if query.startswith("[") and query.endswith("]"): if "," in query: query = ",".split(query[1:-1]) return [...
5,346,928
def test_unpack_raw_package_input(): """Test dissasembly of the user's raw package input.""" # test for sources with branch source = "someuser/repository:devel_branch" extras = "[pre-commit, testing, docs]" full_input = source + extras out_source, out_extras = utils.unpack_raw_package_input(full...
5,346,929
def binary_loss(pred_raw, label_raw, loss_func, weight=None, class_weight=None, class_weight_norm=False, reduction='mean', avg_factor=None, smooth=1.0): """ :param pred: [N, C, *] sco...
5,346,930
def picture_upload_to(instance, filename): """ Returns a unique filename for picture which is hard to guess. Will use uuid.uuid4() the chances of collision are very very very low. """ ext = os.path.splitext(filename)[1].strip('.') if not ext: ext = 'jpg' filename = '%s.%s' % (uuid.uu...
5,346,931
def showerActivityModel(sol, flux_max, b, sol_max): """ Activity model taken from: Jenniskens, P. (1994). Meteor stream activity I. The annual streams. Astronomy and Astrophysics, 287., equation 8. Arguments: sol: [float] Solar longitude for which the activity is computed (radians). ...
5,346,932
def create_directories(directory_name): """ Create directories """ # Create directory try: # Create target Directory os.mkdir(directory_name) logger.info("Directory %s Created", directory_name) except FileExistsError: logger.info("Directory %s already exists", di...
5,346,933
def setup_loggers(): """ Configure loggers. """ # Create logging path if not os.path.isdir(Config.LOGGING_PATH): os.makedirs(Config.LOGGING_PATH) # Set log format default_log_format = ( "[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d]" " %(message)s" ...
5,346,934
def new_update_template(args): """ Command line function that creates or updates an assignment template repository. Implementation of both the new_template and update_template console scripts (which perform the same basic functions but with different command line arguments and defaults). Cr...
5,346,935
def download_azure_storage_blob_file( file_name, container_name, connection_string, destination_file_name=None): """ Download a selected file from Google Cloud Storage to local storage in the current working directory. """ local_path = os.path.normpath(f'{os.getcwd()}...
5,346,936
def test_from_int_error(): """Verify from_int error """ x = uut.FixedPoint(1) # Verify that passing in something other than an int throws an error errmsg = re.escape(f'Expected {type(1)}; got {type(13.0)}.') with nose.tools.assert_raises_regex(TypeError, errmsg): x.from_int(13.0)
5,346,937
def request_slow_log(db_cluster_id, start_datetime, end_datetime, page_number, page_size): """ 请求慢SQL日志 :param db_cluster_id: :param start_datetime: :param end_datetime: :param page_number: :param page_size: :return: """ request = DescribeSlowLogRecordsRequest() request.set_a...
5,346,938
def pad_omni_image(image, pad_size, image_dims=None): """Pad an omni-directional image with the correct image wrapping at the edges. Parameters ---------- image Image to perform the padding on *[batch_shape,h,w,d]* pad_size Number of pixels to pad. image_dims Image dimen...
5,346,939
def add_film( film: FilmCreate, db: Session = Depends(get_db), user: User = Depends(get_current_user), ) -> Any: """ Add new film """ if not user.role.can_add_films: raise ForbiddenAction db_film = db.query(Film).filter(Film.name == film.name).first() if db_film is not None:...
5,346,940
def load_cube_file(lines, target_mode=None, cls=ImageFilter.Color3DLUT): """Loads 3D lookup table from .cube file format. :param lines: Filename or iterable list of strings with file content. :param target_mode: Image mode which should be after color transformation. The default i...
5,346,941
def vector_to_Hermitian(vec): """Construct a Hermitian matrix from a vector of N**2 independent real-valued elements. Args: vec (torch.Tensor): (..., N ** 2) Returns: mat (ComplexTensor): (..., N, N) """ # noqa: H405, D205, D400 N = int(np.sqrt(vec.shape[-1])) mat = torch.z...
5,346,942
def new_recipe(argv): """Makes a new recipe template""" verb = argv[1] parser = gen_common_parser() parser.set_usage( f"Usage: %prog {verb} [options] recipe_pathname\n" "Make a new template recipe." ) # Parse arguments parser.add_option("-i", "--identifier", help="Recipe identifier...
5,346,943
def view_payment(request): """ A view that renders the payment page template """ user = request.user # Check if user has already paid and redirect them to definitions app. if user.has_perm('definitionssoftware.access_paid_definitions_app'): return redirect(reverse('view_definitionssoftware')) ...
5,346,944
def augment_bag(store, bag, username=None): """ Augment a bag object with information about it's policy type. """ if not bag.store: bag = store.get(bag) if not username: username = bag.policy.owner policy_type = determine_tank_type(bag, username) bag.icon = POLICY_ICONS[polic...
5,346,945
async def test_login_refresh_token_row_na_401(): """Test the login flow using refresh_token.""" with account_mock() as mock_api: account = MyBMWAccount(TEST_USERNAME, TEST_PASSWORD, get_region_from_name(TEST_REGION_STRING)) await account.get_vehicles() with mock.patch( "bimm...
5,346,946
async def test_track_template_rate_limit(hass): """Test template rate limit.""" template_refresh = Template("{{ states | count }}", hass) refresh_runs = [] @ha.callback def refresh_listener(event, updates): refresh_runs.append(updates.pop().result) info = async_track_template_result( ...
5,346,947
def clear_pristine_meshes() -> None: """Clear the pristine bmesh data.""" global pristine_meshes for bm in pristine_meshes.values(): bm.free() pristine_meshes.clear()
5,346,948
def province_id_to_home_sc_power() -> Dict[utils.ProvinceID, int]: """Which power is this a home sc for?""" content = get_mdf_content(MapMDF.STANDARD_MAP) home_sc_line = content.splitlines()[2] tag_to_id = _tag_to_id(get_mdf_content(MapMDF.STANDARD_MAP)) # Assume powers are ordered correctly id_to_power = ...
5,346,949
def evaluate_cubic_spline(x, y, r, t): """Evaluate cubic spline at points. Parameters: x : rank-1 np.array of np.float64 data x coordinates y : rank-1 np.array of np.float64 data y coordinates r : rank-1 np.array of np.float64 output of solve_coeffs()...
5,346,950
async def test_iter_pulls_from_buffer(): """Check that the EventIterable emits buffered data if available.""" e = emitter.EventEmitter() i = iterable.EventIterable(e, 'test') iterator = await i.__aiter__() sentinel = object() e.emit('test', sentinel, test=sentinel) await asyncio.sleep(0) ...
5,346,951
def get_username(host, meta_host, config): """Find username from sources db/metadata/config.""" username = host.username or meta_host.get("username") if is_windows_host(meta_host): username = username or "Administrator" default_user = get_config_value(config["users"], meta_host["os"]) usern...
5,346,952
def get_all_tests(): """ Collect all tests and return them :return: A test suite as returned by xunitparser with all the tests available in the w3af framework source code, without any selectors. """ return _get_tests('all.xml')
5,346,953
def spinner_clear(): """ Get rid of any spinner residue left in stdout. """ sys.stdout.write("\b \b") sys.stdout.flush()
5,346,954
def main(): """Builds OSS-Fuzz project's fuzzers for CI tools. Note: The resulting fuzz target binaries of this build are placed in the directory: ${GITHUB_WORKSPACE}/out Returns: 0 on success or nonzero on failure. """ return build_fuzzers_entrypoint()
5,346,955
def find_first_img_dim(import_gen): """ Loads in the first image in a provided data set and returns its dimensions Intentionally returns on first iteration of the loop :param import_gen: PyTorch DataLoader utilizing ImageFolderWithPaths for its dataset :return: dimensions of image """ for x,...
5,346,956
def trib(x1,y1,x2,y2,x3,y3,color): """ Usage: trib x1 y1 x2 y2 x3 y3 color Parameters: x1, y1 : the coordinates of the first triangle corner x2, y2 : the coordinates of the second corner x3, y3 : the coordinates of the third corner color: the index...
5,346,957
def restaurantJSON(): """ Returns all restaurants by JSON call """ restaurants = session.query(Restaurant) return jsonify(Restaurants=[r.serialize for r in restaurants])
5,346,958
def _to_histogram_plotgroup(use_spec, plotgroup_id, plot_id, read_type, bincounts, output_dir, png_name): """ Create a histogram of length distribution. """ plot_spec = use_spec.get_plot_spec(plotgroup_id, plot_id) png_file = op.join(output_dir, png_name) png, thumb = plot_read_lengths_binned(bi...
5,346,959
def prepare_string(x, max_length=None): """ Converts a string from LaTeX escapes to UTF8 and truncates it to max_length """ # data = latex2text(x, tolerant_parsing=True) try: data = latex_to_unicode(filter_using_re(x)) if max_length is not None: data = (data[:max_length-5] + '[.....
5,346,960
def q_b(m0, m1, m2, n0, n1, n2): """Stretch""" return math.sqrt((m0 - n0)**2 + (m1 - n1)**2 + (m2 - n2)**2)
5,346,961
def poly_union(poly_det, poly_gt): """Calculate the union area between two polygon. Args: poly_det (Polygon): A polygon predicted by detector. poly_gt (Polygon): A gt polygon. Returns: union_area (float): The union area between two polygons. """ assert isinstance(poly_det, ...
5,346,962
def get_stoich(geom_i, geom_j): """ get the overall combined stoichiometry """ form_i = automol.geom.formula(geom_i) form_j = automol.geom.formula(geom_j) form = automol.formula.join(form_i, form_j) stoich = '' for key, val in form.items(): stoich += key + str(val) return stoic...
5,346,963
async def test_export_chat_invite_link(bot: Bot): """ exportChatInviteLink method test """ from .types.dataset import CHAT, INVITE_LINK chat = types.Chat(**CHAT) async with FakeTelegram(message_data=INVITE_LINK): result = await bot.export_chat_invite_link(chat_id=chat.id) assert result ...
5,346,964
def get_all_text(url): """Retrieves all text in paragraphs. :param str url: The URL to scrap. :rtype: str :return: Text in the URL. """ try: response = requests.get(url) # If the response was successful, no Exception will be raised response.raise_for_status() except H...
5,346,965
def metadata_partitioner(rx_txt: str) -> List[str]: """Extract Relax program and metadata section. Parameters ---------- rx_txt : str The input relax text. Returns ------- output : List[str] The result list of partitioned text, the first element is the relax program...
5,346,966
def make_aware(value, timezone): """ Makes a naive datetime.datetime in a given time zone aware. """ if hasattr(timezone, 'localize'): # available for pytz time zones return timezone.localize(value, is_dst=None) else: # may be wrong around DST changes return value.rep...
5,346,967
def to_dict(funs): """Convert an object to a dict using a dictionary of functions. to_dict(funs)(an_object) => a dictionary with keys calculated from functions on an_object Note the dictionary is copied, not modified in-place. If you want to modify a dictionary in-place, do adict.update(to_dict(funs)...
5,346,968
def parse_duration_string_ms(duration): """Parses a duration string of the form 1h2h3m4s5.6ms4.5us7.8ns into milliseconds.""" pattern = r'(?P<value>[0-9]+\.?[0-9]*?)(?P<units>\D+)' matches = list(re.finditer(pattern, duration)) assert matches, 'Failed to parse duration string %s' % duration times = {'h': 0, ...
5,346,969
def test_get_file_cancelled(cbcsdk_mock, connection_mock): """Test the response to the 'get file' command.""" cbcsdk_mock.mock_request('POST', '/appservices/v6/orgs/test/liveresponse/sessions', SESSION_INIT_RESP) cbcsdk_mock.mock_request('GET', '/appservices/v6/orgs/test/liveresponse/sessions/1:2468', SESSI...
5,346,970
def fin(activity): """Return the end time of the activity. """ return activity.finish
5,346,971
def add_outgoing_flow(node_id, successor_node_id, bpmn_diagram): """ :param node_id: :param successor_node_id: :param bpmn_diagram: """ if bpmn_diagram.diagram_graph.node[node_id].get(consts.Consts.outgoing_flow) is None: bpmn_diagram.diagram_graph.node[node_id][consts.Consts.outgoing_f...
5,346,972
def test_work_dbpedia_query(): """CreativeWork - dbpedia_fr : Should pass""" work1 = CreativeWork( title="Arrival", author="ABBA", author_is_organisation=True, endpoints=[Endpoint.dbpedia_fr], query_language=Lang.French) work1.query(strict_mode=True, check_type=True...
5,346,973
def unfreeze_map(obj): """ Unfreezes all elements of mappables """ return {key: unfreeze(value) for key, value in obj.items()}
5,346,974
def iterate_entries(incident_id: Optional[str], query_filter: Dict[str, Any], entry_filter: Optional[EntryFilter] = None) -> Iterator[Entry]: """ Iterate war room entries :param incident_id: The incident ID to search entries from. :param query_filter: Filters to search entries. ...
5,346,975
def get_date( value: Optional[Union[date, datetime, str]], raise_error=False ) -> Optional[date]: """ Convert a given value to a date. Args: raise_error: flag to raise error if return is None or not value: to be converted. Can be date/datetime obj as well as str formatted in ...
5,346,976
def make_working_directories (): """ Creates directories that we will be working in. In particular, we will have DOC_ROOT/stage-PID and DOC_ROOT/packages-PID """ global doc_root import os.path, os stage_dir = os.path.join (doc_root, "stage-" + str (os.getpid ())) package_dir = os.path.join ...
5,346,977
def k_param(kguess, s): """ Finds the root of the maximum likelihood estimator for k using Newton's method. Routines for using Newton's method exist within the scipy package but they were not explored. This function is sufficiently well behaved such that we should not have problems solving for k...
5,346,978
def hex_to_bin(value: hex) -> bin: """ convert a hexadecimal to binary 0xf -> '0b1111' """ return bin(value)
5,346,979
def four_oneports_2_twoport(s11: Network, s12: Network, s21: Network, s22: Network, *args, **kwargs) -> Network: """ Builds a 2-port Network from list of four 1-ports Parameters ---------- s11 : one-port :class:`Network` s11 s12 : one-port :class:`Network` s12 s21 : one-port...
5,346,980
def find_xml_command(rvt_version, xml_path): """ Finds name index src path and group of Commands in RevitPythonShell.xml configuration. :param rvt_version: rvt version to find the appropriate RevitPythonShell.xml. :param xml_path: path where RevitPythonShell.xml resides. :return: Commands dictionary...
5,346,981
def put_data_to_s3(data, bucket, key, acl=None): """data is bytes not string""" content_type = mimetypes.guess_type(key)[0] if content_type is None: content_type = 'binary/octet-stream' put_object_args = {'Bucket': bucket, 'Key': key, 'Body': data, 'ContentType': content_t...
5,346,982
def join_analysis_json_path(data_path: Path, analysis_id: str, sample_id: str) -> Path: """ Join the path to an analysis JSON file for the given sample-analysis ID combination. Analysis JSON files are created when the analysis data is too large for a MongoDB document. :param data_path: the path to the...
5,346,983
def user_profile(uname=None): """ Frontend gets user's profile by user name or modify user profile (to do). Return user's complete profile and the recommendations for him (brief events). :param uname: user's name, a string :return: a json structured as {'user': [(0, 'who', 'password', 'email@student...
5,346,984
def circuit_status(self, handle: ResultHandle) -> CircuitStatus: """ Return a CircuitStatus reporting the status of the circuit execution corresponding to the ResultHandle """ if handle in self._cache: return CircuitStatus(StatusEnum.COMPLETED) raise CircuitNotRunError(handle)
5,346,985
def run_users(mode: str, email: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = ''): """Users CLI entrypoint""" if mode not in MODES: raise ValueError(f"`mode` must be one of `{MODES}`. Value `{mode}` is given") if mode == LIST_USERS: run_list_users() elif...
5,346,986
def _add_enum(params, name, enum): """Adds enum information to our template parameters.""" enum_info = { 'name': name, 'identname': _ident(name), 'description': _format_comment(name, _get_desc(enum)), 'members': []} for en in enum.get('enum', []): member = {'identnam...
5,346,987
def run_pyfunnel(test_dir): """Run pyfunnel compareAndReport function. The test is run: * with the parameters, reference and test values from the test directory passed as argument; * from current directory (to which output directory path is relative). Args: test_dir (str): path ...
5,346,988
def get_portfolio() -> pd.DataFrame: """ Get complete user portfolio Returns: pd.DataFrame: complete portfolio """ portfolio = get_simple_portfolio() full_portfolio = pd.DataFrame() for ticket in portfolio.index: full_portfolio = full_portfolio.append( _clea...
5,346,989
def create(): """Create and scaffold application, module""" pass
5,346,990
def findZeros( vec, tol = 0.00001 ): """Given a vector of a data, finds all the zeros returns a Nx2 array of data each row is a zero, first column is the time of the zero, second column indicates increasing or decreasing (+1 or -1 respectively)""" zeros = [] for i in range( vec.size - ...
5,346,991
def test_multiply(time_data: TimeData, mult_arg: Union[float, Dict[str, float]]): """Test multiply""" from resistics.time import Multiply time_data_new = Multiply(multiplier=mult_arg).run(time_data) assert time_data_new.data.dtype == time_data.data.dtype to_mult = mult_arg if isinstance(to_mul...
5,346,992
def test_notice(): """ NOTICE command """ assert like("NOTICE #ch :hello, world", pack_command( "NOTICE", target="#ch", message="hello, world")) assert like("NOTICE WiZ :hello, world", pack_command( "NOTICE", target="WiZ", message="hello, world"))
5,346,993
def get_index(square_num: int) -> List[int]: """ Gets the indices of a square given the square number :param square_num: An integer representing a square :return: Returns a union with 2 indices """ for i in range(4): for j in range(4): if puzzle_state[i][j] == square_num: ...
5,346,994
def _ResolveName(item): """Apply custom name info if provided by metadata""" # ---------------------------------------------------------------------- def IsValidName(value): return bool(value) # ---------------------------------------------------------------------- if Attributes....
5,346,995
def extract_errno(errstr): """ Given an error response from a proxyfs RPC, extracts the error number from it, or None if the error isn't in the usual format. """ # A proxyfs error response looks like "errno: 18" m = re.match(PFS_ERRNO_RE, errstr) if m: return int(m.group(1))
5,346,996
def index(): """ Index page """ return render_template("index.html");
5,346,997
def solve(in_array): """ Similar to 46442a0e, but where new quadrants are flips of the original array rather than rotations :param in_array: input array :return: expected output array """ array_edgelength = len(in_array[0]) # input array edge length opp_end = array_edgelength*2-1 # used...
5,346,998
def trim_all(audio, rate, frame_duration, ambient_power=1e-4): """Trims ambient silence in the audio anywhere. params: audio: A numpy ndarray, which has 1 dimension and values within -1.0 to 1.0 (inclusive) rate: An integer, which is the rate at which samples are taken fra...
5,346,999