id
stringlengths
3
8
content
stringlengths
100
981k
3332167
import torch import torch.nn as nn import torch.nn.functional as F from mylib.torch_utils import kaiming_init def conv1x1(in_channels, out_channels, **kwargs): return nn.Conv2d(in_channels, out_channels, kernel_size=1, **kwargs) def conv3x3(in_channels, out_channels, stride=1, **kwargs): return...
3332175
import collections import os import numpy as np from PIL import Image def read_obj_with_group(filename, swapyz=False): vertices = [] colors = [] normals = [] texcoords = [] faces = [] normal_idxs = [] texcoord_idxs = [] materials = [] mtl = None group = [[], [], []] material = None for line ...
3332197
from typing import Any, IO import sys class Base: '''An output stream that supports tokens.''' def write(self, thing: Any) -> None: '''Show anything that can be converted to a string.''' self.override_write(str(thing)) def override_write(self, string: str) -> None: '''Print a strin...
3332266
import os import sys import time import numpy as np import configparser import json et = 1e-8 def load_json(path): with open(path,'r') as load_f: load_dict = json.load(load_f) return load_dict def save_json(path, data): with open(path,'w') as f: json.dump(data,f) def print_dict(x): for key in x: print(k...
3332271
import sys import re import os import subprocess def extension(file): return file.split(".")[-1] def clean_name(name): return name.replace("\\\\", "/").replace("\\", "/") def process_file(fullname): content = "" with open(fullname, "r") as f: content = f.read() parent = ""...
3332295
from __future__ import print_function import itertools import os import sys from functools import wraps from ruskit import cli NO_RETRY = -1 COLOR_MAP = { "red": 31, "green": 32, "yellow": 33, "blue": 34, "purple": 35 } def echo(*values, **kwargs): end = kwargs.get("end", '\n') color...
3332347
def function_1(): function_2() function_3() return def function_2(): function_3() function_1() return def function_3(): return # def function_4(): # function_5() # return # def function_5(): # function_6() # function_7() # return # def function_6(): # function_5...
3332392
from .simple_net import * from .cifar_net import * from .basic_conv import * from .preresnet import * from .resnet import * from .convnet import *
3332396
import functools from ...drivers.channel_order import ChannelOrder USAGE = """ A ChannelOrder can be initialized with: * A list, tuple or string of length three: '012', 'bgr', (0, 2, 1) * An integer from 0 to 5.""" NAMES = { 'r': 0, 'g': 1, 'b': 2, 'R': 0, 'G': 1, 'B': 2, '0': 0, '1':...
3332464
import numpy as np class StandardScaler(object): """ Standardize features by removing the mean and scaling to unit variance. Parameters ---------- copy : bool, optional If False, do inplace scaling. with_mean : bool, optional If True, center the data before scaling. wi...
3332488
import os import unittest from gcn.classification.baseline_trainer import BaselineTrainer from gcn.classification.baseline import LSTMClassifier class TestBaselineTrainer(unittest.TestCase): def test_build(self): root = os.path.join(os.path.dirname(__file__), "../../") trainer = BaselineTrainer(r...
3332495
from __future__ import absolute_import from . import loss # NOQA from . import accuracy # NOQA from .mc_dropout import mc_dropout # NOQA from .crop import crop # NOQA from .stride_pooling import stride_pooling_2d # NOQA from .stride_pooling import stride_pooling_3d # NOQA from .stride_pooling import stride_pooli...
3332512
from torchvision.transforms import ToTensor, Compose, RandomAffine from torch.utils.data import Dataset import pandas as pd from os.path import join from PIL import Image, ImageOps import numpy as np import random class SketchyDB(Dataset): """ class representing the Sketchy Database """ def __init__(self, ro...
3332541
from ray.tune.utils.util import deep_update, flatten_dict, get_pinned_object, \ merge_dicts, pin_in_object_store, UtilMonitor, validate_save_restore, \ warn_if_slow __all__ = [ "deep_update", "flatten_dict", "get_pinned_object", "merge_dicts", "pin_in_object_store", "UtilMonitor", "...
3332569
from io import StringIO from unittest.mock import patch from django.contrib.auth.models import User from django.core import management from django.core.management.base import CommandError from django.db.models.signals import post_save from django.test import TestCase from options.models import Option from courses.mod...
3332594
import re def restore_text(text): text = re.sub('=', '', text) text = re.sub(',', '', text) text = ' '.join(text.split()).strip() return text def split_bs_text_by_domain(bs_text, bsdx_text): res_text_list = [] bs_text = bs_text.strip('<sos_b>').strip('<eos_b>').strip() bsdx_text = bsdx_text...
3332634
import krpc import math import time conn = krpc.connect(name="Orbital Test") vessel = conn.space_center.active_vessel srf_frame = vessel.orbit.body.reference_frame orb_frame = vessel.orbital_reference_frame semi_major = vessel.orbit.semi_major_axis current_radius = vessel.orbit.radius gm = vessel.orbit.body.gravitati...
3332637
import codecs import numpy as np import nltk from star_clustering import StarCluster wordlist = nltk.corpus.words.words('en-basic') print('Getting vectors...') words = [] vectors = [] count = 0 with codecs.open('Data/wiki-news-300d-1M.vec', 'r', 'utf-8') as f: for i, line in enumerate(f): """ if i...
3332639
from django import forms from django.conf import settings from django.core.exceptions import ImproperlyConfigured from .models import Company, Office from .widgets import AddressWidget if not settings.GOOGLE_ADDRESS['API_KEY']: raise ImproperlyConfigured("GOOGLE_API_KEY is not configured in settings.py") class ...
3332655
import logging import os from argparse import ArgumentParser import torch import torch.nn as nn from src.detr.matcher import build_matcher from src.utils.configs import get_default_configuration, load_config from src.utils.confusion import BinaryConfusionMatrix from src.data import data_factory import src.uti...
3332768
import pytest from ... import bs2051 from ..gain_calc import GainCalc @pytest.fixture(scope="module") def layout(): return bs2051.get_layout("4+5+0") @pytest.fixture(scope="module") def layout_without_lfe(layout_with_lfe): return layout_with_lfe.without_lfe @pytest.fixture(scope="module") def gain_calc(la...
3332772
from django.contrib import admin # Register your models here. from msgvis.apps.enhance import models admin.site.register(models.Dictionary) admin.site.register(models.Word) admin.site.register(models.TopicModel) admin.site.register(models.Topic) admin.site.register(models.TopicWord) admin.site.register(models.Message...
3332819
import numpy as np import pandas as pd import matplotlib.pyplot as plt import pprint import config.settings import config.strategy from core.utility import chunk_trades, sharpe, drawdown from multiprocessing_on_dill import Pool #, Process, Manager from contextlib import closing class accountCurve(): """ Accou...
3332837
from PyQt5.QtCore import Qt from PyQt5.QtGui import ( QColor, ) from PyQt5.QtWidgets import ( QColorDialog, QDialog, ) from .forms import settings_forecolor_bgcolor class SettingsForForeBgColor(QDialog): def __init__(self, parent=None, category=None, config=None): self.category = category ...
3332857
import click import os import json import pandas as pd import datetime import logging import gitlab import joblib from sklearn.preprocessing import OneHotEncoder from titanic.model_config import titanic_model_container, build_feature_matrix from typing import List, Dict from hypermodel.platform.local.services impor...
3332918
from magma import * from loam import Peripheral class SPI(Peripheral): name = 'spi' IO = ["MOSI", Out(Bit), "MISO", In(Bit), "SCLK", Out(Bit), "CS", Out(Bit)] def __init__(self, name='spi0', board=None): super(SPI,self).__init__(name, board) def on(self): ...
3332943
from .db import yield_db_session, yield_db_session_ctx from .models import ( EthereumBlock, EthereumLabel, EthereumTransaction, PolygonBlock, PolygonLabel, PolygonTransaction, ) from enum import Enum from typing import Type, Union class AvailableBlockchainType(Enum): ETHEREUM = "ethereum...
3333017
from lib.base_controller import CommandController class CollectinfoCommandController(CommandController): log_handler = None def __init__(self, log_handler): CollectinfoCommandController.log_handler = log_handler
3333035
from ztom import ActionOrder # compatibility class OrderWithAim(ActionOrder): def __init__(self, symbol, amount: float, price: float, side: str, cancel_threshold: float=0.000001, max_order_updates: int=10): print("Please change OrderWithAim to ActionOrder") input("Press Enter to...
3333071
import pytest from flask_restful_swagger import swagger def empty_func(): pass def func_with_many_args(arg1, arg2, arg3, kwarg1=None, kwarg2=None): allargs = (arg1, arg2, arg3, kwarg1, kwarg2) print("func_with_many_args: %s, %s, %s, %s, %s" % allargs) class EmptyClass: pass @pytest.mark.paramet...
3333079
import pytest from hyp.base import BaseResponder, BaseAdapter from fixtures import CommentSerializer class TestBaseResponder(object): def test_error_raised_if_adapter_not_specified(self): # No Adapter specified class BadResponder(BaseResponder): TYPE = 'comments' SERIALIZE...
3333087
from sys import path import modules import modules.common from os.path import abspath, dirname import threading import time path.append(dirname(abspath(__file__))) def get_version(): return "0.1.0-experimental" def get_loaded_modules(): l = [] for m in modules.common.Modules.list: l.append(m.ge...
3333129
import os # Returns the content of ./wbn/subresource.wbn if the request has an "Accept" # header including "application/webbundle;v=b1" type, otherwise returns an # empty body with status code 400. def main(request, response): headers = [ (b"Content-Type", b"application/webbundle"), (b"X-Content-T...
3333168
from __future__ import print_function from ggplot import * import pandas as pd p = ggplot(mtcars, aes('factor(cyl)', 'mpg')) print(p + geom_violin()) diamonds['clarity'] = pd.Categorical(diamonds['clarity'], ordered=True, categories='I1 SI2 SI1 VS2 VS1 VVS2 VVS1 IF'.split()) prin...
3333183
import json def dump_json(data, file, indent=None): try: with open(file, 'w') as f: json.dump(data, f, indent=indent) except Exception as e: raise e def load_json(file): try: with open(file, 'r') as f: data = json.load(f) except Exception as e: r...
3333229
from typing import NewType, Dict, Any, Callable, Iterable, Union, IO, AnyStr from pathlib import Path ValueObject = NewType("ValueObject", Dict[str, Any]) CmpFunc = NewType("CmpFunc", Callable[[Any, Iterable], bool]) FileDictStringLike = Union[str, Path, IO[AnyStr], Dict[str, any]]
3333361
from rest_framework import status from rest_framework.exceptions import APIException class APIReactionExists(APIException): status_code = status.HTTP_409_CONFLICT default_detail = "Reaction already exists." class APITooManyReactions(APIException): status_code = status.HTTP_413_REQUEST_ENTITY_TOO_LARGE ...
3333396
import datetime as dt import numpy as np from ravenpy.config.commands import LU from ravenpy.models import SACSMA, SACSMA_OST from ravenpy.utilities.testdata import get_local_testdata TS = get_local_testdata( "raven-gr4j-cemaneige/Salmon-River-Near-Prince-George_meteo_daily.nc" ) hru = SACSMA.HRU( area=4250...
3333409
import exploit_api import sys def get_xxe_with_payload_in_get_query_parameter(our_url): with open('products_xxe_with_payload.xml', 'r') as f: xml_template = f.read() return xml_template.format(our_server_url=our_url) def import_xml(our_url, victim_url): token_header = exploit_api.get_header_...
3333435
from typing import Tuple, Union from pydantic.dataclasses import dataclass from pythae.config import BaseConfig @dataclass class BaseNFConfig(BaseConfig): """This is the Base Normalizing Flow config instance. Parameters: input_dim (tuple): The input data dimension. Default: None. """ input_...
3333466
import torch import models.archs.CNLRN_arch as CNLRN_arch import models.archs.PreDeblur_arch as PreDeblur_arch import models.archs.discriminator_vgg_arch as SRGAN_arch import models.archs.RRDBNet_arch as RRDBNet_arch import models.archs.EDVR_arch as EDVR_arch # Generator def define_G(opt): opt_net = opt['network_...
3333471
from yaml import load, dump from jinja2 import Template import sys try: from yaml import CLoader as Loader, CDumper as Dumper except ImportError: from yaml import Loader, Dumper ksy = load(open(sys.argv[1]).read(), Loader=Loader) template = open("template.lua").read() template = Template(template,trim_blocks...
3333501
from ._base import BaseOAuth, _FlaskRequestType, TestBaseOAuth from typing import Dict, Tuple from flask_jwt_router.oauth2.google import Google class GoogleTestUtil(Google, TestBaseOAuth): def create_test_headers(self, *, email: str, entity=None, scope="function") -> Dict[str, str]: """ :key emai...
3333548
expected_output = { 'neighbors': { '10.1.1.1': { 'interface': 'p4/1', 'ldp_id': '10.1.1.1:0', 'max_hold': 15, 'time_left': 14 }, '10.5.5.5': { 'interface': 'p3/2', 'ldp_id': '10.5.5.5:0', 'max_hold': 15, 'time_left': 11 }, '10.4.4.4': { 'interf...
3333562
import sass def main(sass_dir, css_dir): sass.compile(dirname=(sass_dir, css_dir), output_style='compressed') if __name__ == '__main__': import sys main(sys.argv[1], sys.argv[2])
3333585
import pymel.core as pm import pulse.nodes import pulse.utilnodes from pulse.buildItems import BuildAction, BuildActionError class AddIKFKControlAction(BuildAction): def validate(self): if not self.ikfkControl: raise BuildActionError('ikfkControl must be set') if not self.follower: ...
3333678
import optparse from OSC import * from OSC import _readString, _readFloat, _readInt if __name__ == "__main__": s = OSCServer(("127.0.0.1", 7500), return_port=7500) s.addMsgHandler("/out", s.msgPrinter_handler) print s st = threading.Thread(target=s.serve_forever) st.start() try: while True: time.sleep(3...
3333685
from flask import Flask, Response from flask_socketio import SocketIO, send, emit from queue import Queue import base64 import cv2 import numpy as np from PIL import Image import io d = dirname(dirname(abspath(__file__))) app = Flask(__name__) app.queue = Queue() socketio = SocketIO(app) @socketio.on('connect', names...
3333691
import io import json import pickle import numpy as np from numpy import save from numpy import load import argparse from nltk import word_tokenize from hmm import build_vocab2idx, create_dictionaries, create_transition_matrix, create_emission_matrix, initialize, viterbi_forward, viterbi_backward from utils import proc...
3333731
import torch import torch.nn as nn import numpy as np from utils import * from auto_LiRPA.bound_ops import * from datasets import cifar10_mean, cifar10_std from torch.autograd import Variable import pdb import random criterion = ce_loss def init_delta(X, epsilon, data_min, data_max): delta = torch.zeros_like(X) ...
3333758
from unittest import TestCase from api import Deck, State, util import random class TestState(TestCase): #Use seed to deterministically generate a state for which #we know what should happen. Uses seed=50 #Can possibly remove the asserts for get_card_states, perspectives might be enough. def test_trump_jack_ex...
3333804
codes = { "a" : ".-", "b" : "-...", "c" : "-.-.", "d" : "-..", "e" : ".", "f" : "..-.", "g" : "--.", "h" : "....", "i" : "..", "j" : ".---", "k" : "-.-", "l" : ".-..", "m" : "--", "n" : "-.", "o" : "---", "p" : ".--.", "q" : "--.-", "r" : ".-.", "s" : "...", "t" : "-", "u" : "..-", "v" : "...-", "w" : ".--", "x" : "-.....
3333814
from .backbones.flownets import FlowNetS from .heads.fc_rot_trans_head import FC_RotTransHead from .heads.conv_out_head import ConvOutHead from .heads.top_down_head import TopDownHead import timm BACKBONES = {"FlowNetS": FlowNetS} # register timm models # yapf: disable # "resnet18", "resnet18d", "tv_resnet34", "resn...
3333880
from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class ITagHeader(Base): __slots__ = () _SDM_NAME = 'iTagHeader' _SDM_ATT_MAP = { 'ITAGEthertypeEthertypeValue': 'iTagHeader.iTAGEthertype.ethertypeValue-1', 'ITAGPcp': 'iTagHeader.iTAGEthertype.iTAG.pcp-2', ...
3333891
class Theme(): BG_COLOR = '#fff' COLOR_1 = '#b9b28b' COLOR_2= '#8ba7b9' COLOR_3 = '#b98b99' COLOR_4 = '#7A976B' TEXT_COLOR = '#1B3D2F'
3333923
from bolero.representation import Behavior import numpy as np from numpy.testing import assert_array_equal class TestBehavior(Behavior): """A simple test behavior. Multiplies every input by a value specified in the meta parameters. """ def __init__(self, test_value_a, test_value_b): #test_val...
3333985
import tensorflow as tf from tensorpack.models import BatchNorm, LayerNorm, InstanceNorm, layer_register, VariableHolder from tensorpack.utils.argtools import get_data_format import numpy as np from config import config as FLAGS def get_rn(zero_init=FLAGS.zero_init): """ Zero init gamma is good for resnet. S...
3334004
import os import os.path as osp import importlib.util from pprint import pprint def add_unit_test_app_extension(base_actions, project_path=os.getcwd()): _spec = importlib.util.spec_from_file_location("idf_ext", osp.join(os.environ["IDF_PATH"], "tools", "unit-test-app", "idf_ext.py")) _unit_test_app_idf_ext = i...
3334007
import glob import json import os import re from pathlib import Path from typing import Dict, List, TypeVar from genson import SchemaBuilder from tqdm import tqdm from pokeapi_ditto.commands.models import COMMON_MODELS from pokeapi_ditto.common import from_path T = TypeVar("T") def _replace_common_model(item: T, n...
3334057
from django.db import models class AbstractApplicationKeyValue(models.Model): """ Abstract model for application+Key/value pair. """ application = models.CharField(max_length=300, db_index=True, help_text="Application identifier. Max 300 chars.") key = models.CharField(max_length=300, db_index=True, help_...
3334060
from __future__ import print_function try: from builtins import range, zip except: pass import os, sys, glob, h5py, socket, shutil, time, re, \ subprocess import numpy as np from collections import deque from subprocess import Popen, PIPE from pyglib.io.fio import file_exists import pyglib.run.environ ...
3334175
import pdb import numpy as np import mxnet as mx assert mx.__version__ > '0.11.0' # required for autograd.grad() from mxnet import nd from mxnet import gluon from mxnet import autograd from typing import Tuple from .layers import LatentLayer from .layers import ObservationLayer EPSILON = np.finfo(float).eps class...
3334231
import os heading_text = '# Do not modify this file directly. It is auto-generated with Python.\n\n' root_dir = os.path.dirname(os.getcwd()) icons_dir = os.path.join(root_dir, "icons") providers_dir = os.path.join(root_dir, "architectures", "providers") def format_text(text): return text.replace("-", " ").title...
3334239
from __future__ import print_function from __future__ import absolute_import from __future__ import division import time import datetime __all__ = [ 'timestamp', 'now' ] def timestamp(): """Generate a timestamp using the current date and time. Returns ------- str The timestamp. ...
3334245
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.modules.xlinebase import XLineBase from txircd.utils import durationToSeconds, ircLower, now from zope.int...
3334259
import magma as m import timeit import pygal def array_2d(i=128, j=128): class Foo(m.Circuit): io = m.IO(I=m.In(m.Array[i, m.Array[j, m.Bit]]), O=m.Out(m.Array[i, m.Array[j, m.Bit]])) k = i // 2 io.O[:k] @= io.I[k:] io.O[k:] @= io.I[:k] data = { "frontend": {}, "backend":...
3334276
from ..schema.nexusphp import Visit class MainClass(Visit): URL = 'https://pt.msg.vg/' USER_CLASSES = { 'downloaded': [1099511627776, 3298534883328], 'share_ratio': [3.55, 4.55], 'days': [420, 700] }
3334342
import numpy as np import pandas as pd from sklearn import metrics, model_selection, ensemble, preprocessing, linear_model import lightgbm as lgb import xgboost as xgb def getCountVar(compute_df, count_df, var_name, count_var="v1"): grouped_df = count_df.groupby(var_name)[count_var].agg('count').reset_index() groupe...
3334343
from django.db import models, IntegrityError from django.conf import settings from ara import redis from ara.db.models import MetaDataModel class Block(MetaDataModel): class Meta(MetaDataModel.Meta): verbose_name = '차단' verbose_name_plural = '차단 목록' unique_together = ( ('block...
3334355
class Command: is_finished: False def generate_message(self): pass def set_response(self, response_data: dict): pass
3334356
from __future__ import absolute_import class TokenType(object): def __init__(self, name, contains_syntax=False): self.name = name self.contains_syntax = contains_syntax def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.name) class TokenTypes(object): """ B...
3334357
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models class Notification(models.Model): enabled = models.BooleanField(default=True) def format_output(self): return { "enabled": self.enabled, "queue_notifications": [ ...
3334443
import pytest from statham.schema.elements import Element, Object from statham.schema.exceptions import FeatureNotImplementedError from statham.schema.parser import parse, parse_element def test_parser_detects_definitions(): schema = { "definitions": { "foo": {"type": "object", "title": "Foo"...
3334456
import torch import torchvision.models as models from fastai2.data.external import * from fastai2.data.transforms import * from fastai2.data.block import * from fastai2.vision.models.xresnet import * from fastai2.vision.core import * from fastai2.vision.data import * from fastai2.vision.augment import * from torch.ut...
3334516
import decimal satoshi_to_btc = decimal.Decimal(1e8) btc_to_satoshi = 1 / satoshi_to_btc def convert_to_satoshis(btc): """ Converts an amount in BTC to satoshis. This function takes care of rounding and quantization issues (i.e. IEEE-754 precision/representation) and guarantees the correct BTC valu...
3334536
from .utils import * import math import os from .label_config import max_step, max_param from misc import get_distance_to_center from .complex_base import draw_new_base ################################### # generate club chairs # seat-top can be: square, circle, rectangle # supports can be: circle, square # bottom bas...
3334571
import os import copy def _merge(a, b): """ a overwrites values in b """ for k in a.keys(): if isinstance(a[k], dict) and k in b and isinstance(b[k], dict): b[k] = _merge(a[k], b[k]) else: b[k] = a[k] return b def merge(a, b): """ makes copies before merg...
3334598
import urllib2 import httplib #url = 'http://localhost:13400/boot?mac=BC-30-5B-BD-5E-B9&uuid=44454C4C-4C00-1058-8058-B4C04F505131' url = 'http://172.25.57.83:13400/boot?mac=BC-30-5B-BD-5E-B9&uuid=44454C4C-4C00-1058-8058-B4C04F505131' proxy_handler = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_handler...
3334608
from typing import Tuple import torch import torch.nn as nn from torch_geometric.data import Data from .appnp_propagation import APPNPPropagation from .page_rank import PageRankDiffusion class CertaintyDiffusion(nn.Module): """simple parameterless baseline for node classification with a representation of uncertai...
3334645
from typing import Dict, Optional, Tuple import numpy as np import pandas as pd import recourse as rs from lime.lime_tabular import LimeTabularExplainer from carla import log from carla.recourse_methods.processing import encode_feature_names from ...api import RecourseMethod from ...processing.counterfactuals import...
3334681
from numbers import Real, Integral from typing import Tuple from pytypes import typechecked from valid8 import validate_arg def ex1_pep484(value): from mini_lambda import x @typechecked @validate_arg('x', x >= 0) def my_function(x: Integral): # <- type hint in signature pass my_function...
3334709
import re, datetime from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.http import Http404 from django.views.generic import date_based, list_detail from basic.events.models import * def event_list(request, page=0): return list_detail.object_l...
3334713
import pytest from async_property import async_cached_property from async_property.cached import AsyncCachedPropertyDescriptor from async_property.proxy import AwaitableOnly, AwaitableProxy pytestmark = pytest.mark.asyncio class MyModel: @async_cached_property async def foo(self) -> str: return 'bar...
3334728
from __future__ import print_function import argparse import glob from astropy.io import fits import numpy as np parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) argopt = parser.add_argument # function short cut argopt('tag', help='Tag, output directory and file prefix (e.g. Object nam...
3334760
from django.contrib.auth.decorators import user_passes_test from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from graphql_relay import from_global_id from api.models import Tutorial, Sprint from ticket.models import Ticket, TicketProduct def group_required(*group_names): ...
3334772
from pathlib import Path from typing import Union, Dict from deepmerge import Merger from ruamel.yaml import YAML from connectbox_exporter.xml2metric import ( DEVICE_STATUS, DOWNSTREAM, UPSTREAM, LAN_USERS, TEMPERATURE, ) IP_ADDRESS = "ip_address" PASSWORD = "password" EXPORTER = "exporter" PORT ...
3334823
import copy import frappe from faker import Faker from frappe.model import (table_fields, data_fieldtypes, no_value_fields, display_fieldtypes, optional_fields, default_fields, numeric_fieldtypes, core_doctypes_list) from frappe.utils import cstr from renovation_core.utils.json_generator impo...
3334824
from __future__ import print_function from fenics import * import matplotlib.pyplot as plt import numpy as np # Create mesh and define function space mesh = UnitSquareMesh(8, 8, "left") U = FunctionSpace(mesh, "CG", 2) # Define variational problem u = TrialFunction(U) v = TestFunction(U) a = dot(u, v) * dx A = asse...
3334860
import dgl import torch def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n] def evaluate_model(g_list, model, device, bs=64, **kwargs): preds = [] with torch.no_grad(): for sub_gs in chunks(g_list, bs): sub_gs = dgl.batch(sub_gs).to(device) sub_...
3334861
import pyutilib.workflow # @code: class TaskA(pyutilib.workflow.Task): def __init__(self, *args, **kwds): pyutilib.workflow.Task.__init__(self, *args, **kwds) self.inputs.declare('x', constant=True) self.inputs.declare('y') self.outputs.declare('z') def execute(self): ...
3334865
from .base_verification import * from .metrics import * #from .xskillscore import * from .flat_metrics import *
3334871
import os from pathlib import Path from optimization.constants import ASSETS_DIR_NAME, RANKED_RESULTS_DIR from utils.metrics_accumulator import MetricsAccumulator from utils.video import save_video from numpy import random from optimization.augmentations import ImageAugmentations from PIL import Image import torch f...
3334879
import base64 import binascii import json import six from django.core.files.base import ContentFile from drf_extra_fields.fields import Base64ImageField from rest_framework.exceptions import ValidationError from rest_framework.relations import SlugRelatedField class NamedBase64ImageField(Base64ImageField): """T...
3334936
import pandas as pd from ccxt import okex3 import time from multiprocessing.dummy import Pool as ThreadPool from datetime import datetime, timedelta from pathlib import Path from concurrent.futures import ProcessPoolExecutor pd.set_option('expand_frame_repr', False) exchange = okex3() contracts = exchange.futuresGetI...
3334969
from disaster_scrapers import Scraper import requests import json class FplStormOutages(Scraper): owner = "simonw" repo = "disaster-data" filepath = "florida/fpl-storm-outages.json" url = "https://www.fplmaps.com/data/storm-outages.js" def fetch_data(self): content = requests.get(self.ur...
3335003
import bitstring def revbits8(n): return int('{:08b}'.format(n)[::-1], 2) def revbits4(n): return int('{:04b}'.format(n)[::-1], 2) def revnib(n): return ((n & 0xF) << 4) | ((n >> 4) & 0xF) def munge(n): return (revbits4(n & 0xF) << 4) | revbits4((n >> 4) & 0xF) def getbits_bin(f): return bitstr...
3335039
class PAMValidationError(Exception): """ Custom exception raised for an Activity Plan validation Error. """ pass class PAMSequenceValidationError(PAMValidationError): """ Custom exception raised for an Activity Plan sequence validation Error. """ pass class PAMTimesValidationError(...
3335042
from __future__ import print_function import numpy as np from nsopy.loggers import GenericDualMethodLogger, DualDgmFgmMethodLogger from nsopy.methods.universal import UniversalPGM, UniversalDGM, UniversalFGM from tests.analytical_oracles import AnalyticalExampleInnerProblem, SecondAnalyticalExampleInnerProblem, Constr...
3335043
import pytest def test_1(): from util import toSet assert {'a' , 'b'} == toSet([{'a' , 'b'},{'a'}]); def test_2(): from util import toSet2 assert {'a'} == toSet2([{'a' , 'b'},{'a'}]);
3335096
import numpy as np from scipy import signal from src.base import get_ancestral_metadata from src.utils.decorators import PartitionByTrial __all__ = [ "body_grav_filter", ] def filter_signal(data, filter_order, cutoff, fs, btype, axis=0): ba = signal.butter(filter_order, cutoff / fs / 2, btype=btype) mu...