content
stringlengths
22
815k
id
int64
0
4.91M
def compile(): """ Compile C extension. """ subprocess.run(['gcc', '-shared', '-o', _c_ext_so_path, '-std=c99', '-fPIC', _c_ext_c_path], cwd=_dir_path)
31,000
def has_edit_metadata_permission(user, record): """Return boolean whether user can update record.""" return EditMetadataPermission(user, record).can()
31,001
def login_user(client, user): """Log in a specified user.""" with client.session_transaction() as sess: sess['user_id'] = user.id if user else None sess['_fresh'] = True
31,002
def truncate_chars_middle(text, limit, sep="..."): """ Truncates a given string **text** in the middle, so that **text** has length **limit** if the number of characters is exceeded, or else **len(text)** if it isn't. Since this is a template filter, no exceptions are raised when they would normally do....
31,003
def parse_block(block, site_name, site_num, year): """Parse a main data block from a BBC file""" # Cleanup difficult issues manually # Combination of difficult \n's and OCR mistakes replacements = {'Cemus': 'Census', 'Description of plot': 'Description of Plot', '...
31,004
def isempty(s): """ return if input object(string) is empty """ if s in (None, "", "-", []): return True return False
31,005
def get_client(host, port=None, username=None, password=None, tenant=None, auth_url=None, auth_strategy=None, auth_token=None, region=None, is_silent_upload=False, insecure=True, aws_access_key=None, aws_secret_key=None): """ Returns a ...
31,006
def raw(text): """Returns a raw string representation of text""" new_str = '' for char in text: try: new_str += trans_map[char] except KeyError: new_str += char return new_str
31,007
def airtovac(wave_air): """ taken from idl astrolib ;+ ; NAME: ; AIRTOVAC ; PURPOSE: ; Convert air wavelengths to vacuum wavelengths ; EXPLANATION: ; Wavelengths are corrected for the index of refraction of air under ; standard conditions. Wavelength values below...
31,008
def make_qa_plot(cset, kind='image', outfilen='qa_plot'): """ Generate Quality Assurance plots by visualizing each channel where significant emission occurs in the image cube of interest (i.e., `.image` or `.residual`). Parameters ---------- cset : CubeSet kind : str Kind of ima...
31,009
def clamp(val, min_, max_): """clamp val to between min_ and max_ inclusive""" if val < min_: return min_ if val > max_: return max_ return val
31,010
def plot_confusion_matrix(cm, labels=3, fname=''): """Plot the confusion matrix and save to file Args: cm (np.ndarray): The confusion matrix labels (int): Number of labels fname (str): Path to file for saving """ disp = ConfusionMatrixDisplay(confusion_matrix=cm, dis...
31,011
def GetUserLink(provider, email): """Retrieves a url to the profile of the specified user on the given provider. Args: provider: The name of the provider email: The email alias of the user. Returns: Str of the url to the profile of the user. """ user_link = '' if email and provider == Provider....
31,012
def _as_bytes0(path): """Crashes translation if the path contains NUL characters.""" res = _as_bytes(path) rstring.check_str0(res) return res
31,013
def updateCompareProjectShoppingList(): """Updates the shopping list for the working project in the compareTab""" treeOutput = alltreeCompareProject workingProject = selectedCompareProject2.get() result = JobMaterials.getAllProjectMaterials(workingProject) alltreeCompareProject.delete(*al...
31,014
def get_ip(request): """Determines user IP address Args: request: resquest object Return: ip_address: requesting machine's ip address (PUBLIC) """ ip_address = request.remote_addr return ip_address
31,015
def _is_valid_new_style_arxiv_id(identifier): """Determine if the given identifier is a valid new style arXiv ID.""" split_identifier = identifier.split('v') if len(split_identifier) > 2: return False elif len(split_identifier) == 2: identifier, version = split_identifier if not...
31,016
def download_suite(request, domain, app_id): """ See Application.create_suite """ if not request.app.copy_of: request.app.set_form_versions(None) return HttpResponse( request.app.create_suite() )
31,017
def get_graph(mol): """ Converts `rdkit.Chem.Mol` object to `PreprocessingGraph`. """ if mol is not None: if not C.use_aromatic_bonds: rdkit.Chem.Kekulize(mol, clearAromaticFlags=True) molecular_graph = PreprocessingGraph(molecule=mol, constants=C) return molecul...
31,018
def dict_fetchall(cursor): """ Returns all rows from a cursor as a dict """ desc = cursor.description return [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ]
31,019
def test_tvh_widget_popup(tvh_manager): """Test the popup displays the correct information.""" tvh_manager.c.bar["top"].fake_button_press(0, "top", 0, 0, 1) _, text = tvh_manager.c.widget["tvhwidget"].eval("self.popup.text") assert text == ( "Upcoming recordings:\n" "Fri 26 Nov 18:55: TV...
31,020
def count_vowels(s): """Used to count the vowels in the sequence""" s = s.lower() counter=0 for x in s: if(x in ['a','e','i','o','u']): counter+=1 return counter
31,021
def _is_valid_dtype(matrix, complex_dtype=False, all_dtype=False): """ Check to see if it's a usable float dtype """ if all_dtype: return matrix.dtype in NUMPY_FLOAT_DTYPES + NUMPY_COMPLEX_DTYPES elif complex_dtype: return matrix.dtype in NUMPY_COMPLEX_DTYPES else: return matrix....
31,022
def test_health_check_custom_check(): """ Should return Custom health check results. """ loader = load_from_dict( health_convention=dict( include_build_info="false", ), ) graph = create_object_graph(name="example", testing=True, loader=loader) graph.use("health_c...
31,023
def assess_edge(self, edge, fsmStack, request, **kwargs): """ Try to transition to ASSESS, or WAIT_ASSESS if not ready, or jump to ASK if a new question is being asked. """ fsm = edge.fromNode.fsm if not fsmStack.state.linkState: # instructor detached return fsm.get_node('END') elif...
31,024
def viable_source_types_for_generator_real (generator): """ Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators) """ source_types = generator.source_types () if not s...
31,025
def negSamplingCostAndGradient(predicted, target, outputVectors, dataset, K=10): """ Negative sampling cost function for word2vec models Implement the cost and gradients for one predicted word vector and one target word vector as a building block for word2vec models, usin...
31,026
def get_start_block(block): """ Gets the deepest block to use as the starting block. """ if not block.get('children'): return block first_child = block['children'][0] return get_start_block(first_child)
31,027
def transform_rank_list(lam_ref, A, b, rank): """ A is a list here. We sum the first `rank` elements of it to return a matrix with the desired rank. """ _A = sum(A[0:rank]) _b = b _d = _A @ lam_ref + _b assert np.linalg.matrix_rank(_A) == rank, "Unexpected rank mismatch" return _A, _...
31,028
def FindWindowsWithTitle(title_to_search): """Finds windows with given title. Args: title_to_search: Window title substring to search, case-insensitive. Returns: A list of HWND that match the search condition. """ desktop_handle = None return FindWindowsWithText(desktop_handle, title_to_search)
31,029
def main_update(next_image_step): """ This includes some functionality for image / file writing at a specified frequency, Assumes global variables: time, step, files_freq, next_image_step if numerical dt exceeds next specified writing point override dt make sure we hit that point ...
31,030
def record(packets: Iterable[Packet], pcap_path: str, *, src_ip: str = "127.0.0.1", dst_ip: str = "127.0.0.1", lidar_port: int = 7502, imu_port: int = 7503, use_sll_encapsulation: bool = False) -> int: """Record a sequence of sensor packet...
31,031
def assemble_batches(inputs, crop_mode='center_only'): """ Assemble DataFrame of image crops for feature computation. Input: inputs: list of filenames (center_only, corners, and selective_search mode) OR input DataFrame (list mode) mode: string 'list': take the image windows from the input as...
31,032
def __VF2_feasible(graph1, graph2, vertex1, vertex2, map21, map12, terminals1, terminals2, subgraph): """ Returns :data:`True` if two vertices `vertex1` and `vertex2` from graphs `graph1` and `graph2`, respectively, are feasible matches. `mapping21` and `mapping12` are the current state of the mappi...
31,033
async def place_rectangle( interface, element, x, y, width, height, include_all_sides=True, variant=None ): """Place a rectangle of an element. Parameters ---------- interface The editor interface. x X coordinate of the upper left corner. y Y coordinate of the upper ...
31,034
def rainbow_strokes(strokes: bpy.types.GPencilStrokes): """ strokesのインデックスに合せて頂点カラーを設定します """ n = [colorize_stroke(stroke, i, True) for i, stroke in enumerate(strokes)] return n # logger.debug(f"update:{sum(n)}") # logger.debug(rainbow.cache_info())
31,035
def calc_Q_hat_hs_d_t(Q, A_A, V_vent_l_d_t, V_vent_g_i, mu_H, mu_C, J_d_t, q_gen_d_t, n_p_d_t, q_p_H, q_p_CS, q_p_CL, X_ex_d_t, w_gen_d_t, Theta_ex_d_t, L_wtr, region): """(40-1a)(40-1b)(40-2a)(40-2b)(40-2c)(40-3) Args: Q: 当該住戸の熱損失係数(W/(m2・K)) A_A: 床面積の合計(m2) V_vent_l_d_t: 日付dの時刻tにおける局所換気量(m3...
31,036
def test_install_galaxy_role(runtime_tmp: Runtime) -> None: """Check install role with empty galaxy file.""" pathlib.Path(f"{runtime_tmp.project_dir}/galaxy.yml").touch() pathlib.Path(f"{runtime_tmp.project_dir}/meta").mkdir() pathlib.Path(f"{runtime_tmp.project_dir}/meta/main.yml").touch() # this s...
31,037
def test_runrecipe_load_valid() -> None: """Test loading a valid run recipe from file.""" with open(RUNRECIPE_VALID) as fp: assert RunRecipe.load_from_file(fp) == RunRecipe( script=["ping example.com", "git init"], ports=[(3, 2), (7, 204)], sockets=[("/var/opt/example...
31,038
def get_all_infoproviders(): """ Endpunkt `/infoproviders`. Response enthält Informationen über alle, in der Datenbank enthaltenen, Infoprovider. """ try: return flask.jsonify(queries.get_infoprovider_list()) except Exception: logger.exception("An error occurred: ") err ...
31,039
def maidenhead(dec_lat, dec_lon): """Convert latitude and longitude to Maidenhead grid locators.""" try: dec_lat = float(dec_lat) dec_lon = float(dec_lon) except ValueError: return '' if _non_finite(dec_lat) or _non_finite(dec_lon): return '' if 90 < math.fabs(dec_la...
31,040
def parse_worker_string(miner, worker): """ Parses a worker string and returns the coin address and worker ID Returns: String, String """ worker_part_count = worker.count(".") + 1 if worker_part_count > 1: if worker_part_count == 2: coin_address, worker = worker.s...
31,041
def test_table_answer_element_deser_no_rows(): """Check deserialization creates empty table when no rows are present.""" answer = { "answerElements": [ {"metadata": {"columnMetadata": [{"name": "col1", "schema": "Node"}]}} ] } table = TableAnswer(answer) assert len(table...
31,042
def get_inference_sequence(file_path): """ :param file_path: path of 2D bounding boxes :return: """ with open(file_path + '.json', 'r') as f: detected_bdbs = json.load(f) f.close() boxes = list() for j, bdb2d in enumerate(detected_bdbs): box = bdb2d['bbox'] ...
31,043
def _DC_GetBoundingBox(self): """ GetBoundingBox() -> (x1,y1, x2,y2) Returns the min and max points used in drawing commands so far. """ return (self.MinX(), self.MinY(), self.MaxX(), self.MaxY())
31,044
def map_text( text: Union[str, Text, Iterable[str], Iterable[Text]], mapping: StringMapper ) -> Union[str, List[str]]: """ Replace text if it matches one of the dictionary keys. :param text: Text instance(s) to map. :param mapping: Mappings to replace text. """ if isinstance(tex...
31,045
def _load_components(config: ConfigType) -> ConfigType: """Load the different componenets in a config Args: config (ConfigType) Returns: ConfigType """ special_key = "_load" if config is not None and special_key in config: loaded_config = read_config_file(config.pop(spe...
31,046
def _value_to_variant(value: typing.Union[bytes, int, float, str]) -> GLib.Variant: """ Automatically convert a Python value to a GLib.Variant by guessing the matching variant type. """ if isinstance(value, bool): return GLib.Variant("b", value) elif isinstance(value, bytes): re...
31,047
def demo(num_sents=2000, max_rules=200, min_score=3, error_output="errors.out", rule_output="rules.yaml", randomize=False, train=.8, trace=3): """ Brill Tagger Demonstration :param num_sents: how many sentences of training and testing data to use :type num_sents: int :param max_ru...
31,048
def ha_rise_set(el_limit, lat, dec): """ Hour angle from transit for rising and setting. Returns pi for a source that never sets and 0 for a source always below the horizon. @param el_limit : the elevation limit in radians @type el_limit : float @param lat : the observatory latitude in radians @type...
31,049
def create(transactions, user=None): """# Create Transactions Send a list of Transaction objects for creation in the Stark Bank API ## Parameters (required): - transactions [list of Transaction objects]: list of Transaction objects to be created in the API ## Parameters (optional): - user [Proje...
31,050
def get_quote(symbol): """ Returns today's stock price """ contents = get_content(symbol) return contents('.time_rtq_ticker span').text()
31,051
def load_pil(data, is_file = False): """ Parses a string or file written in PIL notation! """ # We only assign reactions in a postprocessing step, # because there are no macrostates in nuskell. set_io_objects(D = NuskellDomain, C = NuskellComplex) out = dsd_read_pil(data, is_file) clear_io_objec...
31,052
def get(obj, key, default=None, pattern_default=(), apply_transforms=True): """ Get a value specified by the dotted key. If dotted is a pattern, return a tuple of all matches >>> d = {'hello': {'there': [1, '2', 3]}} >>> get(d, 'hello.there[1]|int') 2 >>> get(d, 'hello.there[1:]') ['2', ...
31,053
def movep(src, dst, overlay = True): """ 移動文件 overlay: True / False, True為自動覆蓋 """ if not os.path.isdir(dst): raise TypeError("dst must be a directory.") # 移動文件 if os.path.isfile(src): dst_dir = os.path.join(dst, os.path.basename(src)) if os.path.exists(dst_dir):...
31,054
def write_proba_predictions(ids, y_proba_pred, predpath=os.path.join(data_path, 'id_ssl.csv')): """Write the probability of belonging to each class in a csv file.""" assert len(ids) == y_proba_pred.shape[0] with open(predpath, 'w') as f: f.write('Id,Class1,Class2,Class3,C...
31,055
def str_view(request): """ A simple test view that returns a string. """ return '<Response><Message>Hi!</Message></Response>'
31,056
def _run_script(script, start_with_ctty, args, kwargs): """ Meant to be called inside a python subprocess, do NOT call directly. """ enter_pty(start_with_ctty) result = script(*args, **kwargs) # Python-spawned subprocesses do not call exit funcs - https://stackoverflow.com/q/34506638/29078...
31,057
def get_feed_list(feeds): """ Return List of Proto Feed Object """ feeds_pb_list = [feeds_pb2.Feed(**_get_valid_fields_feed(feed)) for feed in feeds] return feeds_pb2.FeedList(data=feeds_pb_list)
31,058
def group_interpellet_interval_plot(FEDs, groups, kde, logx, **kwargs): """ FED3 Viz: Plot the interpellet intervals as a histogram, first aggregating the values for devices in a Groups. Parameters ---------- FEDs : list of FED3_File objects FED3 files (loaded by load.FED3_File) gro...
31,059
def filter(args): """ %prog filter frgfile idsfile Removes the reads from frgfile that are indicated as duplicates in the clstrfile (generated by CD-HIT-454). `idsfile` includes a set of names to include in the filtered frgfile. See apps.cdhit.ids(). """ p = OptionParser(filter.__doc__) ...
31,060
def _beta(x, p): """Helper function for `pdf_a`, beta = pi * d(1 - omega(x), omega(p)).""" omega = _amplitude_to_angle return np.pi * _circ_dist(1 - omega(x), omega(p))
31,061
def set_reporting_max_width(w): """ Set the max width for reported parameters. This is used to that failures don't overflow terminals in the event arguments are dumped. :param w: The new max width to enforce for the module :type w: int :return: True """ _REPR_MAX_WIDTH[0] = int(w) r...
31,062
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
31,063
def get_mnsp_offer_index(data) -> list: """Get MNSP offer index""" interconnectors = (data.get('NEMSPDCaseFile').get('NemSpdInputs') .get('PeriodCollection').get('Period') .get('InterconnectorPeriodCollection') .get('InterconnectorPeriod')) ...
31,064
def main() -> None: """ Executes the main bulk of this function. :raises RuntimeError: If something goes wrong. """ if len(_ROUTE) == 0: raise RuntimeError('The route must contain at least one location') if _NOW.time() > _DAY_END: raise RuntimeError('There are no more working h...
31,065
def _find_clusters( data, cluster_range: Tuple[int, int] = None, metric: str = "silhouette_score", target=None, **kwargs, ): """Finds the optimal number of clusters for K-Means clustering using the selected metric. Args: data: The data. cluster_range: A tuple of the minimum ...
31,066
def _gate_objectives_li_pe(basis_states, gate, H, c_ops): """Objectives for two-qubit local-invariants or perfect-entangler optimizaton""" if len(basis_states) != 4: raise ValueError( "Optimization towards a two-qubit gate requires 4 basis_states" ) # Bell states as in "Theor...
31,067
def get_pip_package_list(path: str) -> Generator[pkg_resources.Distribution, None, None]: """Get the Pip package list of a Python virtual environment. Must be a path like: /project/venv/lib/python3.9/site-packages """ packages = pkg_resources.find_distributions(path) return packages
31,068
def write_ruassump(rufail,rulist): """Writes rectifier environment assumption Parameters ---------- rufail : int how many rectifiers may fail at once time genlist : list of all generators """ if len(rulist) > 0: f.write('assumptions += '"'"'&\\n\\t[]((ru'+str(rulist[0])) ...
31,069
def hasGLUExtension( specifier ): """Given a string specifier, check for extension being available""" from OpenGL.GLU import gluGetString, GLU_EXTENSIONS if not AVAILABLE_GLU_EXTENSIONS: AVAILABLE_GLU_EXTENSIONS[:] = gluGetString( GLU_EXTENSIONS ) return specifier.replace(as_8_bit('.'),as_8_bit(...
31,070
def do_slots_information(parser, token): """Calculates some context variables based on displayed slots. """ bits = token.contents.split() len_bits = len(bits) if len_bits != 1: raise TemplateSyntaxError(_('%s tag needs no argument') % bits[0]) return SlotsInformationNode()
31,071
def get_region_of_interest(img, sx=0.23, sy=0.15, delta=200, return_vertices=False): """ :param img: image to extract ROI from :param sx: X-axis factor for ROI bottom base :param sy: Y-axis factor for ROI top base :param delta: ROI top base length :param return_vertices: whether to return the RO...
31,072
def load_search_freq(fp=SEARCH_FREQ_JSON): """ Load the search_freq from JSON file """ try: with open(fp, encoding="utf-8") as f: return Counter(json.load(f)) except FileNotFoundError: return Counter()
31,073
def _sum_of_squares(a, axis=0): """ Square each element of the input array, and return the sum(s) of that. Parameters ---------- a : array_like Input array. axis : int or None, optional Axis along which to calculate. Default is 0. If None, compute over the whole array `a...
31,074
def assert_equal(actual: numpy.ndarray, desired: list): """ usage.orange3: 1 usage.scipy: 7 usage.statsmodels: 1 usage.xarray: 1 """ ...
31,075
def get_preprocess_fn(pp_pipeline, remove_tpu_dtypes=True): """Transform an input string into the preprocessing function. The minilanguage is as follows: fn1|fn2(arg, arg2,...)|... And describes the successive application of the various `fn`s to the input, where each function can optionally have one or m...
31,076
def check_udev_properties(yaml_data, uinput): """ Compare the properties our new uinput device has with the ones from the recording and ring the alarm bell if one of them is off. """ yaml_udev_section = fetch(yaml_data, "udev") yaml_udev_props = fetch(yaml_udev_section, "properties") yaml_pr...
31,077
def check_with(ctx, check, what, *args, **kwargs): """ Perform `check`, also looking at directories specified by the --with-X commandline option and X_HOME environment variable (X = what.upper()) The extra_args """ import os from os.path import abspath # adds 'extra_paths' and oth...
31,078
def mock_successful_encode_job(mocker): """Mock everything required for a successful transcode""" mocker.patch("cloudsync.api.VideoTranscoder.encode") mocker.patch( "cloudsync.api.get_et_job", return_value={"Id": "1498220566931-qtmtcu", "Status": "Complete"}, )
31,079
def nodeset(v): """Convert a value to a nodeset.""" if not nodesetp(v): raise XPathTypeError, "value is not a node-set" return v
31,080
def get_char_embs(char_emb_path, char_emb_size, alphabet_size=1422): """Get pretrained character embeddings and a dictionary mapping characters to their IDs. Skips IDs 0 and 1, since these are reserved for PAD and UNK, respectively. Input: char_emb_path: path to glove.840B.{char_embedding_size}d-char...
31,081
def _get_reverse_complement(seq): """ Get the reverse compliment of a DNA sequence. Parameters: ----------- seq Returns: -------- reverse_complement_seq Notes: ------ (1) No dependencies required. Pure python. """ complement_seq = "" for i in seq...
31,082
def wave_reduce_min_all(val): """ All threads get the result """ res = wave_reduce_min(val) return broadcast(res, 0)
31,083
def predict_class(all_headlines): """ Predict whether each headline is negative or positive. :param all_headlines: all headlines :return: headlines with predictions """ clf, v = load_classifier("SVM") headlines = [] for h in all_headlines: headlines.append(h.to_array()) df...
31,084
def find_tickets_for_seat_manager( user_id: UserID, party_id: PartyID ) -> list[DbTicket]: """Return the tickets for that party whose respective seats the user is entitled to manage. """ return db.session \ .query(DbTicket) \ .filter(DbTicket.party_id == party_id) \ .filter(D...
31,085
def insert_features_from_iters(dataset_path, insert_features, field_names, **kwargs): """Insert features into dataset from iterables. Args: dataset_path (str): Path of the dataset. insert_features (iter of iter): Collection of iterables representing features. field_names (it...
31,086
def test_solution() -> None: """Solution to Challenge 3.""" ct = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" pt = b"Cooking MC's like a pound of bacon" ct_bytes = bytes.fromhex(ct) key = attacks.find_single_xor_key(ct_bytes) assert ciphers.SingleXor(key).decrypt(ct_byt...
31,087
def test_failed_resolve(webapp): """Test basic failure to resolve an IP for a domain - because it's unregistered. """ domain = 'imprettysurethatthisdomaindoesnotexist.com' response = webapp.get('/api/ip/{}'.format(Domain(domain).to_hex())) assert response.status_code == 200 assert response....
31,088
def check_table(conn, table, interconnect): """ searches if Interconnect exists in table in database :param conn: connect instance for database :param table: name of table you want to check :param interconnect: name of the Interconnect you are looking for :return: results of SQL query searching...
31,089
def ensure_folder(path: str): """Read the file path and recursively create the folder structure if needed.""" folder_path: str = dirname(realpath(path)) make_dirs(folder_path)
31,090
def get_host_config_tar_response(host): """ Build the tar.gz attachment response for the GetHostConfig view. Note: This is re-used to download host config from the admin interface. :returns: HttpResponseAttachment """ filename = '{host}_v{version}.tar.gz'.format( host=host....
31,091
def deploy(*slugs): """ Deploy the latest app(s) to S3 and, if configured, to our servers. """ if slugs[0] == '': print 'You must specify at least one slug, like this: "deploy:slug" or "deploy:slug,slug"' return for slug in slugs: deploy_single(slug)
31,092
async def update_product_remove_tag_by_id( *, product_id: int, session: Session = Depends(get_session), db_product: Product = Depends(get_product_or_404), db_tag: Tag = Depends(get_tag_or_404), ): """ Remove tag from product """ existing_product = db_product["db_product"] existin...
31,093
def aggregate_results_data(results, include_raw=False): """This function aggregates the results of an archive/unarchive operation into an easy-to-parse dictionary. .. versionchanged:: 4.1.1 This function can now properly handle the ``ARCHIVED`` status when returned. .. versionadded:: 4.1.0 :pa...
31,094
def post_save_create_interaction_activity(sender, instance, created, **kwargs): """ """ if created: RebuzzInteractions.objects.create(rebuzz=instance) RebuzzNotification.objects.create(rebuzz=instance, user=instance.author) _create_activity( instance.author, User...
31,095
def checkpoint_valid(epoch: int): """Create a checkpoint for a valid run.""" model_out_path = "model_valid_{}.pth".format(epoch) torch.save(model, model_out_path) logger.debug("Checkpoint saved to {}".format(model_out_path))
31,096
def hard_sigmoid(x: tf.Tensor) -> tf.Tensor: """Hard sigmoid activation function. ```plot-activation activations.hard_sigmoid ``` # Arguments x: Input tensor. # Returns Hard sigmoid activation. """ return tf.clip_by_value(x+0.5, 0.0, 1.0)
31,097
def get_image_as_np_array(filename: str): """Returns an image as an numpy array """ img = Image.open(filename) return np.asarray(img)
31,098
def update_move_local_plot(): """ This function just keeps our local plot moves off the same drive as our remote plot moves so we don't saturate a single drive with multiple inbound plots. """ log.debug("update_move_local_plot() Started") try: if chianas.current_internal_drive == get_in...
31,099