id
stringlengths
3
8
content
stringlengths
100
981k
11493761
from django.contrib.auth.models import User from django.urls import path from . import views import blog urlpatterns=[ path('', blog.views.blogPage), path('login/', views.loginUser, name='login'), path('logout/', views.logoutUser, name='logout'), path('profile/', views.userProfile, name='profile') ]
11493818
from gcg.data.timer import timeit from gcg.data.logger import logger from gcg.algos.gcg import GCG class GCGinference(GCG): def __init__(self, exp_name, env_params, env_eval_params, rp_params, rp_eval_params, labeller_params, pol...
11493827
from typing import Dict from boa3.model.builtin.interop.interopevent import InteropEvent from boa3.model.variable import Variable class NotifyMethod(InteropEvent): def __init__(self): self._event_name_key = 'notification_name' from boa3.model.type.type import Type identifier = 'notify' ...
11493855
import argparse import cv2 import random from glob import glob import time import os, sys, inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) code_dir = os.path.dirname(os.path.dirname(current_dir)) sys.path.insert(0, code_dir) from tools.utils import mkdir from data.folde...
11493881
import os TEST_BUCKET = os.environ.get("GCSFS_TEST_BUCKET", "gcsfs_test") TEST_PROJECT = os.environ.get("GCSFS_TEST_PROJECT", "project") TEST_REQUESTER_PAYS_BUCKET = "gcsfs_test_req_pay"
11493894
from textwrap import dedent from setuptools import setup, find_packages setup( version = '5.5.0.post6', name = 'clingo-cffi-system', description = 'CFFI-based bindings to the clingo solver.', long_description = dedent('''\ This package provides CFFI-based bindings to the clingo solver. ...
11493895
from networks.backbone import resnet def build_backbone(backbone, output_stride, BatchNorm, nInputChannels, pretrained): if backbone == "resnet101": return resnet.ResNet101( output_stride, BatchNorm, nInputChannels=nInputChannels, pretrained=pretrained, ...
11493925
import os import requests import getpass import configargparse from .progress_bar import CustomProgress from .metadata import Metadata from .constants import extensions class Crawler: base_url = 'https://www.hackerrank.com/' user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gec...
11493954
from jumpscale.loader import j PYTHON_PACKAGES = [ "jupyterlab", "voila", "voila-gridstack", "voila-vuetify", "matplotlib", "ipywidgets", "jupyterlab_code_formatter", ] class notebooks: def __init__(self): self.notebook_dir = j.sals.fs.join_paths(j.core.dirs.BASEDIR) def ...
11493999
from os.path import dirname, join from .printer import prt description = "Tutorial: Import, type, sort, and hash partition a file." # File is stored in same directory as this python file. # In a real project, set "input directory" in config file instead! filename = join(dirname(__file__), 'data.csv') def main(urd)...
11494004
import re from django.db import models from logging import getLogger from api.exceptions import InvalidInput logger = getLogger(__name__) class DomainMetadata(models.Model): """ This table contains metadata for all domains. CREATE TABLE public.domainmetadata ( id integer NOT NULL, domai...
11494017
from pypy.annotation import model as annmodel from pypy.tool.pairtype import pair, pairtype from pypy.jit.hintannotator.bookkeeper import getbookkeeper from pypy.rpython.lltypesystem import lltype, lloperation from pypy.rpython.ootypesystem import ootype from pypy.translator.simplify import get_funcobj, get_functype U...
11494024
import os import pickle import sys from gensim.models.word2vec import Word2Vec import numpy from sklearn.cluster import KMeans from customlogging import logger import conf if __name__ == '__main__': w2vmodelfile = os.path.join(conf.W2V_DIR, 'model') if not os.path.exists(w2vmodelfile): print('Word2v...
11494039
import json import os from newrelic.agent import NewRelicContextFormatter # Set DEBUG = True to enable debugging application. DEBUG = os.environ.get("ITS_DEBUG", "false").lower() == "true" # We don't want to enforce type checks in production environments (probably) ENFORCE_TYPE_CHECKS = ( os.environ.get("ITS_EN...
11494089
from typing import Tuple, Union, List, Optional, Any, Callable from pydantic import BaseModel, StrictInt, StrictBool from torch.utils import data from tensorfn.config import Config class DataLoader(Config): batch_size: StrictInt = 1 shuffle: StrictBool = False num_workers: StrictInt = 0 ...
11494145
class ListNode: def __init__(self, data, next=None): self.val = data self.next = next def make_list(elements): head = ListNode(elements[0]) for element in elements[1:]: ptr = head while ptr.next: ptr = ptr.next ptr.next = ListNode(element) return hea...
11494162
from qtpy import QtCore, QtGui, QtWidgets from perforce.AppInterop import interop from perforce import PerforceUtils def displayErrorUI(e): error_ui = QtWidgets.QMessageBox() error_ui.setWindowFlags(QtCore.Qt.WA_DeleteOnClose) eMsg, type = PerforceUtils.parsePerforceError(e) if type == "warning": ...
11494203
import os import pytest import pandas as pd import numpy as np @pytest.fixture() def gdp_data(request): df = pd.read_csv(os.path.join(os.path.dirname(request.module.__file__), 'data', 'gdp.csv'), parse_dates=['DATE']) df['gdp'] = (np.log(df.GDP) - np.log(df.GDP.shift(1))) * 100. re...
11494204
from enum import Enum, auto class HorizontalLabelAlignment(Enum): LeftOuter = auto() Left = auto() Center = auto() Right = auto() RightOuter = auto() class VerticalLabelAlignment(Enum): Top = auto() Center = auto() Bottom = auto() class FlowPattern(Enum): CoCurrent = auto() ...
11494206
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.boundsdata import boundsdata def test_boundsdata(): """Test module boundsdata.py by downloading boundsdata.csv and testing shape of extrac...
11494271
import pytest import numpy as np import tensorflow as tf from kerod.core import sampling_ops @pytest.mark.parametrize( "np_indicator,num_samples,expected_num_samples", [ [[True, False, True, False, True, True, False], 3, 3], # indicator when less true elements than num_samples [[True,...
11494324
class Solution: def minIncrementForUnique(self, A: 'List[int]') -> 'int': A.sort() num = 0 for i in range(1, len(A)): if A[i] <= A[i - 1]: num += A[i - 1] + 1 - A[i] A[i] = A[i - 1] + 1 return num
11494390
import sys import wx from pubsub import pub import matplotlib if 'linux' not in sys.platform: matplotlib.use("WXAgg") try: import seaborn seaborn.set() except ImportError: pass from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas from matplotlib.backends.backend_wx import...
11494403
import os from time import sleep import requests from flask import abort, Flask, jsonify, request from zappa.async import task app = Flask(__name__) def is_request_valid(request): is_token_valid = request.form['token'] == os.environ['SLACK_VERIFICATION_TOKEN'] is_team_id_valid = request.form['team_id'] == ...
11494417
import os.path from amitools.binfmt.BinFmt import BinFmt from amitools.binfmt.Relocate import Relocate from amitools.vamos.label import LabelSegment from amitools.vamos.log import log_segload from .seglist import SegList class SegLoadInfo(object): def __init__(self, seglist, bin_img=None, sys_file=None, ami_file...
11494440
import tensorflow as tf import cv2 import time import argparse from posenet.posenet_factory import load_model from posenet.utils import draw_skel_and_kp parser = argparse.ArgumentParser() parser.add_argument('--model', type=str, default='resnet50') # mobilenet resnet50 parser.add_argument('--stride', type=int, defau...
11494444
import face_recognition import numpy as np import pickle from config import ConfigFacialId from config import ConfigVideoFrame class FacialIdDataset(): def __init__(self): self.known_face_names = [] self.known_face_encodings = [] self.all_face_encodings = {} self.realtime_face_enco...
11494477
import collections kaldi_base = "/scail/group/deeplearning/speech/awni/kaldi-stanford/kaldi-trunk/egs/swbd/s5b/" # Symbols laugh = '[laughter]' noise = '[noise]' voc_noise = '[vocalized-noise]' space = '[space]' # Spell out integers integers = ['zero','one','two','three','four','five','six','seven','eight','nine'] ...
11494523
from PyQt5.QtWidgets import QToolButton, QLineEdit, QFileDialog, QDialog, QRadioButton, QPushButton from PyQt5.QtGui import QIcon from PyQt5.QtCore import Qt from PyQt5 import uic import os import configparser from shutil import copytree, rmtree from pulse.utils import get_new_path from data.user_input.project.printMe...
11494561
from pypy.jit.codegen.i386.ri386 import * from pypy.jit.codegen.i386.codebuf import MachineCodeBlock, memhandler def test_alloc_free(): map_size = 65536 data = memhandler.alloc(map_size) for i in range(0, map_size, 171): data[i] = chr(i & 0xff) for i in range(0, map_size, 171): assert ...
11494589
from typing import Tuple from nutshell.preprocessing.cleaner import BaseCleaner, NLTKCleaner from nutshell.preprocessing.tokenizer import BaseTokenizer, Token, NLTKTokenizer class TextPreProcessor: def __init__(self, tokenizer: BaseTokenizer = NLTKTokenizer(), cleaner: BaseCleaner = NLTKCleaner()): """ ...
11494599
from dataclasses import dataclass @dataclass class Guardian: """ A guardian or parent in the league """ first_name: str last_name: str
11494705
from descontos import ( DescontoCincoItens, DescontoMaisDeQuinhentosReais, SemDesconto, ) class CalculadorDescontos: def calcula(self, orcamento): return DescontoCincoItens( DescontoMaisDeQuinhentosReais(SemDesconto()) ).calcula(orcamento) if __name__ == '__main__': ...
11494760
from __future__ import absolute_import from past.builtins import unicode import argparse import logging import os import re import apache_beam as beam from apache_beam.io import ReadFromText from apache_beam.io.iobase import Write from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.optio...
11494781
import rosbag import subprocess from subprocess import Popen import sys import signal import time import os import sys process = None def start(topics, filename, folder='~/bags/'): global process folder = os.path.expanduser(folder) if not os.path.isdir(folder): os.mkdir(folder) os.chdir(os.path.expanduser(fol...
11494787
from ..factory import Type class messagePassportDataSent(Type): types = None # type: "vector<PassportElementType>"
11494803
import ui, scene img_label = 'dog' def set_dog(sender): global img_label img_label = 'dog' def set_cat(sender): global img_label img_label = 'cat' class MyScene(scene.Scene): def setup(self): print(self.size) print(self.bounds) print(self.view.frame) cente...
11494816
import os import logging from logging import Logger import hashlib from pathlib import Path import _pickle as cPickle from collections import defaultdict from typing import List, Dict, Optional, NamedTuple, Union import numpy as np from tqdm import tqdm from torch.utils.data import Dataset from transformers import Ber...
11494823
from .helper import PillowTestCase, hopper import datetime from PIL import Image, ImageMode from io import BytesIO import os try: from PIL import ImageCms from PIL.ImageCms import ImageCmsProfile ImageCms.core.profile_open except ImportError: # Skipped via setUp() pass SRGB = "Tests/icc/sRGB_IE...
11494836
from src.datasets.toxic_spans_tokens import * from src.datasets.toxic_spans_spans import * from src.datasets.toxic_spans_tokens_spans import * from src.datasets.toxic_spans_multi_spans import * from src.datasets.toxic_spans_crf_tokens import *
11494862
if sm.getRandomIntBelow(2) == 0: sm.teleportToPortal(10) # Final portal else: sm.warpInstanceOut(993000601, 0) # Hidden Street : Secluded Forest
11494881
import json import os import socket from resotolib.baseresources import BaseResource from resotolib.config import Config from resotolib.graph import Graph from resotolib.utils import RWLock import resotolib.logger from typing import Iterable, List, Union, Callable, Any, Dict from googleapiclient import discovery from g...
11494907
import scripts.clausecat.clausecat_component import scripts.clausecat.clause_segmentation import scripts.clausecat.clausecat_reader import scripts.clausecat.clausecat_model import scripts.clausecat.clause_aggregation import benepar
11494919
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column from sqlalchemy.types import String, Integer Base = declarative_base() class World(Base): __tablename__ = "world" id = Column(Integer, primary_key = True) randomNumber = Column(Integer) def serialize(self): ...
11494966
import matplotlib.pyplot as plt import numpy as np from slam.FactorGraphSimulator import read_factor_graph_from_file from utils.Visualization import plot_2d_samples from slam.Variables import Variable, VariableType import os from slam.RunBatch import group_nodes_factors_incrementally from scipy import stats import matp...
11494989
import os from collections import OrderedDict import torch import torch.nn as nn from .. import layer as vn_layer from .brick import shufflenet as bsn __all__ = ['shufflenetg2', 'shufflenetg3'] # default shufflenet g2 class Shufflenet(nn.Module): def __init__(self, cfg): super().__init__() out_pl...
11495018
def pressure(r, ro, g): p = np.zeros(len(r)) r = r *1000 for i in range(0,len(r)): r1 = r[i:len(r)] ro1 = ro[i:len(r)] g1 = g[i:len(r)] y = ro1*g1 p1 = trapz(y,r1) p[i] = p1 return p p = pressure(r,ro,g)/1e9 # expressed in GPa z = np.lin...
11495019
from __future__ import print_function from __future__ import absolute_import from __future__ import print_function from __future__ import division import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import sys import time import datetime from src.EN import EntityNetwork import numpy as np import tensorflow as tf import tf...
11495020
import numpy as np import json import requests import sys # python delete_custom_charges.py 0000000000000000000000000000000000000000000000000000000000000000 def load_custom_charges(custom_charges_file): custom_charges_dtype = [("Id", "U36")] custom_charges = np.loadtxt(custom_charges_file, dtype="U36", delimiter...
11495069
from pyNastran.converters.cart3d.cart3d import Cart3D, read_cart3d from pyNastran.converters.tecplot.tecplot import Tecplot, Zone def cart3d_to_tecplot(cart3d_filename, tecplot_filename, log=None, debug=False): """ Converts Cart3d to Tecplot """ if isinstance(cart3d_filename, Cart3D): model = c...
11495073
from functools import wraps import logging import os from django.conf import settings from django.db import ProgrammingError, connection from django.utils import timezone from django_q.models import Schedule from django_q.tasks import schedule from qatrack.qatrack_core.utils import today_start_end logger = logging.g...
11495113
from pathlib import Path import typer from .shell import shell CURRENT_PATH = Path(__file__) ROOT_PATH = CURRENT_PATH.parents[1] NOTEBOOKS_FOLDER = ROOT_PATH / "examples" NOTEBOOKS_TO_SKIP = [] def run_notebooks(): for notebook_path in NOTEBOOKS_FOLDER.glob("*.ipynb"): if notebook_path.name in NOTEBOO...
11495149
import os asciidirectory = os.getcwd() + '/pastes/asciipastes/' #relative path of ASCII pastes. save_path = os.getcwd() + '/decodedexes/' #relative path of stored executables. def writefile(filenm, stuff): writefile = open(filenm,'w') writefile.write(stuff) writefile.close() for filename in os.listdir(as...
11495167
import sys import os import pytest PROJECT_ROOT = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir) ) sys.path.append(PROJECT_ROOT) # Import der Bibliotheken from RFEM.enums import * from RFEM.initModel import Model, SetAddonStatus, CheckIfMethodOrTypeExists from R...
11495171
import json import os from typing import List, Dict import pymysql import yaml def main(): with open("./docker-compose.yaml", "r", encoding="utf8") as f: compose = yaml.safe_load(f.read()) with open("./sql_script_load_order.txt", "r") as f: sql_scripts = f.readlines() sql_scripts = ...
11495207
import factory from application.models import db, User, Role from .role_factory import RoleFactory from werkzeug.security import generate_password_hash, check_password_hash class UserFactory(factory.alchemy.SQLAlchemyModelFactory): class Meta: model = User sqlalchemy_session = db.session sq...
11495221
from collections import namedtuple from .util import fatal Env = namedtuple('Env', ['name', 'short', 'other']) ENVIRONMENTS = [ Env('development', 'dev', ['debug']), Env('staging', 'staging', ['stage']), Env('production', 'prod', ['release']), Env('testing', 'test', ['qa']) ] STANDARD_ENV_NAMES = [en...
11495225
from typing import Dict, List def _merge(name, d, override_keys): override = d.pop("override", None) if override is not None: if not isinstance(override, dict): raise ValueError( f"{name}.override: got {type(override)}, must be a dictionary" ) for k in o...
11495234
from feathr.anchor import FeatureAnchor from feathr.source import Source from feathr.feature_derivations import DerivedFeature from feathr.feature import Feature from feathr.transformation import Transformation from typing import Set class RepoDefinitions: """A list of shareable Feathr objects defined in the proj...
11495239
import re from share.transform.chain import * EMAIL_RE = re.compile(r'\S+@\S+') class WorkIdentifier(Parser): uri = IRI(ctx) class AgentIdentifier(Parser): uri = IRI(ctx, urn_fallback=True) class RelatedAgent(Parser): schema = GuessAgentType(ctx, default='organization') name = ctx class IsAffi...
11495242
from attributes.unit_test.discoverer import TestDiscoverer class CSharpTestDiscoverer(TestDiscoverer): def __init__(self): self.language = 'C#' self.languages = ['C#'] self.extensions = ['*.cs'] self.frameworks = [ self.__nunit__, self.__vs_unit_testing__, ...
11495269
import bpy from io_scene_vrm.common.human_bone import HumanBoneName from io_scene_vrm.editor.vrm0.property_group import Vrm0HumanoidPropertyGroup def test() -> None: bpy.ops.icyp.make_basic_armature() armatures = [obj for obj in bpy.data.objects if obj.type == "ARMATURE"] assert len(armatures) == 1 a...
11495275
import io import sys import unittest from unittest.mock import patch, PropertyMock from fzfaws.ec2.stop_instance import stop_instance from fzfaws.ec2 import EC2 from fzfaws.utils import BaseSession from botocore.stub import Stubber import boto3 class TestEC2Stop(unittest.TestCase): def setUp(self): self.c...
11495314
from data_collector import DataCollector from node import Node from node_repository import NodeRepository from stats_repository import StatsRepository class SeamonServer(object): @staticmethod def add_node(name, ip_address, port): NodeRepository.save(Node(name=name, ip_address=ip_address, port=port)) ...
11495443
import os from os.path import join import csv import cv2, copy import numpy as np import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms, utils from PIL import Image import torchaudio import sys from scipy.io import wavfile import json def read_sal_text(txt_file): test_list =...
11495498
import sys import os from datetime import datetime, timedelta input_file = sys.argv[1] num_workers = 8 if len(sys.argv) > 2: num_workers = int(sys.argv[2]) input_fd = open(input_file, 'r') times = [] accuracys = [] time_start = 0 for line in input_fd: strs = line.split() if time_start == 0 and (len(strs) == 9 o...
11495527
import gym, snake_gym import neat import pickle env = gym.make("snake-tiled-v0") state = env.reset() done = False config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, './config') genome = pickle.load(open("winner.pk...
11495559
import base64 from flask import Flask, redirect, request, session, url_for, jsonify from spotify import OAuth, Client app = Flask(__name__) app.config['SECRET_KEY'] = 'supersecret' def get_auth(token=None): auth = OAuth( 'CLIENT_ID', # Replace these with your client id and secret 'CLIENT_SECRET'...
11495561
class Solution: def largestPalindrome(self, n): """ :type n: int :rtype: int """ ans = [9, 987, 123, 597, 677, 1218, 84, 475] return ans[n - 1]
11495576
from unittest import mock from ros_tcp_endpoint.unity_service import UnityService import rospy @mock.patch.object(rospy, "Service") def test_unity_service_send(mock_ros_service): mock_tcp_server = mock.Mock() unity_service = UnityService("color", mock.Mock(), mock_tcp_server) assert unity_service.node_nam...
11495584
import mxnet as mx import argparse import logging import os # load data def get_mnist_iter(args): train_image = os.path.join(args.data_url + 'train-images-idx3-ubyte') train_label = os.path.join(args.data_url + 'train-labels-idx1-ubyte') try: import moxing.mxnet as mox except: assert os....
11495593
import matplotlib.pyplot as plt import numpy as np hug = np.loadtxt("hugoniot.txt") # read in the headings with open("hugoniot.txt", "r") as f: line = f.readline() rho = float(line.split("=")[-1]) line = f.readline() p = float(line.split("=")[-1]) line = f.readline() rho_det = float(line.spl...
11495622
import numpy as np from rlberry.envs.benchmarks.ball_exploration.ball2d import get_benchmark_env from rlberry.agents.torch.ppo import PPOAgent from rlberry.manager import AgentManager, plot_writer_data, evaluate_agents from rlberry.exploration_tools.discrete_counter import DiscreteCounter # ---------------------------...
11495643
import os from unittest import TestCase from runcommands.collection import Collection from runcommands.command import command from runcommands.run import run from runcommands.runner import CommandRunner CONFIG_FILE = os.path.join(os.path.dirname(__file__), "commands.toml") @command def test(a, b, c, d=None): r...
11495653
import os import numpy as np import george from george import kernels from scipy import integrate class sigmad_gp: def __init__(self): print('Initialize sigma_d emulator') self.cosmos = np.loadtxt(os.path.dirname( os.path.abspath(__file__)) + '/../data/cparams_4d.dat') self.yda...
11495660
from sklearn_explain.tests.skl_datasets import skl_datasets_test as skltest skltest.test_class_dataset_and_model("BinaryClass_500" , "SGDClassifier_3")
11495661
import math from military.soldier import TROOP_RADIUS class RankPosition: def __init__(self, unit, rank, position, canvas): self.unit = unit self.rank = rank self.position = position self.canvas = canvas self.x, self.y = 0, 0 self.soldier = None def change_...
11495668
import pytest from e2e_tests.conftest import TestPorts, run_tunneler_container, TunnelerType, TunneledType, \ run_test_tcp_single_client_single_short_echo, run_test_tcp_single_client_multiple_short_echo, \ run_test_tcp_single_client_single_long_echo, run_test_tcp_multiple_clients_single_short_echo, \ run_t...
11495677
import os import sys from abc import abstractmethod class AbstractRemoteObject(): '''This is an abstract class that all RemoteObjects will inherit from. This is an abstract class to ridgidly define the abstract methods of this RemoteObject class''' def __init__(self, *args, **kwargs): ...
11495706
from setuptools import setup, find_packages import os import re def hoplite_plugins(): hoplite_top_level = os.path.split(__file__)[0] plugin_dir = os.path.join(hoplite_top_level, "hoplite", "builtin_plugins") plugins = [] for directory, dirnames, filenames in os.walk(plugin_dir): for filename ...
11495720
import argparse import logging import os import cv2 as cv import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from scipy.stats import norm import math from config import im_size, epsilon, epsilon_sqr, device from scipy.ndimage import gaussian_filter, morphology from skimage.measure...
11495754
import pytest import numpy as np from orbit.eda import eda_plot def test_eda_plot(iclaims_training_data): df = iclaims_training_data df['claims'] = np.log(df['claims']) # test plotting _ = eda_plot.ts_heatmap(df=df, date_col='week', value_col='claims', seasonal_interval=52, normalization=True) ...
11495756
import numpy as np from pyquante2.grid.lebedev import lebedev class atomic_grid(object): def __init__(self,atom,**kwargs): atno,x,y,z = atom.atuple() if kwargs.get('radial','EulerMaclaurin') == 'Legendre': grid_params = LegendreGrid(atno,**kwargs) else: grid_params ...
11495780
from homeassistant.components.device_tracker import SOURCE_TYPE_GPS from homeassistant.components.device_tracker.config_entry import TrackerEntity from .baseentity import FordpassEntity from .const import STATES_MANAGER,FORD_VEHICLES async def async_setup_entry(hass, config_entry, async_add_entities): vehi...
11495788
import warnings from datetime import datetime, timedelta from .workbook import Workbook from .xlsbpackage import XlsbPackage __version__ = '0.0.8' def open_workbook(name, *args, **kwargs): """Opens the given workbook file path. Args: name (str): The name of the XLSB file to open. Returns: ...
11495823
import os from moviepy.editor import * from moviepy.video import fx ABS_PATH = os.path.abspath(__file__) BASE_DIR = os.path.dirname(os.path.dirname(ABS_PATH)) DATA_DIR = os.path.join(BASE_DIR, "data") SAMPLE_DIR = os.path.join(DATA_DIR, "samples") SAMPLE_INPUTS = os.path.join(SAMPLE_DIR, "inputs") SAMPLE_OUTPUTS = os....
11495856
from random import randrange class MillerRabinPrimalityTest: def __call__(self, n: int, k: int = 10) -> bool: if n == 2: return True if not n & 1: return False def check(a, s, d, n): x = pow(a, d, n) if x == 1: return True ...
11495874
class DocSimilarity: def __init__(self, model, docs): from signs.similarity import doc_similarity as sims from signs.utils.html_print import html_print self._sims = sims self._model = model self._docs = docs self._html_print = html_print ...
11495875
from django.core.cache import cache from rest_framework.authentication import (BaseAuthentication, get_authorization_header) from .exceptions import PermissionDenied from .models import check_auth_token from ..profiles.models import User class GoogleLoginAuthentication(Base...
11495883
import spacy from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.linear_model import LogisticRegression ########################## import ...
11495887
AWS_ACCESS_KEY_ID = 'aws_access_key_id' AWS_SECRET_ACCESS_KEY = 'aws_secret_access_key' TABLE_NAME = 'event_created' BUCKET_NAME = 'bucket' CONNECTION = 'host=localhost port=5432 dbname=postgres user=postgres password=<PASSWORD>'
11495911
from django.apps import AppConfig class BoilerplateAppConfig(AppConfig): name = 'boilerplate_app'
11495988
import io import json import csv import jsontableschema from jsontableschema.exceptions import InvalidObjectType from sqlalchemy.dialects.postgresql import insert class TransformStream(object): def __init__(self, fun): self.fun = fun def read(self, *args, **kwargs): return self.fun() def typ...
11495992
from arekit.common.entities.base import Entity from arekit.common.experiment.annot.algo.base import BaseAnnotationAlgorithm from arekit.common.labels.provider.base import BasePairLabelProvider from arekit.common.news.parsed.base import ParsedNews from arekit.common.news.parsed.providers.entity_service import EntityServ...
11496009
import os from pypact.input.groupstructures import ALL_GROUPS from pypact.util.decorators import freeze_it from pypact.util.jsonserializable import JSONSerializable from pypact.util.numerical import get_float, is_float from pypact.util.exceptions import PypactException, PypactOutOfRangeException, PypactDeserializeExce...
11496027
from django.contrib import admin from metaci.testresults.models import TestMethod, TestResult, TestResultAsset @admin.register(TestResult) class TestResultAdmin(admin.ModelAdmin): list_display = ("build_flow", "method", "duration", "outcome") list_filter = ("build_flow__build__repo", "method", "method__testc...
11496028
from roonapi import RoonApi, RoonDiscovery appinfo = { "extension_id": "python_roon_test", "display_name": "Python library for Roon", "display_version": "1.0.0", "publisher": "gregd", "email": "<EMAIL>", } # Can be None if you don't yet have a token try: core_id = open("my_core_id_file").read(...
11496034
import requests from Services.ApiAddressService import ApiAddressService from Services.StorageCookieService import StorageCookieService class AuthApiService(object): def __init__(self): self.apiaddress = ApiAddressService() self.storagecookie = StorageCookieService() def Version(self): ...
11496048
import pickle class HP: def __init__(self, grid_size, max_iter, discount): self.grid_size = grid_size self.max_iter = max_iter self.discount = discount def __str__(self): return " | ".join(["{} = {}".format(k,v) for k,v in self.__dict__.iteritems()]) class RlHp: def _...
11496081
import bugsnag from django.http import HttpResponse from django.shortcuts import render def index(request): return HttpResponse(b'Some content!') """ (some nonsense goes here) """ def unhandled_crash(request): raise RuntimeError('failed to return in time') def unhandled_crash_in_template...