content
stringlengths
22
815k
id
int64
0
4.91M
def mosaic_cut(image, original_width, original_height, width, height, center, ptop, pleft, pbottom, pright, shiftx, shifty): """Generates a random center location to use for the mosaic operation. Given a center location, cuts the input image into a slice that will be concatenated with other slices...
5,900
def get_children_info(category_id: str) -> list[dict]: """Get information about children categories of the current category. :param: category_id: category id. :return: info about children categories. """ # Create the URL url = f'{POINT}/resources/v2/title/domains/{DOMAIN}/' \ f'catego...
5,901
def GetTypedValue(field_type, value): """Returns a typed value based on a schema description and string value. BigQuery's Query() method returns a JSON string that has all values stored as strings, though the schema contains the necessary type information. This method provides conversion services to make it e...
5,902
def migrate_users(session): """ select us.id, us.user_id, us.school_id from user_school us inner join `user` u on u.user_id = us.user_id and u.active inner join school s on s.school_id = us.school_id and s.hidden_pd_school = 0; """ for user in _get_file_data('user.csv'): typer.echo(f...
5,903
def predict_from_file(audio_file, hop_length=None, fmin=50., fmax=MAX_FMAX, model='full', decoder=torchcrepe.decode.viterbi, return_harmonicity=False, return_p...
5,904
def test(): """Runs the unit tests without test coverage.""" tests = unittest.TestLoader().discover('cabotage/tests', pattern='test*.py') result = unittest.TextTestRunner(verbosity=2).run(tests) if result.wasSuccessful(): return 0 return 1
5,905
def nm_to_uh(s): """Get the userhost part of a nickmask. (The source of an Event is a nickmask.) """ return s.split("!")[1]
5,906
def write(app, cnx): """ Given an app and a SQL connection, write the app features into the feature table. :param app: The Android Application object with the data :param cnx: SQL Connection :return: """ cursor = cnx.cursor() results = app.features table_name = 'features' sp...
5,907
def upload_example_done(request, object_id): """ This view is a callback that receives POST data from uploadify when the download is complete. See also /media/js/uploadify_event_handlers.js. """ example = get_object_or_404(Example, id=object_id) # # Grab the post data sent by our ...
5,908
def epoch_in_milliseconds(epoch): """ >>> epoch_in_milliseconds(datetime_from_seconds(-12345678999.0001)) -12345679000000 """ return epoch_in_seconds(epoch) * 1000
5,909
def ForestSorter(basename, isortorder = 'random', ibackup = True, icompress = False): """ Sorts a forest file and remaps halo IDs. The sort fields (or sort keys) we ordered such that the first key will peform the outer-most sort and the last key will perform the inner-most sort. Parameters ...
5,910
def timeout(time: int = 30): """ Raise a timeout if a function does not return in time `time`. Use as a context manager, so that the signal class can reset it's alarm for `SIGALARM` :param int time: Time in seconds to wait for timeout. Default is 30 seconds. """ assert time >= 0, '...
5,911
def get_workspaces(clue, workspaces): """ Imports all workspaces if none were provided. Returns list of workspace names """ if workspaces is None: logger.info("no workspaces specified, importing all toggl workspaces...") workspaces = clue.get_toggl_workspaces() logger.info("T...
5,912
def create_hparams(hparams_string=None, hparams_json=None, verbose=True): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( training_stage='train_style_extractor',#['train_text_encoder','train_style_extractor','train_style_attention','train_r...
5,913
def set_log_extras(record): """set_log_extras [summary]. [extended_summary] Args: record ([type]): [description] """ record["extra"]["datetime"] = datetime.now( timezone.utc ) # Log datetime in UTC time zone, even if server is using another timezone record["extra"]["host"]...
5,914
def ChromiumFetchSync(name, work_dir, git_repo, checkout='origin/master'): """Some Chromium projects want to use gclient for clone and dependencies.""" if os.path.isdir(work_dir): print '%s directory already exists' % name else: # Create Chromium repositories one deeper, separating .gclient files. par...
5,915
def use_proxy_buffer(snippets_stack, vstate): """ Forward all changes made in the buffer to the current snippet stack while function call. """ buffer_proxy = VimBufferProxy(snippets_stack, vstate) old_buffer = vim_helper.buf try: vim_helper.buf = buffer_proxy yield finall...
5,916
def AddAlphaAddonsFlags(parser): """Adds the --addons flag to the parser for the alpha track.""" AddAddonsFlagsWithOptions(parser, api_adapter.ALPHA_ADDONS_OPTIONS)
5,917
def f(path, n): """Hierarchical Clustering """ p_d.prepare_data(path, n) data = pd.DataFrame.from_dict(p_d.globaldict) X = data.iloc[[0, 1], :].values X = X.transpose() print(X.shape) X = X[0:1000] print(X) hiclust(X)
5,918
def kld_error(res, error='simulate', rstate=None, return_new=False, approx=False): """ Computes the `Kullback-Leibler (KL) divergence <https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`_ *from* the discrete probability distribution defined by `res` *to* the discrete probabilit...
5,919
def article_detail(request, slug): """ Show details of the article """ article = get_article_by_slug(slug=slug, annotate=True) comment_form = CommentForm() total_views = r.incr(f'article:{article.id}:views') return render(request, 'articles/post/detail.html', {'article': ar...
5,920
def deactivate(userid, tfa_response): """ Deactivate 2FA for a specified user. Turns off 2FA by nulling-out the ``login.twofa_secret`` field for the user record, and clear any remaining recovery codes. Parameters: userid: The user for which 2FA should be disabled. tfa_response: Use...
5,921
def hsi_normalize(data, max_=4096, min_ = 0, denormalize=False): """ Using this custom normalizer for RGB and HSI images. Normalizing to -1to1. It also denormalizes, with denormalize = True) """ HSI_MAX = max_ HSI_MIN = min_ NEW_MAX = 1 NEW_MIN = -1 if(denormalize): scaled...
5,922
def measure_complexity(export_dir_root: str = './benchmark'): """ Run keyword extraction benchmark """ _file = '{}/complexity.json'.format(export_dir_root) if os.path.exists(_file): with open(_file, 'r') as f: complexity = json.load(f) else: model_list = kex.VALID_ALGORITHMS ...
5,923
def safe_elem_text(elem: Optional[ET.Element]) -> str: """Return the stripped text of an element if available. If not available, return the empty string""" text = getattr(elem, "text", "") return text.strip()
5,924
def resource(filename): """Returns the URL a static resource, including versioning.""" return "/static/{0}/{1}".format(app.config["VERSION"], filename)
5,925
def get_legacy_description(location): """ Return the text of a legacy DESCRIPTION.rst. """ location = os.path.join(location, 'DESCRIPTION.rst') if os.path.exists(location): with open(location) as i: return i.read()
5,926
def read_q_stats(csv_path): """Return list of Q stats from file""" q_list = [] with open(csv_path, newline='') as csv_file: reader = csv.DictReader(csv_file) for row in reader: q_list.append(float(row['q'])) return q_list
5,927
def _validate(config): """Validate the configuation. """ diff = set(REQUIRED_CONFIG_KEYS) - set(config.keys()) if len(diff) > 0: raise ValueError( "config is missing required keys".format(diff)) elif config['state_initial']['status'] not in config['status_values']: raise ...
5,928
def test_view_connect_task_with_user_different_email( task, authorized_client, customer_user): """Task was placed from different email, than user's we are trying to assign it to.""" task.user = None task.user_email = 'example_email@email.email' task.save() assert task.user_email != cust...
5,929
def exp_by_squaring(x, n): """ Compute x**n using exponentiation by squaring. """ if n == 0: return 1 if n == 1: return x if n % 2 == 0: return exp_by_squaring(x * x, n // 2) return exp_by_squaring(x * x, (n - 1) // 2) * x
5,930
def pipInstall(upgrade: bool = False): """pipInstall. 自动处理依赖项 """ # 配置pip源为清华源 os.system( 'pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple' ) # return 控制是否仅执行到pip更新 # return 0 # 更新pip>=10.0.0 os.system('pip install pip -U') # 第三方库列表 depLi...
5,931
def schedule_item_update(item): """ Synchronises a JWP video to the passed :py:class:`mediaplatform.models.MediaItem`. If this necessitates creating a new JWP video, a new upload endpoint is also created. Upload endpoints are not created if the JWP video already exists. """ # TODO: split this i...
5,932
def correct_tree_leaf_names(filename_in, filename_out): """Correct a single tree - Replaces the first _ into @: transition between orothofinder and pdc - Removes the ENA|id| since pdc removes it too """ tree = Phylo.read(filename_in, "newick") ena_regex = re.compile(r"ENA\|[A-Z0-9]*\|") for ...
5,933
def _compare(expected, actual): """ Compare SslParams object with dictionary """ if expected is None and actual is None: return True if isinstance(expected, dict) and isinstance(actual, SslParams): return expected == actual.__dict__ return False
5,934
def update_token(refresh_token, user_id): """ Refresh the tokens for a given user :param: refresh_token Refresh token of the user :param: user_id ID of the user for whom the token is to be generated :returns: Generated JWT token """ token = Token.query.filter_by(refr...
5,935
def minimax(board): """ Returns the optimal action for the current player on the board. """ def max_value(state, depth=0): if ttt.terminal(state): return (None, ttt.utility(state)) v = (None, -2) for action in ttt.actions(state): v = max(v, (action, mi...
5,936
def random_order_dic_keys_into_list(in_dic): """ Read in dictionary keys, and return random order list of IDs. """ id_list = [] for key in in_dic: id_list.append(key) random.shuffle(id_list) return id_list
5,937
def package(config_file, destination): """Package an existing Docker image following the UP42 specification. (cf. https://docs.up42.com/). \b Arguments: config_file: A path to a valid YAML config file. destination: A path to the output directory for the generated files. """ loguru...
5,938
def read_json(json_path: Union[str, Path]) -> Dict: """ Read json file from a path. Args: json_path: File path to a json file. Returns: Python dictionary """ with open(json_path, "r") as fp: data = json.load(fp) return data
5,939
def igraph_to_csc(g, save=False, fn="csc_matlab"): """ Convert an igraph to scipy.sparse.csc.csc_matrix Positional arguments: ===================== g - the igraph graph Optional arguments: =================== save - save file to disk fn - the file name to be used when writing (appendmat = True by de...
5,940
def xml2dict(data): """Turn XML into a dictionary.""" converter = XML2Dict() if hasattr(data, 'read'): # Then it's a file. data = data.read() return converter.fromstring(data)
5,941
def balance_dataset(data, size=60000): """Implements upsampling and downsampling for the three classes (low, medium, and high) Parameters ---------- data : pandas DataFrame A dataframe containing the labels indicating the different nightlight intensity bins size : int The number...
5,942
def updateStopList(userId, newStop): """ Updates the list of stops for the user in the dynamodb table """ response = dynamodb_table.query( KeyConditionExpression=Key('userId').eq(userId)) if response and len(response["Items"]) > 0: stops = response["Items"][0]['stops'] else: ...
5,943
def create_indices(new_data): """ Updates index files for faster FILTER functionality. :param new_data: New data to enter into data indexes. Of the form { "stb": box_id_string, "date": date_string YYYY-MM-DD, "title": title_string, ...
5,944
def is_blacklisted_module(module: str) -> bool: """Return `True` if the given module matches a blacklisted pattern.""" # Exclude stdlib modules such as the built-in "_thread" if is_stdlib_module(module): return False # Allow user specified exclusions via CLI blacklist = set.union(MODULE_BLA...
5,945
def api_detach(sess, iqn): """ Detach the given volume from the instance using OCI API calls. Parameters ---------- sess: OCISession The OCISEssion instance.. iqn: str The iSCSI qualified name. Returns ------- bool True on success, False otherwise. ...
5,946
def ComponentLibrary(self, lib_name, *args, **kwargs): """Pseudo-builder for library to handle platform-dependent type. Args: self: Environment in which we were called. lib_name: Library name. args: Positional arguments. kwargs: Keyword arguments. Returns: Passthrough return code from env.St...
5,947
def write_file(directory, file_name, data): """Write data to file.""" directory = get_directory(directory) with open(directory + file_name, "w") as open_file: open_file.write(str(data).strip())
5,948
def _build_geojson_query(query): """ See usages below. """ # this is basically a translation of the postgis ST_AsGeoJSON example into sqlalchemy/geoalchemy2 return func.json_build_object( "type", "FeatureCollection", "features", func.json_agg(func.ST_AsGeoJSON(query.s...
5,949
async def on_device_state_changed( coordinator: OverkizDataUpdateCoordinator, event: Event ) -> None: """Handle device state changed event.""" if not event.device_url: return for state in event.device_states: device = coordinator.devices[event.device_url] device.states[state.nam...
5,950
def test_command_line_interface() -> None: """Test the CLI.""" assert "Usage: nessie" in execute_cli_command([]) assert "Usage: nessie" in execute_cli_command(["--help"]) assert __version__ in execute_cli_command(["--version"]) references = ReferenceSchema().loads(execute_cli_command(["--json", "bra...
5,951
def p_quanexpr_logic_or(p): """expr : expr OR expr""" p[0] = ( 'z3.Or( ' + val(p[1]) + ' , ' + val(p[3]) +' ) ' , body(p[1]) + body(p[3]) )
5,952
def test_non_empty_proto(): """Build a graph proto from an example proto.""" proto = pbutil.FromFile(TEST_PROTO, xla_pb2.HloProto()) graph = xla.BuildProgramGraphProto(proto) assert len(graph.node) == 155 assert len(graph.function) == 5
5,953
def url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&'): """URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. If `encode_keys` is set to ``Tr...
5,954
def test_return_ruleobj_list_with_no_pyobj_specified(reinitialize_ruleclass_variables): """Raises NoRulesError if no rules list is specified as argument.""" with pytest.raises(SystemExit): _return_ruleobj_list_from_listrules(pyobj=None)
5,955
def copy_variables(infile, outfile): """Create variables corresponding to the file dimensions by copying from infile""" for var_name in ['TIME', 'LATITUDE', 'LONGITUDE']: varin = infile.variables[var_name] outVar = outfile.createVariable(var_name, varin.datatype, ...
5,956
def create_export_and_wait_for_completion(name, bucket, prefix, encryption_config, role_arn=None): """ Request QLDB to export the contents of the journal for the given time period and S3 configuration. Before calling this function the S3 bucket should be created, see :py:class:`pyqldbsamples.export_jour...
5,957
async def test_opp_binary_sensor_notification(opp, numato_fixture): """Test regular operations from within Open Peer Power.""" assert await async_setup_component(opp, "numato", NUMATO_CFG) await opp.async_block_till_done() # wait until services are registered assert opp.states.get("binary_sensor.numato...
5,958
def sample_student(user, **kwargs): """create and return sample student""" return models.Student.objects.create(user=user, **kwargs)
5,959
def normalise_field_value(value): """ Converts a field value to a common type/format to make comparable to another. """ if isinstance(value, datetime): return make_timezone_naive(value) elif isinstance(value, Decimal): return decimal_to_string(value) return value
5,960
def edit_wn_list(item_list, list_name, all_values, tenant_file_name): """ Edit WAN network list :param item_list: Item list to save :param list_name: Name of List :param all_values: All values :param tenant_file_name: File-system friendly tenant_name :return: shallow copy of item_list. "...
5,961
def startserver(): """ Python Hydrus CLI. """ pass
5,962
def parse_yaml(stream: Any) -> Tuple[Swagger, List[str]]: """ Parse the Swagger specification from the given text. :param stream: YAML representation of the Swagger spec satisfying file interface :return: (parsed Swagger specification, parsing errors if any) """ # adapted from https://stackover...
5,963
def createOptFlow_Farneback(): # real signature unknown; restored from __doc__ """ createOptFlow_Farneback() -> retval """ pass
5,964
def dataset_first_n(dataset, n, show_classes=False, class_labels=None, **kw): """ Plots first n images of a dataset containing tensor images. """ # [(img0, cls0), ..., # (imgN, clsN)] first_n = list(itertools.islice(dataset, n)) # Split (image, class) tuples first_n_images, first_n_classes...
5,965
def unit_conversion(thing, units, length=False): """converts base data between metric, imperial, or nautical units""" if 'n/a' == thing: return 'n/a' try: thing = round(thing * CONVERSION[units][0 + length], 2) except TypeError: thing = 'fubar' return thing, CONVERSION[units]...
5,966
def timed(func): """Decorate function to print elapsed time upon completion.""" @functools.wraps(func) def wrap(*args, **kwargs): t1 = default_timer() result = func(*args, **kwargs) t2 = default_timer() print('func:{} args:[{}, {}] took: {:.4f} sec'.format( func._...
5,967
def plot_rollouts_segment_wise( segments_ground_truth: List[List[StepSequence]], segments_multiple_envs: List[List[List[StepSequence]]], segments_nominal: List[List[StepSequence]], use_rec: bool, idx_iter: int, idx_round: Optional[int] = None, state_labels: Optional[List[str]] = None, sa...
5,968
def fade_out(s, fade=cf.output.fade_out): """ Apply fade-out to waveform time signal. Arguments: ndarray:s -- Audio time series float:fade (cf.output.fade_out) -- Fade-out length in seconds Returns faded waveform. """ length = int(fade * sr) shape = [1] * len(s.shape) shape[0] = length win ...
5,969
def AddAsyncFlag(parser, default_async_for_cluster=False): """Add an async flag.""" if default_async_for_cluster: modified_async_flag = base.Argument( '--async', action=arg_parsers.StoreTrueFalseAction, dest='async_', help="""\ Return immediately, without waiting for the oper...
5,970
def _build_theme_template(template_name, env, files, config, nav): """ Build a template using the theme environment. """ log.debug("Building theme template: {}".format(template_name)) try: template = env.get_template(template_name) except TemplateNotFound: log.warning("Template skipped...
5,971
def create_arch(T, D, units=64, alpha=0, dr_rate=.3): """Creates the architecture of miint""" X = K.Input(shape=(T, D)) active_mask = K.Input(shape=(T, 1)) edges = K.Input(shape=(T, None)) ycell = netRNN(T=T, D=D, units=units, alpha=alpha, dr_rate=dr_rate) yrnn = K.layers.RNN(ycell, return_sequences=True) Y = ...
5,972
def redact(str_to_redact, items_to_redact): """ return str_to_redact with items redacted """ if items_to_redact: for item_to_redact in items_to_redact: str_to_redact = str_to_redact.replace(item_to_redact, '***') return str_to_redact
5,973
def FibreDirections(mesh): """ Routine dedicated to compute the fibre direction of components in integration point for the Material in Florence and for the auxiliar routines in this script. First three directions are taken into the code for Rotation matrix, so always it should be present i...
5,974
def put(consul_url=None, token=None, key=None, value=None, **kwargs): """ Put values into Consul :param consul_url: The Consul server URL. :param key: The key to use as the starting point for the list. :param value: The value to set the key to. :param flags: This can be used to specify an unsig...
5,975
def test_not_found_error(client): """Tests response for invalid URLs""" response = client.get('/') assert b'Resource not found' in response.data assert response.status_code == 404
5,976
def prepare_w16(): """ Prepare a 16-qubit W state using sqrt(iswaps) and local gates, respecting linear topology """ ket = qf.zero_state(16) circ = w16_circuit() ket = circ.run(ket) return ket
5,977
def get_All_Endpoints(config): """ :return: """ url = 'https://{}:9060/ers/config/endpoint'.format(config['hostname']) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } body = {} response = requests.request('GET', url, headers=headers, data=body, auth=HTTPBasicAuth('Admin', 'C1...
5,978
def download_if_needed(folder_name): """ Folder name will be saved as `.cache/textattack/[folder name]`. If it doesn't exist on disk, the zip file will be downloaded and extracted. Args: folder_name (str): path to folder or file in cache Returns: str: path to the downloade...
5,979
def get_local_repository_directory(): """ Return settins.LOCAL_REPO_DIR. Ruturn None on any errors. """ if os.path.isdir(settings.LOCAL_REPO_DIR): return settings.LOCAL_REPO_DIR else: logger.error("Local repository directory not found. LOCAL_REPO_DIR: '{}'.".format(settings.LOCAL...
5,980
def synthetic_peptides_by_subsequence( num_peptides, fraction_binders=0.5, lengths=range(8, 20), binding_subsequences=["A?????Q"]): """ Generate a toy dataset where each peptide is a binder if and only if it has one of the specified subsequences. Parameters ---------...
5,981
def gce_zones() -> list: """Returns the list of GCE zones""" _bcds = dict.fromkeys(['us-east1', 'europe-west1'], ['b', 'c', 'd']) _abcfs = dict.fromkeys(['us-central1'], ['a', 'b', 'c', 'f']) _abcs = dict.fromkeys( [ 'us-east4', 'us-west1', 'europe-west4', ...
5,982
def main() -> None: """Main function""" # get command-line args args = parseargs() # load configuration if is_none_or_empty(args.conf): raise ValueError('config file not specified') with open(args.conf, 'rb') as f: config = json.load(f) logger.debug('loaded config from {}: {}...
5,983
def empty_netbox_query(): """Return an empty list to a list query.""" value = { "count": 0, "next": None, "previous": None, "results": [], } return value
5,984
def get_process_metrics(proc): """ Extracts CPU times, memory infos and connection infos about a given process started via Popen(). Also obtains the return code. """ p = psutil.Process(proc.pid) max_cpu = [0, 0] max_mem = [0, 0] conns = [] while proc.poll() is None: try: ...
5,985
def tau_from_T(Tobs, Tkin): """ Line optical depth from observed temperature and excitation temperature in Kelvin """ tau = -np.log(1.-(Tobs/Tkin)) return tau
5,986
def check_missing_files(): """ check for files that are in exposure_files but not on S3 """ from grizli.aws import db import boto3 from tqdm import tqdm from grizli import utils s3 = boto3.resource('s3') s3_client = boto3.client('s3') bkt = s3.Bucket('grizli-v2') fi...
5,987
def direct_by_type(hostname, check_type, ports): """Send request to correct type checker """ try: if check_type == 'tcp': tcp_port_check(hostname, ports) elif check_type == 'http': http_port_check(hostname, ports) else: dict_insert(errors, hostname, ch...
5,988
def drateint(rate, totc, c, gammac, phim, drtinc, iaq): """ drateint(rate, totc, c, gammac, phim, drtinc, iaq) Defined at ../src/drateint.f lines 131-267 Parameters ---------- rate : float totc : float c : float gammac : float phim : float drtinc : float ia...
5,989
def mod_init(mlogger=None): """Oh please, please, turn me into a class ;-) """ global logger logger = mlogger
5,990
def test_type_error_one(six_key_ht): """Type Error check when only one input is not HashTable.""" with pytest.raises(TypeError) as err: left_join(six_key_ht, 15) assert err == 'Input must be HashTable.'
5,991
def create_classes_names_list(training_set): """ :param training_set: dict(list, list) :return: (list, list) """ learn_classes_list = [] for k, v in training_set.items(): learn_classes_list.extend([str(k)] * len(v)) return learn_classes_list
5,992
def getSpecialDistribution(queries, kind, burstCount=1, requestsPerBurst=1, pauseLength=1.0): """get a distribution that virtualizes some specifique network situation. totalTime is the total amount of time the query transmission will take. Used parameters for the distributions: - bursts: burstCount, requestsPerBur...
5,993
async def bound_fetch(sem, session, url, method="GET", postdata="", **headers): """Deprecated, search aiohttp semaphore. """ async with sem: await fetch(session, url, method, postdata, **headers)
5,994
def test_cat(index): """Perform several tests with varying execution times.""" time.sleep(1 + (index * 0.1)) assert True
5,995
def get_petastorm_dataset(cache_dir: str, partitions: int=4): """ This Dataloader assumes that the dataset has been converted to Delta table already The Delta Table Schema is: root |-- sample_id: string (nullable = true) |-- value: string (nullable = true) |-- sample_label: string (nullable = tru...
5,996
def get_corners(square_to_edges, edge_to_squares): """Get squares ids of squares which place in grid in corner.""" return get_squares_with_free_edge(square_to_edges, edge_to_squares, 2)
5,997
def test_main_u_opt_one_glyph_in_common(fixtures_dir, tmp_path): """ The fonts have one glyph in common; the option is to use the union of names, so all three SVGs should be saved. """ ab_font_path = os.path.join(fixtures_dir, 'ab.ttf') bc_font_path = os.path.join(fixtures_dir, 'bc.ttf') out...
5,998
async def get_untagged_joke(): """ Gets an untagged joke from the jokes table and sends returns it :return: json = {joke_id, joke} """ df = jokes.get_untagged_joke() if not df.empty: response = {"joke": df["joke"][0], "joke_id": int(df["id"][0])} else: response = {"joke": "No...
5,999