content stringlengths 5 1.05M |
|---|
from sanic import Sanic
from .views import SubscribeView
def init_routes(app: Sanic):
app.add_route(SubscribeView.as_view(), '/subscribe/<uid:uuid>', methods=['GET'])
|
import aiopubsub
from loguru import logger
import numpy as np
from tasty_alpha.broker import Broker
from tasty_alpha.exchange import Exchanges
from tasty_alpha.market import Markets
from tasty_alpha.order import LimitOrder, MarketOrder, OrderSide
from tasty_alpha.sampling.bar import Bar
from tasty_alpha.strategy import... |
import copy
from os import path, stat
import cocos
import cocos.actions
import cocos.sprite
import cocos.layer
import pyglet
from . import data, settings
from ..chart import Line, BaseNote, Drag, Flick, Hold, chart
__all__ = ['preview']
combo_label = None
score_label = None
def update_labels():
global combo_l... |
#!/usr/bin/env python3
# Copyright (c) 2021 The Finalcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Common utility functions
'''
import shutil
import sys
import os
from typing import List
def determine_w... |
import copy
import logging
import colorama
from math import floor
def colourize_string(string, colour):
return '{color_begin}{string}{color_end}'.format(
string=string,
color_begin=colour,
color_end=colorama.Style.RESET_ALL)
def initialize_logger_format(logger):
"""
Initialize the ... |
from .downloader import Downloader
from .lyrics import SongLyrics
from .search import Search, DownloadedSongs, yt_search
from .vocalremover import VocalRemover
__all__ = ['SongLyrics','Downloader','Search','DownloadedSongs','VocalRemover','yt_search'] |
"""
homeassistant.components.camera.foscam
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This component provides basic support for Foscam IP cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.foscam/
"""
import logging
from homeassistant.helpers imp... |
#!/usr/bin/env python
"""
Module for reading TXT files
This expects a segment from class derived in convert_text
"""
# do not delete - needed in time_aligned_text
from asrtoolkit.data_handlers.data_handlers_common import footer, header, separator
from asrtoolkit.data_structures.segment import segment
def format_seg... |
import shutil
import sys
import os, os.path
import imp
import blogofile.main
from blogofile import argparse
## These are commands that are installed into the blogofile
## command-line utility. You can turn these off entirely by removing
## the command_parser_setup parameter in the module __dist__ object.
def setup(p... |
"""
pinq.compat
~~~~~~~~~~~
"""
from collections import defaultdict, Iterable
from functools import reduce
from itertools import chain, dropwhile, groupby, islice, takewhile, tee
from operator import eq
try:
from functools import lru_cache
except ImportError:
def lru_cache(maxsize=128, typed=False):
"... |
from django.urls import reverse
from tests.base.main_test_case import MainTestCase
class UserRecipesViewTest(MainTestCase):
def test_userRecipes_whenNotLoggedIn_shouldRedirectToSignInWithNext(self):
self.create_recipe()
response = self.client.get(reverse('my-recipes'))
self.assertRedirect... |
"""
This module creates a rudimentary form entering system within an ipython
notebook and creates a food stack plot with the entered data.
"""
import ipywidgets as widgets
from IPython.display import clear_output
from stack_plotting import stack_plot, food_stack_plot
# a list of lists of values to be plotted in eac... |
"""
Main script for processing an image:
it preprocesses the image, detects the line, estimate line curve
and do the path planning
"""
from __future__ import print_function, with_statement, division, absolute_import
import argparse
import cv2
import numpy as np
from constants import REF_ANGLE, MAX_ANGLE, EXIT_KEYS, ... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position i... |
#!/usr/bin/python
#Import modules for CGI handling
import cgi, cgitb
import Cookie, os, time
import requests
# Instantiate a SimpleCookie object
cookie = Cookie.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
Use... |
import sys
import os
from os import listdir
from os.path import isfile, join
class DisparityAndImagesPath:
def __init__(self):
self.imageLeftFilename = None
self.imageRightFilename = None
self.disparityLeftFilename = None
self.disparityRightFilename = None
def isValid(self):
return (self.imageLeftFilename ... |
#!/usr/bin/env python
'''
Copyright (c) 2019, Robot Control and Pattern Recognition Group, Warsaw University of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions... |
import re
import hazm
import nltk
import pandas as pd
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer, WordNetLemmatizer
nltk.download("wordnet")
nltk.download("stopwords")
class Preprocess:
def fit(self, data, lang):
is_fa = data["lang"] == "fa"
fa_data = data[is_fa]
... |
import time
from pyferm.actions import action
class hold(action):
def __init__(self, name, parent, **kwargs):
super().__init__(name, parent, **kwargs)
def run(self):
self.value = self.params["value"]
self.low = self.params["controls"]["low"]
self.high = self.params["controls"]... |
from enos.core.constant.DeliveryTopicFormat import DeliveryTopicFormat
from enos.core.constant.MethodConstants import MethodConstants
from enos.core.message.BaseRequest import BaseRequest
from enos.core.message.BaseRequest import BaseBuilder
from enos.core.util.Deprecation import deprecated
from enos.message.upstream.o... |
import pytest
def test_arrange():
"""
Blank line in Arrange Block
"""
x = 3
y = 4
result = x ** 2 + y ** 2
assert result == 25
def test_act():
"""
Blank line in Act Block
"""
nothing = None
with pytest.raises(AttributeError):
nothing.get_something()
def... |
from typing import Dict, Iterable, List
from collections import defaultdict
import re
import networkx
TEST_INPUT = """Tile 2311:
..##.#..#.
##..#.....
#...##..#.
####.#...#
##.##.###.
##...#.###
.#.#.#..##
..#....#..
###...#.#.
..###..###
Tile 1951:
#.##...##.
#.####...#
.....#..##
#...######
.##.#....#
.###.#####
#... |
from collections import Counter
a = input()
b = Counter(input())
print(b.most_common()[-1][0])
|
"""This module contains functions for retrieving song data
from the Spotify dataset files.
MIT License
Copyright (c) 2021 Andrew Qiu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restr... |
import telebot
from os import environ
from extra import *
# Nuevo import para poder enviar cosas inline
# Declaración del bot
bot = telebot.TeleBot(environ['TELEGRAM_TOKEN'])
bot.delete_webhook()
# Declaración de los comandos
@bot.message_handler(commands=['start'])
def start_handler(m):
"Función que maneja los usu... |
addrById = {
1: '13:9a', # disi
2: '19:15', # disi
3: '11:0c', # disi
4: '12:8a', # disi
5: '11:a3', # disi
6: '10:9b', # disi
7: '18:33', # disi
8: '10:89', # disi
9: '11:4a', # disi
10: 'c8:0c', # disi
11: '18:32', # disi
12: '17:93', # disi
13: '02:d8',... |
""" Comparison Analysis FinBrain API """
__docformat__ = "numpy"
import argparse
from typing import List
import requests
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from pandas.plotting import register_matplotlib_converters
import numpy as np
import seaborn as sns
from g... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Test the Census ETL schema package
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),".."))
from schema import *
def test_range_funcs():
r1 = Range(1,1)
r2 = Range(1,1)
assert r1==r2
r3 = Range(2,2)
assert r1 < r3
def test... |
"""
Journald configuration
======================
Combiner for parsing of journald configuration. man journald.conf describes where various
journald config files can reside and how they take precedence one over another. The combiner
implements the logic and provides an interface for querying active settings.
The jour... |
from __future__ import annotations
from abc import ABC, abstractmethod
from nuplan.common.actor_state.state_representation import TimePoint
from nuplan.common.utils.split_state import SplitState
class InterpolatableState(ABC):
"""
Interface for producing interpolatable arrays from objects. Objects must have... |
from django.shortcuts import render
from applications.forms import ApplicationForm
from datetime import datetime
from django.views.generic import ListView
from django.views.generic.edit import FormView
from .models import ApplicationPeriod, ApplicationGroup
class ApplicationInfoView(ListView):
template_name = "app... |
from random import randrange as rd
# Target class
#
# Provides functions to randomly place the target in a valid location.
# Additionally, contains x and y coordinates, and color of the target
class Target:
def __init__(self, boardSize, board, robots):
self.board_size_ = boardSize
self.set_target(... |
from threading import Thread
import zmq
timeout = 0.1
class Subscriber(object):
def __init__(self, addrs, wsmanager):
self.addrs = addrs
self.wsmanager = wsmanager
self.kill = False
def run(self):
ctx = zmq.Context()
sockets = []
poller = zmq.Poller()
... |
import cProfile
import timeit
from hk1980 import LatLon
stmt = "LatLon(22.284034, 114.137814).to_hk80()"
time = timeit.timeit(stmt=stmt, globals=globals(), number=100)*1000
print(f"{time=} ms")
cProfile.run(stmt) |
#!/usr/bin/env pybricks-micropython
import struct, threading
from pybricks import ev3brick as brick
from pybricks.ev3devices import (
Motor,
TouchSensor,
ColorSensor,
InfraredSensor,
UltrasonicSensor,
GyroSensor,
)
from pybricks.parameters import (
Port,
Stop,
Direction,
Button... |
from pydantic import BaseSettings
class Settings(BaseSettings):
PROJECT_NAME: str = "AIOAuth FastAPI example"
PROJECT_HOST: str = "0.0.0.0"
PROJECT_PORT: int = 8001
DEBUG: bool = True
PSQL_DSN: str
JWT_PUBLIC_KEY: str
JWT_PRIVATE_KEY: str
ACCESS_TOKEN_EXP: int = 900 # 15 minutes
... |
"""
Django settings for arches_bchp project.
"""
import os
import arches
import inspect
from django.utils.translation import gettext_lazy as _
try:
from arches.settings import *
except ImportError:
pass
APP_NAME = 'arches_bchp'
APP_ROOT = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 11:01:16 2015
@author: hehu
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model ... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import py... |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
organisation_name = "nerdvegas"
application_name = "rez-gui"
|
from models.armedforces.formations.units.unitmixin import UnitMixin
from models.configurations import SIMULATOR_CONFIG as CONFIG
class TestUnitMixin():
def setup(self):
print("setup")
self.unit = UnitMixin()
def test_init(self):
print("test_init")
assert self.unit.recharge >=... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# map_setup.py
#
# Copyright (c) 2012-2013 PAL Robotics SL. All Rights Reserved
#
# Authors:
# * Enrique Fernández
import rospy
import rosparam
from std_msgs.msg import String
import os
class MapSetupException(Exception):
pass
class MapSetup:
def __init__(... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
import sys
import roslib
import gencpp
import genmsg
from roslib import packages,msgs
import os
from io import StringIO
import argparse
NAME='create_boost_header'
def write_boost_includes(s, spec):
"""
... |
from logging import getLogger
from typing import Callable, Optional, Union, List, Set
from aiogram import Dispatcher, Bot
from state_manager import BaseStorage
from state_manager.event_processors.aiogram import AiogramEventProcessor
from state_manager.routes.base.state import BaseStateRouter, BaseMainStateRouter
from... |
from __future__ import annotations
from hypothesis import assume, event, example, given, infer, strategies as st
import json
import pytest
from sqlalchemy.future import create_engine
from typing import Dict, List, NamedTuple, Optional, Protocol, TypeVar
from jterritory.api import Endpoint, Invocation, Response
from jt... |
from . import monokai, darkly, github, tomorrow_night, tomorrow
|
import json
import requests
import time
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from datetime import date
class BayesianABTesting:
def __init__(self, likelihood_function: str, data: dict):
"""
A convenience wrapper class for commonly used Bay... |
# novalidate
# fmt: off
from collections import namedtuple
#: NetworkTables Entry Information
EntryInfo = namedtuple('EntryInfo', [
# Entry name
'name',
# Entry type
'type',
# Entry flags
'flags',
# Timestamp of last change to entry (type or value).
#'last_change',
])
#: NetworkTa... |
from PyQt5 import QtCore, QtGui, QtWidgets
class ROITable(QtWidgets.QWidget):
"""
GUI element holding information of regions segmented from
low resolution image stored in slide scanner image
"""
def __init__(self, parent=None, table_widget=None):
super(ROITable, self).__init__(table_wid... |
from .lattice import gen_lattice
|
CONFIG_PATH_ENV_KEY='APTIBLE_CONFIG_PATH'
ACCESS_TOKEN_ENV_KEY='APTIBLE_ACCESS_TOKEN'
|
from crowdin_api import CrowdinClient
from time import sleep
import urllib.request
import json
import re
from pathlib import Path
class UECrowdinClient(CrowdinClient):
def __init__(
self,
token: str,
logger=None,
organization: str = None,
project_id: int = None,
sil... |
from config.redfish1_0_config import config
from config.auth import *
from config.settings import *
from logger import Log
from json import loads, dumps
import pexpect
import pxssh
import subprocess
LOG = Log(__name__)
class Auth(object):
"""
Class to abstract python authentication functionality
"""
@... |
import sys
import igraph as _ig
from . import _c_louvain
from ._c_louvain import ALL_COMMS
from ._c_louvain import ALL_NEIGH_COMMS
from ._c_louvain import RAND_COMM
from ._c_louvain import RAND_NEIGH_COMM
from collections import Counter
# Check if working with Python 3
PY3 = (sys.version > '3')
def _get_py_capsule(g... |
# -*- coding: utf-8 -*-
import json
import unittest
from flask import url_for
from flask_testing import TestCase
from flask_login import login_user
from app import create_app, db
from app.models import User, Todo, TodoList
class TodolistAPITestCase(TestCase):
def create_app(self):
return create_app('t... |
#!/usr/bin/env python3
import wdt
# Compute cost field from image
cost_field = wdt.map_image_to_costs('images/ex2.png')
# Plot the cost field
wdt.plot(cost_field)
# Compute the distance transform from the cost field
distance_transform = wdt.get_weighted_distance_transform(cost_field)
# Plot the result
wdt.plot(distanc... |
"""
Provides a formatter for AoE2 AI rule files (.per)
"""
from antlr4 import FileStream, InputStream, StdinStream, CommonTokenStream, ParseTreeWalker
from .perparse import PERLexer, PERParser
from .formatted_per_listener import FormattedPERListener
def format_per(*, in_path=None, in_string=None, in_stdin=False, out... |
# ----------------------------------------------------------------------------
# Copyright (c) 2020, Franck Lejzerowicz.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------... |
from ..token import currency_equals
from ..currency import Currency, ETHER
from ...constants import SolidityType
from ...utils import validate_solidity_type_instance
from .fraction import Fraction
class CurrencyAmount(Fraction):
@property
def currency(self):
return self._currency
@staticmethod
... |
def _create_ref(ref_type, pkg_name, name):
"""Creates a reference for the specified type.
Args:
ref_type: A `string` value. Must be one of the values in
`reference_types`.
pkg_name: The package name as a `string`.
name: The name of the item as a `string`.
Returns:... |
# Imports
from sqlalchemy import String, Integer, Float, Boolean, Column, and_, ForeignKey
from connection import Connection
from datetime import datetime, time, date
import time
from pytz import timezone
import pandas as pd
import numpy as np
import os
from os import listdir
from os.path import isfile, join
from open... |
"""20.07.2015 PyOSE: Stacked exomoons with the Orbital Sampling Effect."""
import PyOSE
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib import rc
#import xlwt
#from tempfile import TemporaryFile
from numpy import pi
# Set stellar parameters
StellarRadius = 0.7 * 696342. # km
limb1 = 0.597... |
# This is similar to test1, but this time B2 also inherits from B1, which allows it to override its config data.
# B2 also overrides base1_2, like D1.
# The order of inheritace in F is also reversed ([D1, B2] instead of [B2, D1])
# Since the last override of base1_2 in inheritance order is in B2, base1_2 must now
# hav... |
# coding=utf-8
import unittest
import requests as req
from app.api.base import base_name as names
from app.api.base.base_sql import Sql
from app.api.src.touches_from_api import add_new_point
class TestSetPoint(unittest.TestCase):
def test_set_point(self):
origin_x = 55.02999
origin_y = 82.921098... |
from flask import (
redirect,
request,
url_for,
Blueprint,
render_template
)
from flask_sqlalchemy import model
from sqlalchemy.orm import session
from . import models
todo = Blueprint("todo", __name__)
def get_entry(id):
return models.Entry.query.filter(models.Entry.id == id).first()
def ... |
# -*- coding=utf-8 -*-
# Copyright (c) 2019 Dan Ryan
from datetime import datetime, timedelta
from typing import List
from airflow import DAG
from airflow.hooks.S3_hook import S3Hook
from airflow.models import Variable
from airflow.operators.python_operator import PythonOperator
from airflow_salesforce_plugin.hooks i... |
# Copyright (c) 2020 Simons Observatory.
# Full license can be found in the top level "LICENSE" file.
import os
import sys
import numpy as np
from scipy.signal import firwin, fftconvolve
import toast
class Lowpass:
""" A callable class that applies the low pass filter """
def __init__(self, wkernel, fmax,... |
from PIL import Image
from random import shuffle
import sys
from scipy.misc import imread
from scipy.linalg import norm
from scipy import sum, average
import numpy as np
def memoize(f):
""" Memoization decorator for functions taking one or more arguments. """
class memodict(dict):
def __init__(self, f)... |
# -*- coding: utf-8 -*-
import pytest
from wemake_python_styleguide.violations.naming import (
PrivateNameViolation,
TooShortVariableNameViolation,
WrongVariableNameViolation,
)
from wemake_python_styleguide.visitors.ast.naming import (
VARIABLE_NAMES_BLACKLIST,
WrongNameVisitor,
)
function_test ... |
import unittest
from markdown_to_trello.markdown_to_trello import MarkdownToTrello, SaveCards, Card
import pytest
class ConverterTest(unittest.TestCase):
def test_simplest(self):
text = 'Do groceries'
cards = MarkdownToTrello(text).convert_to_cards()
self.assertTrue(len(cards), 1)
... |
import unittest
from data_objects import Rover
from services import turn_commands as tc
from tests.test_environment import rovers
from parameterized import parameterized
class TestTurnLeftFromNorthCommand(unittest.TestCase):
def test_turn_turns_rover_to_west(self):
s = tc.TurnLeftFromNorthCommand()
... |
# BUG: shift with large periods creates mulfunctioning dtypes with master branch #44978
import numpy as np
import pandas as pd
print(pd.__version__)
df = pd.DataFrame(np.random.rand(5, 3))
result = df.shift(6, axis=1, fill_value=None)
print(result)
expected = pd.DataFrame(np.full((5, 3), np.nan))
pd.testing.asse... |
"""
Competitive Programming Sanity Checker
"""
__author__ = 'Kevin Yap'
__version__ = '1.0.0'
__license__ = 'MIT'
|
import os
import datetime as dt
from text import *
# from IPython.display import clear_output as clear
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
class Player:
def __init__(self, world):
self.location = world.start
self.items = []
self.maxhealth = 100
self.h... |
"""
config.py
List some configuration parameters for training model
Modified by: Caleb Harris (caleb.harris94@gatech.edu)
on: 4/10/2020
"""
import os
from os import path as op
from hyperopt import hp
# Set filepaths pointing to data that will be used in training
data_dir = 'imgs//DC_imgs//classify_fixes'
t... |
import os
import importlib
# automatically infer the user module name (in case there is a change during the development)
user_module_name = os.path.split(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))[1]
submodule_name = os.path.split(os.path.abspath(os.path.dirname(__file__)))[1]
# automatically impo... |
import math
from whylogs.proto import LongsMessage
class IntTracker:
"""
Track statistics for integers
Parameters
---------
min
Current min value
max
Current max value
sum
Sum of the numbers
count
Total count of numbers
"""
DEFAULTS = {
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
Spark utilities.
"""
from .spark_net import run_spark_net_from_known_assembly, run_spark_net # noqa: F401
|
import os
import sqlite3
from colorama import Fore
import re
tables_path = os.path.dirname(__file__) + "/tables/"
database_name = "elements_limits.db"
objects_file = "objects.txt"
conn = sqlite3.connect(tables_path + database_name)
cursor = conn.cursor()
def get_sql(sql):
cursor.execute(sql)
... |
from setuptools import setup
import configs
try:
readme = open('README.rst').read()
except:
readme = 'Configs: Configuration for Humans. Read the docs at `configs.rtfd.org <http://configs.rtfd.org>`_'
setup(
name=configs.__title__,
version=configs.__version__,
author=configs.__author__,
descr... |
from __future__ import absolute_import
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
import torchvision as tv
from faster_rcnn.faster_rcnn import FasterRCNN
import faster_rcnn.network as network
"""
def get_resnet50_frcnn():
# Create a FasterRCNN with ResNet50 back... |
class Solution:
def XXX(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
## 旋转题目 找规律 简单的
## 时间99.5 按层向内旋转
left = 0
right = len(matrix)-1
temp = [0 for i in range(len(matrix))]
while left<... |
#!/usr/bin/env python
# Example to solve dense LP problem using (e04mf/lp_solve)
# Solve the problem
# min cvec^T * x
# subject to bl <= A * x <= bu
# and if present: blx <= x <= bux
from naginterfaces.library import opt
from naginterfaces.base import utils
import numpy as np
print('naginterfaces.l... |
import fnmatch
import glob
import io
import itertools
import logging
import os
import subprocess
from sqlalchemy.orm.exc import NoResultFound
from aeromancer.db.models import Project, File, Line
from aeromancer import filehandler
from aeromancer import utils
LOG = logging.getLogger(__name__)
def discover(repo_roo... |
import pygame
def load_png(name):
"""
Load image and return image object
"""
try:
image = pygame.image.load(name)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error:
print('Cannot loa... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from group_norm import *
from torch.utils.data import DataLoader, Dataset, TensorDataset
from gamm... |
# -*- coding: utf-8 -*-
"""Generates summaries of the relation ontology."""
import datetime
import os
from operator import itemgetter
import requests
import yaml
from tabulate import tabulate
from tqdm import tqdm
HERE = os.path.abspath(os.path.dirname(__file__))
DIRECTORY = os.path.join(HERE, 'docs', '_data')
os.m... |
import subprocess
import os
import re
import shutil
import pytest
from test_cookie import basic_project_dict
PROJECT_DIRECTORY = os.path.realpath(os.path.curdir)
def remove_dir(dirpath):
shutil.rmtree(os.path.join(PROJECT_DIRECTORY, dirpath))
def _check_configure(result):
try:
log_configure = sub... |
# SPDX-License-Identifier: MIT
"""
This module contains enumerations for channels of a given monitor mode.
"""
import enum
#===================================================================================================
#===================================================================================... |
from __future__ import division
import numpy as np
from photutils.morphology import centroid_com, centroid_1dg, centroid_2dg
def recenter(image, pos, window_size = 15, method = "2dg", threshold = 10.):
"""
Recenter each star in each frame of the image cube before performing
aperture photometry to take c... |
"""
DB API中定义了一些数据库操作的错误及异常,下表列出了这些错误和异常:
异常 描述
Warning 当有严重警告时触发,例如插入数据是被截断等等。必须是 StandardError 的子类。
Error 警告以外所有其他错误类。必须是 StandardError 的子类。
InterfaceError 当有数据库接口模块本身的错误(而不是数据库的错误)发生时触发。 必须是Error的子类。
DatabaseError 和数据库有关的错误发生时触发。 必须是Error的子类。
DataError 当有数据处理时的错误发生时触发,例如:除零错误,数据超范围等等。 必须是DatabaseError的子类。
Operationa... |
import json
# Read json
def read_json(json_file_path):
with open(json_file_path, 'r') as rf:
data = rf.read()
data_json = json.loads(data)
return data_json
# Dump json
def dump_json(json_file_path, data):
with open(json_file_path, 'w') as wf:
json.dump(data, wf, indent=4)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayCreditAutofinanceLoanCloseModel(object):
def __init__(self):
self._applyno = None
self._orgcode = None
self._outorderno = None
self._reson = No... |
from common_grader import CommonGrader
import random
class RandomPointsGrader(CommonGrader):
def __init__(self, *args):
super(RandomPointsGrader, self).__init__(*args)
def do_grade(self):
return random.uniform(0.0, 100.0), random.uniform(0.0, 100.0)
|
import unittest
import sys
from sqlite.crud_operations import CrudOperations
class CrudeOperations(unittest.TestCase):
def setUp(self):
self.crud = CrudOperations()
def test_read_all(self):
self.assertIsNotNone(self.crud.read_all())
self.assertIsInstance(self.crud.read_all(),list)
... |
from django.test import TestCase
from app.models import Location, Category, Image
# Create your tests here.
# location model tests
class LocationTestCase(TestCase):
def setUp(self):
"""
Create a location for every test
"""
Location.objects.create(name="Location 1")
def test_l... |
# Copyright (c) 2005-2009 Jaroslav Gresula
#
# Distributed under the MIT license (See accompanying file
# LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
#
# content:
# even if the cid is forced then a simple font is used (if an encoding understood by PDF is used)
# if it is not possible to use a simple font ... |
import datetime
import hashlib
import http
from enum import Enum
from typing import Optional, List, Dict
from pydantic import (
BaseModel,
AnyUrl,
constr,
conint,
HttpUrl,
root_validator,
validator,
)
class AccessMethodType(str, Enum):
s3 = "s3"
gs = "gs"
ftp = "ftp"
gsift... |
from django.db import models
from django.db.utils import DatabaseError
from django.utils import timezone
import logging
logger = logging.getLogger('django')
class LikeManager(models.Manager):
def create(self, creds, **validated_data):
try:
already_liked = Like.objects.all() \
.fil... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.