content
stringlengths
22
815k
id
int64
0
4.91M
def GetTSAWaitTimes(airportCode): """ Returns data from the TSA Wait Times API for a particular airport shortcode. :param airportCode: 3-letter shortcode of airport :return: Returns the full parsed json data from TSA Wait Times API """ base_url = "http://apps.tsa.dhs.gov/MyTSAWebService/GetTSOWa...
28,000
def False(context): """Function: <boolean> false()""" return boolean.false
28,001
def namedtuple_to_dict(model_params): """Transfers model specification from a named tuple class object to dictionary.""" init_dict = {} init_dict["GENERAL"] = {} init_dict["GENERAL"]["num_periods"] = model_params.num_periods init_dict["GENERAL"]["num_choices"] = model_params.num_choices ...
28,002
def roberts(stream: Stream, *args, **kwargs) -> FilterableStream: """https://ffmpeg.org/ffmpeg-filters.html#roberts""" return filter(stream, roberts.__name__, *args, **kwargs)
28,003
def options(opt): """ Command-line options """ opt.add_option('--want-rpath', action='store_true', default=False, dest='want_rpath', help='enable the rpath for qt libraries') opt.add_option('--header-ext', type='string', default='', help='header extension for moc files', dest='qt_header_ext') for i in '...
28,004
def run_code(): """ codec api response { "error": { "decode:": "error message" }, "output": { "status_code": 0, "result": { "data_type": "event", "data": { "humidity": { "time": 1547660823, ...
28,005
def _strip_paths(notebook_json: Mapping, project_root: Path): """Strip user paths from given notebook.""" project_root_string = str(project_root) + os.sep mutated = False for cell in notebook_json["cells"]: if cell["cell_type"] == "code": for output in cell["outputs"]: ...
28,006
def build_dense_conf_block(x, filter_size=32, dropout_rate=None): """ builds a dense block according to https://arxiv.org/pdf/1608.06993.pdf :param x: :param dropout_rate: :param filter_size :return: """ x = BatchNormalization(axis=-1, epsilon=1.1e-5)(x) x = Activation('relu')(x) ...
28,007
def _viz_flow(u, v, logscale=True, scaledown=6): """ Copied from @jswulff: https://github.com/jswulff/pcaflow/blob/master/pcaflow/utils/viz_flow.py top_left is zero, u is horizon, v is vertical red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12 """ color_wheel = _color_wheel() n_cols =...
28,008
def submission_history(request, course_id, learner_identifier, location): """Render an HTML fragment (meant for inclusion elsewhere) that renders a history of all state changes made by this user for this problem location. Right now this only works for problems because that's all StudentModuleHistory rec...
28,009
def tou(month, weekday, hour): """ Calculate TOU pricing """ if weekday in [0, 6]: return OFFPEAK else: if month in [5, 6, 7, 8, 9, 10]: if hour in [11, 12, 13, 14, 15, 16]: return ONPEAK elif hour in [7, 8, 9, 10, 17, 18, 19, 20]: ...
28,010
def build_doctree(tree, prefix, parent): """ Build doctree dict with format: dict key = full class/type name (e.g, "confluent_kafka.Message.timestamp") value = object """ for n in dir(parent): if n.startswith('__') or n == 'cimpl': # Skip internals and the C module (i...
28,011
def get_job(request): """ Retrieve a specific Job URL: /admin/Jobs/GetOne :param request: :return: """ id = request.GET.dict().get("id") response = { 'status': 1, 'status_message': 'Success', 'job': job.objects.filter(id=id) } return HttpResponse(json.du...
28,012
def cpt_lvq_merid_deriv(temp, sphum): """Meridional derivative of c_p*T + L_v*q on pressure coordinates.""" deriv_obj = LatCenDeriv(cpt_lvq(temp, sphum), LAT_STR) return deriv_obj.deriv()
28,013
def ZonalStats(fhs, dates, output_dir, quantity, unit, location, color = '#6bb8cc'): """ Calculate and plot some statictics of a timeseries of maps. Parameters ---------- fhs : ndarray Filehandles pointing to maps. dates : ndarray Datetime.date object corresponding to fhs. ...
28,014
def test_zaehlpunkte(client): """Tests if any zaehkpunkte exist.""" zp = client.zaehlpunkte() assert len(zp) > 0 assert len(zp[0]["zaehlpunkte"]) > 0
28,015
def callback(event): """ Reacts to a user click on the window """ # switch on the status global status # if still initializing, ignore the click and don't do anything if status == Status.init: return # if ready, start the race or show the distance map elif status == Status.ready: if cars: status = Stat...
28,016
def hubert_pretrain_large( encoder_projection_dropout: float = 0.0, encoder_attention_dropout: float = 0.0, encoder_ff_interm_dropout: float = 0.0, encoder_dropout: float = 0.0, encoder_layer_drop: float = 0.0, ) -> HuBERTPretrainModel: # Overriding the signature so that the return type is corre...
28,017
def random_scaled_rotation(ralpha=(-0.2, 0.2), rscale=((0.8, 1.2), (0.8, 1.2))): """Compute a random transformation matrix for a scaled rotation. :param ralpha: range of rotation angles :param rscale: range of scales for x and y :returns: random transformation """ affine = np.eye(2) if rsc...
28,018
def time_as_int() -> int: """ Syntactic sugar for >>> from time import time >>> int(time()) """ return int(time.time())
28,019
def test_end_response_is_one_send(): """Test that ``HAPServerHandler`` sends the whole response at once.""" class ConnectionMock: sent_bytes = [] def sendall(self, bytesdata): self.sent_bytes.append([bytesdata]) return 1 def getsent(self): return se...
28,020
def create_schema(conn): """Create the trace database schema on a given SQLite3 connection. """ sql = [ ''' CREATE TABLE processes( id INTEGER NOT NULL PRIMARY KEY, run_id INTEGER NOT NULL, parent INTEGER, timestamp INTEGER NOT NULL, ...
28,021
def compute_norm_cond_entropy_corr(data_df, attrs_from, attrs_to): """ Computes the correlations between attributes by calculating the normalized conditional entropy between them. The conditional entropy is asymmetric, therefore we need pairwise computation. The computed correlations are stored in ...
28,022
def should_retry_http_code(status_code): """ :param status_code: (int) http status code to check for retry eligibility :return: (bool) whether or not responses with the status_code should be retried """ return status_code not in range(200, 500)
28,023
def softmax(x): """Calculates the softmax for each row of the input x. Your code should work for a row vector and also for matrices of shape (n, m). Argument: x -- A numpy matrix of shape (n,m) Returns: s -- A numpy matrix equal to the softmax of x, of shape (n,m) """ # Apply exp() el...
28,024
def detect_gid_list(ibs, gid_list, verbose=VERBOSE_AZURE, **kwargs): """Detect gid_list with azure. Args: gid_list (list of int): the list of IBEIS image_rowids that need detection Kwargs (optional): refer to the Azure documentation for configuration settings Args: ibs (wbia.IBEISCont...
28,025
def inertia_tensor_eigvals(image, mu=None, T=None): """Compute the eigenvalues of the inertia tensor of the image. The inertia tensor measures covariance of the image intensity along the image axes. (See `inertia_tensor`.) The relative magnitude of the eigenvalues of the tensor is thus a measure of the...
28,026
def test_info(): """Test for qcengine info""" outputs = [] for arg in cli.info_choices: output = run_qcengine_cli(["info", arg]) if arg not in {"all", "config"}: # output of config changes call-to-call depending e.g. on mem available outputs.append(output) default_output = ...
28,027
def extract_values(inst): """ :param inst: the instance :return: python values extracted from the instance """ # inst should already be python return inst
28,028
def voc_ap(rec, prec, use_07_metric=False): """ ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the VOC 07 11 point method (default:False). """ if use_07_metric: # 11 point metric ap = 0. for t in np.arange(0., 1.1, 0.1): if np.sum(rec ...
28,029
def is_on_path(prog): """Checks if a given executable is on the current PATH.""" r = runcmd("which %s" % prog) if r.failed: return False else: return r
28,030
def validate_entry(new_text) -> bool: """Função callback para validação de entrada dos campos na janela ExperimentPCR. É chamada toda vez que o usuário tenta inserir um valor no campo de entrada. Uma entrada válida deve atender os seguintes requisitos: -Ser composto apenas de números intei...
28,031
def eia_cbecs_land_call(*, resp, url, **_): """ Convert response for calling url to pandas dataframe, begin parsing df into FBA format :param resp: df, response from url call :param url: string, url :return: pandas dataframe of original source data """ # Convert response to dataframe ...
28,032
def add_l2_interface(interface_name, interface_desc=None, interface_admin_state="up", **kwargs): """ Perform a POST call to create an Interface table entry for physical L2 interface. :param interface_name: Alphanumeric Interface name :param interface_desc: Optional description for the interface. Defaul...
28,033
def language_descriptions(): """ Return a dict of `LanguageDesc` instances keyed by language name. """ global languages if languages is None: languages = {} for language in pkg_resources.WorkingSet().iter_entry_points( group='textx_languages'): register_la...
28,034
async def test_async_get_next_pickup_event_no_event_left(aresponses): """Test getting the next pickup event. No event after today.""" response = aresponses.Response( text=load_fixture("pickup_data_response_1.json"), status=200, headers={"Content-Type": "text/html"}, ) aresponses....
28,035
def load_fixtures(fixtures_dict=None): """ Loads fixtures specified in fixtures_dict. This method must be used for fixtures that don't have associated data models. We simply want to load the meta into dict objects. fixtures_dict should be of the form: { 'actionchains': ['actionchain1.jso...
28,036
def generate_sbm(sizes, probs, maxweight=1): """Generate a Stochastic Block Model graph. Assign random values drawn from U({1, ..., maxw}) to the edges. sizes : list of sizes (int) of the blocks probs : matrix of probabilities (in [0, 1]) of edge creation between nodes dependi...
28,037
def eq_portions(actual: str, expected: str): """ Compare whether actual matches portions of expected. The portions to ignore are of two types: - ***: ignore anything in between the left and right portions, including empty - +++: ignore anything in between left and right, but non-empty :param actual:...
28,038
def _get_encoder( in_features: int, embed_dim: int, dropout_input: float, pos_conv_kernel: int, pos_conv_groups: int, num_layers: int, num_heads: int, attention_dropout: float, ff_interm_features: int, ff_interm_dropout: float, drop...
28,039
def print_tree(tree, indent=0): """Prints the parse tree for debugging purposes. This does not expand HTML entities; that should be done after processing templates.""" assert isinstance(tree, (WikiNode, str)) assert isinstance(indent, int) if isinstance(tree, str): print("{}{}".format(" " *...
28,040
def _soft_threshold(a, b): """Soft-threshold operator for the LASSO and elastic net.""" return np.sign(a) * np.clip(np.abs(a) - b, a_min=0, a_max=None)
28,041
def predict(input_tokens): """register predict method in pangu-alpha""" token_ids, valid_length = register.call_preprocess(preprocess, input_tokens) ############# two output ################### # p, p_args = register.call_servable(token_ids) # add_token = register.call_postprocess(postprocess, p, p_...
28,042
def get_sim_data(): """ Create the data needed to initialize a simulation Performs the steps necessary to set up a stratified plume model simulation and passes the input variables to the `Model` object and `Model.simulate()` method. Returns ------- profile : `ambient.Profile` object ...
28,043
def _organize_arch(fils, pth): """Allocate data from each specific type of file (keys from the input dict) to a new dict Arguments: fils {dict} -- Dictionary containing type of files and list of files Returns: [dict] -- [description] """ import numpy as np imgdat...
28,044
def gather_allele_freqs(record, all_samples, males, females, pop_dict, pops, no_combos = False): """ Wrapper to compute allele frequencies for all sex & population pairings """ #Get allele frequencies calc_allele_freq(record, all_samples) if len(males) > 0: calc_allele_freq(record, male...
28,045
def get_selected(n=1): """ Return the first n selected object, or None if nothing is selected. """ if get_selection_len(): selection = bpy.context.selected_objects if n == 1: return selection[0] elif n == -1: return selection[:] else: r...
28,046
def label_src_vertno_sel(label, src): """ Find vertex numbers and indices from label Parameters ---------- label : Label Source space label src : dict Source space Returns ------- vertno : list of length 2 Vertex numbers for lh and rh src_sel : array of int ...
28,047
def get_subjects(creative_work): """ Returns generated html of subjects associated with the Creative Work HTML or 0-length string Parameters: creative_work -- Creative Work """ html_output = '' #! Using LOC Facet as proxy for subjects facets = list( REDIS_DATASTORE.smembers(...
28,048
def run_tests(runner: cmake_runner.CMakeRunner, args: argparse.Namespace, build_config: str) -> bool: """Run tests for the current project. Args: runner: Cmake runner object. args: Arguments for cmake. build_config: Name of configuration target. Returns: True when testing ran succe...
28,049
def test_api_versions_synced_with_botocore(api_version_args): """Verify both boto3 and botocore clients stay in sync.""" service_name, botocore_session, boto3_session = api_version_args resource = boto3_session.resource(service_name) boto3_api_version = resource.meta.client.meta.service_model.api_ve...
28,050
def build(new_opts={}): """ Build graph Args: new_opts: dict with additional opts, which will be added to opts dict/ """ opts.update(new_opts) images_ph, labels_ph, train_phase_ph = placeholder_inputs() logits = inference(images_ph, train_phase_ph) loss_out = loss(logits, lab...
28,051
def bubblesort(s, debug=1): """ 冒泡排序 :param s: 要排序的数组 :return : for i in range(len(s)-1) 找出元素s[i]….s[len(s)]中的最小元素 与s[i]交换 """ c = 0 for i in range(len(s) - 1): for j in range(1, len(s) - i): if s[j - 1] > s[j]: print('j-1=', j - 1,...
28,052
def sort(request): """Boolean sort keyword for concat and DataFrame.append.""" return request.param
28,053
def is_comprehension(leaf): """ Return true if the leaf is the beginning of a list/set/dict comprehension. Returns true for generators as well """ if leaf.type != 'operator' or leaf.value not in {'[', '(', '{'}: return False sibling = leaf.get_next_sibling() return (sibling.type in...
28,054
def get_class(x): """ x: index """ # Example distribution = [0, 2000, 4000, 6000, 8000, 10000] x_class = 0 for i in range(len(distribution)): if x > distribution[i]: x_class += 1 return x_class
28,055
def generate_checksum(message, previous_csum=0): """Generate checksum for messages with CALL_REQ, CALL_REQ_CONTINUE, CALL_RES,CALL_RES_CONTINUE types. :param message: outgoing message :param previous_csum: accumulated checksum value """ if message.message_type in CHECKSUM_MSG_TYPES:...
28,056
def square(x): """Elementwise square of a tensor. """ return T.sqr(x)
28,057
def update_email_body(parsed_email, key): """ Finds and updates the "text/html" and "text/plain" email body parts. Parameters ---------- parsed_email: email.message.Message, required EmailMessage representation the downloaded email key: string, required The object key that will b...
28,058
def create_collaborators(collaborators, destination_url, destination, credentials): """Post collaborators to GitHub INPUT: collaborators: python list of dicts containing collaborators info to be POSTED to GitHub destination_url: the root url for the GitHub API destination: the team and r...
28,059
def complexity_recurrence(signal, delay=1, dimension=3, tolerance="default", show=False): """Recurrence matrix (Python implementation) Fast Python implementation of recurrence matrix (tested against pyRQA). Returns a tuple with the recurrence matrix (made of 0s and 1s) and the distance matrix (the non-bina...
28,060
def _git_enable_release_branch(): """Enable desired release branch.""" with _git_enable_branch(RELEASE_BRANCH): yield
28,061
def train(params): """ Trains error model. Arguments: params (dict): hyperparameters with which to train """ p, x = load_error_data() # calculate means p_mean = p.mean(axis=(0, 1)) p_std = p.std(axis=(0, 1)) x_mean = x.mean(axis=(0, 1)) x_std = x.std(axis=(0, 1)) #...
28,062
def RunAll(test_spark=False): """Running all tests.""" # Uncomment to test writing tables. # RunTest("ground_test") # RunTest("ground_psql_test") # RunTest("closure_test") # RunTest("dialects/trino/grounding_test") RunTest("in_expr_test") RunTest("equals_true_test") if test_spark: RunTest("diale...
28,063
def test_md042_bad_link_empty_fragment(): """ Test to make sure we get the expected behavior after scanning a good file from the test/resources/rules/md004 directory that has consistent asterisk usage on a single level list. """ # Arrange scanner = MarkdownScanner() supplied_arguments =...
28,064
def check_max_line_length_configured(repo: RepoLinter) -> None: """ checks for the max-line-length setting in .pylintrc """ # default setting if "pylintrc" in repo.config: if "max_line_length" not in repo.config[CATEGORY]: logger.debug("max_line_length not set in config, no need to run....
28,065
def assert_bake_ok(result: Result): """Check bake result is ok""" assert result.exit_code == 0 assert result.project_path.is_dir() assert result.project_path.is_dir()
28,066
def get_awb_shutter( f ): """ Get AWB and shutter speed from file object This routine extracts the R and B white balance gains and the shutter speed from a jpeg file made using the Raspberry Pi camera. These are stored as text in a custom Makernote. The autoexposure and AWB white balance valu...
28,067
def rgb2lab(rgb_arr): """ Convert colur from RGB to CIE 1976 L*a*b* Parameters ---------- rgb_arr: ndarray Color in RGB Returns ------- lab_arr: ndarray Color in CIE 1976 L*a*b* """ return xyz2lab(rgb2xyz(rgb_arr))
28,068
def format_rfidcard(rfidcard): """ :type rfidcard: apps.billing.models.RfidCard """ return { 'atqa': rfidcard.atqa if len(rfidcard.atqa) > 0 else None, 'sak': rfidcard.sak if len(rfidcard.sak) > 0 else None, 'uid': rfidcard.uid, 'registered_at': rfidcard.registered_at.is...
28,069
def make_exposure_shares(exposure_levels, geography="geo_nm", variable="rank"): """Aggregate shares of activity at different levels of exposure Args: exposure_levels (df): employment by lad and sector and exposure ranking geography (str): geography to aggregate over variable (str): varia...
28,070
def init_ranks(mpi_comm): """Returns rank information of the local process in `mpi_comm`. Args: mpi_comm (type:TODO) MPI Communicator from mpi4py Returns: rank_info (list): Elements are: * rank (`mpi_comm.rank`) * intra_rank (ran...
28,071
def boxscores(sports=["basketball/nba"], output="dict", live_only=True, verbose=False): """ ~ 10 seconds """ links = boxlinks(sports=sports, live_only=live_only, verbose=verbose) boxes = [boxscore(link) for link in links] return boxes
28,072
def pygame_loop(): """ To be called every iteration. Updates the screen if needed. """ global needs_update, message, robot_position, pen_down, pen_surface, show_robot # Go through events to check whether user has quit. for event in pygame.event.get(): if event.type == pygame.QUIT: #...
28,073
def test_encode_tags2(): """ Test encoding tags with TimeSeries """ with assert_raises(ValueError): TimeSeriesName.encode_metric("cpu", None) with assert_raises(ValueError) as ex: TimeSeriesName.encode_metric(None, {1: 2}) with assert_raises(ValueError) as ex: TimeSer...
28,074
def runningMedian(seq, M): """ Purpose: Find the median for the points in a sliding window (odd number in size) as it is moved from left to right by one point at a time. Inputs: seq -- list containing items for which a running median (in a sliding window) is t...
28,075
def min_max_normalize(img): """ Center and normalize the given array. Parameters: ---------- img: np.ndarray """ min_img = img.min() max_img = img.max() return (img - min_img) / (max_img - min_img)
28,076
def find_common_features(experiment: FCSExperiment, samples: list or None = None): """ Generate a list of common features present in all given samples of an experiment. By 'feature' we mean a variable measured for a particular sample e.g. CD4 or FSC-A (forward scatter) Paramete...
28,077
def propMove(*args, **kwargs): """ Performs a proportional translate, scale or rotate operation on any number of objects. Returns: None """ pass
28,078
def generate_blend_weights(positions, new_p, n_neighbors): """ Use inverse distance and K-Nearest-Neighbors Interpolation to estimate weights according to [Johansen 2009] Section 6.2.4 """ distances = [] for n, p in positions.items(): distance = np.linalg.norm(new_p - p) heapq.h...
28,079
def revert_rst(sitename, doc_name, directory=''): """reset a source document in the given directory to the previous contents raises AttributeError on missing document name FileNotFoundError if document doesn't exist FileNotFoundError if no backup present """ if not doc_name: ...
28,080
def check_method(adata): """Check that method output fits expected API.""" assert "connectivities" in adata.obsp assert "distances" in adata.obsp return True
28,081
def load_model(Model, params, checkpoint_path='', device=None): """ loads a model from a checkpoint or from scratch if checkpoint_path='' """ if checkpoint_path == '': model = Model(params['model_params'], **params['data_params']) else: print("model:", Model) ...
28,082
def uncom_ec2_sync_cmdb(): """没有使用合规的ami的ec2数据同步""" with DBContext('w') as session: uncom_ec2_list = get_uncom_ec2() session.query(UnComEc2).delete(synchronize_session=False) # 清空数据库的所有记录 for uncom_ec2 in uncom_ec2_list: instance_id = uncom_ec2["instance_id"] ami...
28,083
def install_miniconda(install_path): """Bootstrap miniconda to a given path.""" execute("bash miniconda.sh -b -p {}".format(install_path))
28,084
def get_widget_type_choices(): """ Generates Django model field choices based on widgets in holodeck.widgets. """ choices = [] for name, member in inspect.getmembers(widgets, inspect.isclass): if member != widgets.Widget: choices.append(( "%s.%s" % (member.__m...
28,085
def iau2000a(jd_tt): """Compute Earth nutation based on the IAU 2000A nutation model. `jd_tt` - Terrestrial Time: Julian date float, or NumPy array of floats Returns a tuple ``(delta_psi, delta_epsilon)`` measured in tenths of a micro-arcsecond. Each value is either a float, or a NumPy array with...
28,086
def numpy_ndarray(pa_arr): """Return numpy.ndarray view of a pyarrow.Array """ if pa_arr.null_count == 0: # TODO: would memoryview.cast approach be more efficient? see xnd_xnd. return pa_arr.to_numpy() pa_nul, pa_buf = pa_arr.buffers() raise NotImplementedError('numpy.ndarray view of...
28,087
async def _async_get_states_and_events_with_filter( hass: HomeAssistant, sqlalchemy_filter: Filters, entity_ids: set[str] ) -> tuple[list[Row], list[Row]]: """Get states from the database based on a filter.""" for entity_id in entity_ids: hass.states.async_set(entity_id, STATE_ON) hass.bus.a...
28,088
def decrypt_password(private_key: PrivateKey, encrypted: str) -> str: """Return decrypt the given encrypted password using private_key and the RSA cryptosystem. Your implementation should be very similar to the one from class, except now the public key is a data class rather than a tuple. """ n = p...
28,089
def load_jed(fn): """ JEDEC file generated by 1410/84 from PALCE20V8H-15 06/28/20 22:42:11* DM AMD* DD PALCE20V8H-15* QF2706* G0* F0* L00000 0000000000000000000000000100000000000000* """ ret = {} d = OrderedDict() with open(fn) as f: li = 0 for l in f: ...
28,090
def setup(client): """ Setup function for testing_cog extension Args: client (app.client.BotClient): Client that connects to discord API """ client.add_cog(TestCog(client))
28,091
def plaintext(text, keeplinebreaks=True): """Extract the text elements from (X)HTML content >>> plaintext('<b>1 &lt; 2</b>') u'1 < 2' >>> plaintext(tag('1 ', tag.b('<'), ' 2')) u'1 < 2' >>> plaintext('''<b>1 ... &lt; ... 2</b>''', keeplinebreaks=False) u'1 < 2' :param text: `...
28,092
def check_out_dir(out_dir, base_dir): """Creates the output folder.""" if out_dir is None: out_dir = pjoin(base_dir, default_out_dir_name) try: os.makedirs(out_dir, exist_ok=True) except: raise IOError('Unable to create the output directory as requested.') return out_dir
28,093
def test_nested_conditional_events(circuit): """Test tested conditional events (an edge case that nobody needs).""" cnt = edzed.Counter('counter') init(circuit) assert cnt.output == 0 cnt.event(edzed.EventCond(edzed.EventCond('inc', 'ERR'), None), value=True) assert cnt.output == 1 cnt.even...
28,094
def setup(): """Initial deployment setup""" _set_venv_name() run("mkvirtualenv {venv_name}".format(**env)) with cd(env.vhost_path): run('mkdir -p {shared_dirs}'.format(**env)) execute(setup_remote)
28,095
def fetch_rows(product): """ Returns the product and a list of timestamp and price for the given product in the current DATE, ordered by timestamp. """ # We query the data lake by passing a SQL query to maystreet_data.query # Note that when we filter by month/day, they need to be 0-padded strin...
28,096
def create_learner(sm_writer, model_helper): """Create the learner as specified by FLAGS.learner. Args: * sm_writer: TensorFlow's summary writer * model_helper: model helper with definitions of model & dataset Returns: * learner: the specified learner """ learner = None if FLAGS.l...
28,097
def train(env_id, num_timesteps, run, kappa, vf_phi_update_interval, log): """ Train TRPO model for the mujoco environment, for testing purposes :param env_id: (str) Environment ID :param num_timesteps: (int) The total number of samples :param seed: (int) The initial seed for training """ w...
28,098
def load_decoder(autoencoder): """ Gets the decoders associated with the inputted model """ dim = len(autoencoder.get_config()['input_layers']) mag_phase_flag = False decoders = [] if dim == 2: mag_phase_flag = True decoders.append(autoencoder.get_layer('mag_decoder')) ...
28,099