content
stringlengths
22
815k
id
int64
0
4.91M
def train(x_mat: ndarray, k: int, *, max_iters: int = 10, initial_centroids: Iterable = None, history: bool = False): """ 进行k均值训练 :param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数 :param k: 聚类数目 :param max_iters: 最大迭代次数 :param initial_centroids: 初始聚类中心,不提供别的话将随机挑选聚类中心 :param history: 是否返回历史信息 :...
25,500
def download4(url, user_agent='wswp', num_retries=2): """Download function that includes user agent support""" # wswp: web scraping with python print 'Downloading:', url headers = {'User-agent': user_agent} request = urllib2.Request(url, headers=headers) try: html = urllib2.urlopen(reque...
25,501
def test_intersectionAndUnion_3classes() -> None: """ (0,0) are matched once. (1,1) are matched once. (2,2) are matched once, giving us intersection [1,1,1] for those three classes. No way to compute union of two sets, without understanding where they intersect. Union of sets {0} union {0} -> {...
25,502
def testv1(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('./tests/api/v1', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
25,503
def test_container_add_constructed_component(model_with_container: MockModel): """Verify behaviour when adding a newly constructed Container.""" empty_container = model_with_container.empty_container component = Component(name="Component") empty_container += component assert component in empty_conta...
25,504
def test_api_create_article(api): """Test Apple Create Article API""" response = api.create_article( {"title": "A Title"}, {"key1": "value1"}, {'image1.jpg': 'FFFDASFAFADADFA', 'image2.jpg': 'AFFDASFAFADADFA'}, ) assert "name='request().json()'" in repr(response) ...
25,505
def test_API_tilejson(app, event): """Test /tilejson.json route.""" from cogeo_tiler.handler import app urlqs = urllib.parse.urlencode([("url", cog_path)]) event["path"] = "/tilejson.json" res = app(event, {}) assert res["statusCode"] == 500 headers = res["headers"] assert headers["Con...
25,506
def get_third_order_displacements(cell, symmetry, is_plusminus='auto', is_diagonal=False): """Create dispalcement dataset Note ---- Atoms 1, 2, and 3 are defined as follows: Atom 1: The first disp...
25,507
def test_atomic_positive_integer_enumeration_3_nistxml_sv_iv_atomic_positive_integer_enumeration_4_4(mode, save_output, output_format): """ Type atomic/positiveInteger is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/positiveInteger/Schema+Instance/NISTSchema-SV-I...
25,508
def get_result_type(action): """Gets the corresponding ROS action result type. Args: action: ROS action name. Returns: Result message type. None if not found. """ msg_type = rostopic.get_topic_type("{}/result".format(action))[0] # Replace 'ActionResult' with 'Result'. retu...
25,509
def get_turbulence(sequence): """ Computes turbulence for a given sequence, based on `Elzinga & Liefbroer's 2007 definition <https://www.researchgate.net/publication/225402919_De-standardization_of_Family-Life_Trajectories_of_Young_Adults_A_Cross-National_Comparison_Using_Sequence_Analysis>`_ which is also implemen...
25,510
def reflect(array, holder=1): """ Reflects a np array across the y-axis Args: array: array to be reflected holder: a holder variable so the function can be used in optimization algorithms. If <0.5, does not reflect. Returns: Reflected array """ c = array.copy() if ...
25,511
def create_and_return_logger(logger_name, filename="log"): """ Function to create a custom logger that will print to terminal as well as write to a log file Accepts: Logger name for script that is calling logger, and filename for log. Returns: Logger object and Log file path. """ LOG_FIL...
25,512
def _get_all_entries(entry_list, keep_top_dir): """ Returns a list of all entries (files, directories) that should be copied. The main purpose of this function is to evaluate 'keep_top_dir' and in case it should not be kept use all the entries below the top-level directories. """ all_files = [] ...
25,513
def process_exclude_items(exclude_items=[]): """ Process the exclude items to get list of directories to NOT be scanned :return: a list of directories to not be scanned if any, otherwise an empty list """ logger.debug("Parsing exclude items ...") parsed_list = [] for item in exclude_items: ...
25,514
def absolute_name_scope(scope, reuse=tf.AUTO_REUSE): """Builds an absolute tf.name_scope relative to the current_scope. This is helpful to reuse nested name scopes. E.g. The following will happen when using regular tf.name_scope: with tf.name_scope('outer'): with tf.name_scope('inner'): prin...
25,515
def regina_edge_orientation_agrees(tet, vert_pair): """ Given tet and an ordered pair of (regina) vert nums of that tet, does this ordering agree with regina's ordering of the verts of that edge of the triangulation """ edge_num = vert_pair_to_edge_num[tuple(vert_pair)] mapping = tet.faceMapping...
25,516
async def populate_challenge( challenge_status: str = "process", is_public: bool = True, user_id: Optional[UUID] = USER_UUID, challenge_id: UUID = POPULATE_CHALLENGE_ID, ) -> Challenge: """Populate challenge for routes testings.""" if not user_id: user_id = uuid4() u...
25,517
def is_common_prefix(words: List[str], length: int) -> bool: """Binary Search""" word: str = words[0][:length] for next_word in words[1:]: if not next_word.startswith(word): return False return True
25,518
def freq_upsample(s, upsample): """ padding in frequency domain, should be used with ifft so that signal is upsampled in time-domain. Args: s : frequency domain signal upsample : an integer indicating factor of upsampling. Returns: padded signal """ if upsample =...
25,519
def test_eager_fill(): """ Test Fill op is callable """ fill_op = data_trans.Fill(3) expected = np.array([3, 3, 3, 3]) assert np.array_equal(fill_op([4, 5, 6, 7]), expected)
25,520
def get_cryptowatch_exchanges(): """ -> cryptowat.ch for information purposes :return: """ json_files = glob.glob("../input/currency_info/" + "*.json") currency_at_exchange = {} for file in json_files: with open(file, 'r') as fin: data = json.load(fin) my_set...
25,521
def test_parse_06(): """Parse key with no values.""" hexainput = [':::key1', 'value1', 'value2', ':::key2'] expected = [{'key1': ['value1', 'value2'], 'key2': []}] result = hexaparse(hexainput) assert result == expected
25,522
def write_pc(filename, xyz, rgb=None): """ write into a ply file ref.:https://github.com/loicland/superpoint_graph/blob/ssp%2Bspg/partition/provider.py """ if rgb is None: # len(xyz[0]): for a xyz list, I don't use `.shape`. rgb = np.full((len(xyz), 3), 255, dtype=np.int32) if no...
25,523
def streaming_parsing_covering(groundtruth_categories, groundtruth_instances, predicted_categories, predicted_instances, num_classes, max_instances_per_category, ...
25,524
def get_rxn_lookup(medObj:Union[m.Medication, m.LocalMed, m.NDC]): """ DEPRECATED Lookup RxCUI for codes from a different source :param medObj: :return: """ if isinstance(medObj, m.RxCUI): smores_error('TBD') return 0, [] success_count, errors = 0, [] non_rxc_dict = ...
25,525
def log(ctx: ContextObject, number: int, since: str, until: str, author: str, revision_range: str, paths: Tuple[click.Path]) -> None: """Show commit log. REVISION_RANGE optional branch, tag or hash to start viewing log from. If of the form <hash>..<hash> only show log for given range PATHS optional li...
25,526
def identity(dims): """ Create an identity linear operator :param dims: array of dimensions """ dims = expand_dims(dims) return identity_create(dims)
25,527
def _gen_samples_2d(enn_sampler: testbed_base.EpistemicSampler, x: chex.Array, num_samples: int, categorical: bool = False) -> pd.DataFrame: """Generate posterior samples at x (not implemented for all posterior).""" # Generate the samples data = [] rng...
25,528
def rules(r_index, c_index, lives, some_board, duplicate_board): """Apply Conway's Rules to a board Args: r_index (int): Current row index c_index (int): Current column index lives (int): Number of ALIVE cells around current position some_board (List of lists of strings):...
25,529
def readfq(filehandle): """Fastq iterator. Args: filehandle (file): open file handle Yields: Fastq """ fqclean = (x.strip("\r\n") for x in filehandle if x.strip()) while True: rd = [x for x in islice(fqclean, 4)] if not rd: raise StopIteration ...
25,530
async def test_form_import(hass): """Test we get the form with import source.""" await setup.async_setup_component(hass, "persistent_notification", {}) harmonyapi = _get_mock_harmonyapi(connect=True) with patch( "homeassistant.components.harmony.util.HarmonyAPI", return_value=harmonyapi, ),...
25,531
def get_describe_tasks(cluster_name, tasks_arns): """Get information about a list of tasks.""" return ( ecs_client() .describe_tasks(cluster=cluster_name, tasks=tasks_arns) .get("tasks", []) )
25,532
def train(log_path, radar_product, eval_increment=5, num_iterations=2500, checkpoint_frequency=100, lr=.0001, model_name=utils.ML_Model.Shallow_CNN, dual_pol=True, high_memory_mode=False, num_temporal_data=0): """"Train the shallow CNN model on a single radar product. Args: ...
25,533
def make_bcc110(latconst=1.0): """ Make a cell of bcc structure with z along [110]. """ s= NAPSystem(specorder=_default_specorder) #...lattice a1= np.array([ 1.0, 0.0, 0.0 ]) a2= np.array([ 0.0, 1.414, 0.0 ]) a3= np.array([ 0.0, 0.0, 1.41...
25,534
def test_config(ctx): """ Test that you have properly filled in the necessary aws fields, your boto install is working correctly, your s3 bucket is readable and writable (also by your indicated role), etc. """ client = boto3.client("sts") account_id = client.get_caller_identity()["Account"...
25,535
def mode_mods_to_int(mode: str) -> int: """Converts mode_mods (str) to mode_mods (int).""" # NOTE: This is a temporary function to convert the leaderboard mode to an int. # It will be removed when the site is fully converted to use the new # stats table. for mode_num, mode_str in enumerate(( ...
25,536
def sender(sim, cable): """A process which randomly generates messages.""" while True: # wait for next transmission sim.sleep(5) cable.put('Sender sent this at %d' % sim.now)
25,537
def ntu_tranform_skeleton(test): """ :param test: frames of skeleton within a video sample """ remove_frame = False test = np.asarray(test) transform_test = [] d = test[0, 0:3] v1 = test[0, 1 * 3:1 * 3 + 3] - test[0, 0 * 3:0 * 3 + 3] v1 = v1 / np.linalg.norm(v1) v2_ = test[0, ...
25,538
def request_to_dataframe(UF): """Recebe string do estado, retona DataFrame com faixa de CEP do estado""" #Try to load the proxy list. If after several attempts it still doesn't work, raise an exception and quit. proxy_pool = proxy_list_to_cycle() #Set initial values for post request's parameters....
25,539
def read_sto_mot_file(filename): """ Read sto or mot file from Opensim ---------- filename: path Path of the file witch have to be read Returns ------- Data Dictionary with file informations """ data = {} data_row = [] first_line = () e...
25,540
def verify_cef_labels(device, route, expected_first_label, expected_last_label=None, max_time=90, check_interval=10): """ Verify first and last label on route Args: device ('obj'): Device object route ('str'): Route address expected_first_label ('str'): Expected fir...
25,541
def fcat(*fs): """Concatenate a sequence of farrays. The variadic *fs* input is a homogeneous sequence of functions or arrays. """ items = list() for f in fs: if isinstance(f, boolfunc.Function): items.append(f) elif isinstance(f, farray): items.extend(f.flat...
25,542
def plot_2images(phi1, phi2): """Plot two images from MNIST Args: phi1: MNIST image phi2: MNIST image Returns: plot of the images """ if phi1.shape == (28,28): f, axarr = plt.subplots(2) axarr[0].imshow(np.reshape(phi1,(28,28)), cmap='Greys', vmin...
25,543
def get_path_to_spix( name: str, data_directory: str, thermal: bool, error: bool = False, file_ending: str = "_6as.fits", ) -> str: """Get the path to the spectral index Args: name (str): Name of the galaxy data_directory (str): dr2 data directory thermal (bool): non...
25,544
def hexpos (nfibres,diam) : """ Returns a list of [x,y] positions for a classic packed hex IFU configuration. """ positions = [[np.nan,np.nan] for i in range(nfibres)] # FIND HEX SIDE LENGTH nhex = 1 lhex = 1 while nhex < nfibres : lhex += 1 nhex = 3*lhex**2-3*lhex+1 if nhex != nfibres: lhex -= 1 nhex ...
25,545
def parse_object_properties(html): """ Extract key-value pairs from the HTML markup. """ if isinstance(html, bytes): html = html.decode('utf-8') page = BeautifulSoup(html, "html5lib") propery_ps = page.find_all('p', {'class': "list-group-item-text"}) obj_props_dict = {} for p in ...
25,546
def send_email(subject, sender, recipients, text_body, html_body): """Send an email. Args: subject: subject sender: sender recipients: recipients text_body: text body html_body: html body """ msg = Message(subject, sender=sender, recipients=recipients) msg.bo...
25,547
def test_warped_vrt_add_alpha(dsrec, path_rgb_byte_tif): """A VirtualVRT has the expected VRT properties.""" with rasterio.Env() as env: with rasterio.open(path_rgb_byte_tif) as src: vrt = WarpedVRT(src, crs=DST_CRS, add_alpha=True) records = dsrec(env) assert len(re...
25,548
async def test_reconcile_patch_failed(clean_booked_grace_time_mock, report_mock, respx_mock): """ Check that when patch to /license/reconcile response status_code is not 200, should raise exception. """ respx_mock.patch("/lm/api/v1/license/reconcile").mock( return_value=Response( sta...
25,549
def rgb2hex(r, g, b, normalised=False): """Convert RGB to hexadecimal color :param: can be a tuple/list/set of 3 values (R,G,B) :return: a hex vesion ofthe RGB 3-tuple .. doctest:: >>> from colormap.colors import rgb2hex >>> rgb2hex(0,0,255, normalised=False) '#0000FF' ...
25,550
def test_hookrelay_registry(pm): """Verify hook caller instances are registered by name onto the relay and can be likewise unregistered.""" class Api: @hookspec def hello(self, arg): "api hook 1" pm.add_hookspecs(Api) hook = pm.hook assert hasattr(hook, "hello") ...
25,551
def flac_stream_file(filename: str, frames_to_read: int = 1024, seek_frame: int = 0) -> Generator[array.array, None, None]: """Streams the flac audio file as interleaved 16 bit signed integer sample arrays segments. This uses a fixed chunk size and cannot be used as a generic miniaudio deco...
25,552
def main(): """Run the main job.""" cliffs = ee.FeatureCollection(definitions.EE_CLIFF_FOOTPRINTS) cliffs = cliffs.map(get_data) # export results to drive for local download task1 = ee.batch.Export.table.toDrive( collection=cliffs, description='exporting cliff data to drive', fileFormat='CS...
25,553
def creates_user(page_users, new_user) -> None: """I create a new user.""" page_users.set_user(new_user) # Fill the fields p_action = FillUserAction(_page=page_users) p_action.fill_name() \ .fill_password() \ .confirm_password() del p_action # Create p_action = ...
25,554
def model_choices_from_protobuf_enum(protobuf_enum): """Protobufs Enum "items" is the opposite order djagno requires""" return [(x[1], x[0]) for x in protobuf_enum.items()]
25,555
def load_boxes_and_labels(cfg, mode): """ Loading boxes and labels from csv files. Args: cfg (CfgNode): config. mode (str): 'train', 'val', or 'test' mode. Returns: all_boxes (dict): a dict which maps from `video_name` and `frame_sec` to a list of `box`. Each `box` i...
25,556
def test_registrationform_userprofile_disable_csrf(app_with_userprofiles_csrf, form_test_data): """App with CSRF enabled and UserProfile, test if reg. form removes it.""" remote_apps = current_oauthclient.oauth.remote_apps first_remote_app = list(remote_app...
25,557
def kmeans(boxes, k): """ Group into k clusters the BB in boxes. http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans :param boxes: The BB in format Nx4 where (x1,y1,x2,y2) :param k: the number of clusters. :return: k clusters with the element in...
25,558
def observation_min_max_in_hex_grid_json(request: HttpRequest): """Return the min, max observations count per hexagon, according to the zoom level. JSON format. This can be useful to dynamically color the grid according to the count """ zoom = extract_int_request(request, "zoom") species_ids, datas...
25,559
def is_path(value, default="", expand=None): """Parse a value as a path Parameters ---------- expand: expandvars and expandhome on loaded path **Warning: expand currently can't work with interpolation** """ # TODO: fix interpolation and expand ! if str(value) == "None": ...
25,560
def find_suites(): """ Return a dict of suitename and path, e.g. {"heat_equation": /home/safl/bechpress/suites/cpu/heat_equation.py"} """ p = subprocess.Popen( ["bp-info", "--suites"], stdout = subprocess.PIPE, stderr = subprocess.PIPE ) out, err = p.communicate() ...
25,561
def test_tag_retention_without_tag(event, glsc): """tag retention should be null if tags is null""" choices = get_event_model_form_choices(event) event_dict = create_event_dict(event) event_dict["fish_tags"] = None event_dict["tag_ret"] = 50 form = StockingEventForm(event_dict, choices=choice...
25,562
def parseHtml(html): """ BeautifulSoup でパースする Parameters ---------- html : str HTML ソース文字列 Returns ------- soup : BeautifulSoup BeautifulSoup オブジェクト """ soup = BeautifulSoup(html, 'html.parser') return soup
25,563
def test_str(): """test Parameter.__str__()""" node = Parameter(wraptext("1"), wraptext("foo"), showkey=False) assert "foo" == str(node) node2 = Parameter(wraptext("foo"), wraptext("bar")) assert "foo=bar" == str(node2)
25,564
def am_score(probs_data, probs_gen): """ Calculate AM Score """ mean_data = np.mean(probs_data, axis=0) mean_gen = np.mean(probs_gen, axis=0) entropy_gen = np.mean(entropy(probs_gen, axis=1)) am_score = entropy(mean_data, mean_gen) + entropy_gen return am_score
25,565
def load_image(path_image, size=None, bgr_mean=[103.939, 116.779, 123.68]): """ Loads and pre-process the image for SalGAN model. args: path_image: abs path to image size: size to input to the network (it not specified, uses SalGAN predifined) bgr_mean: mean values (BGR) to extract ...
25,566
def GetWsdlNamespace(version): """ Get wsdl namespace from version """ return "urn:" + serviceNsMap[version]
25,567
def is_PC(parcels): """ Dummy for Pinal County. """ return (parcels.county == 'PC').astype(int)
25,568
def test_create_default_instance_through_method(): """ This test creates the default instance with the default plugins, several times for profiling purposes """ parse_with_default_method2 = try_to_annotate_with_profile(parse_with_default_method) # TODO one day use pytest benchmark instead start = perf...
25,569
def check_password(password: str) -> int: """Use Have I Been Pwned to determine whether a password is bad. If the request fails, this function will assume the password is fine, but log an error so that administrators can diagnose it later. :param password: The password to validate. :return: A posi...
25,570
def rqpos(A): """ RQ decomp. of A, with phase convention such that R has only positive elements on the main diagonal. If A is an MPS tensor (d, chiL, chiR), it is reshaped and transposed appropriately before the throughput begins. In that case, Q will be a tensor of the same size, while R ...
25,571
def rate_text(chunk, rating): """ Update the given rating with what is found in the given text. Returns None. """ for word in chunk.split(): word = ''.join(filter((lambda c: c.isalnum()), word)) rating['__total__'] += 1 for lang in COLLECTED_DIGESTED.get(word, []): ...
25,572
def load_checkpoint(model, filename, map_location=None, strict=False, logger=None, show_model_arch=True, print_keys=True): """ Note that official pre-trained models use `GroupNorm` in backbone. ...
25,573
def basic_image_2(): """ A 10x10 array with a square (3x3) feature Equivalent to results of rasterizing basic_geometry with all_touched=True. Borrowed from rasterio/tests/conftest.py Returns ------- numpy ndarray """ image = np.zeros((20, 20), dtype=np.uint8) image[2:5, 2:5] = 1...
25,574
def save_tiled_tsdf_comparison_image(out_path, good_case_sdfs, bad_case_sdfs, vertical_tile_count=4, padding_width=1, scale=2): """ :param out_path: path (directory + filename) where to save the image :param good_case_sdfs: a list of tuples in form (canonical_tsdf, liv...
25,575
def download(url, verbose, user_agent='wswp', num_retries=2, decoding_format='utf-8', timeout=5): """ Function to download contents from a given url Input: url: str string with the url to download from user_agent: str Default 'wswp' num_retries:...
25,576
def split_checkbox_responses(dict,keys,delimiter=";",prefix=" ",padding="\n"): """Break out comma-delimited responses into indented (or prefixed) lines. Arguments: dict (dictionary) : dictionary on which to do this substitution keys (list) : list of keys to be so replaced delimite...
25,577
def _write_deform(model: Union[BDF, OP2Geom], name: str, loads: List[AEROS], ncards: int, op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int: """ (104, 1, 81) NX 2019.2 Word Name Type Description 1 SID I Deformation set identification number ...
25,578
def polygonize(geometries, **kwargs): """Creates polygons formed from the linework of a set of Geometries. Polygonizes an array of Geometries that contain linework which represents the edges of a planar graph. Any type of Geometry may be provided as input; only the constituent lines and rings will be u...
25,579
def slerp(input_latent1, input_latent2, interpolation_frames=100): """Spherical linear interpolation ("slerp", amazingly enough). Parameters ---------- input_latent1, input_latent2 : NumPy arrays Two arrays which will be interpolated between. interpolation_frames : int, optional ...
25,580
def parent_version_config(): """Return a configuration for an experiment.""" config = dict( _id="parent_config", name="old_experiment", version=1, algorithms="random", metadata={ "user": "corneauf", "datetime": datetime.datetime.utcnow(), ...
25,581
def sanitize_k8s_name(name): """From _make_kubernetes_name sanitize_k8s_name cleans and converts the names in the workflow. """ return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-', name.lower())).lstrip('-').rstrip('-')
25,582
def handle_connect(event): """Connect events occur when a device is responding to a MDM command. They contain the raw responses from the device. https://developer.apple.com/enterprise/documentation/MDM-Protocol-Reference.pdf """ xml = base64.b64decode(event['acknowledge_event']['raw_payload']) ...
25,583
def test_dt_tz_column_naive_input_pg(pg_dt): """Included here as a way of showing that this mimics postgres' behavior""" pg_dt.execute(DTTable.__table__.insert().values(id=1, dt_tz=datetime(2018, 1, 1, 5, 0, 0))) result = pg_dt.execute(sqlalchemy.select([dt_table.c.dt_tz])).scalar() assert result == dat...
25,584
def main(): """ Process command line arguments and run x86 """ run = X86Run() result = run.Run() return result
25,585
def gen_key(uid, section='s'): """ Generate store key for own user """ return f'cs:{section}:{uid}'.encode()
25,586
def convert_atom_to_voxel(coordinates: np.ndarray, atom_index: int, box_width: float, voxel_width: float) -> np.ndarray: """Converts atom coordinates to an i,j,k grid index. This function offsets molecular atom coordinates by (box_width/2, box_width/2, box_width/2) and then divides by ...
25,587
def get_toolset_url(): """URL of a platform specific Go toolset archive.""" # TODO(vadimsh): Support toolset for cross-compilation. arch = { 'amd64': 'x86-64', 'x86_64': 'x86-64', 'i386': 'x86-32', 'x86': 'x86-32', }.get(platform.machine().lower()) variant = TOOLSET_VARIANTS.get((sys.platform,...
25,588
def plot_det_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None, log_wandb=False): """Function for plotting DET curve Args: y_true_arr (list/np.array): list of all GT arrays y_pred_proba_arr (list/np.array): list of all predicted probabili...
25,589
def harmonic_separation(audio, margin=3.0): """ Wraps librosa's `harmonic` function, and returns a new Audio object. Note that this folds to mono. Parameters --------- audio : Audio The Audio object to act on. margin : float The larger the margin, the larger the separation....
25,590
def _apply_op_flag_vals_for_opdef( opdef, user_flag_vals, force_flags, op_cmd, args, resource_flagdefs, op_flag_vals, ): """Applies opdef and user-provided flags to `op_flag_vals`. Also applies resolved resource flag defs per flag vals `resource_flagdefs`. Attempts to resol...
25,591
def merge( left, right, how: str = "inner", on=None, left_on=None, right_on=None, left_index: bool = False, right_index: bool = False, sort: bool = False, suffixes=("_x", "_y"), copy: bool = True, indicator: bool = False, validate=None, ): # noqa: PR01, RT01, D200 ...
25,592
def generate_modal(title, callback_id, blocks): """ Generate a modal view object using Slack's BlockKit :param title: Title to display at the top of the modal view :param callback_id: Identifier used to help determine the type of modal view in future responses :param blocks: Blocks to add to the mo...
25,593
def dir_thresh(img, sobel_kernel=3, thresh=(0.7, 1.3)): """ #--------------------- # This function applies Sobel x and y, # then computes the direction of the gradient, # and then applies a threshold. # """ # Take the gradient in x and y separately sobelx = cv2.Sobel(img, cv2.CV_64F...
25,594
def test_notimplemented_method(name, page_class): """All methods raise NotImplementedError""" t = page_class() func = getattr(t, name) with pytest.raises(NotImplementedError): func()
25,595
def seconds_to_time( time ): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ if not time: return "0s" from datetime import datetime, timedelta if isinstance( time, timedelta ) or ...
25,596
def bq_use_legacy_sql(): """ Returns BIGQUERY_LEGACY_SQL if env is set """ return os.environ.get('BIGQUERY_LEGACY_SQL', 'TRUE')
25,597
def load_txt_into_set(path, skip_first_line=True): """Load a txt file (one value per line) into a set.""" result = set() file = open_file_dir_safe(path) with file: if skip_first_line: file.readline() for line in file: line = line.strip() result.add(li...
25,598
def failed(obj): """Returns True if ``obj`` is an instance of ``Fail``.""" return isinstance(obj, Fail)
25,599