id
stringlengths
3
8
content
stringlengths
100
981k
3234634
from waflib import Options from waflib import Logs from waflib import Context from waflib import Errors import re import waflib import os def options(ctx): import optparse grp = ctx.parser.get_option_group("--gfortran") if grp==None: grp=optparse.OptionGroup(ctx.parser,"compiler options") grp.add_option...
3234662
class Solution: def divide(self, dividend: int, divisor: int) -> int: if divisor == 0: return None diff_sign = (divisor < 0) ^ (dividend < 0) dividend = abs(dividend) divisor = abs(divisor) result = 0 max_divisor = divisor shift_count = 1 ...
3234668
import tensorflow as tf def gather_elems_2d(params: tf.Tensor, idxs: tf.Tensor, name: str, idxs_2d=False) -> tf.Tensor: """ Gather elements from params specified by idxs. This is useful when dealing with params tensors that have shape [batch size, N] and we want to grab elements from each row of param...
3234673
import cv2 from time import time from base import FeatureExtractorThread from utils import save_image, debug class SIFTThread(FeatureExtractorThread): def __init__(self, image_path, name, config): super(SIFTThread, self).__init__(image_path, name) self.results = None self.config = config ...
3234681
import pytest def pytest_addoption(parser): parser.addoption("--cat", action="store", default="main") parser.addoption("--vi", action="store", default="thetao") parser.addoption("--gl", action="store", default="gn") parser.addoption("--ei", action="store", default="historical") parser.addoption("-...
3234699
import pytest import roleml from roleml import exceptions def test_predict_1(clean_game_na): assert clean_game_na["expected_roles"] == roleml.predict(clean_game_na["game"], clean_game_na["game"]["timeline"]) def test_predict_2(clean_game_euw): assert clean_game_euw["expected_roles"] == roleml.predict(clean...
3234703
import numpy as np import scipy.misc as sp import matplotlib.pyplot as plt from sklearn.cluster import KMeans from PIL import Image class SpotifyBackgroundColor(): """Analyzes an image and finds a fitting background color. Main use is to analyze album artwork and calculate the background color Spotify se...
3234707
import scrapy from scrapy.loader import ItemLoader from scrapy.exceptions import CloseSpider from fbcrawl.spiders.fbcrawl import FacebookSpider from fbcrawl.items import EventsItem, parse_date, parse_date2 from datetime import datetime class EventsSpider(FacebookSpider): """ Parse FB events, given a page (ne...
3234708
import json import fire from transformers import AutoTokenizer def add_cross_sentence(sentences, tokenizer, max_length=200): """add_cross_sentence add cross sentences with adding equal number of left and right context tokens. """ new_sents = [] all_tokens = [] sent_lens = [] last_id = se...
3234717
from django.urls import include, path, re_path from .utils import URLObject from .views import empty_view, view_class_instance testobj3 = URLObject("testapp", "test-ns3") testobj4 = URLObject("testapp", "test-ns4") app_name = "included_namespace_urls" urlpatterns = [ path("normal/", empty_view, name="inc-normal-...
3234760
import sys import parse_sequences_file k, l, kmer_to_seq, kmer_abundance = parse_sequences_file.parse(sys.argv[1]) #print(k,l) nb_unique = len([kmer for kmer in kmer_abundance if kmer_abundance[kmer] == 1]) nb_distinct = len(kmer_abundance) perc_only_once = 100.0*nb_unique / nb_distinct print("percentage of distinc...
3234835
from PIL import Image import collections import shutil import traceback from functools import partial import pprint import logging import argparse import os import numpy as np import math from tqdm import tqdm import copy from einops import repeat, rearrange import torch import torch.distributed as dist import torch.m...
3234847
from dataclasses import dataclass from typing import Union from loopchain.blockchain.types import Address, ExternalAddress from loopchain.blockchain.transactions import Transaction as BaseTransition @dataclass(frozen=True) class Transaction(BaseTransition): from_address: ExternalAddress to_address: Address ...
3234848
from pathlib import Path import unittest from saw_client import * from saw_client.llvm import Contract, cryptol, void, i8, ptr_ty class FContract(Contract): def specification(self): x = self.alloc(ptr_ty(i8)) self.execute_func(x) p = self.alloc(i8) self.points_to(x, p) se...
3234854
def extractWateriftWordpressCom(item): ''' Parser for 'waterift.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('<NAME>', '<NAME> ~ Pleasure Trainin...
3234970
from nesta.core.luigihacks.estask import LazyElasticsearchTask from nesta.core.luigihacks.misctools import find_filepath_from_pathstub as f3p import luigi from datetime import datetime as dt import logging class NiHLolveltyRootTask(luigi.WrapperTask): production = luigi.BoolParameter(default=False) index = lui...
3234985
from collections import namedtuple from cacofonisk.callerid import CallerId class MissingUniqueid(KeyError): pass class Channel(object): """ A Channel holds Asterisk channel state. It can be dialed, bridge, and updated with new data. All of the above is typical low level Asterisk channel behav...
3234994
import requests from .. import conf # This will be a proper Queue MESSAGES = [] def emit2(base_endpoint, payload, to_uuid=None): if to_uuid: base_endpoint += ("/%s" % to_uuid) print(payload) payload["key"] = conf.KEY r = requests.post(conf.ENDPOINT + '/ocarina/api/' + base_endpoint + '/', json...
3235034
import datetime import time from .slims import Record def display_results(records: list[Record], fields: list[str], number: int = None) -> None: """Prints to display the filtered results as a list of elements with their selected fields. Args: records (list): List of results to display fields...
3235040
from flask import Flask app = Flask(__name__) import faas.index import faas.restart import faas.oom import faas.logs import faas.info import faas.stop_listener require_authentication = False application_tokens = [] log_directory = ""
3235074
def reformat_position(position): """ reformat position to be float values """ raw_position = vars(position)["_raw"] position_dict = {} for key in raw_position.keys(): try: position_dict[key] = float(raw_position[key]) except ValueError: continue return positio...
3235077
import asyncio import unittest from hackq_trivia.question_handler import QuestionHandler class MyTestCase(unittest.TestCase): async def setUpAsync(self): self.qh = QuestionHandler() def setUp(self) -> None: self.loop = asyncio.get_event_loop() self.loop.run_until_complete(self.setUpA...
3235103
import time from multiworld.core.image_env import ImageEnv from rlkit.core import logger from rlkit.envs.vae_wrapper import temporary_mode import cv2 import numpy as np import os.path as osp import pickle, os from test_latent_space.test_LSTM import compare_latent_distance from test_latent_space.test_LSTM2 import test...
3235113
from bootstrapvz.base import Task from bootstrapvz.common import phases from bootstrapvz.common.tasks import image from bootstrapvz.common.tools import log_check_call import os class CreateImageTarball(Task): description = 'Creating tarball with image' phase = phases.image_registration predecessors = [ima...
3235117
import importlib import sys from os import getcwd from os.path import join from mlcomp.worker.executors import Executor @Executor.register class Click(Executor): def __init__(self, module: str, command: str = None, **kwargs): super().__init__(**kwargs) self.module = module self.command =...
3235140
import numpy as np import pandas as pd import random from collections import deque import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, LSTM, BatchNormalization from tensorflow.keras.callbacks import ModelCheckpoint from tensorflow.keras.callbacks im...
3235204
from ntc_rosetta.parsers.ntc.ios.ntc_vlan.vlan import Vlan from yangify import parser from yangify.parser.text_tree import parse_indented_config class NTCParser(parser.RootParser): """ IOSParser expects as native data a dictionary where the `dev_conf` key is reserved for the device configuration. """...
3235267
from __future__ import annotations import logging import operator import sys from abc import ABC, abstractmethod from functools import reduce from itertools import zip_longest from pathlib import Path from typing import Optional, Union import freqtrade.vendor.qtpylib.indicators as qta from freqtrade.strategy import C...
3235290
from __future__ import annotations import ast from pathlib import Path from typing import Iterator, NamedTuple import astroid from ._contract import Category, Contract from ._extractors import get_contracts, get_definitions class Func(NamedTuple): name: str body: list contracts: list[Contract] node...
3235302
import collections class Threshold(collections.namedtuple("Threshold", ["rate", "per"])): """A threshold is a :class:`collections.namedtuple` representing a limit of events per span of time. In a threshold, only :attr:`rate` events are allowed per :attr:`per` seconds. """ @classmethod de...
3235326
from ..app import Blueprint from scanner.core.plugincall import callfunction user = Blueprint('user', __name__) plugin=callfunction() @user.route("/home",methods=["get","post"]) def home(): return str(plugin.pocscan("http://cn.changhong.com/"))
3235356
import json, requests, sys, getopt def do_fxhash_request(id, take, skip): url = "https://api.fxhash.xyz/graphql/" query = f"""{{ generativeTokensByIds(ids: {id}){{ name metadataUri metadata objkts(take: {take}, skip: {skip}) {{ name metadataUr...
3235383
from pyradioconfig.parts.bobcat.calculators.calc_wisun import CALC_WiSUN_Bobcat class calc_wisun_viper(CALC_WiSUN_Bobcat): pass
3235390
from __future__ import print_function import os import sys import tarfile import zipfile from future.standard_library import install_aliases import requests import utility install_aliases() SQLTOOLSSERVICE_RELEASE = "v3.0.0-release.72" SQLTOOLSSERVICE_BASE = os.path.join(utility.ROOT_DIR, 'sqltoolsservice/') # Sup...
3235399
from django.db.models import BooleanField from django.db.models import F from django.db.models import Q from django.db.models import Value from django.db.models.expressions import CombinedExpression from django.db.models.expressions import Func from django.db.models.sql.where import WhereNode class WhenQ(Q): """ ...
3235459
import os from os.path import dirname, join from pathlib import Path import setuptools # The directory containing this file HERE = os.path.abspath(os.path.dirname(__file__)) # The text of the README file NAME = "fedot" VERSION = "0.4.1" AUTHOR = "NSS Lab" SHORT_DESCRIPTION = "Evolutionary structural learning framewo...
3235463
from scipy.io.wavfile import read import os import torch import numpy as np MAX_WAV_VALUE = 32768.0 def load_wav_to_torch(full_path): """ Loads wavdata into torch array """ sampling_rate, data = read(full_path) return torch.FloatTensor(data.astype(np.float32)) / MAX_WAV_VALUE, sampling_rate d...
3235490
from os.path import isabs, join import os import sys import subprocess import re try: subprocess.check_output( '{} -c "import numba"'.format(sys.executable), shell=True ) print('numba available, importing jit') from numba import jit except: print('cannot import numba, creating dummy jit def...
3235634
def lif_neuron_inh(n_steps=1000, alpha=0.5, beta=0.1, exc_rate=10, inh_rate=10): """ Simulate a simplified leaky integrate-and-fire neuron with both excitatory and inhibitory inputs. Args: n_steps (int): The number of time steps to simulate the neuron's activity. alpha (float): The input scaling factor...
3235669
from django.contrib.admin import helpers from django.core.urlresolvers import reverse from django.db import transaction from django.shortcuts import render, redirect from django.template.response import TemplateResponse from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as ...
3235670
import torch import torch.nn as nn import torchvision import numpy as np import os plot_dir = 'imgs' os.makedirs(plot_dir, exist_ok=True) # image data dataset_name = 'mnist' # choices - ['mnist', 'fashion'] img_size = 32 nc = 1 # training info lr = 1e-4 batch_size = 64 nz = 32 ngf = 16 device = torch.device('cuda' i...
3235691
from flask import blueprints cfps_bp = blueprints.Blueprint("cfps", __name__) from . import cli # noqa isort:skip
3235698
from .context import assert_equal, process_sympy import pytest def pytest_generate_tests(metafunc): metafunc.parametrize('s', metafunc.cls.BAD_STRINGS) class TestAllBad(object): # These bad latex strings should raise an exception when parsed BAD_STRINGS = [ "(", ")", # "a / b /",...
3235714
from cupytorch import Tensor from .activation import LogSoftmax from .module import Module class L1Loss(Module): def forward(self, input: Tensor, target: Tensor) -> Tensor: output = (input - target).abs() return output.mean() class MSELoss(Module): def forward(self, input: Tensor, target: ...
3235793
import sys import pytest import discord_logging log = discord_logging.init_logging(debug=True) sys.path.append("src") from database import Database from praw_wrapper import reddit_test @pytest.fixture def database(): return Database(debug=True, publish=True) @pytest.fixture def reddit(): return reddit_test.Red...
3235847
import asyncio from collections import namedtuple from io import BytesIO import rx import boto3 from boto3.session import Session from cyclotron import Component Source = namedtuple('Source', ['response']) Sink = namedtuple('Sink', ['request']) # Sink objects Configure = namedtuple('Configure', [ 'access_key', '...
3235860
import os import pysam from .outlier import outlier_analysis def postprocess(df, data_dir, perform_outlier_analysis, pon): path_to_cosmic = "{}/cosmic/CosmicCodingMuts.indel.vcf.gz".format(data_dir) path_to_non_somatic = "{}/non_somatic/non_somatic.vcf.gz".format(data_dir) non_somatic = pysam.VariantFile...
3235883
def robots_tween_factory(handler, _registry): def robots_tween(request): response = handler(request) # If the view hasn't set its own X-Robots-Tag header then set one that # tells Google (and most other crawlers) not to index the page and not # to follow links on the page. #...
3235885
from setuptools import setup import for_lossless_music with open('requirements.txt') as f: requires = f.readlines() with open('README.rst') as f: readme = f.read() setup( name='for-lossless-music', version=for_lossless_music.__version__, packages=['for_lossless_music'], url='https://github.co...
3235907
from .config import PixivAPITestCase, tape from pixiv import AppCursor class AppCursorTests(PixivAPITestCase): @tape.use_cassette('testcursoritems.json') def testcursoritems(self): items = list(AppCursor(self.api.search_illust, word='original').items(5)) self.assertEqual(len(items), 5) @...
3235930
from xv_leak_tools.test_templating.templating import TemplateEvaluator, Replacee, Each # This list will contain all the individual test configurations TESTS = [] TEMPLATE = { 'name': "TestTorrentTrackerIPLeakNet", 'devices': [ { "discovery_keys": { "device_id": "localhost" ...
3235938
import asyncio import logging from aiohttp.web import Application, WebSocketResponse, json_response from aiohttp.http_websocket import WSMsgType, WSCloseCode from lbry.wallet.util import satoshis_to_coins from .node import Conductor PORT = 7954 class WebSocketLogHandler(logging.Handler): def __init__(self, se...
3235973
import torch import copy from typing import Any, Optional from collections import OrderedDict from ctools.worker.agent import BaseAgent, AgentAggregator # ######################## Learner ###################################### def create_dqn_learner_agent(model: torch.nn.Module, is_double: bool = True) -> BaseAgent: ...
3235988
from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from ..alphabets import gap_letter def add_seqnums_to_letter_annotations(seqrec, include_gaps=True): # If seqnums is already present, don't override it. if "seqnums" in seqrec.letter_annotations: return seqrec if include_gaps: se...
3236033
from os.path import join from dvha.paths import TG263_CSV, PREF_DIR class ROIMapGenerator: """Class to interact with the TG263 table and generate compliant ROI Name Maps""" def __init__(self): # Load TG263 table with open(TG263_CSV, "r") as doc: keys = [key.strip() for key in doc....
3236058
from pytorch_lightning import LightningModule from pytorch_lightning.strategies import DeepSpeedStrategy from deepspeed.ops.adam import DeepSpeedCPUAdam, FusedAdam from transformers.optimization import AdamW, get_scheduler def add_module_args(parent_args): parser = parent_args.add_argument_group('Basic Module') ...
3236061
import sys from PyQt4 import QtGui, QtCore import sip from sqlalchemy.orm import sessionmaker from gui.experiments_tab import ExperimentsTab from gui.feasibility_tab import FeasibilityTab from gui.plotter_tab import PlotterTab import logging from sqlalchemy import create_engine from gui.settings_tab import SettingsT...
3236063
import argparse import os import time import numpy as np from utils import model, utils from utils.utils import print_arguments parser = argparse.ArgumentParser() parser.add_argument('--audio1_path', default='audio/b_1.wav', type=str, help='预测第一个音频') parser.add_argument('--audio2_path', default='audio/a_...
3236094
import numpy as np from . import msequence import scipy.stats as stats import scipy def order(nstim,ntrials,probabilities,ordertype,seed=1234): ''' Function will generate an order of stimuli. :param nstim: The number of different stimuli (or conditions) :type nstim: integer :param ntrials: The tot...
3236118
from boa3.builtin import public class Example: def __init__(self, arg0: int, arg1: str): pass @public def build_example_object() -> Example: return Example(42, '42')
3236170
from . import TestGramex from datetime import datetime from gramex.http import OK from gramex.services import info from nose.tools import eq_ class TestSchedule(TestGramex): def test_startup(self): # Check if code in schedules with startup: true are executed self.check('/schedule-key', text='1', c...
3236173
from requests_cache import CachedSession from datetime import timedelta session = CachedSession(backend='memory', expire_after=timedelta(hours=1)) def new_session(new_session): global session session = new_session return session
3236236
import sys inname, outname = sys.argv[1:3] def warnings_filter(insequence): for l in insequence: if 'WARNING' in l: yield l.replace('\tWARNING', '') with open(inname) as infile: with open(outname, "w") as outfile: filter = warnings_filter(infile) for l in filter: ...
3236249
import math import string import sys import nltk from nltk.tokenize import wordpunct_tokenize class TF_IDF_Scratch: """ Initializes the algorithm with preferred language, a list of stopwords, and a list of punctuations If language is unspecified, it defaults to English If stopwords is unspecifie...
3236347
from banyan_c import DictTree from banyan_c import TreeView from ._common_base import _CommonInitInfo from ._common_base import _updator_metadata from ._common_base import _adopt_updator_methods from ._common_base import RED_BLACK_TREE from ._common_base import SPLAY_TREE from ._common_base import SORTED_LIST from ._v...
3236358
from django.http import Http404, HttpResponse, JsonResponse from django.shortcuts import get_object_or_404, redirect from auth.helpers import api_required from posts.models.post import Post @api_required def md_show_post(request, post_type, post_slug): post = get_object_or_404(Post, slug=post_slug) if post....
3236372
import unittest import numpy as np from scipy import sparse from linkedin.learner.ds.indexed_dataset import IndexedDataset from linkedin.learner.ds.indexed_model import IndexedModel from linkedin.learner.prediction.linear_scorer import score_linear_model from linkedin.learner.utils.functions import sparse_diag_matrix...
3236404
import os import logging from torch.utils import data import numpy as np import yaml logger = logging.getLogger(__name__) # Fields class Field(object): def load(self, data_path, idx): raise NotImplementedError def check_complete(self, files): raise NotImplementedError class Shapes3dDatase...
3236409
from types import SimpleNamespace import rasterio import os import time from rasterio.windows import Window from cos_backend import COSBackend def obtain_meta(chunk, splits): with rasterio.open(chunk) as src: profile = src.profile profile.update(width=profile['width'] * splits) profile.up...
3236410
import torch import torch.nn as nn import matplotlib.pyplot as plt import numpy as np import cv2 from light_weight_refinenet.models.resnet import rf_lw50 from light_weight_refinenet.utils.visualize import * from light_weight_refinenet.utils.helpers import prepare_img class LwrfInfer: def __init__(self, use_cuda, ...
3236417
from .augmentations.background_noise import AddBackgroundNoise from .augmentations.colored_noise import AddColoredNoise from .augmentations.band_pass_filter import BandPassFilter from .augmentations.gain import Gain from .augmentations.high_pass_filter import HighPassFilter from .augmentations.impulse_response import A...
3236429
from time import time import nose.core from noseprogressive.result import ProgressiveResult class ProgressiveRunner(nose.core.TextTestRunner): """Test runner that makes a lot less noise than TextTestRunner""" def __init__(self, cwd, totalTests, stream, **kwargs): super(ProgressiveRunner, self).__in...
3236459
from datetime import timedelta from typing import TYPE_CHECKING from sqlalchemy import or_ from grouper.constants import ILLEGAL_NAME_CHARACTER from grouper.email_util import send_async_email from grouper.models.async_notification import AsyncNotification from grouper.settings import settings if TYPE_CHECKING: f...
3236549
from .DispNetS import DispNetS from .PoseNet import PoseNet from .DepthNet import DepthNet from .UpSampleNet import UpSampleNet
3236616
import sys from PIL import Image import warnings warnings.filterwarnings("ignore", "(Possibly )?corrupt EXIF data", UserWarning) try: im = Image.open(sys.argv[1]).convert('RGB') # remove images with too small or too large size if (im.size[0] < 10 or im.size[1] < 10 or im.size[0] > 10000 or im.size[1] > 1...
3236639
import asyncio import contextlib import json import logging import math import os import random import shutil import aiohttp import discord import rcon from redbot.core import commands, Config, bank from redbot.core.utils.chat_formatting import box, pagify from .formatter import ( shop_stats, dlist, rlist...
3236648
import json import os from bs4 import BeautifulSoup import requests from pynfl import utils class Game(utils.DataModelClass): def __init__(self, **kwargs): self.id = None self.location = None self.time = None self.date = None self.week = None self.site = None ...
3236701
name = 'STEM' identifier = 'edu.cornell.birds.stem' version = '0.0.2' def package_dependencies(): return ['edu.utah.sci.vistrails.rpy']
3236718
import base64 import struct from hashlib import sha256 from Crypto.Cipher import AES MAGIC = '::::MAGIC::::' PAD_BLOCK_LEN = 16 KEY_LEN = 16 def jenkins_encrypt(value, master_key, secret_key_base64): ''' filter to encrypt values that we insert into xml config files ''' # if we're passed dicts from a shell c...
3236721
import numpy as np import torch import torch.nn as nn import rl_sandbox.constants as c from rl_sandbox.auxiliary_tasks.auxiliary_tasks import AuxiliaryTask from rl_sandbox.model_architectures.shared import Flatten class Koopman(AuxiliaryTask): def __init__(self, rec_dim, batch_s...
3236723
import pandas as pd from .dictionary import Dictionary, CharDictionary import pickle from typing import Dict, List import torch import os import numpy as np # from torchpie.config import config MULTIPLE_CHOICE_TASKS = ['action', 'transition'] def load_csv_from_dataset(task: str, split: str) -> pd.DataFrame: retu...
3236760
import os import sys import argparse from utils import indoor3d_util #---- input arguments parser = argparse.ArgumentParser(description='Process input arguments.') parser.add_argument('--raw_data_dir', help='directory where raw dataset is stored') parser.add_argument('--output_folder', default='...
3236763
from cores.config import conf import argparse import mxnet as mx import cores.utils.misc as misc import os import logging from cores.train_multi_wrapper import train_multi_wrapper from cores.generate_bg_cues import generate_bg_cues if __name__ == "__main__": parser = argparse.ArgumentParser(description="Training p...
3236777
from toee import * def OnBeginSpellCast( spell ): print "Goodberry OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level game.particles( "sp-transmutation-conjure", spell.caster ) def OnSpellEffect( spell ): print "Goodberry OnS...
3236792
import os import sys sys.path.append("../") from libs.configs import cfgs scr_tsv = './dcl_log/{}/dcl_meta.tsv'.format(cfgs.VERSION) omega = 180 / 4 fr = open(scr_tsv, 'r') lines = fr.readlines() fr.close() fw_tsv = open(os.path.join('dcl_log/{}'.format(cfgs.VERSION), 'dcl_meta_{}.tsv'.format(omega)), 'w') # fw_...
3236795
from .seq_post_processor import SeqPostProcessor from .beam_search import BeamSearch from .bpe import BPE
3236829
import sys, math, time from unittest import SkipTest try: import IPython from IPython.core.display import clear_output except: clear_output = None raise SkipTest("IPython extension requires IPython >= 0.12") # IPython 0.13 does not have version_info ipython2 = hasattr(IPython, 'version_info') and (IPy...
3236861
import numpy as np import tensorflow as tf import tensorflow.python.platform from tensorflow.models.rnn import rnn from tensorflow.models.rnn import rnn_cell from bi_rnn import bi_rnn from utils import * ############################################### # NN creation functions # #################...
3236865
import tkinter as tk import tkinter.messagebox as msg class TextArea(tk.Text): def __init__(self, master, **kwargs): super().__init__(**kwargs) self.master = master self.config(wrap=tk.WORD) # CHAR NONE self.tag_configure('find_match', background="yellow") self.find_mat...
3236887
from dataclasses import dataclass, asdict, fields, MISSING from typing import Optional @dataclass class Locator: """Baseclass for a locator entry.""" def __str__(self): values = [] for field in fields(self): if field.default is not MISSING: break values...
3236897
import os import textwrap from conans import tools from tests.utils.test_cases.conan_client import ConanClientTestCase class NoLibToolTests(ConanClientTestCase): conanfile = textwrap.dedent("""\ import os from conans import ConanFile, tools class AConan(ConanFile): url = "fa...
3236904
import k3d import numpy as np import pytest from .plot_compare import * from k3d.helpers import download import vtk from vtk.util import numpy_support vertices = [ -10, 0, -1, 10, 0, -1, 10, 0, 1, -10, 0, 1, ] indices = [ 0, 1, 3, 1, 2, 3 ] def test_mesh(): global vertices, indices ...
3236915
import os import io import ConfigParser as CP from xml.etree import ElementTree as ET from contextlib import contextmanager PLUGIN_DIR = os.path.dirname(os.path.dirname(__file__)) EXPORT_PRESETS_DIR = os.path.join(PLUGIN_DIR, "export_preset") CONFIG_DIR = os.path.join(os.path.expanduser( "~/.openpype"), "openpype...
3236927
from django.dispatch import Signal user_enrolled = Signal(providing_args=['experiment', 'alternative', 'user', 'session'])
3236976
import k2 s1 = ''' 0 0 1 0.1 0 1 2 0.2 1 2 -1 0.3 2 ''' s2 = ''' 0 1 1 1 0 1 2 2 1 2 -1 3 2 ''' a_fsa = k2.Fsa.from_str(s1) b_fsa = k2.Fsa.from_str(s2) c_fsa = k2.intersect(a_fsa, b_fsa) connected = k2.connect(c_fsa) a_fsa.draw('a_fsa_1.svg', title='a_fsa') b_fsa.draw('b_fsa_1.svg', title='b_fsa') c_fsa.draw('before_co...
3236985
import argparse import torch from torchsummaryX import summary import options as option from models import create_model parser = argparse.ArgumentParser() parser.add_argument( "-opt", type=str, default="options/setting1/test/test_setting1_x4.yml", help="Path to option YMAL file of Predictor.", ) args...
3237048
import torch from mmpose.models import build_loss def test_smooth_l1_loss(): # test SmoothL1Loss without target weight loss_cfg = dict(type='SmoothL1Loss') loss = build_loss(loss_cfg) fake_pred = torch.zeros((1, 3, 2)) fake_label = torch.zeros((1, 3, 2)) assert torch.allclose(loss(fake_pred,...
3237065
import torch from torch.nn import Module, Linear from torch.optim.lr_scheduler import LambdaLR import numpy as np def reparameterize_gaussian(mean, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn(std.size()).to(mean) return mean + std * eps def gaussian_entropy(logvar): const = 0.5 * float(l...
3237116
import os import cv2 import glob import h5py import json import joblib import argparse import numpy as np from tqdm import tqdm import os.path as osp import scipy.io as sio import sys sys.path.append('.') from lib.models import spin from lib.core.config import TCMR_DB_DIR, BASE_DATA_DIR from lib.utils.utils import tq...
3237131
from Crypto.Cipher import AES class DecrypterProvider(object): def __init__(self, network, m3u8, get_by_comparison = False): self.__network = network self.m3u8 = m3u8 self.key = None self.uri = self.m3u8.data["keys"][1]["uri"] if get_by_comparison: self.get_key_...