content stringlengths 5 1.05M |
|---|
"""Test suites for MetaGenScope."""
|
from rest_framework import serializers
from django.contrib.auth import get_user_model
from accounts.models import User
class UserSerializer(serializers.ModelSerializer):
"""Serializer class for User object"""
class Meta:
model = User
fields = ('username', 'password', 'phone', 'address', 'gen... |
from .icosweepnet import IcoSweepNet
|
# Create your models here.
from django.db import models
from django.utils import timezone
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=100,default="")
... |
import os
import math
import tqdm
import torch
import itertools
import traceback
import numpy as np
import model.ModifiedGenerator as ModifiedGenerator
import model.MultiScaleDiscriminator as MultiScaleDiscriminator
import stft_loss.MultiResolutionSTFTLoss as MultiResolutionSTFTLoss
device = torch.device("cuda:0" if t... |
# Generated by Django 2.0 on 2018-03-02 03:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('trade', '0004_item_verified'),
]
operations = [
migrations.CreateModel(
name='PasswordResetReques... |
from dataclasses import dataclass
import numpy as np
"""
Useful function to compute various estimation errors
Copyright @donelef, @jbrouill on GitHub
"""
def fro_error(y: np.array, y_hat: np.array) -> float:
"""
Computes the Frobenius error of an estimation.
:param y: true parameters as numpy ... |
from setuptools import setup, find_packages
setup(
name='doctools',
version='0.2.2',
description='docblock manipulation utilities',
long_description=open('README.rst').read(),
py_modules=['doctools'],
install_requires=['pytest', 'pytest-cov'],
author = 'Adam Wagner',
author_email = 'aw... |
import pandas as pd
import os
test = os.listdir('test_labels')
train = os.listdir('train_labels')
test_labels = pd.DataFrame()
train_labels = pd.DataFrame()
test_labels = pd.concat([pd.read_csv('test_labels/'+i, index_col = 0)
for i in test]).drop_duplicates()
print('Hemos creado la test')
... |
# LyricsGenius
# Copyright 2018 John W. Miller
# See LICENSE for details.
import json
import os
class Artist(object):
"""An artist with songs from the Genius.com database."""
def __init__(self, json_dict):
""" Artist Constructor
Properties:
name: Artist name.
image_u... |
def hybrid(max_duration: float) -> None:
pass
|
from random import randint
from django.core.cache import cache
from conf_site.proposals.tests import ProposalTestCase
from conf_site.reviews.models import ProposalVote
from conf_site.reviews.tests.factories import ProposalVoteFactory
class ProposalVoteCountRefreshTestCase(ProposalTestCase):
def setUp(self):
... |
import time
import json
import sys
import hashlib
import operator
import numpy as np
import os
from datetime import datetime
import re
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import matplotlib.dates as mdates
from matplotlib import rcParams... |
import yaml
from pymongo import MongoClient, ASCENDING, DESCENDING
from repo.controllers.path_manager import MONGO_CONFIG_PATH
class MongoManager():
def __init__(self, host=None, port=None):
if host is None:
with open(MONGO_CONFIG_PATH) as f:
conf = yaml.safe_load((f.read()))... |
import basic
tools = basic.tools()
crawler = basic.crawlerComponent()
token = ''
test = 'https://u19481746.pipipan.com/fs/19481746-372048608'
result = tools.solveCtLink(test,crawler)
if result != 'error':
link = tools.shortLink(result,token,crawler)
else:
link = 'error'
print(link)
|
from .page_all_requests import * # noqa
from .page_request_details import * # noqa |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
from utils.utils import my_shuffle
from utils.emoji import Emoji
def job(bot):
print("Sending message...")
msg = "#bomdia Smininos! É hora de acordar... {}".format(
Emoji.SUN_BEHIND_CLOUD,
Emoji.SMILING_FACE_WITH_OPEN_MOUTH)
chat_... |
from os import path
from shorter.start.environment import BASE_DIR, MIGR_DIR, ROOT_DIR, THIS_DIR
TEST_DIR = path.abspath(path.dirname(path.dirname(__file__)))
def test_rootdir():
assert ROOT_DIR == path.dirname(TEST_DIR)
def test_basedir():
assert BASE_DIR == path.join(path.dirname(TEST_DIR), "shorter")
... |
import pandas as pd
from os import remove
import re
from config import HOME_URL
import logging
from dbhelper import DBHelper
import io
from datetime import datetime, timezone, timedelta
from config import SALT
import hashlib
class ParkMap:
park_data = []
asc_columns = [4,7,10,13,16,19,22]
desc_columns = [... |
# aln_stats has functions
# Should raise warning when there are empty comparisons
# should avoid capitalizing sequences
#------------------------------------------------------------
import sys, os, re
import pandas as pd
from itertools import combinations
from utils import get_file_paths_from_dir, substring_delim, cds... |
import os
class NCEOptions(object):
""" Default options for the noise contrastive estimation loss criterion. Modify as needed. """
def __init__(self):
self.num_sampled = 25
self.remove_accidental_hits = True
self.subtract_log_q = True
self.unique = True
self.array_path ... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: settings
Description :
Author : cat
date: 2018/1/22
-------------------------------------------------
Change Activity:
2018/1/22:
------------------------------------------------... |
from redbot.core.bot import Red
from .banmessage import BanMessage
async def setup(bot: Red) -> None:
cog = BanMessage(bot)
bot.add_cog(cog)
|
from helper.pre_processing import *
video_info = video_files[0]
data = generate_pickle(video_info, 'a')
for i in range(0, 100):
img_path = os.path.join(r'F:\DataSet\Aggression_Out\mv1', str(i).zfill(6) + '.jpg')
test_path = os.path.join(r'F:\DataSet\Aggression_Out\test', str(i).zfill(6) + '.jpg')
img = cv2... |
from math import radians, cos, sin
moves = []
def parse_line(line):
d, v = line[0], line[1:]
moves.append((d, int(v)))
with open('input', 'r') as f:
for line in f:
line = line.strip()
parse_line(line)
def rotate(waypoint, degrees):
r = radians(degrees)
x, y = waypoint
x_prim... |
import os
os.system("ls -l; pip install discordpy-slash")
import webserver
import io
import re
import json
import time
import base64
import asyncio
import discord
import inspect
import aiohttp
import datetime
import textwrap
import traceback
import contextlib
from discordpy_slash import slash
from random import choic... |
from typing import Optional
from pydantic import BaseModel, validator
class AuditLogDetails(BaseModel):
parameter_name: str
time: int
action: str
user: str
value: Optional[str]
decrypted_value: Optional[str]
type: Optional[str]
description: Optional[str]
version: Optional[int]
... |
import numpy as np
import time
import cv2
INPUT_FILE='e.png'
OUTPUT_FILE='predicted.jpg'
LABELS_FILE='yolo-coco/coco.names'
CONFIG_FILE='yolo-coco/yolov3.cfg'
WEIGHTS_FILE='best.pt'
CONFIDENCE_THRESHOLD=0.7
def obj_det():
LABELS = open(LABELS_FILE).read().strip().split("\n")
np.random.seed(4)
COLORS = np... |
#!python
import sys
import os
import glob
import argparse
import atexit
import shutil
import tempfile
import subprocess
temp_dir = tempfile.mkdtemp(prefix='vpview-tmp')
atexit.register(lambda: shutil.rmtree(temp_dir))
if os.name == 'nt':
div = '\\'
else:
div = '/'
# Helper class to list files with a given exten... |
import datetime
from operator import attrgetter
from django.core.exceptions import FieldError
from django.db import models
from django.db.models.fields.related import ForeignObject
from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature
from django.test.utils import isolate_apps
from django.utils import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import numpy as np
import pyrotein as pr
from display import plot_rmsd_dmat
import pprint
# Set job name...
job_name = "xfam"
# load the data...
rmsd_dmat = np.load("rmsd_dmat.seq.npy")
len_res = np.load("rmsd_len.seq.npy")
nseqi = np.load("nseqi.seq.npy... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import argparse
import logging
import onnx
import os
import pathlib
import tempfile
from collections import deque
from enum import IntEnum
from ..onnx_model_utils import get_producer_consumer_maps, optimize_model, \
iter... |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import six
from celery.exceptions import MaxRetriesExceededError
from celery.schedules import crontab
from celery.task import task
from celery.task.base import periodic_task
from celery.utils.log import get_tas... |
import unittest
import random
import multiprocessing
import numpy as np
import warnings
from sklearn.metrics import accuracy_score, explained_variance_score
from sklearn.datasets import make_classification
from sklearn.feature_selection import f_classif, f_regression
from sklearn.preprocessing import StandardScaler
fr... |
from settings.settings import Settings
class AWSSettings(Settings):
def __init__(self):
super().__init__()
self.raw_bucket = 'data-pipeline-demo-raw'
self.enriched_bucket = 'data-pipeline-demo-enriched'
|
import fire
def hello(name):
"""
python3 fn.py Yazid
> Hello Yazid!
"""
return 'Hello {name}!'.format(name=name)
if __name__ == '__main__':
fire.Fire(hello)
|
from splunklib.searchcommands import dispatch, GeneratingCommand, Configuration, Option
import logging
import os
import sys
import log_helper
from datetime import datetime
import uuid
import json
import splunk.rest as rest
import boto3
debug_logger = log_helper.setup(logging.INFO, 'GetAWSPriceListDebug', 'get_aws_pric... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Tim(MakefilePackage):
homepage = "https://github.com/buildsi/build-abi-test-tim"
git =... |
"""Three-dimensional Cone-beam Tomography simulation.
The struture study from Nikolay.st_sim.py
Generate intensity frames based on Fresnel diffraction
theory. :class:`TomoSim` does the heavy lifting of calculating
the wavefront propagation to the detector plane.
:class:`STConverter` exports simulated data to a `CXI`_ ... |
from assertpy import assert_that
from click.testing import CliRunner
from elementalcms.core import FlaskContext
from elementalcms.management import cli
from tests import EphemeralElementalFileSystem
class TestCreateCommandShould:
def test_fail_when_language_is_not_supported(self, default_elemental_fixture, defa... |
# coding: utf8
'''
# -------------------------------------------------------------------------------------------------------
# CONVERTER GEODATABASE
# -------------------------------------------------------------------------------------------------------
# Michel Metran
# Setembro de 2017
# Python Script to ArcGIS
# D... |
from devices import LogicDevice
from devices.basic import Xor, Not, And
from utils.basevariable import BaseVariable
class Expression(BaseVariable):
def __init__(self, value: LogicDevice):
self.value = value
class Variable(BaseVariable):
def __init__(self, name):
self.name = name
def __s... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from game_map.models import Structure, Chunk
from websocket_controller.message_utils import round_down, error_message, require_message_content
from city_game_backend import CONSTANTS
from game_map.utils import struct_2_dict
# from django.core import serializers
import json
from websocket_controller.WebsocketRoutes impo... |
__author__ = 'Jiafan Yu'
class SimpleAverage:
def __init__(self, step_ahead, window_size=168):
self.step_ahead = step_ahead
self.window_size = window_size
pass
def predict(self, X):
x_load = X[:, range(self.window_size, 2 * self.window_size)]
recent_load_indices = rang... |
from packit.actions import ActionName
SYNCED_FILES_SCHEMA = {
"anyOf": [
{"type": "string"},
{
"type": "object",
"properties": {
"src": {
"anyOf": [
{"type": "string"},
{"type": "array", "it... |
# -*- coding: utf-8 -*-
import os # validate_path
import tkinter as tk # GuiC3D
def validate_path(path, isempty=False, metadata=False):
"""Check if the path exist. If a path is not provided, ask the user to type one.
:param path: path to validata
:type path: str
:param isempty: check if the folder ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 13 22:43:19 2019
@author: soumi
"""
from bs4 import BeautifulSoup
from RectUtils.RectObj import RectObj
# set attribute for Icon
def styleIconAttribute(top, left,width, height, position="absolute", color = "white"):
styleDic = {}
styleDic["background-color"] = ... |
import os
import time
import argparse
import numpy as np
import pickle
# Custom Classes
import preprocess
def save_pickle(variable, fileName):
with open(fileName, 'wb') as f:
pickle.dump(variable, f)
def load_pickle_file(fileName):
with open(fileName, 'rb') as f:
return pickle.load(f)
def... |
# -*- coding: utf-8 -*-
# These classes and functions were implemented following the DOCs from the original glm (OpenGL Mathematics) lib.
# You can find it here: http://glm.g-truc.net/0.9.8/index.html
# Also, some parts of it were implemented following the Mack Stone's glm Python code in GitHub.
# His code can be foun... |
char_embedding_len = 100
word_embedding_len = 100
char_hidden_size = 512
context_hidden_size = 1024
agg_hidden_size = 128
num_perspective = 12
class_size = 2
max_char_len = 15
max_word_len = 15
batch_size = 100
char_vocab_len = 1692
learning_rate = 0.0002
keep_prob = 0.7
epochs = 50
|
import os
import sys
from drink_partners.settings import constants
SIMPLE_SETTINGS = {
'OVERRIDE_BY_ENV': True,
'CONFIGURE_LOGGING': True
}
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'drink_partners.contrib.... |
# -*- coding: utf-8 -*-
"""Condition synchronization
"""
import time
import threading
import random
class Producer(threading.Thread):
def __init__(self, integers, condition):
super(Producer, self).__init__()
self.integers = integers
self.condition = condition
def run(self):
... |
#!/usr/bin/python3
# Convert features and labels to numpy arrays
import ast
import numpy
from lxml import etree
from sklearn.preprocessing import LabelEncoder
# Local imports
from data_tools import data_util
debug = True
''' Convert the dataframe feature column to a numpy array for processing
use_numpy: True ... |
from kat.harness import Query
from abstract_tests import AmbassadorTest, ServiceType, HTTP
import json
class MaxRequestHeaderKBTest(AmbassadorTest):
target: ServiceType
def init(self):
self.target = HTTP()
def config(self):
yield self, self.format("""
---
apiVersion: ambassador/v1
kind: M... |
#!/usr/bin/env python
# Copyright (C) 2017 Udacity Inc.
#
# This file is part of Robotic Arm: Pick and Place project for Udacity
# Robotics nano-degree program
#
# All Rights Reserved.
# Author: Harsh Pandya
# import modules
import rospy
import tf
from kuka_arm.srv import *
from trajectory_msgs.msg im... |
table_data=[[]for i in range(5)]
print(table_data)
for i in range(4):
table_data[i].append(i)
print(table_data)
|
from django.contrib import admin
from .models import Category, Request, RequestImage, PoliceOffice
admin.site.register(PoliceOffice)
admin.site.register(Category)
admin.site.register(Request)
admin.site.register(RequestImage)
|
import pyodbc
try:
connect = pyodbc.connect(r'Driver= {Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\ichil\Downloads\Database2.accdb')
print("Connected to a Database") |
import sys
import threading
try:
# python 2
from thread import error as ThreadError
except:
# python 3
ThreadError = RuntimeError
import greenlet
DEBUG = False
class DeadLockError(Exception):
pass
class Lock(object):
def __init__(self):
if DEBUG:
sys.stdout.write('L')
... |
#!/bin/python3
import math
import os
import random
import re
import sys
def Type_Number(n):
if n%2 != 0:
print("Weird")
if n%2 == 0:
if (n>20):
print("Not Weird")
elif (n>=6):
print("Weird")
elif (n>=2):
print("Not Weird")
if __name... |
import re
from io import BytesIO
from time import sleep
from typing import Optional
from typing import Optional, List
from telegram import TelegramError, Chat, Message
from telegram import Update, Bot
from telegram import ParseMode
from telegram.error import BadRequest
from telegram.ext import MessageHandler, Filters,... |
import random
import string
import ipaddress
import struct
from typing import Dict, Optional
import asyncio
from aiohttp import ClientSession
from urllib.parse import urlencode
from pprint import pformat
from bcoding import bdecode
from torrent import Torrent
import util
PEER_ID = 'SISTER-' + ''.join(
random.choic... |
import torch
import numpy as np
import cv2
from dataset import FashionMNIST
from linear import Conceptor
from semantic import Semantic_Memory
from nearest import Nearest_Neighbor
from perspective import *
class Static_Hierarchy_Classifier:
def __init__(self, device, num_classes):
print("init")
sel... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Huawei.MA5300.get_version
# sergey.sadovnikov@gmail.com
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ------------------------... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Frame(Component):
"""A Frame component.
Frame is a wrapper for the <frame> HTML5 element.
For detailed attribute info see:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/frame
Keyword ar... |
from . import *
class AWS_KinesisAnalytics_ApplicationOutput_KinesisFirehoseOutput(CloudFormationProperty):
def write(self, w):
with w.block("kinesis_firehose_output"):
self.property(w, "ResourceARN", "resource_arn", StringValueConverter())
self.property(w, "RoleARN", "role_arn", StringValueConverter... |
expected_output = {
'vpn_id': {
1000: {
'encap': 'MPLS',
'esi': '0001.00ff.0102.0000.0011',
'eth_tag': 0,
'label': 100001,
'mp_info': 'Remote all-active, ECMP Disable',
'mp_resolved': True,
'pathlists': {
'... |
'''
Created on 31 Oct 2012
@author: kreczko
'''
from __future__ import division
import unittest
from random import random
import numpy as np
from rootpy.plotting import Hist2D
# under test
from tools.Calculation import calculate_purities
from tools.Calculation import calculate_stabilities
from tools.Calculation impor... |
import numpy as np
from torch import Tensor
from train_utils import training_step, model_validation
def test_train_step(module_dict):
model = module_dict["model"]
optimizer = module_dict["optimizer"]
criterion = module_dict["criterion"]
train_dataloader = module_dict["train_dataloader"]
for ba... |
from formula3 import formula
from const import *
from math import *
v_circ = formula("circular orbit velocity",
v='({u}/{r})**0.5',
u='{r}*{v}**2',
r='{u}/{v}**2')
v_elip = formula("elipse orbit velocity",
v='(2*{u}/{r}-{u}/{a})**0.5',
u='{r}*{v}**2',
r='{u}/{v}**2')
delta_v = formula("",
dv='g*isp*log(mi/mf)... |
from functools import singledispatch
from . import numpy
@singledispatch
def RmsProp(machine, learning_rate=0.001, beta=0.9, epscut=1.0e-7):
r"""RMSProp optimizer.
RMSProp is a well-known update algorithm proposed by Geoff Hinton
in his Neural Networks course notes `Neural Networks course notes
<http... |
"""
Native Japanese pronunciations for characters based on Kunyomi
pronunciations from Wiktionary. These include guesses on application
of rendaku.
"""
__author__ = """
rws@uiuc.edu (Richard Sproat)
"""
KUNYOMI_ = {}
RENDAKU_ = {}
def RendakuWorldBet(worldbet):
"""If the romaji is marked with '*' the form may unde... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import scipy.io
from scipy.stats import norm as scipy_norm
import seaborn as sns
from utils.misc import mkdir
from utils.plot import plot_prediction_bayes, plot_MC
from utils.lhs import lhs
from args import args, device
p... |
import asyncio
import logging
import sys
from lib.interface import OrderBook
ftx = __import__('2_ftx_ans')
# Create a class to represent a candlestick (or bar) with open, high, low and close variables
class Bar:
# create an empty bar
def __init__(self):
self.open = None
self.high = None
... |
__test__ = False
if __name__ == '__main__':
import eventlet
import eventlet.tpool
import gc
import pprint
class RequiredException(Exception):
pass
class A(object):
def ok(self):
return 'ok'
def err(self):
raise RequiredException
a = A()
... |
from distutils.core import setup
import py2exe
setup(console=['debugFinderJs.py'])
|
from enum import Enum
from entity import Entity
from core.database import FromDB, DBData
from core.constants import AfflictType
from typing import Optional
class AffGroup(Enum):
DOT = 1
CC = 2
class Affliction(FromDB, table="AbnormalStatusType"):
def __init__(self, aff_type: AfflictType, entity: Entity)... |
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... |
# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
"""
Module that implements pure-python equivalents of the functions in the
_speedups extension module.
"""
from numpy import clip, invert, isnan, isinf, array, transpose, zeros, \
compress, where, take, float32, ones_like
import numpy as np
import operator
def array_combine(a, b, op=operator.and_, func=lambda x:... |
def roll_dX(X):
op = {}
for i in range(X):
op[i+1] = 1.0/X
return op
def app(dyct,key,val):
if key in dyct:
dyct[key]+=val
else:
dyct[key]=val
return dyct
def p_add(a,b):
op = {}
for akey in a:
for bkey in b:
op = app(op, akey+bkey, a[akey]*b[bkey])
return op
def p_subtract(a,b):
op = {}
for a... |
#!/usr/bin/env python3
import numpy as np
from dataclasses import dataclass
from typing import Tuple
@dataclass
class PIDSettings:
""" PID Controller Settings. """
kp: float
ki: float
kd: float
max_i: float # windup
max_u: float # max effort
cutoff_freq: float # used for derivative f... |
from django.shortcuts import redirect
from django.urls import reverse_lazy
from django.views.generic import ListView, DetailView, RedirectView
from django.views.generic.edit import CreateView, DeleteView, UpdateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import redirect... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import unittest
import torch
from fairseq.modules.multihead_attention import MultiheadAttention
class TestMultiheadAttention(unittest.TestC... |
from datetime import date
from datetime import datetime as dt
from functools import reduce
import unittest
from context import utils
from context import data_driven_design as ddd
import logging
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
#from .context import data_driven_design as ddd
class TestDa... |
import unittest
from iobeam.resources import device
_PROJECT_ID = 1
_DEVICE_ID = "py_test_id"
_DEVICE_NAME = "py_test_device"
class TestDevice(unittest.TestCase):
def test_validConstructor(self):
d = device.Device(_PROJECT_ID, _DEVICE_ID, deviceName=_DEVICE_NAME)
self.assertEqual(_PROJECT_ID, d... |
import argparse
import torch.nn.functional as F
from .. import load_graph_data
from ..train import train_and_eval
from ..train import register_general_args
from .gat import GAT
def gat_model_fn(args, data):
heads = ([args.n_heads] * args.n_layers) + [args.n_out_heads]
return GAT(data.graph,
a... |
import os
import json
import dateutil.parser
from urllib.parse import urlparse
from datetime import datetime
from celery import shared_task
from django.conf import settings
from django.utils.timezone import utc
@shared_task
def load_data_to_db(paren_result, session_id):
from ..models import Sit... |
# Autogenerated from KST: please remove this line if doing any edits by hand!
import unittest
from valid_short import _schema
class TestValidShort(unittest.TestCase):
def test_valid_short(self):
r = _schema.parse_file('src/fixed_struct.bin')
|
import re
from avmess.controllers.login import LoginHandler
from avmess.controllers.register import RegisterHandler
from avmess.controllers.messages import MessageHandler
from avmess.controllers.connect import ConnectionHandler
from avmess.controllers.rooms import RoomHandler
class Router(object):
urlpatterns =... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-09 13:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cre... |
#!/usr/bin/env python3
import OpenGL.GL as GL
import numpy as np
import assimpcy
from core.shader import Shader
from core.mesh import Mesh
VERTEX_SHADER_NAME = 'model/model.vert'
FRAGMENT_SHADER_NAME = 'model/model.frag'
class Model(Mesh):
def __init__(self, lights_manager, attributes, index=None,
... |
import time
from unittest import TestCase
import numpy as np
from algorithms.agent import AgentRandom
from algorithms.tests.test_wrappers import TEST_ENV_NAME
from algorithms.topological_maps.topological_map import hash_observation
from utils.envs.doom.doom_utils import doom_env_by_name, make_doom_env
from utils.util... |
"""Manage and handle price data fron the main awattprice package."""
import asyncio
from decimal import Decimal
from typing import Optional
import awattprice
from awattprice.defaults import Region
from box import Box
from liteconfig import Config
from loguru import logger
class DetailedPriceData:
"""Store extr... |
import os, time
def cmd_say(msg):
os.system("echo '{}' | say".format(msg))
def count_down_by_seconds(num):
while num > 0:
print("还剩{}秒".format(num))
num=num - 1
time.sleep(1)
print('录制结束')
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read() |
import requests
from flask import jsonify, send_from_directory, Response, request
from flask_yoloapi import endpoint, parameter
import settings
from funding.bin.utils import get_ip
from funding.bin.qr import QrCodeGenerator
from funding.factory import app, db_session
from funding.orm.orm import Proposal, User
@app.r... |
# -*- coding: utf-8 -*-
from bpy.types import Panel
from mmd_tools import register_wrap
from mmd_tools.core.camera import MMDCamera
@register_wrap
class MMDCameraPanel(Panel):
bl_idname = 'OBJECT_PT_mmd_tools_camera'
bl_label = 'MMD Camera Tools'
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'... |
#Write import statements for classes invoice and invoice_item
from src.assignments.assignment9.invoice import Invoice
from src.assignments.assignment9.invoice_item import InvoiceItem
'''
LOOK AT THE TEST CASES FOR HINTS
Create an invoice object
In the loop:
Create a new InvoiceItem
Create a user controlled loop to cont... |
# -*- coding: utf-8 -*-
"""
slicr.utils
~~~~~~~~~~~
Utility functions and helpers.
:copyright: © 2018
"""
from collections import namedtuple
def convert_args(args_dict):
"""Convert dictionary to named tuple enabling class like attribute access.
:param args_dict: Dictionary of arguments to convert.
:ty... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.