content
stringlengths
22
815k
id
int64
0
4.91M
def add_landmarks(particle, d, angle): """ Adds a set of landmarks to the particle. Only used on first SLAM cycle when no landmarks have been added. :param particle: The particle to be updated :param d: An array of distances to the landmarks :param angle: An array of observation angles for the ...
12,900
def walk_forward_val_multiple(model, ts_list, history_size=HISTORY_SIZE, target_size=TARGET_SIZE) -> float: """ Conduct walk-forward validation for all states, average the results. Parameters ---------- model -- The model to be validated ...
12,901
def main(): """The 'real' entry point of this program""" # parse args parser = argparse.ArgumentParser( prog=hdtop.const.PROG_NAME, description=hdtop.const.DESCRIPTION ) parser.add_argument( "action", default="start", nargs="?", choices=_SUBPARSERS, he...
12,902
def inverse_project_lambert_equal_area(pt): """ Inverse Lambert projections Parameters: pt: point, as a numpy array """ X = pt[0] Y = pt[1] f = np.sqrt(1.0-(X**2.0+Y**2.0)/4) return tensors.Vector([f*X,f*Y,-1.0+(X**2.0+Y**2.0)/2])
12,903
def _get_field_default(field: dataclasses.Field): """ Return a marshmallow default value given a dataclass default value >>> _get_field_default(dataclasses.field()) <marshmallow.missing> """ # Remove `type: ignore` when https://github.com/python/mypy/issues/6910 is fixed default_factory = f...
12,904
def download_file_from_s3( s3_path: str, local_path: str, create_dirs: bool = True, silent: bool = False, raise_on_error: bool = True, boto3_kwargs: Optional[Dict[str, Union[str, float]]] = None, ) -> bool: """Download a file from s3 to local machine. Args: s3_path: Full path on...
12,905
def get_all_votes(poll_id: int) -> List[Tuple[str, int]]: """ Get all votes for the current poll_id that are stored in the database Args: poll_id (int): Telegram's `message_id` for the poll Returns: List[Tuple[str, int]]: A list with the current votes in tuples (user, votes) """ ...
12,906
def plotWavefunc(x, potential, num_states, wave_vectsX, wave_vectsY, energy, func_name): """ This function is for the visualization of the Potential Energy Functions and Corresponding Wave Functions which are the solutions of to the wave equation. Inputs: x : ...
12,907
def getUnitConversion(): """ Get the unit conversion from kT to kJ/mol Returns factor: The conversion factor (float) """ temp = 298.15 factor = Python_kb/1000.0 * temp * Python_Na return factor
12,908
def find_where_and_nearest(array, value): """ Returns index and array[index] where value is closest to an array element. """ array = np.asarray(array) idx = (np.abs(array - value)).argmin() return idx, array[idx]
12,909
def twoexpdisk(R,phi,z,glon=False, params=[1./3.,1./0.3,1./4.,1./0.5,logit(0.1)]): """ NAME: twoexpdisk PURPOSE: density of a sum of two exponential disks INPUT: R,phi,z - Galactocentric cylindrical coordinates or (l/rad,b/rad,D/kpc) glon= (False) if True, inpu...
12,910
def init_linear(input_linear): """ 初始化全连接层权重 """ scope = np.sqrt(6.0 / (input_linear.weight.size(0) + input_linear.weight.size(1))) nn.init.uniform_(input_linear.weight, -scope, scope) if input_linear.bias is not None: scope = np.sqrt(6.0 / (input_linear.bias.size(0) + 1)) input...
12,911
def sc(X): """Silhouette Coefficient""" global best_k score_list = [] # 用来存储每个K下模型的平局轮廓系数 silhouette_int = -1 # 初始化的平均轮廓系数阀值 for n_clusters in range(3, 10): # 遍历从2到10几个有限组 model_kmeans = KMeans(n_clusters=n_clusters, random_state=0) # 建立聚类模型对象 cluster_labels_tmp = model_kmeans.f...
12,912
def is_tcp_port_open(host: str, tcp_port: int) -> bool: """Checks if the TCP host port is open.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2) # 2 Second Timeout try: sock.connect((host, tcp_port)) sock.shutdown(socket.SHUT_RDWR) except ConnectionRef...
12,913
def recursive_apply_dict(node: dict, fn: Callable) -> Any: """ Applies `fn` to the node, if `fn` changes the node, the changes should be returned. If the `fn` does not change the node, it calls `recursive_apply` on the children of the node. In case the recursion on the children results in one or mo...
12,914
def encode_image_array_as_jpg_str(image): """Encodes a numpy array into a JPEG string. Args: image: a numpy array with shape [height, width, 3]. Returns: JPEG encoded image string. """ image_pil = Image.fromarray(np.uint8(image)) output = six.BytesIO() image_pil.save(output, format='JPEG') jpg...
12,915
def minify_response(response): """Minify response to save bandwith.""" if response.mimetype == u'text/html': data = response.get_data(as_text=True) response.set_data(minify(data, remove_comments=True, remove_empty_space=True, ...
12,916
def test_RangeManager_9(qtbot, full_range, selection, value_type): """Entering invalid value in an entry field (especially the case when text contains `,`)""" slider_steps = 1000 selection_to_range_min = 0.01 rman = RangeManager(slider_steps=slider_steps, selection_to_range_min=selection_to_range_min)...
12,917
def get_shorturlhash(myurl): """Returns a FNV1a hash of the UNquoted version of the passed URL.""" x = get_hash(unquote(myurl)) return x
12,918
def main(): """Run DeePaC CLI.""" seed = 0 np.random.seed(seed) tf.random.set_seed(seed) rn.seed(seed) modulepath = os.path.dirname(__file__) builtin_configs = {"rapid": os.path.join(modulepath, "builtin", "config", "nn-img-rapid-cnn.ini"), "sensitive": os.path.join(mo...
12,919
def main(): """ Monitor serial port and write it to stdout. """ # Parse arguments arguments, parser = parse_arguments() # Open serial port port = serial.Serial(arguments.port, arguments.baud) # Read and write until CTRL + C start = time.time() try: while True: ...
12,920
def filter_privacy_level(qs, clearance_level, exact=False): """ Function to exclude objects from a queryset, which got a higher clearance level than the wanted maximum clearance level. :qs: Django queryset. :clearance_level: Minimum clearance level. :exact: Boolean to check for the exact cleara...
12,921
def test_compare_device_types(): """Tests that constants are configured and compared correctly.""" assert DeviceType.CEILING_FAN == "CF" assert DeviceType.is_fan("CF") assert DeviceType.MOTORIZED_SHADES == "MS" assert DeviceType.is_shades("MS") assert DeviceType.FIREPLACE == "FP" assert De...
12,922
def test_update_clinvar_id(adapter, user_obj, institute_obj): """record an official clinvar submission name for a submission""" submission_id = get_new_submission(adapter, user_obj, institute_obj) # Update the submission with the official clinvar name updated_submission = adapter.update_clinvar_id(cli...
12,923
def validate_ceph_vol_params(config): """ Checks the presence of Ceph Volume parameters """ logger.info("checking ceph_vol_params") ceph_vols = config_utils.get_ceph_vol(config) for ceph_vol in ceph_vols: validate_dict_data(ceph_vol, consts.HOST_KEY) ceph_host = ceph_vol[const...
12,924
def get_configuration_store(name=None,resource_group_name=None,opts=None): """ Use this data source to access information about an existing App Configuration. ## Example Usage ```python import pulumi import pulumi_azure as azure example = azure.appconfiguration.get_configuration_store(n...
12,925
def plot_particles(gauge_solutions, t, gaugenos='all', kwargs_plot=None, extend='neither'): """ Plot particle locations as points for some set of gauges. """ from matplotlib import pyplot as plt gaugenos = check_gaugenos_input(gauge_solutions, gaugenos) if kwargs_plo...
12,926
def _linear(args, output_size, bias, scope=None, use_fp16=False): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch x n, Tensors. output_size: int, second dimension of W[i]. bias: boolean, whether to add a bias term or not. bi...
12,927
def find_CI(method, samples, weights=None, coverage=0.683, logpost=None, logpost_sort_idx=None, return_point_estimate=False, return_coverage=False, return_extras=False, options=None): """Compute credible intervals and point estimates from samples. Arguments --------- ...
12,928
def test_cli_add(): """Should execute the command as expected.""" result = lobotomy.run_cli(["add", "lambda.create_function", "-"]) assert result.code == "ECHOED"
12,929
def calculating(gas_in, water_in, electricity_in): """ The Function that is responsible for calculating utility bills """ global resources_for_count resources_for_count = {'gas': 0.0, 'water': 0.0, 'electricity': 0.0} dict_remembering('rate_dictionary.txt', stable_rate_dict) calculate_chek('gas',...
12,930
def test_s3_service_readme(app): """Runs the example from the README.""" import os from flask import Flask from flask_warehouse import Warehouse # 1. Configuring Warehouse app = Flask(__name__) app.config['WAREHOUSE_DEFAULT_SERVICE'] = 's3' # or 'file' for filesystem app.c...
12,931
def load_csv(filename, fields=None, y_column=None, sep=','): """ Read the csv file.""" input = pd.read_csv(filename, skipinitialspace=True, usecols=fields, sep=sep, low_memory=False) input = input.dropna(subset=fields) # dtype={"ss_list_price": float, "ss_wholesale_cost": float} ...
12,932
def Normalize(array): """Normalizes numpy arrays into scale 0.0 - 1.0""" array_min, array_max = array.min(), array.max() return ((array - array_min)/(array_max - array_min))
12,933
def obtener_cantidad_anualmente(PaisDestino, AnioInicio, AnioFin): """ Obtener cantidad de vuelos entrantes anualmente dado un pais destino y un rango de años Obtiene la cantidad total de vuelos entrantes de cada año :param PaisDestino: Pais al que llegan los vuelos :type PaisDestino: str :param...
12,934
def calculate_shap_for_test(training_data, y, pipeline, n_points_to_explain): """Helper function to compute the SHAP values for n_points_to_explain for a given pipeline.""" points_to_explain = training_data[:n_points_to_explain] pipeline.fit(training_data, y) return _compute_shap_values(pipeline, pd.Dat...
12,935
def spdk_log_execution(duts, tester, log_handler): """ Change default logger handler. """ log_handler.config_execution('spdk') tester.logger.config_execution('tester') for dutobj in duts: dutobj.logger.config_execution( 'dut' + settings.LOG_NAME_SEP + '%s' % dutobj.crb['My IP...
12,936
def searchapi(): """status""" if len(sys.argv) == 1: q = "" else: q = sys.argv[1] result = requests.post("http://0.0.0.0:5000/search_user", data={"q": q}) try: data = result.json() if data: print("[{}] {}".format(data["id"], data["name"])) else: ...
12,937
def read_num_write(input_string): """ read in the number of output files """ pattern = ('NumWrite' + one_or_more(SPACE) + capturing(INTEGER)) block = _get_training_data_section(input_string) keyword = first_capture(pattern, block) assert keyword is not None return keyword
12,938
def stock_zh_a_minute(symbol: str = 'sh600751', period: str = '5', adjust: str = "") -> pd.DataFrame: """ 股票及股票指数历史行情数据-分钟数据 http://finance.sina.com.cn/realstock/company/sh600519/nc.shtml :param symbol: sh000300 :type symbol: str :param period: 1, 5, 15, 30, 60 分钟的数据 :type period: str :p...
12,939
def randomize_case(s: str) -> str: """Randomize string casing. Parameters ---------- s : str Original string Returns ------- str String with it's letters in randomized casing. """ result = "".join( [c.upper() if random.randint(0, 1) == 1 else c.lower() for c...
12,940
def _get_results(): """Run speedtest with speedtest.py""" s = speedtest.Speedtest() print("Testing download..") s.download() print("Testing upload..") s.upload() return s.results.ping, s.results.download, s.results.upload
12,941
def example_create_topics(a, topics): """ Create topics """ new_topics = [NewTopic(topic, num_partitions=3, replication_factor=1) for topic in topics] # Call create_topics to asynchronously create topics, a dict # of <topic,future> is returned. fs = a.create_topics(new_topics) # Wait for opera...
12,942
def load_conf() -> None: """Loads configuration from .env file""" env_path = Path(".") / ".env" load_dotenv(dotenv_path=env_path) global RESURRECT_PATH RESURRECT_PATH = ( Path(os.getenv("RESURRECT_PATH", default="~/.tmux/resurrect")) .expanduser() .resolve() ) verbos...
12,943
def rx_data_handler(name, packet): """ Callback function for incoming XBee transmission. Args: name(str): name to identify the callback function in a dispatcher. packet(dict): package received from the XBee API. """ # Split datapack header and payload -- Small misc packs. if...
12,944
def test_deletion_of_resource_owner_consumer(models_fixture): """Test deleting of connected user.""" app = models_fixture with app.app_context(): with db.session.begin_nested(): db.session.delete(User.query.get(app.resource_owner_id)) # assert that c1, t1, t2 deleted as...
12,945
def test_PipeJsonRpcSendAsync_4(): """ Message timeout. """ def method_handler1(): ttime.sleep(1) conn1, conn2 = multiprocessing.Pipe() pc = PipeJsonRpcReceive(conn=conn2, name="comm-server") pc.add_method(method_handler1, "method1") pc.start() async def send_messages(): ...
12,946
def findCursor(query, keyname, page_no, page_size): """Finds the cursor to use for fetching results from the given page. We store a mapping of page_no->cursor in memcache. If this result is missing, we look for page_no-1, if that's missing we look for page_no-2 and so on. Once we've found one (or we get back to ...
12,947
def _get_seq(window,variants,ref,genotypeAware): """ Using the variation in @variants, construct two haplotypes, one which contains only homozygous variants, the other which contains both hom and het variants by placing those variants into the reference base string @param variants: A vcf_eval.ChromV...
12,948
def launch_stats(db_obj, project, seed, query, state, cycles): """ (experimental) Obtain statistics of the runs using snapshots pulled down to the local directory. """ import pandas as pd from glob import glob from disp.castep_analysis import SCFInfo query = generate_fw_query(project, s...
12,949
def interp_logpsd(data, rate, window, noverlap, freqs, interpolation='linear'): """Computes linear-frequency power spectral density, then uses interpolation (linear by default) to estimate the psd at the desired frequencies.""" stft, linfreqs, times = specgram(data, window, Fs=rate, noverlap=noverlap, windo...
12,950
def load_replica_camera_traj(traj_file_path): """ the format: index """ camera_traj = [] traj_file_handle = open(traj_file_path, 'r') for line in traj_file_handle: split = line.split() #if blank line, skip if not len(split): continue camera_traj.a...
12,951
def test_model(sess, graph, x_, y_): """ :param sess: :param graph: :param x_: :param y_: :return: """ data_len = len(x_) batch_eval = batch_iter(x_, y_, 64) total_loss = 0.0 total_acc = 0.0 input_x = graph.get_operation_by_name('input_x').outputs[0] input_y = graph...
12,952
def epanechnikov(h: np.ndarray, Xi: np.ndarray, x: np.ndarray) -> np.ndarray: """Epanechnikov kernel. Parameters: h : bandwidth. Xi : 1-D ndarray, shape (nobs, 1). The value of the training set. x : 1-D ndarray, shape (1, nbatch). The value at which the kernel density is being estimated...
12,953
def punctuation(chars=r',.\"!@#\$%\^&*(){}\[\]?/;\'`~:<>+=-'): """Finds characters in text. Useful to preprocess text. Do not forget to escape special characters. """ return rf'[{chars}]'
12,954
def part_a(instances): """Do all the work for part a: use gradient descent to solve, plot objective value vs. iterations (log scale), step length vs. iterations, and f(x) - p* vs. iterations (log scale). Also, experiment with different alpha and beta values to see their effect on total iterations r...
12,955
def log_http_request(f): """Decorator to enable logging on an HTTP request.""" level = get_log_level() def new_f(*args, **kwargs): request = args[1] # Second argument should be request. object_type = 'Request' object_id = time.time() log_name = object_type + '.' + str(object_...
12,956
def look_at(vertices, eye, at=[0, 0, 0], up=[0, 1, 0]): """ "Look at" transformation of vertices. """ if (vertices.ndimension() != 3): raise ValueError('vertices Tensor should have 3 dimensions') place = vertices.place # if list or tuple convert to numpy array if isinstance(at, lis...
12,957
def _count(expr, pat, flags=0): """ Count occurrences of pattern in each string of the sequence or scalar :param expr: sequence or scalar :param pat: valid regular expression :param flags: re module flags, e.g. re.IGNORECASE :return: """ return _string_op(expr, Count, output_type=types....
12,958
def simplex3_vertices(): """ Returns the vertices of the standard 3-simplex. Each column is a vertex. """ v = np.array([ [1, 0, 0], [-1/3, +np.sqrt(8)/3, 0], [-1/3, -np.sqrt(2)/3, +np.sqrt(2/3)], [-1/3, -np.sqrt(2)/3, -np.sqrt(2/3)], ]) return v.transpose()
12,959
def open_backed_up(fname, mode='r', suffix='~'): """A context manager for opening a file with a backup. If an exception is raised during manipulating the file, the file is restored from the backup before the exception is reraised. Keyword arguments: - fname: path towards the file to be opened ...
12,960
def get_output_msg(status, num_logs): """ Returnes the output message in accordance to the script status """ if status == EXECUTION_STATE_COMPLETED: return "Retrieved successfully {} logs that triggered the alert".format(num_logs) else: return "Failed to retrieve logs. Please check the scrip...
12,961
def kSEQK(age): """Age-dependent organ-specific absorbed dose rate per unit kerma rate, normalized against the corresponding value for an adult Parameters ---------- age: float or list Age(s) when kSEQK is evaluated. """ k=[] if (not isinstance(age,list)) and (not isinstance...
12,962
def print_arbitrary_fluxes(fluxes: Fluxes, fid: TextIO, max_columns=5) -> None: """Print fluxes in FISPACT arbitrary flux format. Args: fluxes: what to print fid: output stream max_columns: max number of columns in a row """ print_fluxes(fluxes, fid, True, max_columns)
12,963
def insert_channel_links(message: str) -> str: """ Takes a message and replaces all of the channel references with links to those channels in Slack formatting. :param message: The message to modify :return: A modified copy of the message """ message_with_links = message matches = re.find...
12,964
def roles_remove(user, role): """Remove user from role.""" user_obj = find_user(user) if user_obj is None: raise click.UsageError("User not found.") role = _datastore._prepare_role_modify_args(role) if role is None: raise click.UsageError("Cannot find role.") if _datastore.remov...
12,965
def check_int_uuid(uuid): """Check that the int uuid i pass is valid.""" try: converted = UUID(int=uuid, version=4) except ValueError: return False return converted.int == uuid
12,966
def calc_E_E_C_hs_d_t_i(i, device, region, A_A, A_MR, A_OR, L_CS_d_t, L_CL_d_t): """暖冷房区画𝑖に設置された冷房設備機器の消費電力量(kWh/h)を計算する Args: i(int): 暖冷房区画の番号 device(dict): 暖冷房機器の仕様 region(int): 省エネルギー地域区分 A_A(float): 床面積の合計 (m2) A_MR(float): 主たる居室の床面積 (m2) A_OR(float): その他の居室の床面積 (m2) ...
12,967
def add_irregular_adjectives(ctx): """Add regular irregular adjectives to the database.""" session = ctx.session gender = ENUM['gender'] case = ENUM['case'] number = ENUM['number'] with open(ctx.config['IRREGULAR_ADJECTIVES']) as f: for adj in yaml.load_all(f): stem = Adjec...
12,968
def shift_time(x, dt): """Shift time axis to the left by dt. Used to account for pump & lamp delay""" x -= dt return x
12,969
def eps_xfer(request,client_slug=None,show_slug=None): """ Returns all the episodes for a show as json. Used to synk public url's with the main conference site. """ client=get_object_or_404(Client,slug=client_slug) show=get_object_or_404(Show,client=client,slug=show_slug) # eps = Episode.o...
12,970
def format_types (md, module_name, module_obj): """walk the list of types in the module""" md.append("---") md.append("## [module types](#{})".format(module_name, "types")) for name, obj in inspect.getmembers(module_obj): if obj.__class__.__module__ == "typing": if not str(obj).star...
12,971
def check_massfracs(df): """ """ elements = chem_elements.elements elements = list(set(self.df.columns).intersection(set(elements))) check = df[elements].sum(axis = 1) diff = abs(check - 1.0) if diff.max() >= 1.e-3: raise error_handling.ProgramError("Large errors in sum(mass fr...
12,972
def register(class_, option=None, get_funcs={}): """A decorator to register a function as the way to display an object of class_ """ if option: key = (class_, option) else: key = class_ def decorator(func): class_function_mapping[key] = (func, get_funcs) return func return decorator
12,973
def startup(target: machine.Machine, workload: str, count: int = 5, port: int = 0, **kwargs): """Time the startup of some workload. Args: target: A machine object. workload: The workload to run. count: Number of containers to start. port: The port to ...
12,974
def schema_handler(request): """ Handle schema request from UI. """ logger.debug("schema_handler: enter") req = request.GET.get('payload', '') action = request.GET.get('action', '') logger.debug('Received schema Request (%s)' % action) if not request.user.is_authenticated(): log...
12,975
def log2_fold_change(df, samp_grps): """ calculate fold change - fixed as samp_grps.mean_names[0] over samp_grps.mean_names[1], where the mean names are sorted alphabetically. The log has already been taken, so the L2FC is calculated as mean0 - mean1 :param df: expanded and/or filtered dataframe ...
12,976
def infer_wheel_units(pos): """ Given an array of wheel positions, infer the rotary encoder resolution, encoding type and units The encoding type varies across hardware (Bpod uses X1 while FPGA usually extracted as X4), and older data were extracted in linear cm rather than radians. :param pos: a ...
12,977
def extract_tform(landmarks, plane_name): """Compute the transformation that maps the reference xy-plane at origin to the GT standard plane. Args: landmarks: [landmark_count, 3] where landmark_count=16 plane_name: 'tv' or 'tc' Returns: trans_vec: translation vector [3] quat: quaterni...
12,978
def load_events(fhandle: TextIO) -> annotations.Events: """Load an URBAN-SED sound events annotation file Args: fhandle (str or file-like): File-like object or path to the sound events annotation file Raises: IOError: if txt_path doesn't exist Returns: Events: sound events annota...
12,979
def loadandcleanRAPIDexport(rapidsubproductsexport): """ :param rapidsubproductsexport: an Excel file name with ".xlsx" extention :return: """ exportfile = os.path.realpath("gannt_data/"+ rapidsubproductsexport) df = pd.read_excel(exportfile,na_values=["-"]) df = convertFYQfieldstodates(df) ...
12,980
def set_nan(df, chrom_bed_file): """This function will take in a dataframe and chromosome length bed file and will replace 0's with np.nan according to each chromosome length. This will fix any issues when calculating Z-scores""" # Build dictionary of key=chromosome and value=chromosome_length chrom...
12,981
def configure_smoothing(new_d,smoothing_scans): """ # <batchstep method="net.sf.mzmine.modules.peaklistmethods.peakpicking.smoothing.SmoothingModule"> # <parameter name="Peak lists" type="BATCH_LAST_PEAKLISTS"/> # <parameter name="Filename suffix">smoothed</parameter> # <parameter nam...
12,982
def contact_us(): """ Contact Us Route Route to lead to the contact page Args: None Returns: rendered template for contact_us.html """ return render_template('contact_us.html', title='CONP | Contact Us', user=current_user)
12,983
def costFunc1(x, module, output, col, row, bbox, img, prfObj): """Debugging function. Does the same as costFunc, but col and row are constants, and only the brightness of the prf can be changed. """ model = prfObj.getPrfForBbox(module, output, col, row, bbox) model *= x[0] cost = img-mode...
12,984
def query_field(boresight, r1=None, r2=None, observatory='apo', mag_range=None, mag_column=None, database_params=None): """Selects Gaia DR2 stars for a field, from the database. Parameters ---------- boresight : tuple A tuple with the right ascension and declination of the bores...
12,985
def test_deploy_flow_only_exclude_input_schema_if_none( fc, mocked_responses, input_schema, expected ): """Verify the *input_schema* is not excluded even if it's false-y.""" mocked_responses.add("POST", "https://flows.api.globus.org/flows") fc.deploy_flow( # Included arguments flow_defi...
12,986
def get_throttling_equilibria(simulation_config, input_params, priority_queue=True, dev_team_factor=1.0): """ Returns the equilibrium profiles for throttling configuration under analysis. :param simulation_config: :param input_params: :return: """ desc_inf003 = "THROTTLING_INF003" proce...
12,987
def checkRoot(): """Check if script was run as root""" if not os.geteuid() == 0: sys.exit("You must be root to run this command, please use sudo and try again.")
12,988
def signature(part): """ return the signature of a partial object """ return (part.func, part.args, part.keywords, part.__dict__)
12,989
def test_list_byte_length_nistxml_sv_iv_list_byte_length_1_2(mode, save_output, output_format): """ Type list/byte is restricted by facet length with value 5. """ assert_bindings( schema="nistData/list/byte/Schema+Instance/NISTSchema-SV-IV-list-byte-length-1.xsd", instance="nistData/list...
12,990
def clean_key(func): """Provides a clean, readable key from the funct name and module path. """ module = func.__module__.replace("formfactoryapp.", "") return "%s.%s" % (module, func.__name__)
12,991
def _autolabel(rects, ax, **kwargs): """ Attach a text label above each bar in *rects*, displaying its height. Args: rects: heights of the bar ax: Matplotlib Axes object where labels will be generated. """ fontsize = kwargs.get('fontsize', None) number_decimals = kwargs.get('nu...
12,992
async def async_setup_entry( hass: HomeAssistantType, config_entry: ConfigEntry, async_add_entities: Callable[[list[entity.Entity], bool], None], ): """Add hantest sensor platform from a config_entry.""" integration: AmsHanIntegration = hass.data[DOMAIN][config_entry.entry_id] processor: MeterMe...
12,993
def rotY(M, alpha): """Rotates polygon M around Y axis by alpha degrees. M needs to be a Numpy Array with shape (4,N) with N>=1""" T = np.eye(4) alpha_radians = np.radians(alpha) sin = np.sin(alpha_radians) cos = np.cos(alpha_radians) T[0,0] = cos T[2,2] = cos T[0,2] = sin T[2,0]...
12,994
def is_image_file(filename): """ :param filename: :return: """ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
12,995
def main(src, *, dest=None, exporter=None, filtering=False, pagebreaks=False, save=False, debug=False): """ Runs Otter Export Args: src (``str``): path to source notebook dest (``Optional[str]``): path at which to write PDF exporter (``Optional[str]``): exporter name filteri...
12,996
def invert_comp_specifier(comp_specifier): """ return the opposite (logical negation) of @p comp_specifier """ inverse_map = { Comparison.Equal: Comparison.NotEqual, Comparison.Less: Comparison.GreaterOrEqual, Comparison.LessOrEqual: Comparison.Greater, Comparison.NotEqual: Compa...
12,997
def latlong2utm(point): """ This function converts a point from lat long to utm Input : point : (lat,long) Output : utm point : (x,y,z, n) """ import utm return utm.from_latlon(point[0],point[1])
12,998
def multiply(a,b): """ multiply values Args: a ([float/int]): any value b ([float/int]): any value """ return a*b
12,999