content
stringlengths
22
815k
id
int64
0
4.91M
async def sayd(ctx, *, message: str): """Botに喋らせます(メッセージは自動で削除されます)""" await ctx.send(message) # message can't be deleted in private channel(DM/Group) if not isinstance(ctx.message.channel, discord.abc.PrivateChannel): await ctx.message.delete()
5,332,900
def barycenter_wbc(P, K, logweights, Kb=None, c=None, debiased=False, maxiter=1000, tol=1e-4): """Compute the Wasserstein divergence barycenter between histograms. """ n_hists, width, _ = P.shape if Kb is None: b = torch.ones_like(P)[None, :] Kb = convol_huge_imgs(b, K...
5,332,901
def compute_compensation(line1, line2): """Compute compensation statistic betwen two lines. Explain the stat. Parameters ---------- line1 : ndarray First surface to use (two-dimensional matrix with x-z coordinates of line). line2 : ndarray Second surface to use (two-di...
5,332,902
def syllable_fingerprint(word): """ Use the pronuncation dict to map the potential syllable stress patterns of a word to a ternary string "fingerprint" 0 is a syllable that must be unstressed 1 is a syllable that must be stressed x is a syllable that may be stressed or unstressed e.g. pyth...
5,332,903
def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresp...
5,332,904
def score_matrix(motifs, k): """returns matrix score formed from motifs""" nucleotides = {'A': [0]*k, 'T': [0]*k, 'C': [0]*k, 'G': [0]*k} for motif in motifs: for index, nucleotide in enumerate(motif): nucleotides[nucleotide][index] = nucleotides[nucleotide][index] + 1 i = 0 matr...
5,332,905
def log_loss(y_true, dist_pred, sample=True, return_std=False): """ Log loss Parameters ---------- y_true: np.array The true labels dist_pred: ProbabilisticEstimator.Distribution The predicted distribution sample: boolean, default=True If true, loss will be averaged acro...
5,332,906
def matrix_pencil_method_old(data, p, noise_level=None, verbose=1, **kwargs): """ Older impleentation of the matrix pencil method with pencil p on given data to extract energy levels. Parameters ---------- data -- lists of Obs, where the nth entry is considered to be the correlation function ...
5,332,907
def createDataset(outputPath, imagePathList, labelList, lexiconList=None, checkValid=True): """ Create LMDB dataset for CRNN training. ARGS: outputPath : LMDB output path imagePathList : list of image path labelList : list of corresponding groundtruth texts lexiconList...
5,332,908
def ext_sum(text, ratio=0.8): """ Generate extractive summary using BERT model INPUT: text - str. Input text ratio - float. Enter a ratio between 0.1 - 1.0 [default = 0.8] (ratio = summary length / original text length) OUTPUT: summary - str. Generated summary """ bert_...
5,332,909
def khinalug_input_normal(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace common shortcuts with valid Khinalug characters. """ if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'): return text text = text.replace('c1_', 'č̄') ...
5,332,910
def run(command, instance_size=None): """Runs the given script in foreground. """ project = projects.current_project() job = project.run(command, instance_size=instance_size) print("Started new job", job["jobid"])
5,332,911
def _shift_all_classes(classes_list: List[ndarray], params_dict: Dict[str, Any]): """Shift the locale of all classes. Args: classes_list: List of classes as numpy arrays. params_dict: Dict including the shift values for all classes. Returns: List of shifted classes. """ cl...
5,332,912
def fully_connected_layer(tensor, size=None, weight_init=None, bias_init=None, name=None): """Fully connected layer. Parameters ---------- tensor: tf.Tensor Input tensor. size: int Number of output...
5,332,913
def fetch_osborne_magnetic(version): """ Magnetic airborne survey of the Osborne Mine and surroundings, Australia This is a section of a survey acquired in 1990 by the Queensland Government, Australia. The line data have approximately 80 m terrain clearance and 200 m line spacing. Total field anoma...
5,332,914
def setup(bot: Bot) -> None: """Set up the Internal Eval extension.""" # Import the Cog at runtime to prevent side effects like defining # RedisCache instances too early. from ._internal_eval import InternalEval bot.add_cog(InternalEval(bot))
5,332,915
def lambdify(args, expr, modules=None, printer=None, use_imps=True, dummify=False): """ Returns an anonymous function for fast calculation of numerical values. If not specified differently by the user, ``modules`` defaults to ``["scipy", "numpy"]`` if SciPy is installed, ``["numpy"]`` if o...
5,332,916
def VerifyVersionOfBuiltClangMatchesVERSION(): """Checks that `clang --version` outputs RELEASE_VERSION. If this fails, update.RELEASE_VERSION is out-of-date and needs to be updated (possibly in an `if args.llvm_force_head_revision:` block inupdate. main() first).""" clang = os.path.join(LLVM_BUILD_DIR, 'bin', ...
5,332,917
def cfg_from_file(filename): """Load a config file and merge it into the default options.""" with open(filename, 'r') as f: yaml_cfg = EasyDict(yaml.load(f)) _merge_a_into_b(yaml_cfg, cfg)
5,332,918
def _SetEvenLength(options, paths): """Use the bounding box of paths to set even_length in options. We want the option.smoothness parameter to control the length of segments that we will try to divide Bezier curves into when using the EVEN method. More smoothness -> shorter length. But the user sh...
5,332,919
def _matches(o, pattern): """Match a pattern of types in a sequence.""" if not len(o) == len(pattern): return False comps = zip(o,pattern) return all(isinstance(obj,kind) for obj,kind in comps)
5,332,920
def excl_import_route(): """import exclustions from csv""" form = ExclImportForm() if form.validate_on_submit(): imported = [] try: for row in csv.DictReader(StringIO(form.data.data), EXPORT_FIELDNAMES, quoting=csv.QUOTE_MINIMAL): imported.append(Excl(family=Excl...
5,332,921
def test_join_memoization(): """Testing python memoization disable """ x = random_uuid(0) x.result() for i in range(0, 2): foo = random_uuid(0) assert foo.result() == x.result(), "Memoized results were not used"
5,332,922
def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal and keyword arguments to connect:: @receiver(signal_object, sender=sender) def signal_receiver(sender, **kwargs): ... """ def _decorator(func): sig...
5,332,923
def create_new_connected_component(dict_projections, dict_cc, dict_nodes_cc, g_list_, set_no_proj, initial_method, params, i, file_tags=None): """ If needed, create new connect component and update wanted dicts. :param dict_projections: Embedding dict :param dict_cc: D...
5,332,924
def _run_voice_detection_angle(): """ Private: create a thread to poll the Mic Array and set the DOA Global Variable """ print("EARS | Voice Detection | Voice Detection Loop Starting") print("EARS | Voice Detection | VAD: ", vad_threshold) # Counter to implement simple trigger for publishing to ...
5,332,925
def test_problem_61(answer): """ test_problem_61(answer) :return: """ from euler_python.easy import p061 output = p061.problem061() expected_output = answer['Problem 061'] assert output == expected_output
5,332,926
def test_do_status(config, mocker): """Verify that the Bundler has no additional state to offer.""" logger_mock = mocker.MagicMock() p = Bundler(config, logger_mock) assert p._do_status() == {}
5,332,927
def do_eval(dataset=None, network=None, metric=None, load_checkpoint_path="", eval_type=None, tokenizer_file_path="", generate_length=1, top_k=1, top_p=1.0, temperature=1.0): """ Do evaluation on Translation Args: dataset: the eval dataset. network: the network with loss. ...
5,332,928
def laguerre(x, k, c): """Generalized Laguerre polynomials. See `help(_gmw.morsewave)`. LAGUERRE is used in the computation of the generalized Morse wavelets and uses the expression given by Olhede and Walden (2002), "Generalized Morse Wavelets", Section III D. """ x = np.atleast_1d(np.asarray(...
5,332,929
def EGshelfIIseas2km_ERAI(daily = False, gridpath = '/home/idies/workspace/OceanCirculation/exp_ERAI/grid_glued.nc', kppspath = '/home/idies/workspace/OceanCirculation/exp_ERAI/kpp_state_glued.nc', fldspath = '/home/idies/workspace/Oc...
5,332,930
def generate_pkl_features_from_fasta( fasta_path: str, name: str, output_dir: str, data_pipeline: DataPipeline, timings: Optional[Dict[str, float]] = None): """Predicts structure using Uni-Fold for the given sequence.""" if timings is None: timings = {} ...
5,332,931
def find_all_combinations(participants, team_sizes): """ Finds all possible experience level combinations for specific team sizes with duplicated experience levels (e.g. (1, 1, 2)) Returns a list of tuples representing all the possible combinations """ num_teams = len(team_sizes) participant_levels...
5,332,932
def debug_callback(callback: Callable[..., Any], effect: DebugEffect, *args, **kwargs): """Calls a stageable Python callback. `debug_callback` enables you to pass in a Python function that can be called inside of a staged JAX program. A `debug_callback` follows existing JAX transformation *p...
5,332,933
def normalized_copy(data): """ Normalize timeseries data, using the maximum across all regions and timesteps. Parameters ---------- data : xarray Dataset Dataset with all non-time dependent variables removed Returns ------- ds : xarray Dataset Copy of `data`, with the a...
5,332,934
def test_constructor_missing_config(): """Fail with a TypeError if a configuration object isn't provided.""" with pytest.raises(TypeError): Unpacker()
5,332,935
def _get_exception(ex: Exception) -> Exception: """Get exception cause/context from chained exceptions :param ex: chained exception :return: cause of chained exception if any """ if ex.__cause__: return ex.__cause__ elif ex.__context__: return ex.__context__ else: re...
5,332,936
def recursive_normalizer(value: Any, **kwargs: Dict[str, Any]) -> Any: """ Prepare a structure for hashing by lowercasing all values and round all floats """ digits = kwargs.get("digits", 10) lowercase = kwargs.get("lowercase", True) if isinstance(value, (int, type(None))): pass el...
5,332,937
def send_admin_logfile(subject, log_name): """ Send the System Administrator a log file, using the contents of the log file as the body of the email. Args: subject - The subject line for the email log_name - The name of the log file """ #TODO safty check the log size and send on...
5,332,938
def SimInterfMeasPuls(Stokes,ofnPrefix,SN,nomPolPur,deltaJAmp, rxnoise=1., skynoise=0.): """Simulate an interferometer measurement of the pulsar profile Stokes spectrum, and writes spectrum to text file inputs: Stokes: template Stokes specturm ofnPrefix: output filename prefix, two files are wr...
5,332,939
def rip_and_tear(context) -> Set: """Edge split geometry using specified angle or unique mesh settings. Also checks non-manifold geometry and hard edges. Returns set of colors that are used to color meshes.""" processed = set() angle_use_fixed = prefs.RenderFixedAngleUse # Angle fixed in radia...
5,332,940
def test_validate_declarative_1(): """ Test that we reject children that are not type in enamldef. This also serves to test the good working of try_squash_raise. """ source = dedent("""\ from enaml.widgets.api import * a = 1 enamldef Main(Window): a: pass """) ...
5,332,941
def clean_files(): """Delete unnecessary files.""" flist = [ 'move_to_box.geo', 'temp.geo', 'temp.brep', ] for fil in flist: if os.path.exists(fil): os.remove(fil)
5,332,942
def process_signature(app, _, name, obj, *other_ignored_args): """A callback for each signature in the docs. Here, we build a map of the various config field names to their Field objects so that we can later override the documentation for those types in process_doc_nodes. For full documentation on this call...
5,332,943
def generate_primes(d): """Generate a set of all primes with d distinct digits.""" primes = set() for i in range(10**(d-1)+1, 10**d, 2): string = str(i) unique_string = "".join(set(string)) if len(string) == len(unique_string): # Check that all digits are unique if isprim...
5,332,944
def poinv(A, UPLO='L', workers=1, **kwargs): """ Compute the (multiplicative) inverse of symmetric/hermitian positive definite matrices, with broadcasting. Given a square symmetic/hermitian positive-definite matrix `a`, return the matrix `ainv` satisfying ``matrix_multiply(a, ainv) = matrix_mul...
5,332,945
def logs(timestamp, function_name, task): """ This is a custom function which generates logs in this format: timestamp --> function_name --> task --> status All the logs are displayed on the screen and is also saved in files for later uses. :param timestamp: current date and time :param function_nam...
5,332,946
def parse_ip_element(ip_element, vulnerability_dictionary): """ Looks at every IP element to get the IP address value, get the infos/services/vulns nodes and calls other functions. :param ip_element: DOM Node object :param vulnerability_dictionary: dictionary of vulnerabilities """ ip...
5,332,947
def gen_task3() -> np.ndarray: """Task 3: centre of cross or a plus sign.""" canv = blank_canvas() r, c = np.random.randint(GRID-2, size=2, dtype=np.int8) # Do we create a cross or a plus sign? syms = rand_syms(5) # a 3x3 sign has 2 symbols, outer and centre # syms = np.array([syms[0], syms[0], syms[1], sym...
5,332,948
def test_parameter_shape(): """ Make sure that parameter initialization produces the correct parameter shapes """ X = np.array([1, 2, 3, 4]).reshape((1, -1)) y = np.array([1, 2, 3, 4]).reshape((1, -1)) model = JENN(hidden_layer_sizes=(2, 2)) model._n_x = X.shape[0] model._n_y = y.sha...
5,332,949
def init_susceptible_00(): """ Real Name: b'init Susceptible 00' Original Eqn: b'8e+06' Units: b'person' Limits: (None, None) Type: constant b'' """ return 8e+06
5,332,950
def test_store_records_str_and_repr(): """ StoreRecords: __str__ and __repr__ methods return the same string. """ msg = StoreRecords("logs", records=iter([]), wrapped=False) assert str(msg) == f"<StoreRecords:logs:wrapped=False:records_number=0>" assert repr(msg) == str(msg)
5,332,951
def write_compile_commands(target, source, env): """ generator function to write the compilation database file (default 'compile_commands.json') for the given list of source binaries (executables, libraries) """ getString = base.BindCallArguments(base.getString, target, source, env, None) ...
5,332,952
def spectrum_1D_scalar(data, dx, k_bin_num=100): """Calculates and returns the 2D spectrum for a 2D gaussian field of scalars, assuming isotropy of the turbulence Example: d=np.random.randn(101,101) dx=1 k_bins_weighted,spect3D=spectrum_2D_scalar(d, dx, k_bin_num=100) ...
5,332,953
def get_previous_cat(last_index: int) -> models.Cat: """Get previous cat. Args: last_index (int): View index of last seen cat. """ cat = models.Cat.query.filter(and_(models.Cat.disabled == False, models.Cat.index < last_index)).order_by( desc(models.Cat.index)).first() if cat is None...
5,332,954
def encode(file, res): """Encode an image. file is the path to the image, res is the resolution to use. Smaller res means smaller but lower quality output.""" out = buildHeader(res) pixels = getPixels(file, res) for i in range(0, len(pixels)): px = encodePixel(pixels[i]) out += px return out
5,332,955
def process_image(img): """Resize, reduce and expand image. # Argument: img: original image. # Returns image: ndarray(64, 64, 3), processed image. """ image = cv2.resize(img, (416, 416), interpolation=cv2.INTER_CUBIC) image = np.array(image, dtype='float32') image /=...
5,332,956
def test_get_os_platform_linux(tmp_path): """Utilize an /etc/os-release file to determine platform.""" # explicitly add commented and empty lines, for parser robustness filepath = tmp_path / "os-release" filepath.write_text( dedent( """ # the following is an empty line ...
5,332,957
def unnormalise_x_given_lims(x_in, lims): """ Scales the input x (assumed to be between [-1, 1] for each dim) to the lims of the problem """ # assert len(x_in) == len(lims) r = lims[:, 1] - lims[:, 0] x_orig = r * (x_in + 1) / 2 + lims[:, 0] return x_orig
5,332,958
def is_interdisciplinary(foo, environment): """ Is interdisciplinary Major approach that accepts all kinds of objects and detects whether they can be considered in a defined environment. Arguments: foo (str): might be concept, method, journal, article, sentence, paragraph, person, project. ...
5,332,959
def scalar_projection(vector, onto): """ Compute the scalar projection of `vector` onto the vector `onto`. `onto` need not be normalized. """ if vector.ndim == 1: check(locals(), "vector", (3,)) check(locals(), "onto", (3,)) else: k = check(locals(), "vector", (-1, 3)) ...
5,332,960
def thread_task(lock, stock_id): """ task for thread """ print(f"Start process stock:{stock_id}") df = pd.read_excel(f"tw_{stock_id}.xlsx") # lock.acquire() stock_insert(df) # lock.release() print(f"End of process stock:{stock_id}\n\n")
5,332,961
def update_table(page_current, page_size, sort_by, filter, row_count_value): """ This is the collback function to update the datatable with the required filtered, sorted, extended values :param page_current: Current page number :param page_size: Page size :param sort_by: Column selected for sort...
5,332,962
def serialize(item: Any) -> bytes: """ Serializes the given value into its bytes representation. :param item: value to be serialized :type item: Any :return: the serialized value :rtype: bytes :raise Exception: raised if the item's type is not serializable. """ pass
5,332,963
def get_value(environment_variable, default_value=None): """Return an environment variable value.""" value_string = os.getenv(environment_variable) # value_string will be None if the variable is not defined. if value_string is None: return default_value # Exception for ANDROID_SERIAL. Sometimes serial c...
5,332,964
def autogossip(*args): """\ autogossip on|off -- generate random background conversation """ mode = 'on' if (args and args[0].lower() == 'on') else 'off' stdout.say('Turning autogossip %s.' % mode) global should_autogossip should_autogossip = bool(mode == 'on')
5,332,965
def load_mooring_csv(csvfilename): """Loads data contained in an ONC mooring csv file :arg csvfilename: path to the csv file :type csvfilename: string :returns: data, lat, lon, depth - a pandas data frame object and the latitude, longitude and depth of the morning """ data_line, lat, lon,...
5,332,966
def ez_execute(query, engine): """ Function takes a query string and an engine object and returns a dataframe on the condition that the sql query returned any rows. Arguments: query {str} -- a Sql query string engine {sqlalchemy.engine.base.Engine} -- a database engine obj...
5,332,967
def compute_lima_image(counts, background, kernel): """Compute Li & Ma significance and flux images for known background. Parameters ---------- counts : `~gammapy.maps.WcsNDMap` Counts image background : `~gammapy.maps.WcsNDMap` Background image kernel : `astropy.convolution.Ker...
5,332,968
def vagrant(name=''): """ Run the following tasks on a vagrant box. First, you need to import this task in your ``fabfile.py``:: from fabric.api import * from fabtools.vagrant import vagrant @task def some_task(): run('echo hello') Then you can easily run ...
5,332,969
def cli(ctx, db_url, default_folder): """Welcome to frames. This project is just started and should be considered experimental and unstable. """ pass
5,332,970
def get_list_from(matrix): """ Transforms capability matrix into list. """ only_valuable = [] counter = 1 for row_number in range(matrix.shape[0]): only_valuable += matrix[row_number, counter::].tolist() counter += 1 return only_valuable
5,332,971
def get_user_bubble_text_for_justify_statement(statement: Statement, user: User, is_supportive: bool, _tn: Translator) -> Tuple[str, str]: """ Returns user text for a bubble when the user has to justify a statement and text for the add-position-container :para...
5,332,972
def convert_yolo_to_coco_format( data_dir, out_dir, split, extensions=['.jpg', '.png']): """Convert YOLO format to COCO format. Parameters data_dir: str Path to image directory. out_label_path: str Path to output label json file. extensions: list Supporte...
5,332,973
def g1_constraint(x, constants, variables): """ Constraint that the initial value of tangent modulus > 0 at ep=0. :param np.ndarray x: Parameters of updated Voce-Chaboche model. :param dict constants: Defines the constants for the constraint. :param dict variables: Defines constraint values that depend...
5,332,974
def disconnect(connection_handler): """ Closes a current database connection :param connection_handler: the Connection object :return: 0 if success and -1 if an exception arises """ try: if connection_handler is not None: connection_handler.close() return 0 e...
5,332,975
def init_finder(**kwargs): """Create the global VersionImporter and initialize the finder.""" global FINDER if len(kwargs) > 0: init_loader(**kwargs) # I must insert it at the beginning so it goes before FileFinder FINDER = PyLibImportFinder() sys.meta_path.insert(0, FINDER)
5,332,976
def ensure_directory_exists(folder: Union[str, Path]): """creates a folder if it not already exists Args: folder (str): path of the new folder """ folder = str(folder) if folder == "": return try: os.makedirs(folder) except OSError as err: if err.errno != err...
5,332,977
def throw_out_nn_indices(ind, dist, Xind): """Throw out near neighbor indices that are used to embed the time series. This is an attempt to get around the problem of autocorrelation. Parameters ---------- ind : 2d array Indices to be filtered. dist : 2d array Distances to be fi...
5,332,978
def lead_angle(target_disp,target_speed,target_angle,bullet_speed): """ Given the displacement, speed and direction of a moving target, and the speed of a projectile, returns the angle at which to fire in order to intercept the target. If no such angle exists (for example if the projectile is slower than the targe...
5,332,979
def forward_rate_constants_func(self): """Update forward_rate_constants """ ln10 = torch.log(torch.Tensor([10.0])).to(self.device) self.forward_rate_constants = (self.Arrhenius_A * torch.exp(self.Arrhenius_b * torch.log(self.T) - ...
5,332,980
def fix_attr_encoding(ds): """ This is a temporary hot-fix to handle the way metadata is encoded when we read data directly from bpch files. It removes the 'scale_factor' and 'units' attributes we encode with the data we ingest, converts the 'hydrocarbon' and 'chemical' attribute to a binary integer ins...
5,332,981
def cli(ctx, opt_fp_in_csv, opt_fp_in_img, opt_fp_out_dir): """Generate HTML report from deduped images""" # ------------------------------------------------ # imports import sys from os.path import join from glob import glob import pandas as pd from tqdm import tqdm import jinja2 from flask impor...
5,332,982
def acme_parser(characters): """Parse records from acme global Args: characters: characters to loop through the url Returns: 2 item tuple containing all the meds as a list and a count of all meds """ link = ( 'http://acmeglobal.com/acme/' 'wp-content/themes/acme/tra...
5,332,983
def toStr(s: Any) -> str: """ Convert a given type to a default string :param s: item to convert to a string :return: converted string """ return s.decode(sys.getdefaultencoding(), 'backslashreplace') if hasattr(s, 'decode') else str(s)
5,332,984
def standard_task(self): """这是一个标准的task组件 用于schedule定时任务 """ pass
5,332,985
def standard_atari_env_spec(env): """Parameters of environment specification.""" standard_wrappers = [[tf_atari_wrappers.RewardClippingWrapper, {}], [tf_atari_wrappers.StackWrapper, {"history": 4}]] env_lambda = None if isinstance(env, str): env_lambda = lambda: gym.make(env) if cal...
5,332,986
def load_bikeshare(path='data', extract=True): """ Downloads the 'bikeshare' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'bikeshare' data = _load_file_data(name, path, extract) return data
5,332,987
def file2bytes(filename: str) -> bytes: """ Takes a filename and returns a byte string with the content of the file. """ with open(filename, 'rb') as f: data = f.read() return data
5,332,988
def load_session() -> dict: """ Returns available session dict """ try: return json.load(SESSION_PATH.open()) except FileNotFoundError: return {}
5,332,989
def _preprocess_zero_mean_unit_range(inputs, dtype=tf.float32): """Map image values from [0, 255] to [-1, 1].""" preprocessed_inputs = (2.0 / 255.0) * tf.cast(inputs, tf.float32) - 1.0 return tf.cast(preprocessed_inputs, dtype=dtype)
5,332,990
def fill_like(input, value, shape=None, dtype=None, name=None): """Create a uniformly filled tensor / array.""" input = as_tensor(input) dtype = dtype or input.dtype if has_tensor([input, value, shape], 'tf'): value = cast(value, dtype) return tf.fill(value, input.shape, name) else: ...
5,332,991
def transform_item(key, f: Callable) -> Callable[[dict], dict]: """transform a value of `key` in a dict. i.e given a dict `d`, return a new dictionary `e` s.t e[key] = f(d[key]). >>> my_dict = {"name": "Danny", "age": 20} >>> transform_item("name", str.upper)(my_dict) {'name': 'DANNY', 'age': 20} "...
5,332,992
def _insert_service_modes(target, connection, **kw): """ Inserts service mode IDs and names after creating lookup table. """ statement = target.insert().values([ {"id": 1, "name": "bus"}, {"id": 2, "name": "coach"}, {"id": 3, "name": "tram"}, {"id": 4, "name": "metro"}, {...
5,332,993
def vectorisation(): """generate dataframe with words from a document and corresponding tf-idf values write dataframe to s3 bucket """ v = TfidfVectorizer(stop_words=stop_words, min_df=min_df, max_df=max_df) vectorised_df = pd.DataFrame( v.fit_transform(get_joined_skills()["skills_and_occup_...
5,332,994
def mock_dataset(mocker, mock_mart, mart_datasets_response): """Returns an example dataset, built using a cached response.""" mocker.patch.object(mock_mart, 'get', return_value=mart_datasets_response) return mock_mart.datasets['mmusculus_gene_ensembl']
5,332,995
def loss_function(recon_x, x, mu, logvar): """Loss function for varational autoencoder VAE""" BCE = F.binary_cross_entropy(recon_x, x, size_average=False) # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return BCE + KLD
5,332,996
def resize_img(img, size): """ Given a list of images in ndarray, resize them into target size. Args: img: Input image in ndarray size: Target image size Returns: Resized images in ndarray """ img = scipy.misc.imresize(img, (size, size)) if len(img.shape) == 2: img...
5,332,997
def cloudtopheight_IR(bt, cloudmask, latitude, month, method="modis"): """Cloud Top Height (CTH) from 11 micron channel. Brightness temperatures (bt) are converted to CTHs using the IR window approach: (bt_clear - bt_cloudy) / lapse_rate. See also: :func:`skimage.measure.block_reduce` ...
5,332,998
def info2lists(info, in_place=False): """ Return info with: 1) `packages` dict replaced by a 'packages' list with indexes removed 2) `releases` dict replaced by a 'releases' list with indexes removed info2list(info2dicts(info)) == info """ if 'packages' not in info and 'releases' not in i...
5,332,999