content
stringlengths
22
815k
id
int64
0
4.91M
def all(iterable: object) -> bool: """all.""" for element in iterable: if not element: return False return True
5,345,000
def ind2slice(Is): """Convert boolean and integer index arrays to slices. Integer and boolean arrays are converted to slices that span the selected elements, but may include additional elements. If possible, the slices are stepped. Arguments --------- Is : tuple tuple of indices (slice...
5,345,001
def cleanup_mediawiki(text): """Modify mediawiki markup to make it pandoc ready. Long term this needs to be highly configurable on a site-by-site basis, but for now I'll put local hacks here. Returns tuple: cleaned up text, list of any categories """ # This tag was probably setup via SyntaxHig...
5,345,002
def test_constructing_a_priority_q_is_empty(): """Test that a new PriorityQ is empty.""" from electric_slide.scripts.priority_q import PriorityQ q = PriorityQ() assert q.values == {}
5,345,003
def get_popular_authors(): """Return all authors, most popular first.""" print "--Most_Popular_Authors--" query = "select author_name,total_views from popular_author" db = psycopg2.connect(database=DBNAME) c = db.cursor() c.execute(query) for i, row in c: print i, "--", row, "views" ...
5,345,004
def select_devices(devices): """ 选择设备 """ device_count = len(devices) print("Device list:") print("0) All devices") for i, d in enumerate(devices, start=1): print("%d) %s\t%s" % (i, d['serial'], d['model'])) print("q) Exit this operation") selected = input("\nselect: ") nums = No...
5,345,005
async def test_delay_template(hass): """Test the delay as a template.""" event = "test_event" events = [] delay_alias = "delay step" @callback def record_event(event): """Add recorded event to set.""" events.append(event) hass.bus.async_listen(event, record_event) scri...
5,345,006
def Fill( h ): """fill every empty value in histogram with previous value. """ new_h = [] x,v = h[0] if type(v) == ListType or type(v) == TupleType: l = len(v) previous_v = [0] * l else: previous_v = 0 for x, v in h: if type(v) == ListType or t...
5,345,007
def pendulum(theta, S, mg, drag) -> ps.Composition: """Draw a free body animation of a pendulum. params: theta: the angle from the vertical at which the pendulum is. S: the force exerted toward the pivot. mg: the force owing to gravity. drag: the force acting against the motion ...
5,345,008
def get_items(): """Fetches items from `INITIAL_OFFSET` in batches of `PAGINATION_OFFSET` until there are no more """ offset = INITIAL_OFFSET items = [] while True: batch = get_page_of_items(JSON_ENDPOINT.format(offset)) if not batch: break items.extend(batch) ...
5,345,009
def make_file_directory_internal(base_path): """Generates the database folder structure for internal data.""" # Corrs Data os.mkdir(os.path.join(base_path, 'Corrs')) cor_data = ['Genes', 'Terms'] cor_data_type = ['csv', 'npz'] for cor_dat in cor_data: os.mkdir(os.path.join(base_path, '...
5,345,010
def test_xgb_categorical_split(): """Test toy XGBoost model with categorical splits""" dataset = 'xgb_toy_categorical' tl_model = treelite.Model.load(dataset_db[dataset].model, model_format='xgboost_json') X, _ = load_svmlight_file(dataset_db[dataset].dtest, zero_based=True) expected_pred = load_tx...
5,345,011
def tcombinations_with_replacement(iterable, r): """ >>> tcombinations_with_replacement('ABCD', 0) ((),) >>> tcombinations_with_replacement('ABCD', 1) (('A',), ('B',), ('C',), ('D',)) >>> tcombinations_with_replacement('ABCD', 2) (('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'B'), (...
5,345,012
def discreteFiber(c, s, B=I3, ndiv=120, invert=False, csym=None, ssym=None): """ Generate symmetrically reduced discrete orientation fiber. Parameters ---------- c : TYPE DESCRIPTION. s : TYPE DESCRIPTION. B : TYPE, optional DESCRIPTION. The default is I3. ndiv :...
5,345,013
def random_organism(invalid_data): """ Generate Random Organism return: string containing "organism" name from CanCOGeN vocabulary. """ return random.choice(covid19_vocab_dict.get('organism')), global_valid_data
5,345,014
def test_confirm_user_family(app, session, monkeypatch): """Ensure a user is automatically confirmed in family mode.""" monkeypatch.setitem(app.config, '_JT_SERVER_MODE', 'family') u = auth_service.register_user(session, 'test@jadetree.io', 'hunter2JT', 'Test User') assert u.id == 1 assert u.uid_ha...
5,345,015
def test_set_output_volume(): """ Test if it set the volume of sound (range 0 to 100) """ mock = MagicMock(return_value={"retcode": 0}) with patch.dict(mac_desktop.__salt__, {"cmd.run_all": mock}), patch( "salt.modules.mac_desktop.get_output_volume", MagicMock(return_value="25") ): ...
5,345,016
def fate_bias(adata, group, basis='umap', fate_bias_df=None, figsize=(6, 4), save_show_or_return='show', save_kwargs={}, **cluster_maps_kwargs ): """Plot the lineage (fate) bias of cells states whose vect...
5,345,017
def test_roundtrip(): """Assert that forward/inverse Rosenblatt transforms is non-destructive.""" corr = numpy.array([[ 1.0, -0.9, 0.3], [-0.9, 1.0, 0.0], [ 0.3, 0.0, 1.0]]) dists = chaospy.J(chaospy.Uniform(0, 1), chaospy.Uniform(1, 2), ...
5,345,018
def build_psa_platform(target, toolchain, delivery_dir, debug, git_commit, skip_tests, args): """ Calls the correct build function and commits if requested. :param target: Target name. :param toolchain: Toolchain to be used. :param delivery_dir: Artifact directory, where imag...
5,345,019
def comput_mean_ndcg(df, k): """ Input:rating_info (usr_id, movie_id, rating) output: 平均ndcg 对每一种人 得到他真实分数和预测分数的dataframe 然后得到values """ #df.insert(df.shape[1], 'pred', pred) #print(df.groupby('user_id')) piece = dict(list(df.groupby('user_id'))) ndcg_list = [] f...
5,345,020
def test_warning(prob): """Test that a warning is raised when the probability is not between 0 and 1.""" code = SurfaceCode(3) with pytest.raises(Exception) as exc: IidNoise(code, prob) assert str(exc.value) == "Probability is not between 0 and 1."
5,345,021
def main(): """ Pre-processes all texts in the corpus, tokenizing, lemmatizing, and replacing all NE's by their CoreNLP NER label. The output texts are saved to a specified folder mimicing the corpus texts directory structure. """ cm = CorpusManager() for root, subdirnames, fnames in os.walk(cm.CORENLP_DIRPATH...
5,345,022
def to_im_list(IMs: List[str]): """Converts a list of string to IM Objects""" return [IM.from_str(im) for im in IMs]
5,345,023
def ref_ellipsoid(refell, UNITS='MKS'): """ Computes parameters for a reference ellipsoid Arguments --------- refell: reference ellipsoid name Keyword arguments ----------------- UNITS: output units MKS: meters, kilograms, seconds CGS: centimeters, grams, seconds ""...
5,345,024
def is_number(s): """ Check if it is a number. Args: s: The variable that needs to be checked. Returns: bool: True if float, False otherwise. """ try: float(s) return True except ValueError: return False
5,345,025
def emit(*args, **kwargs): """ The action allows users to add particles to an existing particle object without the use of an emitter. Returns: `int[]` `Integer array containing the list of the particleId attribute values for the created particles in the same order that the position flags were passed.` ...
5,345,026
def index(): """ 搜索提示功能 根据输入的值自动联想,支持中文,英文,英文首字母 :return: response """ start_time = time.time() # 输入词转小写 wd = request.args.get('wd').lower() user_id = request.args.get('user_id') if user_id and user_id != 'None': print(user_id) print(type(user_id)) if not wd...
5,345,027
def combineSets(listOfSets): """ Combines sets of strings by taking the cross product of the sets and \ concatenating the elements in the resulting tuples :param listOfSets: 2-D list of strings :returns: a list of strings """ totalCrossProduct = [''] for i in range(len(listOfSet...
5,345,028
def list_all_connections(pg_id='root', descendants=True): """ Lists all connections for a given Process Group ID Args: pg_id (str): ID of the Process Group to retrieve Connections from descendants (bool): True to recurse child PGs, False to not Returns: (list): List of Connecti...
5,345,029
def find_file(fname): """ Return the full file name (path plus name) to file fname. fname is the name of the file to find. If the file fname is not found, then simply return None. """ for d in get_cli_search_dirs(): full_filename = os.path.join(d, fname) if os.path.exists(full_...
5,345,030
def save_uptime(machine_config, num_seconds, idle_time, data_log_date): """ Create Uptime record and save it in DB. """ uptime = Uptime( stats_machine_config=machine_config, date=data_log_date, number_of_seconds=num_seconds, idle_time=idle_time) uptime.save()
5,345,031
def _GetTombstoneData(device, tombstone_file): """Retrieve the tombstone data from the device Args: device: An instance of DeviceUtils. tombstone_file: the tombstone to retrieve Returns: A list of lines """ return device.old_interface.GetProtectedFileContents( '/data/tombstones/' + tombsto...
5,345,032
def _strTogYear(v): """Test gYear value @param v: the literal string @return v @raise ValueError: invalid value """ try: time.strptime(v+"-01-01", "%Y-%m-%d") return v except: raise ValueError("Invalid gYear %s" % v)
5,345,033
def aca_full_pivoting(A, epsilon): """ACA with full pivoting as in the lecture Takes in a matrix, and returns the CUR decomposition """ # R0 = A Rk = A.copy() I_list = [] J_list = [] while frobenius_norm(Rk) > epsilon*frobenius_norm(A): i, j = np.unravel_index(np.argmax(np.abs(R...
5,345,034
def get_word_cloud(words: List[str], max_words=500, image_path=None, image_name=None): """ Create a word cloud based on a set of words. Args: words (List[str]): List of words to be included in the word cloud. max_words (int): Maximum number of words to be included in...
5,345,035
def get_data_sets(cnn_n_input, data_directory="data_set/", n_data_sets=5): """ Retrieve data and partition it into n_data_sets for cross-validation. """ print("Partitioning data into", str(n_data_sets), "splits.") # Get list of labels list_labels = extract_data.get_labels(data_directory + "lab...
5,345,036
def on_disconnect(unused_client, obj, rc): """Paho callback for when a device disconnects.""" obj.connected = False obj.led.off() print('on_disconnect', error_str(rc))
5,345,037
def _get_pyo_codes(fmt='', dtype='int16', file_out=''): """Convert file and data formats to int codes, e.g., wav int16 -> (0, 0). """ if not fmt: dot_ext = os.path.splitext(file_out)[1] fmt = dot_ext.lower().strip('.') if fmt in pyo_formats: file_fmt = pyo_formats[fmt] else:...
5,345,038
def catch_gpu_memory_error( f ): """ Decorator that calls the function `f` and catches any GPU memory error, during the execution of f. If a memory error occurs, this decorator prints a corresponding message and aborts the simulation (using MPI abort if needed) """ # Redefine the original f...
5,345,039
def horizontal_tail_planform_raymer(horizontal_stabilizer, wing, l_ht,c_ht): """Adjusts reference area before calling generic wing planform function to compute wing planform values. Assumptions: None Source: Raymer Inputs: horizontal_stabilizer [SUAVE data structure] ...
5,345,040
def inherit_check(role_s, permission): """ Check if the role class has the following permission in inherit mode. """ from improved_permissions.roles import ALLOW_MODE role = get_roleclass(role_s) if role.inherit is True: if role.get_inherit_mode() == ALLOW_MODE: return T...
5,345,041
def giveHint(indexValue, myBoard): """Return a random matching card given the index of a card and a game board""" validMatches = [] card = myBoard[indexValue] for c in myBoard: if (card[0] == c[0]) and (myBoard.index(c) != indexValue): validMatches.append(myBoard.index(c)) re...
5,345,042
async def make_getmatch_embed(data): """Generate the embed description and other components for a getmatch() command. As with its parent, remember that this currently does not support non team-vs. `data` is expected to be the output of `get_individual_match_data()`. The following `dict` is ret...
5,345,043
def allreduceCommunicate_op(node, comm): """Make a new instance of AllReduceCommunicateOp and call the instance. Parameters: ---- node : Node The Node to do allreduce Returns: ---- A new Node instance created by Op. """ return AllReduceCommunicateOp(node, comm)
5,345,044
def _micronaut_library(name, srcs = [], deps = [], proto_deps = [], runtime_deps = [], data = [], templates = [], exports = [], **kwargs...
5,345,045
def test_list_all(fake_client): """pye Test organization class 'list_all()' Method """ org = Organizations(fake_client, "https://api.buildkite.com/v2/") org.list_all() fake_client.get.assert_called_with( org.path, query_params={"page": 0}, with_pagination=False )
5,345,046
def compute_scales(work_dir=".", downscaling_method="average", options={}): """Generate lower scales following an input info file""" accessor = neuroglancer_scripts.accessor.get_accessor_for_url( work_dir, options ) pyramid_io = precomputed_io.get_IO_for_existing_dataset( accessor, encod...
5,345,047
def reduce_fn(state, values): """tf.data.Dataset-friendly implementation of mean and variance.""" k, n, ex, ex2 = state # If this is the first iteration, we pick the first value to be 'k', # which helps with precision - we assume that k is close to an average # value and calculate mean and variance with respe...
5,345,048
def winged_edge( face_features: np.ndarray, edge_features: np.ndarray, coedge_features: np.ndarray, coedge_to_next: np.ndarray, coedge_to_mate: np.ndarray, coedge_to_face: np.ndarray, coedge_to_edge: np.ndarray, ): """Create graph according to the `winged edge` configuration.""" coe...
5,345,049
def dollar_format(dollars): """ Args: dollars (any): A dollar value (Any value that can be turned into a float can be used - int, Decimal, str, etc.) Returns: str: The formatted string """ decimal_dollars = Decimal(dollars) if decimal_dollars < 0: return "-${:,.2f}".forma...
5,345,050
def test_delete_training_view_with_deployment(test_app, create_deployment): """ Tests deleting a training view where a model has been deployed """ APP.dependency_overrides[crud.get_db] = lambda: (yield create_deployment) # Give the "server" the same db session assert len(create_deployment.query(Tra...
5,345,051
def check_aea_project( f: Callable, check_aea_version: bool = True, check_finger_prints: bool = False ) -> Callable: """ Check the consistency of the project as a decorator. - try to load agent configuration file - iterate over all the agent packages and check for consistency. """ def wrap...
5,345,052
def solve_scene(kb_db_name, obj_file_path): """ Solve manipulation for the target object in the scene using analogy. Args: kb_db_name(str): The knowledge base database file name. obj_file_path(str): File path to the .obj file. """ # create vpython scene that is used for graphical re...
5,345,053
def sftp(): """ Fixture allowing setup of a mocked remote SFTP session. Yields a 3-tuple of: Transfer() object, SFTPClient object, and mocked OS module. For many/most tests which only want the Transfer and/or SFTPClient objects, see `sftp_objs` and `transfer` which wrap this fixture. """ ...
5,345,054
async def test_bike_is_in_use(rental_manager, random_rental, random_bike, random_bike_factory, bike_connection_manager): """Assert that you can check if a bike is in use.""" assert rental_manager.is_in_use(random_bike) assert not rental_manager.is_in_use(await random_bike_factory(bike_connection_manager))
5,345,055
def find_closest_cross(wire1_path, wire2_path): """ Compare the coordinates of two wire paths to find the crossing point closest (Manhattan Distance) to the origin (0,0). Returns a list of crossing points, the closest crossing point and its distance to the start point """ best...
5,345,056
def test_solution(data: str) -> None: """Test the solution""" solution = Day10() solution.set_input_data(data.split("\n")) assert solution.part_one() == 26397 assert solution.part_two() == 288957
5,345,057
async def check_is_user_exist(user_collection: UserCollection, test_data: dict): """ Check that checking for an existing user is correct. :param user_collection: MongoDB collection. :type user_collection: UserCollection :param test_data: Database test data. :type test_data: dict """ dat...
5,345,058
def add_signature_source(service, **_): """ Add a signature source for a given service Variables: service => Service to which we want to add the source to Arguments: None Data Block: { "uri": "http://somesite/file_to_get", # URI to fetch for parsing the rules ...
5,345,059
def edit_screen_item(self, request, form): """ Edit a screen. """ layout = ManageScreensLayout(self, request) if form.submitted(request): form.update_model(self) request.message(_('Screen modified.'), 'success') request.app.pages_cache.flush() return redirect(layout.manage...
5,345,060
def get_xyz_t(): """ CIELAB to XYZ の逆関数の中の値を XYZ のぞれぞれについて求める。 """ c, l, h = symbols('c, l, h', real=True) xt = (l + 16) / 116 + (c * cos(h)) / 500 yt = (l + 16) / 116 zt = (l + 16) / 116 - (c * sin(h)) / 200 xyz_t = [xt, yt, zt] return xyz_t, c, l, h
5,345,061
async def home(): """ Home page, welcome Returns: Rendered template of homepage """ return await render_template('home.html')
5,345,062
def compute_inverse_interpolation_img(weights, indices, img, b, h_i, w_i): """ weights: [b, h*w] indices: [b, h*w] img: [b, h*w, a, b, c, ...] """ w0, w1, w2, w3 = weights ff_idx, cf_idx, fc_idx, cc_idx = indices k = len(img.size()) - len(w0.size()) img_0 = w0[(...,) + (None,) * k] ...
5,345,063
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
5,345,064
def build_norm_layer(cfg, num_channels, postfix=''): """ Build normalization layer Args: Returns: layer (fluid.dygrah.Layer): created norm layer """ assert isinstance(cfg, dict) and 'type' in cfg cfg_ = cfg.copy() layer_type = cfg_.pop('type') if layer_type not in norm_cfg: ...
5,345,065
def get_split_cifar100_tasks(num_tasks, batch_size): """ Returns data loaders for all tasks of split CIFAR-100 :param num_tasks: :param batch_size: :return: """ datasets = {} # convention: tasks starts from 1 not 0 ! # task_id = 1 (i.e., first task) => start_class = 0, end_class = 4 cifar_transforms = torch...
5,345,066
def _find_loose_date(date_string): """Look for four digit numbers in the string. If there's only one, return it.""" if re.search(r'digit', date_string): # Might be something like "digitized 2010", which we want to avoid. return None # find all the (unique) four digit numbers in the date_stri...
5,345,067
def invoke(command_requested, timeout=DEFAULT_TIMEOUT): """ """ p = subprocess.Popen(command_requested, shell=True, stdin=subprocess.PIPE, stdout=None, stderr=None) p.stdin.close() # since we do not allow invoked processes to listen to stdin, we close stdin to the subprocess try: return_code...
5,345,068
def _cmd_dump(m, line): """Dump entries from the defaults files. Syntax: config dump [*|regex] [section="*|regex"] [ic="1"] Examples: config dump * - dump the entire JSON config data structure. config dump reg[.*] ic="1" - dump variables that match the regu...
5,345,069
def zip_addon(addon: str, addon_dir: str): """ Zips 'addon' dir or '.py' file to 'addon.zip' if not yet zipped, then moves the archive to 'addon_dir'. :param addon: Absolute or relative path to a directory to zip or a .zip file. :param addon_dir: Path to Blender's addon directory to move the zipped archive...
5,345,070
def set_simulation_data( state_energies, T_array, state1_index, state2_index ): """ Create and set SimulationData objects for a pair of specified states """ # Set default UnitData object default_UnitData = UnitData( kb=kB.value_in_unit(unit.kilojoule_per_mole/unit.kel...
5,345,071
def card_banlist_status(banlist_status): """Validate banlist status Args: banlist_status {str}: Banlist status Raises: exceptions.BanlistStatusInvalid: Banlist status must be banned, limited, semi-limited or unlimited """ if not constants.BanlistStatus.is_valid_value(b...
5,345,072
def pfl(flist, num, reverse = False, end = "\n"): """Print formatted list, accepts list of floats, number of elements to print and bool to print from the end of list.""" if reverse: num = -num [print("{:3.3f}".format(i), end = " ") for i in flist[num:]] else: [print("{:3.3f}".for...
5,345,073
def park2_euc(x): """ Comutes the park2 function """ max_val = 5.925698 x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] ret = (2.0/3.0) * np.exp(x1 + x2) - x4*np.sin(x3) + x3 return min(ret, max_val)
5,345,074
def num_compositions_jit(m, n): """ Numba jit version of `num_compositions`. Return `0` if the outcome exceeds the maximum value of `np.intp`. """ return comb_jit(n+m-1, m-1)
5,345,075
def _report_failed_challs(failed_achalls): """Notifies the user about failed challenges. :param set failed_achalls: A set of failed :class:`certbot.achallenges.AnnotatedChallenge`. """ problems = dict() for achall in failed_achalls: if achall.error: problems.setdefault(...
5,345,076
def fake_get_vim_object(arg): """Stubs out the VMwareAPISession's get_vim_object method.""" return fake_vmware_api.FakeVim()
5,345,077
def get_version(*file_paths): """Retrieves the version from replicat_documents/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: ...
5,345,078
def get_old_ids(title): """ Returns all the old ids of a particular site given the title of the Wikipedia page """ raw_data = json.loads( readInDataFromURL("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvlimit=100000&titles=" + title) ) old_ids = dict() # initialize for pag...
5,345,079
def max_expectation_under_constraint(f: np.ndarray, q: np.ndarray, c: float, eps: float = 1e-2, display: bool = False) -> np.ndarray: """ Solve the following constrained optimisation problem: max_p E_p[f] s.t. KL(q || p) <= c :param f: an array of ...
5,345,080
def payload_to_plain(payload=None): """ Converts the myADS results into the plain text message payload :param payload: list of dicts :return: plain text formatted payload """ formatted = u'' for p in payload: formatted += u"{0} ({1}) \n".format(p['name'], p['query_url'].format(p['qty...
5,345,081
async def parse_blog_post(blog_link): """ Given a blog post's URL, this function GETs it and pulls the body out. We then analyze each word with NTLK and write some data into redis. :param blog_link: String :return: Raw text from the blog post w/html tags stripped out """ global blogs_scraped...
5,345,082
def get_credentials_from_request(cloud, request): """ Extracts and returns the credentials from the current request for a given cloud. Returns an empty dict if not available. """ if request.META.get('HTTP_CL_CREDENTIALS_ID'): return get_credentials_by_id( cloud, request, request....
5,345,083
def build_wvc_model(wvc_model_file, atm_lut_file, rdn_header_file, vis=40): """ Build water vapor models. Arguments: wvc_model_file: str Water vapor column model filename. atm_lut_file: str Atmosphere lookup table file. rdn_header_file: str Radiance he...
5,345,084
def nCr(n, r): """n-choose-r. Thanks for the "compact" solution go to: http://stackoverflow.com/questions/2096573/counting-combinations-and-permutations-efficiently """ return reduce( lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n + 1), xrange(1, r + 1)), ...
5,345,085
def test_echo_substitutions_pass(): """Format string interpolations should work.""" context = Context({ 'key1': 'down the', 'echoMe': 'piping {key1} valleys wild'}) with patch_logger( 'pypyr.steps.echo', logging.NOTIFY) as mock_logger_notify: pypyr.steps.echo.run_step(co...
5,345,086
def check_python_version(conf, minver=None): """ Check if the python interpreter is found matching a given minimum version. minver should be a tuple, eg. to check for python >= 2.4.2 pass (2,4,2) as minver. If successful, PYTHON_VERSION is defined as 'MAJOR.MINOR' (eg. '2.4') of the actual python version found, a...
5,345,087
def bcFactory(name): """Factory for boundary condition items. """ from pythia.pyre.inventory import facility from pylith.bc.DirichletTimeDependent import DirichletTimeDependent return facility(name, family="boundary_condition", factory=DirichletTimeDependent)
5,345,088
def decode(value): """Decode utf-8 value to string. Args: value: String to decode Returns: result: decoded value """ # Initialize key variables result = value # Start decode if value is not None: if isinstance(value, bytes) is True: result = value....
5,345,089
def notebook_display_image_svg(listOfImageNames): """ Takes as input a list of images (e.g. png) and displays them in the current cell """ for imageName in listOfImageNames: display(SVG(filename=imageName))
5,345,090
def sequence_rec_sqrt(x_init, iter, dtype=int): """ Mathematical sequence: x_n = x_{n-1} * sqrt(n) :param x_init: initial values of the sequence :param iter: iteration until the sequence should be evaluated :param dtype: data type to cast to (either int of float) :return: element at the given i...
5,345,091
def convert_string_to_type(string_value, schema_type): """ Attempts to convert a string value into a schema type. This method may evaluate code in order to do the conversion and is therefore not safe! """ # assume that the value is a string unless otherwise stated. if schema_type == "fl...
5,345,092
def plot3d(shower): """ Display a 3d plot of a shower Parameters ---------- shower: list of position points (3-floats arrays) """ X = [] Y = [] Z = [] for points in shower: X.append(points[0]) Y.append(points[1]) Z.append(points[2]) fig = plt.figure(...
5,345,093
def counter(path): """Get number of files by searching directory recursively""" if not os.path.exists(path): return 0 count = 0 for r, dirs, files in os.walk(path): for dr in dirs: count += len(glob.glob(os.path.join(r, dr + "/*"))) return count
5,345,094
def add_square_plot(x_start, x_stop, y_start, y_stop, ax, colour = 'k'): """Draw localization square around an area of interest, x_start etc are in pixels, so (0,0) is top left. Inputs: x_start | int | start of box x_stop | int | etc. y_start | int | y_ stop | int | ax | ...
5,345,095
def get_local_coordinate_system(time_dep_orientation: bool, time_dep_coordinates: bool): """ Get a local coordinate system. Parameters ---------- time_dep_orientation : If True, the coordinate system has a time dependent orientation. time_dep_coordinates : If True, the coordinat...
5,345,096
def start_debugging(address): """ Connects to debugpy in Maya, then starts the threads needed to send and receive information from it """ log("Connecting to " + address[0] + ":" + str(address[1])) # Create the socket used to communicate with debugpy global debugpy_socket debugpy_socket...
5,345,097
def _get_tooltip(tooltip_col, gpd): """Show everything or columns in the list.""" if tooltip_col is not None: tooltip = folium.GeoJsonTooltip(fields=tooltip_col) else: tooltip = tooltip_col return tooltip
5,345,098
def encryption(message: str, key: int) -> str: """Return the ciphertext by xor the message with a repeating key""" return b"".join( [bytes([message[i] ^ key[i % len(key)]]) for i in range(len(message))] )
5,345,099