id
stringlengths
3
8
content
stringlengths
100
981k
9903701
import urllib import json import os import re class ARCParser: '''Converts panda job description to ARC job description using AGIS info''' def __init__(self, jobdesc, pandaqueue, siteinfo, logurl, schedulerid, osmap, tmpdir, eventranges, log): self.log = log # The URL-encoded job that is even...
9903708
from mcu.utils import elastic2D # Ref: https://doi.org/10.1021/jacs.8b13075 # Elastic tensors AlB6_1 = [379.9,438.4,23.1,159.6] AlB6_2 = [383,375.3,33.6,132.1] AlB6_3 = [395.1,401,44,173.6] AlB6_4 = [229.9,194.2,7.1,80.3] AlB6_5 = [242.2,171.1,15.6,57.1] AlB6_6 = [149.3,92.2,24.9,63.2] # define a list of elastic ten...
9903730
import unittest from ofxclient import Client from ofxclient import Institution class OfxInstitutionTests(unittest.TestCase): def testClientDefaultsPreserved(self): i = Institution( id='1', org='org', url='http://example.com', username='user...
9903791
from __future__ import annotations import unittest from .function_tests import FunctionTestCase import ATL from ATL import num, Type import numpy as np # --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- # clas...
9903796
from flask_unchained import unchained from py_meta_utils import McsArgs, MetaOption from sqlalchemy_unchained import ModelMetaOptionsFactory as BaseModelMetaOptionsFactory from typing import * class ModelMetaOption(MetaOption): """ The model class for a class. """ def __init__(self): super()._...
9903797
from collections.abc import AsyncIterable from pathlib import Path from typing import Any, get_type_hints ROOT = Path(__file__) while ROOT.name != "steam.py": ROOT = ROOT.parent def is_async_iterable(object: Any) -> bool: try: annotations = get_type_hints(object) except Exception: return ...
9903836
import os, sys sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)) # For replicating the experiments SEED = 42 import argparse import time import random import numpy as np import scipy.sparse as sp import torch np.random.seed(SEED) torch.manual_seed(SEED) from torch import optim import...
9903852
from os.path import join, dirname class Chart: def __init__(self, data, font_color="white", chart_type = "line", title=None, width_factor =1, x_labels=None, chart_it=0): self.chart_type = chart_type ...
9903857
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer PedsMon = DQMEDAnalyzer('SiStripMonitorPedestals', OutputMEsInRootFile = cms.bool(False), StripQualityLabel = cms.string(''), RunTypeFlag = cms.string('CalculatedPlotsOnly'), ##Options : ConDBPlotsOnly , Calcu...
9903897
import yaml import os import sys import logging class Config: def __init__(self, path: str = None): BASE_DIR = os.path.dirname(__file__) CONFIG_DIR = os.path.join(BASE_DIR, 'config') ALT_CONFIG_DIR = path or os.path.join(BASE_DIR, '..', 'config') # Configuration options CO...
9903914
from django.core.management.base import BaseCommand from dimagi.utils.chunked import chunked from corehq.apps.users.models import SQLPermission, UserRole class Command(BaseCommand): help = "Adds download_reports permission to user role if not already present." def handle(self, **options): permission...
9903921
from ._lazyimport import m from .raw import setup_extra_parser # noqa def load(fp, *, loader=None, errors=None, **kwargs): return m.toml.load(fp, **kwargs) def dump(d, fp, *, sort_keys=False, **kwargs): return m.toml.dump(d, fp, **kwargs)
9903966
from pysphero.constants import Api2Error class PySpheroException(Exception): ... class PySpheroRuntimeError(PySpheroException): ... class PySpheroTimeoutError(PySpheroException): ... class PySpheroApiError(PySpheroException): def __init__(self, api_error: Api2Error): super().__init__(f"A...
9904000
from PennCourses.settings.base import * # noqa: F401, F403 PCA_URL = "http://localhost:8000" TEST_RUNNER = "xmlrunner.extra.djangotestrunner.XMLTestRunner" TEST_OUTPUT_VERBOSE = 2 TEST_OUTPUT_DIR = "test-results" CACHES = {"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache",}}
9904010
import argparse import pycomplete parser = argparse.ArgumentParser(__name__) parser.add_argument("-V", "--version", action="version", version="0.1.0") subparsers = parser.add_subparsers() subparser = subparsers.add_parser( "completion", description="Show completion script for given shell" ) subparser.add_argumen...
9904018
import torch from model.modules import * from model import utils class RNNDecoder(nn.Module): """Based on https://github.com/ethanfetaya/NRI (MIT License).""" def __init__(self, n_in_node, edge_types, n_hid, do_prob=0.0, skip_first=False): super(RNNDecoder, self).__init__() self.msg_fc1 = nn...
9904067
import dis import falcon import sys class wrap(object): def __init__(self, f): self.python_fn = f self.name = f.__name__ self.falcon_fn = falcon.wrap(f) def __call__(self, *args, **kwargs): python_result = self.python_fn(*args, **kwargs) falcon_result = self.falcon_fn(*args, **kwargs) ...
9904080
import sys from fs import open_fs from fs.filesize import traditional fs_url = sys.argv[1] count = 0 with open_fs(fs_url) as fs: for _path, info in fs.walk.info(filter=["*.py"], namespaces=["details"]): count += info.size print(f'There is {traditional(count)} of Python in "{fs_url}"')
9904101
import json import os import numpy as np def read_serialized_results(file_path): with open(file_path) as fp: data = json.load(fp) return data def save_serialized_list(input_list, file_path): with open(file_path, 'w') as fp: json.dump(input_list, fp) #RES1 = "VALIDATION_Results_soft_attn...
9904104
import math import numpy as np import tensorflow as tf from configs import cfg from src.dataset import Dataset, load_sick_data from src.evaluator import Evaluator from src.graph_handler import GraphHandler from src.perform_recorder import PerformRecoder from src.utils.file import load_file, save_file from src.utils.r...
9904117
from vision import * from vision.alearn import marginals from vision import visualize, model from vision.toymaker import * import os import multiprocessing import logging import random import ImageColor import pickle logging.basicConfig(level = logging.INFO) #g = frameiterator("/scratch/vatic/uci-basketball") #b = [B...
9904154
from netCDF4 import Dataset import numpy as np import matplotlib.pyplot as plt import math fig, axes = plt.subplots() subcycleNumbers = [120,240,480,960,1920,3840,7680] operatorMethods = ["wachspress","pwl","weak"] Lx = 1280000.0 iMethod = 0 for operatorMethod in operatorMethods: unegs = [] for subcycleNu...
9904163
from __future__ import absolute_import import sporco.admm.admm import sporco.admm.bpdn import sporco.admm.cbpdn import sporco.admm.cbpdntv import sporco.admm.cmod import sporco.admm.ccmod import sporco.admm.ccmodmd import sporco.admm.dictlrn import sporco.admm.bpdndl import sporco.admm.cbpdndl import sporco.admm.tvl2 ...
9904176
import yaml import os from yamlinclude import YamlIncludeConstructor dirname = os.path.dirname(__file__) basedir = os.path.join(dirname, '../schema/') root = os.path.join(basedir, 'deribit_api_v2.yaml') YamlIncludeConstructor.add_to_loader_class(loader_class=yaml.Loader, base_dir=basedir) with open(root) as f: d...
9904187
import random import numpy as np import re def _weighted_var(x, weights): return np.average((x - np.average(x, weights=weights)) ** 2, weights=weights) def goodness_of_fit(transport_plan, metric="L1"): # todo: docs if not isinstance(transport_plan, np.ndarray): transport_plan = np.array(list(tra...
9904235
from json import load, dumps from collections import OrderedDict from .error import SpecificationError class SlurmPipelineBase(object): """ Read a pipeline execution specification or status. @param specification: Either a C{str} giving the name of a file containing a JSON execution specification...
9904254
from os import path from typing import List import matplotlib.pyplot as plt import numpy as np from torch.utils.data import DataLoader, Dataset, Subset from torchvision import transforms from torchvision.datasets import MNIST, CIFAR10, ImageFolder, CIFAR100, FashionMNIST from data import DataManager from configurati...
9904262
from PySide2.QtCore import QProcess from node_launcher.node_set.bitcoind.bitcoind_rpc_client import Proxy from node_launcher.node_set.lib.network_node import NetworkNode from .bitcoind_process import BitcoindProcess from .bitcoind_software import BitcoindSoftware from .bitcoind_configuration import BitcoindConfigurati...
9904272
import datetime from pyhafas import HafasClient from pyhafas.profile import RKRPProfile client = HafasClient(RKRPProfile(), debug=True) id_nordhavn='8600653' id_kongebakken9='A=2@O=Kongebakken 9, 2765 Smørum, Egedal Kommune@X=12294403@Y=55749256@U=103@L=902400113@B=1@p=1618386996@' #print(client.departures( # st...
9904278
import torch from . import metamodel class SingleHiddenLayer(torch.nn.Module): def __init__(self, input_channels, hidden_channels): super(SingleHiddenLayer, self).__init__() self.input_channels = input_channels self.hidden_channels = hidden_channels self.linear1 = torch.nn.Linear...
9904321
import argparse import datasets import lm_dataformat import re import tqdm parser = argparse.ArgumentParser(description="Deduplicate a list of files") parser.add_argument("--data_dir", type=str, required=True) parser.add_argument("--output_dir", type=str, required=True) parser.add_argument("--archive_commit_freq", typ...
9904375
from cas.models import * from cas.backends import * from cas.middleware import * from cas.views import * from cas.decorators import * from cas.exceptions import * from cas.utils import *
9904407
from binaryninja import * from binaryninjaui import * from .dsc import DyldSharedCacheView DyldSharedCacheView.register() class DSCViewWatcher(UIContextNotification): def __init__(self): UIContextNotification.__init__(self) UIContext.registerNotification(self) def __del__(self): UIContext.unregisterNotifica...
9904445
class ServiceHandler(object): @classmethod def service_name(cls): raise NotImplementedError("Sub-class must implement service_name.") @classmethod def processor(cls): raise NotImplementedError("Sub-class must implement processor.") __all__ = ["ServiceHandler"]
9904446
from .fixed_obj import FixedObj import pymunk import pygame as pg from pygame import gfxdraw from ..constants import goal_color from .gravity_obj import MOVING_OBJ_COLLISION_TYPE from .poly import Star GOAL_RADIUS = 4.0 GOAL_OBJ_COLLISION_TYPE = 15 def goal_target_begin_handler(arbiter, space, data): if hasattr(a...
9904521
import datetime from hamutils.cabrillo import CabrilloWriter f=open('./test.cbr', 'wb') cbr = CabrilloWriter(f) cbr.write_tag('CALLSIGN', 'SQ8TEST') cbr.write_tags(category='SINGLE-OP ALL LOW', contest='SOME-CONTEST') cbr.add_qso('15m', 'PH', datetime.datetime.utcnow(), 'SQ8TEST', '59', '001LN', 'K0TEST', '59', '003L...
9904563
import numpy as np import torch import torch.nn as nn from scipy.stats import multivariate_normal from ..components.snake import Snake _nine_offsets = [ ( 0, 0), ( 1, 1), ( 0, 1), (-1, 1), (-1, 0), (-1, -1), ( 0, -1), ( 1, -1), ( 1, 0), ] class GaussianField(): def __in...
9904583
import click from common.document_parser import validators import pandas as pd from pathlib import Path from . import get_default_logger import sys import resource import platform import shutil @click.group() def cli(): """ Document parsing tool """ pass def pdf_to_json( parser_path: str, ...
9904584
import numpy as np def reconstruction_error(XY, XY_completed, missing_mask, name=None): """ Returns mean squared error and mean absolute error for completed matrices. """ value_pairs = [ (i, j, XY[i, j], XY_completed[i, j]) for i in range(XY.shape[0]) for j in range(XY.shap...
9904594
import logging import torch import torch.nn as nn import numpy as np from helperbot.bot import BaseBot from .rnn_stack import RNNStack from .embeddings import BasicEmbeddings class RNNLanguageModel(nn.Module): def __init__(self, embeddings: BasicEmbeddings, rnn_stack: RNNStack, tie_weights: bool = True): ...
9904601
import numpy as np from numpy import random import mmcv from mmdet.datasets.builder import PIPELINES @PIPELINES.register_module() class PadMultiViewImage(object): """Pad the multi-view image. There are two padding modes: (1) pad to a fixed size and (2) pad to the minimum size that is divisible by some num...
9904636
import os,sys def readchemiricBPs(hicbpf): inf = open(hicbpf) Info = {} for line in inf: if line.startswith('chromosome1'): pass else: line = line.strip().split('\t') chr1,sr1,bp1,chr2,sr2,bp2,r1,r2,rt = line chrompair = chr1 + '_' + chr2 if chrompair not in Info: Info[chrompair]=[[sr1,sr2,bp1...
9904702
def create_file(filename, filesize_mb=1): """ Create file for testing purposes. Parameters ---------- filename: str The filename filesize_mb: numeric The file size in Mb. """ with open(filename, "wb") as f: f.seek(1024 * 1024 * filesize_mb) f.write(b"0") ...
9904706
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI class DistributedGardenBoxAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGardenBoxAI')
9904712
import random import string import logging import datetime from dateutil.relativedelta import relativedelta # An abstracted data model for fetching data from honeypot_logs class HoneypotLogTable(object): # Create model for a specific airflow database def __init__(self, table_name, sql_conn_id='airflow_db'): ...
9904762
from pptx import Presentation from pptx_templater.slides import clear def create(srcpath): with open(srcpath, 'rb') as f: source = Presentation(f) dest = Presentation(f) # Clear all slides in destination clear(dest) return source, dest
9904763
import sys sys.path.append("..") import numpy as np from read_aws import * from google_drive_push import * import seaborn as sns import matplotlib.pyplot as plt from pprint import pprint import calendar import re from dockless_exploration_graphs import * '''Single Trips as % of all CaBi passes (not memberships) purch...
9904775
import os.path import string letters = None try: letters = string.ascii_letters except AttributeError: letters = string.letters l = ['_'] * 256 for c in string.digits + letters: l[ord(c)] = c _pathNameTransChars = ''.join(l) del l, c def convertTmplPathToModuleName(tmplPath, ...
9904799
import logging from .decoder import Decoder from .exceptions import SeError,CryptoNotReadyError logger = logging.getLogger(__package__) logger.addHandler(logging.NullHandler()) name = 'pysolaredge'
9904809
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.hvac_templates import HvactemplateZoneVrf log = logging.getLogger(__name__) class TestHvactemplateZoneVrf(unittest.TestCase): def setUp(self): self.fd, self.path = ...
9904824
import numpy as np import os from kcsd import csd_profile as CSD from kcsd import KCSD2D from scipy.integrate import simps from scipy.interpolate import griddata from figure_properties import * import matplotlib.pyplot as plt import matplotlib.cm as cm def integrate_2d(csd_at, true_csd, ele_pos, h, csd_lims): csd_...
9904834
import json import logging import pytest from utils import find_resource app = __import__('diana-rest').app @pytest.fixture def diana_rest(): client = mk_diana_rest() yield client def mk_diana_rest(): service_path = find_resource("resources/test_services.yml") app.app.load_services(service_path) ...
9904901
from rest_framework import status api_url = '/api/storyimages/' def test_api_endpoint_exists(staff_client): response = staff_client.get(api_url) assert response.status_code == status.HTTP_200_OK def test_create_new_storyimage(staff_client, scandal, scandal_photo): """Can create new storyimage and patch...
9904925
from __future__ import division import numpy as np import client import pdb import emcee from softmax_model import SoftmaxModel from mnist_cnn_model import MNISTCNNModel from lfw_cnn_model import LFWCNNModel from svm_model import SVMModel import datasets learning_rate = 1e-2 # Use the Song and Sarwate 2013 implementa...
9904929
from bitshares_pricefeed.sources.manual import Manual def test_manual_fetch(checkers): source = Manual(feed = { 'BTS' : { 'USD' : { 'price': 4.2, 'volume': 1.0}}}) feed = source.fetch() checkers.check_feed(feed, ['USD:BTS'])
9904955
from typing import Dict from telebot import TeleBot from beancount_bot.config import get_config from beancount_bot.i18n import _ from beancount_bot.session import get_session, SESS_TX_TAGS, set_session from beancount_bot.util import stringify_tags class SessionSpecificConfig: """与特定 session 相关的配置""" def ge...
9904958
from sofi.ui import Heading def test_basic(): assert(str(Heading()) == "<h1></h1>") def test_size(): assert(str(Heading(5)) == "<h5></h5>") def test_text(): assert(str(Heading(3, "text")) == "<h3>text</h3>") def test_custom_class_ident_style_and_attrs(): assert(str(Heading(2, "text", cl='abclass', i...
9904989
from validator import Validator, EmailField class V(Validator): email = EmailField() def test_ok(): data = {'email': '<EMAIL>'} v = V(data) assert v.is_valid() def test_wrong_value(): data = {'email': '<<EMAIL>'} v = V(data) assert not v.is_valid(), v.str_errors def test_mock_data...
9904996
import datetime import time from logging import DEBUG, Formatter, StreamHandler, getLogger from typing import List import click from src.db import cruds, schemas from src.db.database import get_context_db logger = getLogger(__name__) logger.setLevel(DEBUG) formatter = Formatter("[%(asctime)s] [%(process)d] [%(name)s]...
9905040
class PropertyMappingFailedException(Exception): pass def get_transformed_properties(source_properties, prop_map): results = {} for key, value in prop_map.items(): if isinstance(value, str): if value in source_properties: results[key] = source_properties[value] ...
9905066
import warnings import chainer import numpy as np from ..utils import label2instance_boxes class MaskRcnnDataset(chainer.dataset.DatasetMixin): def __init__(self, instance_dataset): warnings.warn('MaskRcnnDataset is deprecated, please stop using it.') self._instance_dataset = instance_dataset ...
9905070
import numpy as np from PuzzleLib import Config from PuzzleLib.Backend import gpuarray from PuzzleLib.Modules.Module import ModuleError, Module class Reshape(Module): def __init__(self, shape, showWarnings=True, name=None): super().__init__(name) self.registerBlueprint(locals()) self.showWarnings = showWarn...
9905075
import pandas as pd import os import matplotlib.pyplot as plt from matplotlib.lines import Line2D import numpy as np def report_sum2(path='./data/report/sum2/loss'): graph={} for fname in os.listdir(path): if 'previous' in fname: continue ffname = os.path.join(path, fname) d...
9905149
from __future__ import absolute_import, print_function, division import numpy as np import numba as nb from numba.targets.registry import CPUDispatcher from numba.cffi_support import register_module from . import _wrapper from ._wrapper import lib, ffi register_module(_wrapper) start_instrumentation = lib.start_ins...
9905153
from typing import List from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Session from sqlalchemy.sql import text from app.crud.base import CRUDBase from app.models.Cell import Cell from app.schemas.Cell import CellCreate, CellUpdate class CRUD_Cell(CRUDBase[Cell, CellCreate, CellUpdate]): ...
9905175
import os WEIBO_USERNAME = os.environ.get('WEIBO_USERNAME') WEIBO_PASSWORD = os.environ.get('WEIBO_PASSWORD')
9905187
from typing import Dict, List from datetime import timedelta import pandas as pd from prophet import Prophet import altair as alt import statsmodels.api as sm from statsmodels.tsa.exponential_smoothing.ets import ETSModel from chaos_genius.core.utils import suppress_stdout_stderr # TODO: Add prophet and altair as req...
9905225
import cProfile import logging import os from decorator import contextmanager @contextmanager def perf_trace(file): pr = cProfile.Profile() pr.enable() yield pr pr.disable() file = os.path.abspath(file) if not os.path.exists(os.path.dirname(file)): os.makedirs(os.path.dirname(file)) ...
9905268
from celery import shared_task from django.contrib.auth import get_user_model from django.contrib.sessions.models import Session @shared_task def deactivate_user(*, user_pk): user = get_user_model().objects.get(pk=user_pk) user.is_active = False user.save() for s in Session.objects.all(): if...
9905279
from repo_scraper.constants.result import * from unittest import TestCase from repo_scraper.FileChecker import FileChecker import os module_path = os.path.dirname(os.path.abspath(__file__)) dummy_repo_path = os.path.join(module_path, '..', 'dummy-project') class TestFileChecker(TestCase): def test_json_file_with_...
9905300
import unittest import pydatacoll.utils.logger as my_logger from pydatacoll.utils.func_container import ParamFunctionContainer, param_function from pydatacoll.utils import str_to_number logger = my_logger.get_logger('UtilTest') class UtilTest(unittest.TestCase): def test_func_container(self): class MyAP...
9905326
import itertools import numpy as np from scedar import eda from scedar.eda.slcs import MDLSingleLabelClassifiedSamples as MDLSLCS from scedar.eda.slcs import SingleLabelClassifiedSamples as SLCS from scedar import utils class MIRAC(object): """ MIRAC: MDL iteratively regularized agglomerative clustering. ...
9905332
from accounts.models import register_signals as lostkey_register_signals def init_signals(): ################################################## #LostKey custom signals ################################################## lostkey_register_signals()
9905366
NS_FERD_1p0 = "urn:ferd:CrossIndustryDocument:invoice:1p0" NS_UDT = "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15" NS_RAM = "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12" BASIC = "BASIC" COMFORT = "COMFORT" EXTENDED = "EXTENDED"
9905440
import re class Challenges: @staticmethod def first_factorial(number: int) -> int: """ Iterative approach :param number: an input, first factorial of a number :return: factorial """ found = 1 step = 2 while step <= number: found *= s...
9905459
from django.core.urlresolvers import reverse_lazy from django.views.generic import TemplateView from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import logout from apps.landing.models import Landing from apps.base.views import (BaseView, LoginRequiredMixin) # Create your views here...
9905507
from open_alchemy import init_yaml init_yaml("example-spec.yml", models_filename="models_auto.py")
9905510
import pyasdf import np def read_asdf(tfile): with pyasdf.ASDFDataSet(tfile,MPI=False,mode='r') as ds: data_types = ds.auxiliary_data.list() path = ds.auxiliary_data[data_types[0]].list() Nfft = ds.auxiliary_data[data_types[0]][path[0]].parameters['nfft'] Nseg = ds.auxiliary_data[...
9905552
import argparse import os from dataclasses import dataclass from functools import lru_cache import socket from urllib.parse import parse_qsl, urlencode, urlparse import flask from cached_property import cached_property from pathlib import Path from typing import Dict, List, Optional, Union import cv2 import pandas as...
9905585
import os import pytest from controller import openapis, swaggers, validate dirname = os.path.dirname(__file__) with open(os.path.join(dirname, 'openapi-pass.json'), 'rb') as file: PASS_OPENAPI = file.read() with open(os.path.join(dirname, 'swagger-pass.json'), 'rb') as file: PASS_SWAGGER = file.read() wi...
9905600
import logging import os _logger = logging.getLogger(__name__) def create_sets(features_dir, hparams, proportion_validation=0.1): ''' Create train and validation sets, for all specified speakers :param features_dir: directory containing all the speakers features files :param hparams: ...
9905653
import os from distutils.core import setup version = '1.2.1' README = os.path.join(os.path.dirname(__file__), 'README') setup( name='xtermcolor', version=version, description='Python module for colorizing output with xterm 256 color support', author='<NAME>', author_email='<EMAIL>', packages=['xtermcolor...
9905690
import urllib.request import boto3 def handlerMap(event,context): event['tasks'] = [ { 'url' : 'http://www.robots.ox.ac.uk/~vgg/data/flowers/102/102flowers.tgz', 'filename' : '102flowers.tgz', 's3_key' : 'raw/102flowers.tgz' }, { 'url' : 'http://www.robots.ox.ac.uk/~vgg/data/flowers/102/imagelabels....
9905692
from collections import Counter def numIdenticalPairs(nums): #1 Brute force # count=0 # for i in range(len(nums)): # for j in range(i+1, len(nums)): # if nums[i]==nums[j]: # count+=1 # return count #2 with count removing other for lo...
9905700
from django.conf.urls import handler404, include from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.urls import path, re_path from django.views.generic.base import TemplateView, RedirectView from django.conf import ...
9905716
import private_consts import os, pickle, random def save_data(vocabulary, examples, cal_only): save_file = str() if cal_only: save_file = os.path.expanduser(private_consts.SAVE_DIR)+"uninflated_data.{0}_cal_only.pickle".format(len(examples)) else: save_file = os.path.expanduser(private_consts.SAVE_DIR)+...
9905722
import torch import torch.nn as nn from torchvision.models import resnet50 # from root path call and in the current path call is not the same # if want to fix it. I think sys.path is the choice from model.FAN import FAN from torch.utils.model_zoo import load_url class Generator_loss(nn.Module): def __init__(self)...
9905758
from generic_social_network.app import db from sqlalchemy import Column, Integer, ForeignKey class Follow(db.Model): __tablename__ = 'follows' follower_id = Column(Integer, ForeignKey("users.user_id"), primary_key=True, nullable=False) followed_id = Column(Integer, ForeignKey("users.user_id"), primary_ke...
9905762
from flask import Flask, request from flask_restful import Api, Resource from flask_cors import CORS import json import os from models import db, User, Article, Comment, Like basedir = os.path.dirname(os.path.abspath(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db') app = Flask(__name...
9905774
from neo4j import GraphDatabase from typing import Optional from pandas import DataFrame from numpy import isnan import logging from urllib.parse import urlparse from progress.bar import Bar logger = logging.getLogger('ds-neo4j') def dict_to_property_str(properties: Optional[dict] = None) -> str: def property_t...
9905790
from permabots.serializers import StateSerializer, TelegramChatStateSerializer, TelegramChatStateUpdateSerializer, \ KikChatStateSerializer, KikChatStateUpdateSerializer, MessengerChatStateSerializer, MessengerChatStateUpdateSerializer from permabots.models import State, TelegramChatState, TelegramChat, TelegramUse...
9905859
import homeassistant.loader as loader DOMAIN = 'watson' # List of component names (string) your component depends upon. DEPENDENCIES = ['rest'] DEFAULT_APIKEY = '*' def setup(hass, config): hass.states.set('watson', 'online') # """Set up the Hello MQTT component.""" # rest = loader.get_component('rest'...
9905883
from typing import Union from lark import Lark, Tree, Token from pathlib import Path from functools import lru_cache OPTIONS = {"lark-expansions": {"start": "expansions"}} DEFAULTS = {"parser": "lalr"} SOURCE = {"lark-expansions": "lark"} PATH = Path(__file__).parent / "grammars" @lru_cache(8) def load_grammar(name...
9905917
from datetime import date from mock import patch from requests import Response from contentful.cda import const from contentful.cda.client import Client from contentful.cda.errors import ApiError, Unauthorized from contentful.cda.resources import Entry, Asset, ContentType, ResourceLink, Space from test import BaseTest...
9905964
import numpy as np #from mpi4py import MPI #import mpi4py from reference_lu import * from utils import * import math debugK = 200 debugNumPivots = False def flipbit(n, k): return n ^ (1 << k) # empty pivoting strategy. # in step k, k-th rank chooses his first v rows as pivots def EmptyPivot(k, PivotBuff, A11Buf...
9905970
from django import forms from django.core.exceptions import ObjectDoesNotExist from flask import jsonify, request from flask.views import MethodView from api.tableau_api.constants import (APIKEY_NO_ACCESS_MESSAGE, HEADER_IS_REQUIRED, NO_STUDY_FOUND_MESSAGE, NO_STUDY_PROVIDED_MESS...
9906055
from phi.data import * class AugmentChannel(DerivedChannel): def __init__(self, aug_dimensions, field, affect_flags=(DATAFLAG_TRAIN,)): DerivedChannel.__init__(self, [field]) self.field = self.input_fields[0] self.affect_flags = affect_flags self.aug_dimensions = range(aug_dimensi...
9906062
import argparse import torch import models from utils import plot_confusion_matrix, train def main(args): device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = MalConvPlus(8, 4096, 128, 32).to(device) train(model, train_loader, val_loader, device, "malconv_plus") plot_confusi...
9906089
import os import json from tkinter import W import pandas as pd import pathlib import tempfile import torch from pandarallel import pandarallel from torch.nn import BCEWithLogitsLoss from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_support from datasets import Dat...
9906127
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from django.views.generic.base import TemplateView from kolibri.core.views import RootURLRedirectView class UserAuthView(TemplateView): template_name = "user_auth/user_auth.html" def get(sel...