content
stringlengths
22
815k
id
int64
0
4.91M
def identityMatrix(nrow, ncol): """ Create a identity matrix of the given dimensions Works for square Matrices Retuns a Matrix Object """ if nrow == ncol: t = [] for i in range(nrow): t.append([]) for j in range(ncol): if i == j: ...
5,353,400
def extract_packages(matched, package_source): """ Extract packages installed in the "Successfully installed" line e.g. Successfully installed Abjad Jinja2-2.10 MarkupSafe-1.0 PyPDF2-1.26.0 Pygments-2.2.0 alabaster-0.7.10 \ babel-2.5.1 bleach-2.1.2 decorator-4.1.2 docutils-0.14 entrypoints-0...
5,353,401
def nested_set(d: JSONDict, ks: Tuple[Any, ...], v: Any) -> None: """Set value in nested dictionary. Parameters ---------- d : JSONDict ks : Tuple[str] v : Any Notes ----- Adapted from: https://stackoverflow.com/a/13688108/2528668 """ for k in ks[:-1]: d = d.setdefa...
5,353,402
def chunks(l, n): """ Yield successive n-sized chunks from l. :param l: list to split :param n: number of elements wanted in each list split """ n = 1 if n <= 0 else n for i in range(0, len(l), n): yield l[i:i+n]
5,353,403
def launch_job(cfg, init_method, func, daemon=False): """ Run 'func' on one or more GPUs, specified in cfg Args: cfg (CfgNode): configs. Details can be found in slowfast/config/defaults.py init_method (str): initialization method to launch the job with multiple device...
5,353,404
def _handle_get_static(handler, path_match, data): """ Returns a static file for the frontend. """ req_file = util.sanitize_path(path_match.group('file')) # Strip md5 hash out fingerprinted = _FINGERPRINT.match(req_file) if fingerprinted: req_file = "{}.{}".format(*fingerprinted.groups()) ...
5,353,405
def create_relationship( relationship_type: str, created_by: Identity, source: _DomainObject, target: _DomainObject, confidence: int, object_markings: List[MarkingDefinition], start_time: Optional[datetime] = None, stop_time: Optional[datetime] = None, ) -> Relationship: """Create a ...
5,353,406
def _find_partition(G, starting_cell): """ Find a partition of the vertices of G into cells of complete graphs Parameters ---------- G : NetworkX Graph starting_cell : tuple of vertices in G which form a cell Returns ------- List of tuples of vertices of G Raises ------ Ne...
5,353,407
def projection_from_Rt(rmat, tvec): """ Compute the projection matrix from Rotation and translation. """ assert len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3), rmat.shape assert len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1), tvec.shape return torch.cat([rmat, tvec], dim=-1)
5,353,408
def verify_df(df, constraints_path, epsilon=None, type_checking=None, **kwargs): """ Verify that (i.e. check whether) the Pandas DataFrame provided satisfies the constraints in the JSON .tdda file provided. Mandatory Inputs: df A Pandas DataFrame, to be checked. ...
5,353,409
def usage(): """print the usage of the script Args: NA Returns: None Raises: NA """ print ''' [Usage] acrnalyze.py [options] [value] ... [options] -h: print this message -i, --ifile=[string]: input file -o, --ofile=[string]: output file --vm_exit: to generate vm_exit rep...
5,353,410
def _getallstages_pm(pmstr): """pmstr: a pipelinemodel name in quote return a df: of all leaf stages of transformer. to print return in a cell , use print_return(df) """ pm=eval(pmstr) output=[] for i,s in enumerate(pm.stages): if str(type(s))=="<class 'pyspark.ml.pipeline.Pipe...
5,353,411
def notify_completed_spec(spec_id): """ Spec processing has finished, now we need to record the result """ spec = Spec.objects.get(pk=spec_id) spec.finish() logger.info('✓ %s finished' % spec)
5,353,412
def merge_config(log_conf: LogConf, conf: Config) -> Config: """ Create combined config object from system wide logger setting and current logger config """ #pylint: disable=too-many-locals name = conf.name # take individual conf value, ignore common log_conf value filename = _ITEM_OR_DEFAULT(...
5,353,413
def function(argument1, argument2): """ Description of function. Parameters: argument1 (type): description of argument1 argument2 (type): description of argument2 Output: output1 (type): description of output1 """ return
5,353,414
def wfa_measurement_system_repositories(): """Imports all direct dependencies for wfa_measurement_system.""" wfa_repo_archive( name = "wfa_common_jvm", repo = "common-jvm", sha256 = "b162457bcc6724f77454042e2acaf6a806dd53a2ac7423a79b48ab1cc521a3df", version = "0.25.1", ) ...
5,353,415
def write_csv_file(file_name, encoding, header_list, file_data): """Write a comma separated values (CSV) file to disk using the given Unicode encoding. Arguments: file_name Name of the file to write. encoding The name of a Unicode encoding to be used when reading the fil...
5,353,416
def midpVector(x): """ return midpoint value (=average) in each direction """ if type(x) != list: raise Exception("must be list") dim = len(x) #nx = x[0].shape for i in range(1,dim): if type(x[i]) != np.ndarray: raise Exception("must be numpy array") #if x[i...
5,353,417
def buy_ticket(email, name, quantity): """ Attmempt to buy a ticket in the database :param owner: the email of the ticket buyer :param name: the name of the ticket being bought :param quantity: the quantity of tickets being bought :return: an error message if there is any, or None if register su...
5,353,418
def update_bounds( sig: float, eps: float, target_eps: float, bounds: np.ndarray, bound_eps: np.ndarray, consecutive_updates: int ) -> Tuple[np.ndarray, np.ndarray, int]: # noqa:E121,E125 """ Updates bounds for sigma around a target privacy epsilon. Updates ...
5,353,419
def get_timeseries(rics, fields='*', start_date=None, end_date=None, interval='daily', count=None, calendar=None, corax=None, normalize=False, raw_output=False, debug=False): """ Returns historical data on one or several RICs Parameters ---------- rics: string ...
5,353,420
def usd(value): """Format value as USD.""" return f"${value:,.2f}"
5,353,421
def random_mindist(N, mindist, width, height): """Create random 2D points with a minimal distance to each other. Args: N(int): number of points to generate mindist(float): Minimal distance between each point width(float): Specifies [0, width) for the x-coordinate height(float): ...
5,353,422
def test_ada12_adb(style_checker): """Style check test against ada12.adb """ style_checker.set_year(2006) p = style_checker.run_style_checker('trunk/toto', 'ada12.adb') style_checker.assertEqual(p.status, 0, p.image) style_checker.assertRunOutputEmpty(p)
5,353,423
def deactivate_spotting(ID): """ Function to deactivate a spotting document in Elasticsearch Params: ID::str id of the document to deactivate Returns: bool If the changes have been applied or not """ if not ID: return False try: globa...
5,353,424
def Fraction_Based(nc_outname, Startdate, Enddate): """ This functions calculated monthly total supply based ETblue and fractions that are given in the get dictionary script Parameters ---------- nc_outname : str Path to the NetCDF containing the data Startdate : str Contains th...
5,353,425
def _qrd_solve(r, pmut, ddiag, bqt, sdiag): """Solve an equation given a QR factored matrix and a diagonal. Parameters: r - **input-output** n-by-n array. The full lower triangle contains the full lower triangle of R. On output, the strict upper triangle contains the transpose of the strict low...
5,353,426
def find_version(): """Extract the version number from the CLI source file.""" with open('pyweek.py') as f: for l in f: mo = re.match('__version__ = *(.*)?\s*', l) if mo: return eval(mo.group(1)) else: raise Exception("No version information fo...
5,353,427
def remove_unused_levels(self): """ create a new MultiIndex from the current that removing unused levels, meaning that they are not expressed in the labels The resulting MultiIndex will have the same outward appearance, meaning the same .values and ordering. It will also be .equals() to the orig...
5,353,428
def add_bands(show_id, bands): """Insert the bands to the given Show.""" for band in bands: show_band = ShowsOtherBands( ShowID=show_id, BandName=band["bandName"], BandWebsite=band["bandWebsite"], ) db.session.add(show_band) db.session.com...
5,353,429
def _transform_playlist(playlist): """Transform result into a format that more closely matches our unified API. """ transformed_playlist = dict([ ('source_type', 'spotify'), ('source_id', playlist['id']), ('name', playlist['name']), ('tracks', playlist['tracks']['total'])...
5,353,430
def decode_map_states(beliefs: Dict[Hashable, Any]) -> Any: """Function to decode MAP states given the calculated beliefs. Args: beliefs: An array or a PyTree container containing beliefs for different variables. Returns: An array or a PyTree container containing the MAP states for differe...
5,353,431
def main(project_dir, deploy_dir): """ :param project_dir: 项目的根目录 :param deploy_dir: 部署二进制程序的目录 :return: """ if not os.path.exists(deploy_dir): os.makedirs(deploy_dir) builddir = os.path.join(project_dir, "build") if not os.path.exists(builddir): os.makedirs(builddir) ...
5,353,432
def plot_stretch_Q(datas, stretches=[0.01,0.1,0.5,1], Qs=[1,10,5,100]): """ Plots different normalizations of your image using the stretch, Q parameters. Parameters ---------- stretches : array List of stretch params you want to permutate through to find optimal image normalization. ...
5,353,433
def rad_plot(df, r_lo=0., r_hi=25., weighted=0): """Plot radial distribution.""" plt.figure(figsize=(16, 9)) if weighted == 1: plt.hist(df.r, bins=100, range=[r_lo, r_hi], weights=df.weight/df.r**2, histtype='step', color='black', linewidth=2) plt.ylabel(r'COUNTS/CM$^2$') ...
5,353,434
def printClasses (theDictionary): """Prints a table displaying the student's class information. List classes alphabetically in the left column, their credit-worth in the right column. The last row displays the total number of credits. :param dict[str, int] theDictionary: The student's class inform...
5,353,435
def _isSpecialGenerateOption(target, optName): """ Returns ``True`` if the given option has a special generation function, ``False`` otherwise. """ return _getSpecialFunction(target, optName, '_generateSpecial') is not None
5,353,436
def count_active_days(enable_date, disable_date): """Return the number of days the segment has been active. :param enable_date: The date the segment was enabled :type enable_date: timezone.datetime :param disable_date: The date the segment was disabled :type disable_date: timezone.datetime :ret...
5,353,437
def test_empty_constructor_constructs_empty_weight_graph(): """Test that a new graph is empty.""" from weight_graph import Graph g = Graph() assert len(g.graph) == 0
5,353,438
def numpy_to_python_type(value): """ Convert to Python type from numpy with .item(). """ try: return value.item() except AttributeError: return value
5,353,439
def bigEI_numerical(Ey, t, P=1): """Return the column kp=0 of the matrix E_I, computed numerically.""" lmax = int(np.sqrt(Ey.shape[0]) - 1) K = len(t) map = starry.Map(ydeg=lmax, lazy=False) theta = 360 / P * t bigEI = np.zeros(K) kp = 0 for k in tqdm(range(K), disable=bool(int(os.geten...
5,353,440
def db_select_all(db, query, data=None): """Select all rows""" logger_instance.debug("query = <<%s>>"% (query[:100],)) cursor = db.cursor() try: cursor.execute(query, data) except pymysql.MySQLError: exc_type, exc_value, exc_traceback = sys.exc_info() err_string = "Error fro...
5,353,441
def threshold_abs(image, threshold): """Return thresholded image from an absolute cutoff.""" return image > threshold
5,353,442
def warp_images(img1_loc, img2_loc, h_loc): """ Fill documentation """ rows1, cols1 = img1_loc.shape[:2] rows2, cols2 = img2_loc.shape[:2] print("0") list_of_points_1 = np.array( [[0, 0], [0, rows1], [cols1, rows1], [cols1, 0]], np.float32).reshape(-1, 1, 2) temp_points = np.arr...
5,353,443
def ValidaCpf(msg='Cadastro de Pessoa Física (CPF): ', pont=True): """ -> Função para validar um CPF :param msg: Mensagem exibida para usuário antes de ler o CPF. :param pont: Se True, retorna um CPF com pontuação (ex: xxx.xxx.xxx-xx). Se False, retorna um CPF sem pontuação (ex: xxxxxxxxxxx) ...
5,353,444
def get_xml_path(xml, path=None, func=None): """ Return the content from the passed xml xpath, or return the result of a passed function (receives xpathContext as its only arg) """ #doc = None #ctx = None #result = None #try: doc = etree.fromstring(xml) #ctx = doc.xpathNewConte...
5,353,445
def _raise_error_if_not_drawing_classifier_input_sframe( dataset, feature, target): """ Performs some sanity checks on the SFrame provided as input to `turicreate.drawing_classifier.create` and raises a ToolkitError if something in the dataset is missing or wrong. """ from turicreate.toolkit...
5,353,446
def readXYdYData(filename, comment_character='#'): """ Read in a file containing 3 columns of x, y, dy Lines beginning with commentCharacter are ignored """ return read_columnar_data(filename, number_columns=3, comment_character=comment_character)
5,353,447
def hexlen(x): """ Returns the string length of 'x' in hex format. """ return len(hex(x))+2
5,353,448
def get_db(): """ connectionを取得します """ if not hasattr(g, 'sqlite_db'): g.sqlite_db = connect_db() return g.sqlite_db
5,353,449
def test_load_course( mock_upsert_tasks, course_exists, is_published, is_run_published, blocklisted ): """Test that load_course loads the course""" course = ( CourseFactory.create(runs=None, published=is_published) if course_exists else CourseFactory.build() ) assert Course.o...
5,353,450
def list_manipulation(lst, command, location, value=None): """Mutate lst to add/remove from beginning or end. - lst: list of values - command: command, either "remove" or "add" - location: location to remove/add, either "beginning" or "end" - value: when adding, value to add remove: remove ite...
5,353,451
def test_jones_num_funcs_x_orientation(): """Test functions to convert jones pol strings and numbers with x_orientation.""" jnums = [-8, -7, -6, -5, -4, -3, -2, -1] x_orient1 = "east" jstr = ["Jne", "Jen", "Jnn", "Jee", "Jlr", "Jrl", "Jll", "Jrr"] assert jnums == uvutils.jstr2num(jstr, x_orientatio...
5,353,452
def image_comparison(src_file, dest_file): """Compare the images listed in input csv file and outputs the score,elapsed time along with it into the output csv file""" try: with open(str(src_file), mode='r') as f, open(str(dest_file), mode="w") as csv_file: fieldnames = ["Imag...
5,353,453
def solve( problem, comm=_NoArgumentGiven, dispatcher_rank=0, log_filename=None, results_filename=None, **kwds ): """Solves a branch-and-bound problem and returns the solution. Note ---- This function also collects and summarizes runtime workload statistics, which may in...
5,353,454
def solution(lst): """Given a non-empty list of integers, return the sum of all of the odd elements that are in even positions. Examples solution([5, 8, 7, 1]) ==> 12 solution([3, 3, 3, 3, 3]) ==> 9 solution([30, 13, 24, 321]) ==>0 """ #[SOLUTION] return sum([x for idx, x in enumerate(...
5,353,455
def summarize_traffic_mix(l_d_flow_records, d_filters={}): """ Filter the traffic flow data and execute the processing analysis logic for network behavior metrics. """ o_tcp_src_analysis = TopProtocolAnalysis() o_tcp_dst_analysis = TopProtocolAnalysis() o_upd_src_analysis = TopProtocolAnalysis...
5,353,456
def segment(X, upscale=1.0, denoise=False): """ :param X: :param upscale: :param denoise: :return: """ if upscale > 1.0: X = rescale(X, upscale) if denoise: X = denoise_wavelet(X) thresh = filters.threshold_otsu(X) bw = closing(X > thresh, square(3)) cleared...
5,353,457
def describe_user_pool_client(UserPoolId=None, ClientId=None): """ Client method for returning the configuration information and metadata of the specified user pool app client. See also: AWS API Documentation Exceptions :example: response = client.describe_user_pool_client( UserPoo...
5,353,458
def get_image_info(doc): """Create dictionary with key->id, values->image information """ id_img = dict() #add image information for img_infor in doc['images']: filename = img_infor['file_name'] width = img_infor['width'] height = img_infor['height'] id_img[img_infor['id']] = [filename, width,...
5,353,459
def common_values(series1, series2): """ Shows the differences, intersections and union of two sets. """ values1 = set(series1) values2 = set(series2) intersection = set.intersection(values1, values2) no_values2 = values1 - values2 no_values1 = values2 - values1 total = set.union(values1, va...
5,353,460
def __check_partial(detected,approx, width, height): """ Check if it's a partial shape It's a partial shape if the shape's contours is on the image's edges. Parameters ---------- detected : Shape The detected shape approx : numpy.ndarray Approximates a polygonal curves. ...
5,353,461
def get_svg_size(filename): """return width and height of a svg""" with open(filename) as f: lines = f.read().split('\n') width, height = None, None for l in lines: res = re.findall('<svg.*width="(\d+)pt".*height="(\d+)pt"', l) if len(res) > 0: # need to scale up, may...
5,353,462
def bin_mgf(mgf_files,output_file = None, min_bin = 50, max_bin = 850, bin_size = 0.01, max_parent_mass = 850, verbose = False, remove_zero_sum_rows = True, remove_zero_sum_cols = True, window_filter = True, filter_window_size = 50, filter_window_retain = 3, filter_parent_peak = True): """ Bins an mgf file Bi...
5,353,463
def index(): """Video streaming home page which makes use of /mjpeg.""" return render_template('index.html')
5,353,464
def tex_quoted_no_underscore (s) : """Same as tex_quoted but does NOT quote underscores. """ if isinstance (s, pyk.string_types) : s = _tex_pi_symbols.sub (_tex_subs_pi_symbols, s) s = _tex_to_quote.sub (_tex_subs_to_quote, s) s = _tex_tt_symbols.sub (_tex_subs_tt_symbols, s) ...
5,353,465
def load_from_json_file(filename): """ function that creates an Object from a “JSON file” """ with open(filename, 'r') as f: return json.loads(f.read())
5,353,466
def _variable_to_field(v): """Transform a FuzzyVariable into a restx field""" if isinstance(v.domain, FloatDomain): a, b = v.domain.min, v.domain.max f = fields.Float(description=v.name, required=True, min=a, max=b, example=(a + b) / 2) elif isinstance(v.domain, CategoricalDomain): r...
5,353,467
def abs_ang_mom(u, lat=None, radius=RAD_EARTH, rot_rate=ROT_RATE_EARTH, lat_str=LAT_STR): """Absolute angular momentum.""" if lat is None: lat = u[lat_str] coslat = cosdeg(lat) return radius*coslat*(rot_rate*radius*coslat + u)
5,353,468
def main(): """ Simple pyvmomi (vSphere SDK for Python) script that generates ESXi support bundles running from VCSA using vCenter Alarm """ # Logger for storing vCenter Alarm logs vcAlarmLog = logging.getLogger('vcenter_alarms') vcAlarmLog.setLevel(logging.INFO) vcAlarmLogFile = os.path.join('/v...
5,353,469
def accelerate_backward(env, time=100): """ Accelerates forward for designated timesteps """ print("Accelerating forward for {} timesteps".format(time)) for i in range(time): ensure_orientation(env) env.step(BACKWARD)
5,353,470
def _get_ngrams(segment, max_order): """Extracts all n-grams upto a given maximum order from an input segment. Args: segment: text segment from which n-grams will be extracted. max_order: maximum length in tokens of the n-grams returned by this methods. Returns: ...
5,353,471
def print_donors_list(): """ print a list of existing donors """ print(mr.list_donors()) return False
5,353,472
def log_cef(name, severity, env, *args, **kwargs): """Simply wraps the cef_log function so we don't need to pass in the config dictionary every time. See bug 707060. env can be either a request object or just the request.META dictionary""" c = {'cef.product': getattr(settings, 'CEF_PRODUCT', 'AMO'), ...
5,353,473
def collimate(S, r, phasevec, print_values = False): """Collimate r phase vectors into a new phase vector on [S]. Output: the collimated phase vector ([b(0),b(1),...,b(L'-1)], L') on [S]. Parameters: S: output phase vectors has all multipliers on [S] r: arity, the number of phase vectors that...
5,353,474
def parse_and_load(gw, subj, primitive, cgexpr, g): """ Parse the conceptual grammar expression for the supplied subject and, if successful, add it to graph g. :param gw: parser gateway :param subj: subject of expression :param primitive: true means subClassOf, false means equivalentClass :param...
5,353,475
def pushed(property_name, **kwargs) -> Signal: """ Returns the `pushed` Signal for the given property. This signal is emitted, when a new child property is added to it. From the perspective of a state, this can be achieved with the `ContextWrapper.push(...)` function.<br> __Hint:__ All key-wo...
5,353,476
def upgrade(): """Migrations for the upgrade.""" connection = op.get_bind() # Clean data export_workflow_data(connection) op.drop_table('db_dbworkflowstep_sub_workflows') op.drop_table('db_dbworkflowstep_calculations') op.drop_table('db_dbworkflowstep') op.drop_index('ix_db_dbworkflowd...
5,353,477
async def delete_data(table_name: str, filter: str = Header(None), filterparam: str = Header(None), current_user_role: bool = Depends(security.get_write_permission)): """ Parameters - **table_name** (path): **Required** - Name of the ...
5,353,478
def test_memoryview_supports_int(valid_bytes_128): """ Assert that the `int` representation of a :class:`~ulid.ulid.MemoryView` is equal to the result of the :meth:`~ulid.ulid.MemoryView.int` method. """ mv = ulid.MemoryView(valid_bytes_128) assert int(mv) == mv.int
5,353,479
def do_endpoint(method, handler, endpoint, parameters): """Parse url parameters and ready up the search of the endpoint""" if method != "get": token = handler.session.query(Token).where(Token.session_token == handler.session_token).first() if token: if token.expiry_date < int(time.ti...
5,353,480
def sort(suffixes: tuple, src_path: str, dst_path: str, verbose: bool = False): """ :param suffixes: tuple of file suffixes (mp4, mov) :param src_path: path that contains files needed be sorted :param dst_path: destination path of sorted files :param verbose: prints paths to which were files ...
5,353,481
def _is_dask_series(ddf): """ Will determine if the given arg is a dask dataframe. Returns False if dask is not installed. """ try: import dask.dataframe as dd return isinstance(ddf, dd.Series) except: return False
5,353,482
def square(t, A=1, f=1, D=0): """ t: time A: the amplitude, the peak deviation of the function from zero. f: the ordinary frequency, the number of oscillations (cycles) that occur each second of time. D: non-zero center amplitude """ square_ = A*scipy.signal.square( 2 * np.pi * f...
5,353,483
def self_distance_array(reference, box=None, result=None, backend="serial"): """Calculate all possible distances within a configuration `reference`. If the optional argument `box` is supplied, the minimum image convention is applied when calculating distances. Either orthogonal or triclinic boxes are s...
5,353,484
def mainRecursivePartitioningLoop(A, B, n_cutoff): """ """ # Initialize storage objects n = A.shape[0] groups = numpy.zeros((n,), dtype=int) groups_history = [] counts = {'twoway-single' : 0, 'twoway-pair' : 0, 'threeway-pair' : 0} to_split = {0 : True} ...
5,353,485
def corrSmatFunc(df, metric='pearson-signed', simFunc=None, minN=None): """Compute a pairwise correlation matrix and return as a similarity matrix. Parameters ---------- df : pd.DataFrame (n_instances, n_features) metric : str Method for correlation similarity: pearson or spearman, optiona...
5,353,486
def update(): """Updates graph elements and source.data based on filtering""" filtered_df = select_beers() x_name = axis_map[x_axis.value] y_name = axis_map[y_axis.value] p.xaxis.axis_label = x_axis.value p.yaxis.axis_label = y_axis.value p.title.text = "%d beers selected" % len(filtered_df)...
5,353,487
def rank(values, axis=0, method='average', na_option='keep', ascending=True, pct=False): """ """ if values.ndim == 1: f, values = _get_data_algo(values, _rank1d_functions) ranks = f(values, ties_method=method, ascending=ascending, na_option=na_option, pct=pct) ...
5,353,488
def recover_exception_table(): """ Recover the CIE and FDE entries from the segment .eh_frame """ seg_eas = [ea for ea in idautils.Segments() if not is_invalid_ea(ea)] for seg_ea in seg_eas: seg_name = idc.get_segm_name(seg_ea) if seg_name in [".eh_frame", "__eh_frame"]: recover_frame_entries(s...
5,353,489
def _cmpopts(x, y): """Compare to option names. The options can be of 2 forms: option_name or group/option_name. Options without a group always comes first. Options are sorted alphabetically inside a group. """ if '/' in x and '/' in y: prex = x[:x.find('/')] prey = y[:y.find('/...
5,353,490
def ask(question, choices): """Prompt user for a choice from a list. Return the choice.""" choices_lc = [x.lower() for x in choices] user_choice = "" match = False while not match: print question user_choice = raw_input("[" + "/".join(choices) + "] ? ").strip().lower() for ch...
5,353,491
def test_config_inheritance(): """Inheritance of config and schemas.""" item = Second() assert (6.0, 2, 9.0) == (item.a, item.b, item.c) assert item._options['a'].block_propagation == False assert item._options['c'].block_propagation == False item = Second(a=5.0, b=4) assert (5.0, 4, 9.0) =...
5,353,492
def get_and_validate_user(username, password): """ Check if user with username/email exists and specified password matchs well with existing user password. if user is valid, user is returned else, corresponding exception is raised. """ user_model = apps.get_model("users", "User") qs = ...
5,353,493
def process_tweet(tweet): """Process tweet function. Input: tweet: a string containing a tweet Output: tweets_clean: a list of words containing the processed tweet""" stemmer = PorterStemmer() stopwords_english = stopwords.words('english') # Remove stock market tickers...
5,353,494
def oracle_query_id(sender_id, nonce, oracle_id): """ Compute the query id for a sender and an oracle :param sender_id: the account making the query :param nonce: the nonce of the query transaction :param oracle_id: the oracle id """ def _int32(val): return val.to_bytes(32, byteorder...
5,353,495
def knapsack_with_budget(vals: List[float], weights: List[int], budget: int, cap: int) -> Set[int]: """ Solves the knapsack problem (with budget) of the items with the given values and weights, with the given budget and capacity, in an bottom-up way. :param vals: list[float] ...
5,353,496
def log_mlflow(run_params: Dict, df:pd.DataFrame, df_sim:pd.DataFrame, units:dict) -> None: """ Logs result of model training and validation to mlflow Args: run_params: Dictionary containing parameters of run. Expects keys for 'experiment', 'artifact_dir', 'iteration', and 'index...
5,353,497
def checkvalid_main(args): """Function to quickly check if a certificate update is needed Only runs a small part of the checkgen_main script in order to test for certificate validity. This is used to ensure state in configuration management tooling. """ fqdn = platform.node() if not fqdn: ...
5,353,498
def _basemap_redirect(func): """ Docorator that calls the basemap version of the function of the same name. This must be applied as the innermost decorator. """ name = func.__name__ @functools.wraps(func) def wrapper(self, *args, **kwargs): if getattr(self, 'name', '') == 'basemap':...
5,353,499