id
stringlengths
3
8
content
stringlengths
100
981k
11510350
import argparse import json import datetime from args import get_parser, str2bool from utils import * from mtad_gat import MTAD_GAT from prediction import Predictor if __name__ == "__main__": parser = get_parser() parser.add_argument("--model_id", type=str, default=None, ...
11510352
from rest_framework import viewsets from rest_framework.response import Response from .models import Idc, Cabinet from .serializers import IdcSerializer, CabinetNodepthSerializer class IdcViewset(viewsets.ModelViewSet): """ retrieve: 返回指定Idc信息 list: 返回Idc列表 update: 更新Idc信息 ...
11510359
from pyradioconfig.parts.lynx.calculators.calc_radio import CALC_Radio_lynx class calc_radio_leopard(CALC_Radio_lynx): pass
11510371
def percent_encode(str): if str is None: return "" result_str = "" for char in str.encode(): if char >= 33 and char <= 0x7E and char != 34 and char != 37 and char != 39 and char != 44 and char != 92: result_str += chr(char) else: result_str += "%" ...
11510378
def findMinSum(num): sum = 0 # Find factors of number # and add to the sum i = 2 while(i * i <= num): while(num % i == 0): sum += i num /= i i += 1 sum += num # Return sum of numbers # having minimum product return sum ...
11510382
from telegram.ext import Updater from telegram.ext.dispatcher import Dispatcher from bot.handler import * from bot.handler.abstractHandler import AbstractHandler from config.envs import BOT_TOKEN, PORT, WEBHOOK_URL from logger import Logger class App: updater: Updater dispatcher: Dispatcher def __init__...
11510393
from tods.sk_interface.data_ensemble import * from tods.sk_interface.feature_analysis import * from tods.sk_interface.detection_algorithm import *
11510396
def load_to_exgdb(): cmds = [cmd for cmd in dir(ExgdbMethods) if callable(getattr(ExgdbMethods, cmd)) and not cmd.startswith("_")] for cmd in cmds: setattr(Exgdb, cmd, getattr(ExgdbMethods, cmd)) def load_to_exgdbcmd(): cmds = [cmd for cmd in dir(ExgdbCmdMethods) if callable(getattr(ExgdbCmdMethods...
11510417
def _cc_injected_toolchain_header_library_impl(ctx): hdrs = ctx.files.hdrs transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps] compilation_ctx = \ cc_common.create_compilation_context(headers = depset(hdrs)) info = cc_common.merge_cc_infos( cc_infos = transitive_cc_infos + ...
11510420
import sys; sys.path.append('C:\\Users\\Aaron\\workspace\\DigsbyTrunk\\digsby'); #import os #os.chdir('C:\\Users\\Aaron\\workspace\\DigsbyTrunk\\digsby') from ctypes import windll windll.comctl32.InitCommonControls() import wx from tests.testapp import testapp from win32events import bindwin32 from gui.u...
11510444
import sys import argparse import time import logging import subprocess from watchdog.observers import Observer from watchdog.events import LoggingEventHandler, FileSystemEventHandler class RsyncEventHandler(FileSystemEventHandler): def __init__(self, host, src_dir, dst_dir, flags, exclude): self.host = h...
11510449
from __future__ import print_function from orphics import maps,io,cosmology,lensing,stats from enlib import enmap,bench,lensing as enlensing,resample import numpy as np import os,sys from szar import counts import argparse from scipy.linalg import pinv2 # Parse command line parser = argparse.ArgumentParser(description...
11510472
from typing import List, Tuple import random from interfaces.TaggingOperation import TaggingOperation from tasks.TaskTypes import TaskType """ A tagging implementation of NER systems. I am travelling to London. --> I am travelling to South/Central London. """ def pick_random_word(seed): """ pick random "pre"...
11510484
import sys from math import sqrt def itertxt(filename): with open(filename, "r") as f: for line in f: yield line.rstrip() def loadtxt(filename): return list(itertxt(filename)) def savetxt(filename, txt): with open(filename, "w") as f: for line in txt: print(line...
11510537
import torch.nn as nn import torch class ParameterRegressor(nn.Module): def __init__(self, num_features, num_parts): super(ParameterRegressor, self).__init__() """ convolutional encoder + linear layer at the end Args: num_features: list of ints containing number of feat...
11510583
def f(): if True: if False: x =3 y = 4 return return 19
11510688
import numpy as np import pytest from sklearn.svm import SVC from m2cgen import ast from m2cgen.assemblers import SklearnSVMModelAssembler from tests.assemblers import utils from tests.utils import cmp_exprs def test_rbf_kernel(): estimator = SVC(kernel="rbf", random_state=1, gamma=2.0) estimator.fit([[1],...
11510740
from __future__ import print_function import argparse from datetime import datetime, timedelta import os import pytsk3 import pyewf import struct import sys import unicodecsv as csv from utility.pytskutil import TSKUtil """ MIT License Copyright (c) 2017 <NAME>, <NAME> Please share comments and questions at: htt...
11510791
from __future__ import annotations import random from typing import Dict, Generic, Optional, Sequence, TypeVar from pydantic import BaseModel, Field, PrivateAttr from pydantic.generics import GenericModel from tarkov.bots.bots import BotInventory from tarkov.exceptions import NotFoundError from tarkov.inventory.impl...
11510796
import requests # Vuln Base Info def info(): return { "author": "cckuailong", "name": '''Yuzo Related Posts plugin XSS''', "description": '''The Yuzo Related Posts plugin before 5.12.94 for WordPress has XSS because it mistakenly expects that is_admin() verifies that the request comes from...
11510861
from fpakman.core import resource from fpakman.core.flatpak.constants import FLATPAK_CACHE_PATH from fpakman.core.model import Application, ApplicationData class FlatpakApplication(Application): def __init__(self, base_data: ApplicationData, branch: str, arch: str, origin: str, runtime: bool, ref: str, commit: s...
11510874
import discord from discord.ext import commands class Latency(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="ping", aliases=['pong, latency']) async def ping(self, ctx): pong = round(self.bot.latency * 1000) await ctx.send(f":ping_pong: Pong in {pong}ms") def set...
11510885
from array import array import math from numpy.lib.arraysetops import isin from sympy.utilities.iterables import multiset_permutations from sympy.utilities.iterables import multiset_combinations import itertools from math import factorial import hashlib import numpy as np import gc """ A class to store the packing sc...
11510967
from bson import ObjectId from datetime import datetime, timedelta, timezone from flask import Response, abort, redirect, render_template, request import json import os import pymongo from .app import app, mongo from .utils import json_error, json_response, new_transcription, require_auth @app.route('/') def slash():...
11511027
import django_tables2 as tables from django.conf import settings from django.db.models import Case, When from django_tables2.utils import A from apis_core.apis_labels.models import Label from apis_core.apis_metainfo.models import Uri from apis_core.apis_metainfo.tables import ( generic_order_start_date_written, ...
11511053
from setuptools import setup setup(name='fdfault', version='1.0', description='Tools made to go with fdfault rupture code', url='https://github.com/egdaub/fdfault', author='<NAME>', author_email='<EMAIL>', packages=['fdfault', 'fdfault.analysis'], install_requires=['numpy'])
11511061
from typing import Optional from copy import copy import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from scipy import stats from scipy.special import inv_boxcox, boxcox from statsmodels.tsa.api import STLForecast from statsmodels.tsa.ar_model import AutoReg fr...
11511116
import pytest class TestAPreChargeDecision: @pytest.mark.skip(reason="So the CI build stays green. Remove this to get coding.") def test_should_record_alternative_offence_advice_against_suspects(self): pytest.fail()
11511133
import numpy as np import glob import sys import scipy.io as sio import argparse sys.path.append('../../') from util import env, decompose, angular_distance_np, inverse, Reader parser = argparse.ArgumentParser( description='measure error of input') parser.add_argument('--dataset', type=str, help='redwood or scanne...
11511159
import os from logging.config import fileConfig fileConfig('examples/logging_config.ini') DEGIRO_USERNAME = os.getenv('DEGIRO_USERNAME', '<SECRET>') DEGIRO_PASSWORD = os.getenv('DEGIRO_PASSWORD', '<SECRET>')
11511163
import os from django.conf import settings from django.core.files.base import ContentFile from django.shortcuts import render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.shortcuts import get_object_or_404 f...
11511197
from common import * import dask import dask.array as da @pytest.fixture def df(): x = np.arange(10, dtype=np.float64) y = x**2 df = vaex.from_arrays(x=x, y=y) df = df[['x', 'y']] # make sure we are in this order return df def test_dask_array(df): X = np.array(df) Xd = df.to_dask_array(chu...
11511207
from unittest import TestCase from django.core.management import call_command class RecalculateQueryCountTestCase(TestCase): def test_run_command(self): call_command('recalculate_query_count')
11511211
from montepython.likelihood_class import Likelihood_clocks class cosmic_clocks_BC03_all(Likelihood_clocks): pass
11511218
import sys sys.path.append("../") from helper.utils import * from config import * Print(" "*25+" Merge ") nn_model=pd.read_csv(join(sub_path,"nn_model")) cat_model=pd.read_csv(join(sub_path,"catboost_sub")) cat_model.sort_values("fid",inplace=True) nn_model.sort_values("fid",inplace=True) columns=cat_model.drop(["fid"...
11511239
import itertools import math import warnings from copy import deepcopy from enum import Enum from typing import TYPE_CHECKING from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Sequence from typing import Set from typing impo...
11511266
from __future__ import print_function, absolute_import import unittest import numpy as np from misc import * from sklearn import linear_model from pandas_extensions import base_pandas_extensions_tester class T(base_pandas_extensions_tester.BasePandasExtensionsTester): def test_cv(self): c = linear_...
11511305
import numpy as np import os import csv from PIL import Image import shutil att = open('./Celeb/attrs.txt','r') imgs = os.listdir('./Celeb/data1024') imgs.sort() # print(len(attlines)) attlines = [] while True: attline = att.readline().split() if not attline:break attlines.append(attline) #...
11511310
import praw import inspect, os, sys # set the BASE_DIR import simplejson as json import datetime import reddit.connection import reddit.praw_utils as praw_utils import reddit.queries import sqlalchemy import app.event_handler from utils.common import PageType from app.models import Base, SubredditPage, Subreddit, Post,...
11511311
import json from ..compat import compat_urllib_parse from ..utils import raise_if_invalid_rank_token class TagsEndpointsMixin(object): """For endpoints in ``/tags/``.""" def tag_info(self, tag): """ Get tag info :param tag: :return: """ endpoint = 'tags/{tag!...
11511363
import numpy as np import torch def rotate_pc_along_y(pc, rot_angle): """ params pc: (N, 3+C), (N, 3) is in the rectified camera coordinate params rot_angle: rad scalar Output pc: updated pc with XYZ rotated """ cosval = np.cos(rot_angle) sinval = np.sin(rot_angle) rotmat = np.array([[...
11511379
import pytz def check_associations(collection, association): """All items in collection should contain a reference to the association's database ID""" for item in collection: assert item[association.__class__.__name__.lower() + '_id'] == association['_id'] def check_persistence(target, *target_args...
11511472
from .PBXResolver import * from .PBXSourcesBuildPhase import * from .PBXFrameworksBuildPhase import * from .PBX_Build_Setting import * from .PBX_Constants import * class PBX_Base_Target(PBX_Build_Setting): def __init__(self, lookup_func, dictionary, project, identifier): super(PBX_Base_Target, self)._...
11511489
import numpy import csb.test as test import csb.bio.structure as structure import csb.core import csb.bio.sequence as sequence @test.regression class ChainRegressions(test.Case): def setUp(self): super(ChainRegressions, self).setUp() self.structure = self.config.getPickle('1nz...
11511500
from fastapi import Request, Response from fastapi.responses import RedirectResponse from fps.hooks import register_exception_handler from fps.logging import get_configured_logger logger = get_configured_logger("helloworld") class RedirectException(Exception): def __init__(self, reason, redirect_to): se...
11511507
from spritecss.css import parser from itertools import izip def parser_events(): p = iter(parser.CSSParser(data="sel { decl: val; }\n")) evs = [("selector", {"selector": "sel "}), ("whitespace", {"whitespace": " "}), ("declaration", {"declaration": "decl: val"}), ("whitespace",...
11511544
import numpy as np import jax.numpy as jnp from jax.nn import softplus from utils import softplus_inv from jax.experimental import optimizers from jax import value_and_grad import matplotlib.pyplot as plt import time from sde_gp import SDEGP from approximate_inference import EP, PL, CL, IKS, EKEP import priors import l...
11511581
class Solution: def replaceElements(self, arr: List[int]) -> List[int]: n = len(arr) for i in range(n - 1, -1, -1): if i == n - 1: premax = arr[i] arr[i] = -1 else: cmax = max(premax, arr[i]) arr[i] = premax ...
11511589
from rest_framework import serializers from bullet_point.models import BulletPoint, Endorsement, Flag, Vote from user.serializers import UserSerializer from utils.http import get_user_from_request class EndorsementSerializer(serializers.ModelSerializer): bullet_point = serializers.PrimaryKeyRelatedField( ...
11511599
def calculate_score(str1: str, str2: str, partial_match=False): """ Calculates how close `str1` matches `str2` using fuzzy match. How matching works: – first characters of both `str1` and `str2` *must* match – `str1` length larger than `str2` length is allowed only when `unmatched` is true – ide...
11511647
import datasets from transformers import (AutoTokenizer, DataCollatorForLanguageModeling, TrainingArguments, Trainer, AutoModelForMaskedLM, PreTrainedTokenizerFast) from datasets import load_dataset, concatenate_datasets from transformers import AutoTokenizer, PreTrainedTokenizerFast import r...
11511693
from ..utils import Scraper from bs4 import BeautifulSoup from collections import OrderedDict import json import os import requests class UTSCTimetable: host = 'http://www.utsc.utoronto.ca/~registrar/scheduling/timetable' @staticmethod def scrape(location='.'): Scraper.logger.info('UTSCTimetable...
11511727
from time import * import functools from peewee import * import logging # 这个模块主要用来放一些装饰器的函数。 def db_connnect(text): """ 连接sqlite数据库的装饰器。 :param text: 要连接的数据库名。 :return: None。 """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): db = SqliteD...
11511760
import random import numpy as np import nltk import sklearn import keras import json import scipy from collections import defaultdict import gen_util import keras random.seed(1337) path="../big_domain_desc/" maxlen=120 train_per_cls=100 #seen examples test_per_cls=50 #test examples so 5000 test examples in the end. mo...
11511762
info = [ ('nn::spl::detail::IRandomInterface', 0, '', '0 bytes in - 0 bytes out - Buffer<0,6,0>', ''), ('nn::fssrv::sf::IFileSystemProxy', 1, '', '8 bytes in - 0 bytes out - takes pid - InRaw<8,8,0>', ''), ('nn::fssrv::sf::IFileSystemProxy', 2, '', '0 bytes in - 0 bytes out - OutObject<0,0>', ''), ('nn::fssrv::sf::...
11511781
class BaseStrategy(object): def __init__(self, debug, type): self.debug = debug.log self.type = type def on_tick(self, my_elevators, my_passengers, enemy_elevators, enemy_passengers): pass
11511782
import copy if __name__ == "__main__": ''' ref. https://docs.python.org/3.6/library/copy.html ''' origin_list = [1, 2, [3, 4]] copy1 = copy.copy(origin_list) # shallow copy copy2 = copy.deepcopy(origin_list) # deep (recursive) copy print(copy1 == copy2) print(copy1 is copy2) ...
11511807
from autologin_middleware import ExposeCookiesMiddleware from scrapy.exceptions import NotConfigured class CookiesMiddlewareIfNoSplash(ExposeCookiesMiddleware): @classmethod def from_crawler(cls, crawler): if crawler.settings.get('SPLASH_URL'): raise NotConfigured return super().fr...
11511836
class MyConnMachineOut: """Implementation of the application data type MyConnMachineOut. Generated by: EASy-Producer.""" cmdField: str
11511837
import pytest from ..control import Control @pytest.mark.parametrize( "test_input,expected", [("AC-2", "AC-2"), ("AC-2 (1)", "AC-2 (1)"), ("AC-2(1)", "AC-2 (1)")], ) def test_normalized_name(test_input, expected): control = Control(test_input) assert control.normalized_name() == expected
11511840
cond1 = df['species'] == 'setosa' cond2 = df['sepal length (cm)'] > 5.5 cond3 = df['petal length (cm)'] < 1.3 df[cond1 & (cond2 | cond3)]
11511875
import tensorflow as tf ''' Two layers feed forward model ''' class Feed_forward_two_layers: def get_name(self): return "feed_forward_two_layers" def input_placeholders(self): inputs_placeholder = tf.placeholder(tf.float32, shape=[None, 784], name="inputs") labels_placeholder = tf.pl...
11511878
from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', # Examples: # url(r'^$', 'activitytracker.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', 'home.views.home', name='home'), url(r'^registration/$', 'hom...
11511922
from nspawn.wrapper.sudo import Sudo def test_sudo(): sudo = Sudo() result = sudo.execute_unit(['ls', '-las']) # print(result.stdout) # print(result.stderr) def test_sudo_folder_check(): sudo = Sudo() assert sudo.folder_check("/tmp") is True def test_sudo_folder_assert(): sudo = Sudo()...
11511932
from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.errors import AnsibleFilterError from ansible.module_utils.common._collections_compat import Iterable def users_groups(users, groups=None): if not isinstance(users, Iterable): raise AnsibleFilterError('Expe...
11511956
import pymongo import multiprocessing as mp from pathlib import Path from sc2reaper.sc2reaper import ingest as _ingest from sc2reaper.sc2reaper import DB_NAME, address, port_num from sc2reaper import utils def ingest(path_to_replays, proc): """ Load a replay into a mongo database. """ # So that pysc2...
11512020
from __future__ import annotations import ast import builtins from typing import Optional, List, Union, TypeVar, cast from stdlib_list import stdlib_list from mr_proper.common_types import AnyFuncdef from mr_proper.config import TARGET_PYTHON_VERSION if False: # TYPE_CHECKING from typing import Type T = Type...
11512088
from gym.envs.registration import register register( id='Carla-v0', entry_point='environment.carla_gym.envs:CarlaEnv', )
11512133
from py3plex.core import random_generators ER_multilayer = random_generators.random_multilayer_ER(200, 6, 0.09, directed=True) ER_multilayer.visualize_net...
11512173
import os import torch import argparse import numpy as np from collections import defaultdict from mmcv import Config from mmcv.runner import load_checkpoint, init_dist, get_dist_info from mmcv.parallel import MMDistributedDataParallel from mmdet.apis import set_random_seed, multi_gpu_test from mmdet3d.models import bu...
11512179
import numpy as np import random import os import numpy as np import sys from os import listdir from os.path import isfile, join from tqdm import tqdm import pickle import torch import pandas as pd from skimage import io, transform import numpy as np import matplotlib.pyplot as plt from torch.utils.data import Datase...
11512188
def parse_notifier_schema(schema): return list(filter(lambda x: x != "message" and not schema["properties"][x].get("duplicate"), schema["properties"].keys()))
11512207
import sys import os import unittest import uuid def _create_random_voice(app): id = uuid.uuid4().hex[:3] name = 'vn_' + uuid.uuid4().hex[:4] lang = uuid.uuid4().hex[:2] acc = uuid.uuid4().hex[:2] gender = uuid.uuid4().hex[:5] directory = uuid.uuid4().hex[:5] with app.app_context(): ...
11512232
import random from selenium_ui.bamboo.pages.pages import Login, Logout, ProjectList, BuildList, PlanConfiguration, BuildActivity, \ PlanSummary, BuildSummary, BuildLogs, PlanHistory, JobConfiguration from selenium_ui.conftest import print_timing USERS = "users" BUILD_PLANS = "build_plans" def setup_run_data(dat...
11512243
import sys import uuid import time import traceback import queue import json import datetime import mprpc import logging import socket import dill import pprint import threading import multiprocessing import os import common.LogBase import common.get_rpyc from WebMirror.JobUtils import buildjob from common.util impor...
11512256
import numbers # import numbers.py file class Block_type: def __init__(self, texture_manager, name = "unknown", block_face_textures = {"all": "cobblestone"}): self.name = name # set our block type's vertex positions, texture coordinates, and indices to the default values in our numbers.py file self.vertex_pos...
11512318
load(":wrapped_ctx.bzl", "repo_file", "repo_template") def error(message): return struct(value = None, error = message) def success(value): return struct(value = value, error = None) def globvalue(values, exclude = None, exclude_directories = True): keyword_arguments = {} if exclude: keyword_...
11512323
import os os.environ['KMP_DUPLICATE_LIB_OK']='True' os.environ["CUDA_VISIBLE_DEVICES"] = "0" import cv2 import paddlehub as hub import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import math src_img = cv2.imread('./3.jpg') shape = src_img.shape ss = (round(shape[1]/3),round(shape[0]...
11512353
from __future__ import print_function import time import copy from sys import getsizeof from mpi4py import MPI import numpy as np import hdmedians as hd from scipy import linalg as LA from scipy import fftpack as FT from scipy.optimize import lsq_linear import torch import sys sys.path.append("..") from nn_ops import...
11512376
import IECore import IECoreScene class multiTypeObject( IECore.Op ) : def __init__( self ) : IECore.Op.__init__( self, "Op that returns either a MeshPrimitive or a PointsPrimitive, depending on the input type.", IECore.ObjectParameter( name = "result", description = "", defaultValue = IECoreScen...
11512380
from ..util.functions import weights_check import torch from torch import nn def make_model(model_weights): available_weights = ["SHB"] if model_weights not in available_weights: raise ValueError("Weights {} not available for CSRNet. Available weights: {}".format(model_weights, ...
11512428
from pathlib import Path from .app_settings import AppSettings from .fsr_cfg import FsrSettings from .globals import OPEN_VR_DLL from .openvr_mod import OpenVRMod, OpenVRModType class FsrMod(OpenVRMod): TYPE = OpenVRModType.fsr VAR_NAMES = { 'installed': 'fsrInstalled', 'version': 'fsrVersion...
11512437
from qgreenland.tasks.common.fetch import FetchCmrGranule from qgreenland.tasks.common.misc import ExtractNcDataset from qgreenland.tasks.common.raster import BuildRasterOverviews, WarpRaster from qgreenland.util.luigi import LayerPipeline class BedMachineDataset(LayerPipeline): """Dataproduct IDBMG4. This i...
11512444
from .nbtransom import min_pretty, min_pretty_sub, get_var_name, find_cell, create_code_cell, create_data_cell, get_val, set_val, put_df, save_nb, open_nb
11512531
import json debug = False filename = 'verisc-labels.json' namespace = 'veris' description = 'Vocabulary for Event Recording and Incident Sharing (VERIS)' output = {} output['namespace'] = namespace output['description'] = description output['version'] = 2 output['predicates'] = [] output['values'] = [] with open(fil...
11512579
import os import datetime import json import magic import shutil from pathlib import Path from scripts.artifact_report import ArtifactHtmlReport from scripts.ilapfuncs import logfunc, tsv, timeline, kmlgen, is_platform_windows def get_instagramDevicescam(files_found, report_folder, seeker, wrap_text): for f...
11512604
from pandas_genomics.scalars import Variant def test_create_variant(): variant = Variant("12", 112161652, "rs12462", ref="C", alt=["T"]) assert variant.alleles == ["C", "T"] def test_methods(): variant = Variant("12", 112161652, "rs12462", ref="C", alt=["T"]) variant_also = Variant("12", 112161652, ...
11512611
from time import strftime from time import gmtime import tekore as tk from PIL import Image #import time from modules import d_functions as d_f import os import requests creddir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'credentials') picdir = os.path.join(os.path.dirname...
11512612
import os import uuid import subprocess from jivago.config.properties.application_properties import ApplicationProperties from jivago.lang.annotations import Inject from jivago.templating.rendered_view import RenderedView from jivago.wsgi.annotations import Resource from jivago.wsgi.methods import GET, POST from jiva...
11512626
from typing import Tuple, List import numpy as np from src.base import Optimizer, Layer class Adam(Optimizer): def __init__( self, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8 ): """ :param lr - learning rate :param beta1 - ...
11512634
import torch import torch.nn as nn import numpy as np from functools import partial import torch.nn.init as init import torch.nn.functional as F import math from timm.models.layers import DropPath, to_2tuple import pdb DROPOUT_FLOPS = 4 LAYER_NORM_FLOPS = 5 ACTIVATION_FLOPS = 8 SOFTMAX_FLOPS = 5 class ...
11512642
import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.autograd as autograd from multiprocessing_env import SubprocVecEnv from minipacman import MiniPacman import matplotlib.pyplot as plt from tqdm import tqdm #USE_CUDA = torch.cuda.is_availab...
11512671
from scipy.optimize import minimize; import numpy as np; from scipy import stats import itertools; import analysis; class BaseModel: def __init__(self): self.p = None; def set(self,p): self.p = p; class SexAgeModel(BaseModel): def __init__(self): self.p = np.array([[4.0,3,10.6,12,...
11512697
import matplotlib.pyplot as plt import numpy as np from fractions import Fraction def create_pi_labels(a=0, b=2, step=0.5, ax=None, direction='x'): """ A function that gives back ticks an labels in radians Keyword arguments: a -- lower limit is a*pi (default 0.0) b -- upper limit is b*pi (default...
11512797
from django.db.models import Q from dal_select2.views import Select2QuerySetView class AuthorAutocomplete(Select2QuerySetView): def get_queryset(self): from modules.users.service import _authors, _users if not self.request.user.is_authenticated: return [] if not self.request....
11512802
import unittest from unittest.mock import patch from unittest.mock import Mock import os from programy.services.rest.microsoft.search.service import MicrosoftSearchService from programy.services.config import ServiceConfiguration from programytest.services.testclient import ServiceTestClient from programytest.services....
11512837
from streamlink.plugins.cinergroup import CinerGroup from tests.plugins import PluginCanHandleUrl class TestPluginCanHandleUrlCinerGroup(PluginCanHandleUrl): __plugin__ = CinerGroup should_match = [ 'http://showtv.com.tr/canli-yayin', 'http://haberturk.com/canliyayin', 'http://showmax...
11512852
from setuptools import setup setup(name='pyvue', version='0.1.7', description='Generate HTML strings in pure python, or JSX style code', url='http://github.com/oakfang/pyvue', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=['pyvue'], entry_points={ ...
11512877
import os import sys sys.path.append("phantom_scripts") # This is the main phantom script which creates all phantoms. # Must be run from the folder which contains this file. class Args: pass out_dir = "generated_phantoms" def verify_correct_path(): dirs = [entry for entry in os.listdir('.') if os.path.i...
11512878
from collections import deque import pandas as pd from xml.etree import ElementTree as ET def get_gene_ontology(filename='../../data/go-basic.obo'): # Reading Gene Ontology from OBO Formatted file go = dict() obj = None with open(filename, 'r') as f: for line in f: line = line.strip...