content
stringlengths
22
815k
id
int64
0
4.91M
def solution(A): # O(N^2) """ For a given value A, compute the number with the fewest number of squared values and return them within an array. eg. 26 can be computed with squared values [25, 1] or [16, 9, 1], but the answer is only [25, 1] as ...
27,600
def gmrt_guppi_bb(rawfile, npol=2, header=None, chunk=None, samples_per_frame=4096, nchan=1): """ To read gmrt raw voltages file of GWB to convert to guppi raw :USAGE: -------- $ gmrt_raw_toguppi [-h] [-f FILENAME] [-c CHUNK] [-hdr HEADER] [-hf HEADER_FILE] [-hfo HEADER_FILE_OUTPUT] To read gm...
27,601
def get_device_path(): """Return device path.""" if is_gce(): return None devices = get_devices() device_serial = environment.get_value('ANDROID_SERIAL') for device in devices: if device_serial == device.serial: return device.path return None
27,602
def pattern_maker(size, dynamic): """ Generate a pattern with pixel values drawn from the [0, 1] uniform distribution """ def pattern(): return np.random.rand(size) def static(): a_pattern = pattern() def fn(): return a_pattern return fn return...
27,603
def RMSE(a, b): """ Return Root mean squared error """ return np.sqrt(np.square(np.subtract(a, b)).mean())
27,604
def alpha_a_b(coord, N, silent=True): """Calculate alpha, a, b for a rectangle with coordinates coord and truncation at N.""" [x0, x1, y0, y1] = coord a = 0 for zero in zeros[:N]: a += exp(-zero*y0)/abs(complex(0.5, zero)) b = 0 for zero in zeros[N:]: b += exp(-zero*y0)/abs(...
27,605
async def test_hub_support_wireless(opp): """Test updating hub devices when hub support wireless interfaces.""" # test that the device list is from wireless data list hub = await setup_mikrotik_entry(opp) assert hub.api.support_wireless is True assert hub.api.devices["00:00:00:00:00:01"]._params ...
27,606
def asdataset( dataclass: Any, reference: Optional[DataType] = None, dataoptions: Any = None, ) -> Any: """Create a Dataset object from a dataclass object. Args: dataclass: Dataclass object that defines typed Dataset. reference: DataArray or Dataset object as a reference of shape. ...
27,607
def get_edge_size(reader: ChkDirReader, chunks: list[ChunkRange], tilesize: int) -> int: """Gets the size of an edge tile from an unknown chunk""" for chunk in chunks: data: bytes = deflate_range(reader, chunk.start, chunk.end, True) if data is None: continue try: ...
27,608
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False): """Test model with multiple gpus. This method tests model with multiple gpus and collects the results under two different modes: gpu and cpu modes. By setting 'gpu_collect=True' it encodes results to gpu tensors and use gpu communi...
27,609
def toRegexp(exp,terminate=False,lower=False): """ Case sensitive version of the previous one, for backwards compatibility """ return toCl(exp,terminate,wildcards=('*',),lower=lower)
27,610
def writePLYPointsAndPolygons(filename, xyzs, polygons): """given a list of polygons and a matching list of colours, write the coloured polygons to a PLY file""" dim = xyzs.shape[1] with open(filename, 'w') as f: f.write('ply\nformat ascii 1.0\nelement vertex ') f.write(str(xyzs.shape[0])) f.write('...
27,611
def setup_logging(conf_dict): """Setup logging configurations.""" logging.config.dictConfig(config=conf_dict) log.debug(msg='Setup logging configurations.')
27,612
def marker_used_in_game(marker_id: int) -> bool: """ Determine whether the marker ID is used in the game. :param marker_id: An official marker number, mapped to the competitor range. :returns: True if the market is used in the game. """ return any([marker_id in marker_range for marker_range in ...
27,613
async def data_to_json(data: list): """ 1. Take input data, of a list of tasks. 2. Write the data into a json file (tasks.json) Args: data (list): [list of tasks] """ data = json.dumps(data) with open(filepath, 'w') as file: file.write(data)
27,614
def iround(x): """ Round an array to the nearest integer. Parameters ---------- x : array_like Input data. Returns ------- y : {numpy.ndarray, scalar} The rounded elements in `x`, with `int` dtype. """ return np.round(x).astype(int)
27,615
def multiLineManager(pentadList = [], debugMode = False): """ Takes the complete list of pentads and returns this list once every multilines being put on a single line. That's ALL. """ output = [] currentStatement = "" presentChar = 'a' startingLine = 0 i = 0 state = "Nothing" fo...
27,616
def get_ec2_conn(): """ Requried: env.aws_region, env.aws_access_key, env.aws_secret_access_key return conneciton to aws ec2 """ conn = boto.ec2.connect_to_region( env.aws_region, aws_access_key_id=env.aws_access_key, aws_secret_access_key=env.aws_secret_access_key ...
27,617
def eval_nominal_domain(pool: SamplerPool, env: SimEnv, policy: Policy, init_states: list) -> list: """ Evaluate a policy using the nominal (set in the given environment) domain parameters. :param pool: parallel sampler :param env: environment to evaluate in :param policy: policy to evaluate :p...
27,618
def create_final_comment_objects(): """Goes through the final comments and returns an array of objects.""" arr = [] # Stores objects for line in final_file: row = line.split(",") # Set object variables for each object before adding it to the array comment_number, commen...
27,619
def cmd_yandex_maps(term): """Yandex Maps Search.""" redirect('http://maps.yandex.ru/?text=%s' % term)
27,620
def normalise_target_name(name, used=[], max_length=None): """ Check that name[:max_length] is not in used and append a integer suffix if it is. """ def generate_name(name, i, ml): # Create suffix string i_name = '' if i == 0 else '_' + str(i) # Return concatenated st...
27,621
def construct_pairwise_df(sr: pd.Series, np_fun): """Constructs an upper diagonal df from all pairwise comparisons of a sr""" sr = sr.sort_index() _mat = np.triu(np_fun(sr.to_numpy() - sr.to_numpy()[:, None]), k=1) _mat[np.tril_indices(_mat.shape[0])] = None return pd.DataFrame(_mat, index=sr.index....
27,622
def read_all_csv_subscenarios_from_dir_and_insert_into_db( conn, quiet, subscenario, table, inputs_dir, use_project_method, project_is_tx, cols_to_exclude_str, custom_method, ): """ :param conn: database connection object :param quiet: boolean :param subscenario: stri...
27,623
def privacy(request): """This returns the privacy policy page""" return render(request=request, template_name="registration/privacy.html")
27,624
def seq_search(items, key): """顺序查找""" for index, item in enumerate(items): if item == key: return index return -1
27,625
def _check_moog_files (fp,mode='r',clobber=True,max_filename_length=None): """ Takes a moog keyword and extracts from the moogpars """ # - - - - - - - - - - - - filepath if fp is None: return # - - - - - - - - - - - - check file mode if mode not in ('r','w'): raise ValueError("mod...
27,626
def checkStatus(testNode, testNodeArgs): """Test --terminate-at-block stops at the correct block.""" Print(" ".join([ "The test node has begun receiving from the producing node and", "is expected to stop at or little bigger than the block number", "specified here: ", testNodeArgs...
27,627
def parse_prediction_key(key): """The "name" or "key" of a predictor is assumed to be like: `ProHotspotCtsProvider(Weight=Classic(sb=400, tb=8), DistanceUnit=150)` Parse this into a :class:`PredictionKey` instance, where - `name` == "ProHotspotCtsProvider" - `details` will be the dict: {"Weigh...
27,628
def tick2dayfrac(tick, nbTicks): """Conversion tick -> day fraction.""" return tick / nbTicks
27,629
def load_esol_semi_supervised(unlabeled_size=0.1, seed=2666): """ Parameters ---------- unlabeled_size : (Default value = 0.1) seed : (Default value = 2666) Returns ------- """ esol_labeled = pinot.data.esol() # Get labeled and unlabeled data esol_unlabeled...
27,630
def get_business_day_of_month(year, month, count): """ For a given month get the Nth business day by count. Count can also be negative, e.g. pass in -1 for "last" """ r = rrule(MONTHLY, byweekday=(MO, TU, WE, TH, FR), dtstart=datetime.datetime(year, month, 1), bysetpos=c...
27,631
def inpolygon(wkt, longitude, latitude): """ To determine whether the longitude and latitude coordinate is within the orbit :param wkt(str): the orbit wkt info :param longitude: to determine whether the longitude within the orbit :param latitude: to determine whether the latitude within the orbit :r...
27,632
def matrixMultVec(matrix, vector): """ Multiplies a matrix with a vector and returns the result as a new vector. :param matrix: Matrix :param vector: vector :return: vector """ new_vector = [] x = 0 for row in matrix: for index, number in enumerate(row): x += numb...
27,633
def get_dev_value(weight, error): """ :param weight: shape [N, 1], the importance weight for N source samples in the validation set :param error: shape [N, 1], the error value for each source sample in the validation set (typically 0 for correct classification and 1 for wrong classification) ""...
27,634
def biLSTM(f_lstm, b_lstm, inputs, dropout_x=0.): """Feature extraction through BiLSTM Parameters ---------- f_lstm : VariationalDropoutCell Forward cell b_lstm : VariationalDropoutCell Backward cell inputs : NDArray seq_len x batch_size dropout_x : float Var...
27,635
def refer_expression(captions, n_ground=1, prefix="refer expressions:", sort=True): """ n_ground > 1 ground_indices [1, 0, 2] source_text refer expressions: <extra_id_0> red crayon <extra_id_1> Yellow banana <extra_id_2> black cow target_text <vis_extra_id_1> <vis...
27,636
def url_to_filename(base, url): """Return the filename to which the page is frozen. base -- path to the file url -- web app endpoint of the page """ if url.endswith('/'): url = url + 'index.html' return base / url.lstrip('/')
27,637
def _msd_anom_3d(time, D_alpha, alpha): """3d anomalous diffusion function.""" return 6.0*D_alpha*time**alpha
27,638
def graticule(dpar=None, dmer=None, coord=None, local=None, **kwds): """Draw a graticule on the current Axes. Parameters ---------- dpar, dmer : float, scalars Interval in degrees between meridians and between parallels coord : {'E', 'G', 'C'} The coordinate system of the graticule (mak...
27,639
def upload_files(container): """ Upload html and json files to container :param container: :return: """ print('Enter upload_files()') # Create container cmd = 'az storage container create -n {} --account-name clitestresultstac --account-key {}' os.popen(cmd.format(container, ACCOUNT...
27,640
def make_json_response(status_code, json_object, extra_headers=None): """ Helper function to serialize a JSON object and add the JSON content type header. """ headers = { "Content-Type": 'application/json' } if extra_headers is not None: headers.update(extra_headers) return ...
27,641
def tmp_envfile(tmp_path, monkeypatch): """Create a temporary environment file.""" tmp_file_path = tmp_path / "setenv.txt" monkeypatch.setenv("GITHUB_ENV", os.fspath(tmp_file_path)) return tmp_file_path
27,642
def debug(): """ Runs a tmux session with all services in different panes, enabling you to quickly debug, examine and restart parts of your app quickly. """ _purge_previous_dirs() commands = ["PYTHONPATH={0} {1} {0}/deployment/libexec/run.py -d".format(LOCAL_PROJECT_ROOT, sys.executable)] i...
27,643
def calc_dst_temerin_li(time, btot, bx, by, bz, speed, speedx, density, version='2002n', linear_t_correction=False): """Calculates Dst from solar wind input according to Temerin and Li 2002 method. Credits to Xinlin Li LASP Colorado and Mike Temerin. Calls _jit_calc_dst_temerin_li. All constants are defined...
27,644
def parsestrfile(str_inpath): """Returns dictionary containing :class:`~gemmi.Structure` objects and another one with the file names. :param str_inpath: Either a directory or file path. :type str_inpath: str :raises KeyError: More than one structure file containing same identifier. :return strdict:...
27,645
def evaluate_regression_model( model: object, test_sets: list, show_plot: bool = True, use_rasterization: bool = False, ) -> None: """ Evaluates a trained regression model on test data sets. Parameters ---------- model : object Trained model (must have `predict()` method). ...
27,646
def handle_import(labfile, labjs): """랩 파일이 참고하는 외부 랩 파일 가져오기. Args: labfile (Str): 랩파일 경로 labjs (dict): 랩 데이터 """ if 'import' not in labjs: return labjs if '_imported_' not in labjs: labjs['_imported_'] = [] adir = os.path.dirname(labfile) for imp in lab...
27,647
def reconstruct(vars_to_reconstruct, scheme, order_used): """ Reconstructs all variables using the requested scheme. :param vars_to_reconstruct: The variables at the cell centers. :type vars_to_reconstruct: list of list of double :param Reconstruction.Scheme scheme: The reconstruction scheme to us...
27,648
def dataframe2naf( df_meta: pd.DataFrame, overwrite_existing_naf: bool=False, rerun_files_with_naf_errors: bool=False, engine: str=None, naf_version: str=None, dtd_validation: bool=False, params: dict={}, nlp=None, ) -> pd.DataFrame: """Batch processor for NAF Args: df_m...
27,649
def fs_inplace_rename_regex(src: str, pattern: str, replace: str, only_basename: bool = True, dry_run: bool = False): """DEPRECATED NO MORE DEVELOPMENT""" if only_basename: parent, basename = os.path.split(src) dst = os.path.join(parent, re.sub(pattern, replace, basename)) else: dst ...
27,650
def dev_view(request, slug=""): """View for homepage or individual developer.""" if slug == "": dev_name = list(Dev.objects.all().values_list('dev_name', flat=True)) dev_img_address = list(Dev.objects.values_list('dev_image_address', flat=True)) dev_slug = list(Dev.objects.values_list('...
27,651
def dpuEnableTaskProfile(task): """ Enable profiling facility of DPU Task while running to get its performance metrics task: DPU Task. This parameter should be gotten from the result of dpuCreatTask() Returns: 0 on success, or report error in case of any failure """ return pyc_libn2cube.pyc_...
27,652
def get_isotopic_distribution(z): """ For an element with number ``z``, returns two ``np.ndarray`` objects containing that element's weights and relative abundances. Args: z (int): atomic number Returns: masses (np.ndarray): list of isotope masses weights (np.ndarray): list of ...
27,653
def url_root(): """根路径""" return """ <p>Hello ! Welcome to Rabbit's WebServer Platform !</p> <a href="http://www.miibeian.gov.cn/" target="_blank" style="">京ICP备 18018365 号</a>&#8195;@2018Rabbit """
27,654
def range4(): """Never called if plot_directive works as expected.""" raise NotImplementedError
27,655
def solve_network(): """CLI interface method for solver""" argparser = argparse.ArgumentParser() argparser.add_argument("design", help="JSON file to Analyze") argparser.add_argument("-i", "--input", help="Config file") args = argparser.parse_args() file_c = open(args.input, "r") file_d = ...
27,656
def CreateMatrix(args, context, history_id, gcs_results_root, release_track): """Creates a new iOS matrix test in Firebase Test Lab from the user's params. Args: args: an argparse namespace. All the arguments that were provided to this gcloud command invocation (i.e. group and command arguments combined)...
27,657
def mute_control(net): """ Use this function to set all controllers in net out of service, e. g. when you want to use the net with new controllers :param net: pandapowerNet :return: """ check_controller_frame(net) net.controller['in_service'] = False
27,658
def test_get_worst_rating_shortterm_with_inferring_rating_provider( rtg_inputs_shortterm, ): """Test computation of best ratings on a security (line-by-line) basis.""" actual = rtg.get_worst_ratings(rtg_inputs_shortterm, tenor="short-term") expectations = pd.Series( data=["A-2", "B", "A-1", "D"...
27,659
def run(ctx, dry_run, task_profile): """Create from a task profile, and submit.""" from jsub.command.run import Run task_profile_file = click.format_filename(task_profile) cmd = Run(jsubrc=ctx.obj['jsubrc'], task_profile_file=task_profile_file, dry_run=dry_run) cmd.execute()
27,660
def _download_and_extract_zip_from_github(site_info): """ from https://pelican-blog/archive/master.zip to: /path/pelican-blog """ unique_id = uuid4().hex zip_file_url = site_info["ZIP_URL"] zip_file_name = os.path.join( settings.PELICAN_PUBLISHER["WORKING_ROOT"], "{}-{}.zip"...
27,661
def map_keys(func, d): """ Returns a new dict with func applied to keys from d, while values remain unchanged. >>> D = {'a': 1, 'b': 2} >>> map_keys(lambda k: k.upper(), D) {'A': 1, 'B': 2} >>> assert map_keys(identity, D) == D >>> map_keys(identity, {}) {} """ return dict(...
27,662
def generate_qiniu_token(object_name, use_type, expire_time=600): """ 用于生成七牛云上传所需要的Token :param object_name: 上传到七牛后保存的文件名 :param use_type: 操作类型 :param expire_time: token过期时间,默认为600秒,即十分钟 :return: """ bucket_name = PRIVATE_QINIU_BUCKET_NAME from qiniu import Auth # 需要填写你的 Access ...
27,663
def get_s3_object(bucket, key_name, local_file): """Download a S3 object to a local file in the execution environment Parameters ---------- bucket: string, required S3 bucket that holds the message key: string, required S3 key is the email object Returns ------- ...
27,664
def jaxpr_eqns_input_sizes(jaxpr) -> np.ndarray: """Return a list of input sizes for each equation in the jaxpr. Args: jaxpr: Jaxpr to get input sizes for. Returns: A #eqns * #eqns numpy array of input sizes. cost[l, r] represents the input size of the l-th to (r - 1)-th equation i...
27,665
def extract_message(raw_html): """Returns the content of the message element. This element appears typically on pages with errors. :param raw_html: Dump from any page. """ results = re_message.findall(raw_html) if results: return results[0] return None
27,666
def do_pca_anomaly_scores(obs, n_components): """Returns numpy array with data points labelled as outliers Parameters ---------- data: no_of_clusters: numpy array like data_point score: numpy like data """
27,667
def _weighted_essentially_non_oscillatory_vectorized( eno_order: int, values: Array, spacing: float, boundary_condition: Callable[[Array, int], Array]) -> Tuple[Array, Array]: """Implements a more "vectorized" but ultimately...
27,668
def add_to_bashrc(user, text): """ Add text to a users .bashrc file """ homeDir = os.path.expanduser("~" + user) bashrc_file = homeDir + "/.bashrc" with open(bashrc_file, "a") as myfile: myfile.write(text) myfile.close()
27,669
def test_atomic_normalized_string_max_length_4_nistxml_sv_iv_atomic_normalized_string_max_length_5_1(mode, save_output, output_format): """ Type atomic/normalizedString is restricted by facet maxLength with value 1000. """ assert_bindings( schema="nistData/atomic/normalizedString/Schema+Inst...
27,670
def defaults(dictionary, overwriteNone=False, **kwargs): """ Set default values of a given dictionary, option to overwrite None values. Returns given dictionary with values updated by kwargs unless they already existed. :param dict dictionary: :param overwriteNone: Whether to overwrite None values....
27,671
def sunrise_sunset(): """ Show the sunrise and sunset time.""" st.write("_____________________________________") st.title("Sunrise and Sunset") obs = mgr.weather_at_place(location) weather = obs.weather sunrise_unix = datetime.utcfromtimestamp(int(weather.sunrise_time())) sunrise_date = sun...
27,672
def expected_average_shortest_distance_to_miner( crawl_graph: Union[ ProbabilisticWeightedCrawlGraph[CrawledNode], CrawlGraph[CrawledNode] ], distances: Optional[np.ndarray] = None, miner_probability: Optional[Dict[CrawledNode, float]] = None, ) -> Dict[CrawledNode, float]: """Estimates the ...
27,673
def plot_route(data, pi, costs, title, idx_in_batch = 0, is_tensor = True): """Plots journey of agent Args: data: dataset of graphs pi: (batch, decode_step) # tour idx_in_batch: index of graph in data to be plotted """ if is_tensor: # Remove extra zeros pi_ = get_clean_path(pi[idx_in_batch].cpu().numpy(...
27,674
def strip_logEntry(etree_obj): """In-place remove elements and attributes that are only valid in v2 types from v1 LogEntry. Args: etree_obj: ElementTree ElementTree holding a v1 LogEntry. """ for event_el in etree_obj.findall("event"): if event_el.text not in ( "create", ...
27,675
def warn(msg, *args): """ log warning messages :param str or object msg: the message + format :param list args: message arguments """ _log(logging.WARN, msg, *args)
27,676
def create(name, frontend, backend, database, cache, pipeline): """ creates a synth wireframe with your desired frontend, backend, database, caching service, and ci/cd pipeline """ root_dir = os.path.dirname(os.path.abspath(__file__)) copy_dir = root_dir + "/projects_master/nginx_router/" if no...
27,677
def merge_mapping(ensembl_dict, mygene_website_dict, add_source=False): """First use gene2ensembl as single match NCBI gene ID (if == 1 match). Next, if no gene2ensembl match, then look at gene_info (Entrez) to find which NCBI ID from the NCBI multi mapping list returns the same ensembl symbol as the en...
27,678
def dummy_state_sb(dummy_state: State, dummy_train_dataloader: DataLoader, conv_model: MosaicClassifier, loss_fun_tuple: Callable, epoch: int, batch: int) -> State: """Dummy state with required values set for Selective Backprop """ dummy_state.train_dataloader = dummy_train_dataloader ...
27,679
def create_model(species={}, parameters={}, reactions={}, events={}): """Returns an SBML Level 3 model. Example: species = { 'E': 1, \ 'EM': 0, \ 'EM2': 0, \ 'F': 100, \ } parameters = {'k': (1e-06,'per_min'), \ } r...
27,680
def get_network_connection_query(endpoint_ids: str, args: dict) -> str: """Create the network connection query. Args: endpoint_ids (str): The endpoint IDs to use. args (dict): The arguments to pass to the query. Returns: str: The created query. """ remote_ip_list = args.get...
27,681
def dump_into_json(filename, metrics): """Dump the metrics dictionary into a JSON file It will automatically dump the dictionary: metrics = {'duration': duration, 'voltage_extremes': voltage_extremes, 'num_beats': num_beats, 'mean_hr_bpm': mean_hr_bpm, ...
27,682
def _costfun(params, pose0, fixed_pt3d, n_cams, n_pts, cam_idxs, pt3d_idxs, pts2d, K, px_err_sd): """ Compute residuals. `params` contains camera parameters and 3-D coordinates. """ if isinstance(params, (tuple, list)): params = np.array(params) params = np.hstack((pose0, params...
27,683
def dbg_get_memory_info(*args): """ dbg_get_memory_info() -> PyObject * This function returns the memory configuration of a debugged process. @return: None if no debugger is active tuple(start_ea, end_ea, name, sclass, sbase, bitness, perm) """ return _ida_idd.dbg_get_memory_info(*args)
27,684
def get_headers(base_url: str, client_id: str, client_secret: str, grant_type: str, verify: bool): """ Create header with OAuth 2.0 authentication information. :type base_url: ``str`` :param base_url: Base URL of the IdentityIQ tenant. :type client_id: ``str`` :param client_id: Client Id for O...
27,685
def draw_pie(fracs, labels): """ This method is to plot the pie chart of labels, then save it into '/tmp/' folder """ logging.info("Drawing the pie chart..") fig = plt.figure() plt.pie(fracs, labels=labels, autopct=make_autopct(fracs), shadow=True) plt.title("Top 10 labels for newly opened i...
27,686
def eval_function_old(param, param_type): """ Eval Function (Deprecated) isOwner 0xe982E462b094850F12AF94d21D470e21bE9D0E9C :param param: :param param_type: :return: """ try: splitted_input = param.split(' ') except TypeError: pass else: try: prin...
27,687
def _multi_convert(value): """ Function try and convert numerical values to numerical types. """ try: value = int(value, 10) except ValueError: try: value = float(value) except ValueError: pass return value
27,688
def cprint(text, color='normal', bold=True): """Print the given text using blessings terminal. Arguments: text (str): Text to print. color (str): Color to print the message in. bold (bool): Whether or not the text should be printed in bold. """ if color == 'cyan': to_pri...
27,689
def strip_all_collection_fields(ctx): """ Strip all the `collection` string fields, so whitespace at the beginning and the end are removed. """ with db_session_manager() as session: click.confirm( f"Are you sure you want to run this script? It will strip whitespaces to all the string...
27,690
def destroy_node_and_cleanup(driver, node): """ Destroy the provided node and cleanup any left over EBS volumes. """ volumes = driver.list_volumes(node=node) assert ( INSTANCE_NAME_STRING in node.name ), "Refusing to delete node without %s in the name" % (INSTANCE_NAME_STRING) prin...
27,691
def main(): """ creates a new Assignment, prompts for its values and display them. """ new_assignment = Assignment() new_assignment.prompt() new_assignment.display()
27,692
def dbinom(n, p): """Binomial Distribution n = number of repetitions p = success probability Used when a certain experiment is repeated n times with a 0 ≤ P ≤ 1 probability to succeed once. This doesn't return a value, but rather the specified binomial function """ def b(k): """Retu...
27,693
def array_to_image(x, data_format='channels_last'): """Converts a 3D Numpy array to a PIL Image instance. Args: x: Input Numpy array. data_format: Image data format, either "channels_first" or "channels_last". Returns: A PIL Image instance. Raises: ValueError: if inv...
27,694
def test_celery__TransactionAwareTask__delay__5(celery_session_worker, zcml): """It allows to run two tasks in a single session.""" auth = zope.component.getUtility( zope.authentication.interfaces.IAuthentication) principal = auth.getPrincipal('example.user') z3c.celery.celery.login_principal(pr...
27,695
def worker_process_download_tvtorrent( tvTorUnit, client = None, maxtime_in_secs = 14400, num_iters = 1, kill_if_fail = False ): """ Used by, e.g., :ref:`get_tv_batch`, to download missing episodes on the Plex_ TV library. Attempts to use the Deluge_ server, specified in :numref:`Seedhost Servi...
27,696
def find_fixture( gameweek, team, was_home=None, other_team=None, kickoff_time=None, season=CURRENT_SEASON, dbsession=session, ): """Get a fixture given a gameweek, team and optionally whether the team was at home or away, the kickoff time and the other team in the fixture. "...
27,697
def restart_dhcp(): """Uses systemctl to restart isc-dhcpd server. Note: it is not (yet) in scope to dynamically update the '/etc/dhcp/dhcpd.conf' file.""" command_restart = [ "sudo", "--non-interactive", "-E", "systemctl", "restart", "isc-dhcp-server", ]...
27,698
async def jail(ctx, member: discord.Member, duration: str, *, reason=""): """Jails the member given for the duration given (in the familiar M0DBOT format). Optionally, add a reason which goes in #police_reports. One interesting thing is that consecutive jails override each other, allowing you to extend sentence...
27,699