text stringlengths 2 999k |
|---|
from typing import Optional, Union
from discord.ext import commands
def isfloat(string: str) -> bool:
"""
This function receives a string and returns if it is a float or not.
:param str string: The string to check.
:return: A boolean representing if the string is a float.
:rtype: bool
"""
... |
import pickle
import numpy as np
from garage.replay_buffer import SimpleReplayBuffer
from tests.fixtures.envs.dummy import DummyDiscreteEnv
class TestReplayBuffer:
def test_add_transition_dtype(self):
env = DummyDiscreteEnv()
obs = env.reset()
replay_buffer = SimpleReplayBuffer(env_spec... |
# coding: utf-8
import pprint
import re
import six
class QuotaList:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json ... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from parlai.core.agents im... |
import cv2
import numpy as np
from typing import Tuple, Optional
def resize_image(image: np.ndarray, desired_shape: Tuple[int, int] = (35, 35),
dimension_to_match: Optional[str] = None,
crop_center: Optional[bool] = False,
add_padding: Optional[bool] = False,
... |
from copy import deepcopy
from datetime import datetime
from typing import Dict
from typing import List
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.metrics import MAE
from etna.metrics import MSE
from etna.metrics import SMAPE
from etna.metrics import Metric
from... |
# Generated by Django 3.0.2 on 2020-02-03 10:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('erp', '0008_auto_20200131_2305'),
]
operations = [
migrations.CreateModel(
name='Circulation',
... |
from flask_restful import Resource, Api, reqparse, fields, abort
from flask import jsonify
from sqlalchemy import or_
from ..models import db
from ..models.quote_category import QuoteCategory, QuoteCategorySchema
class QuoteCategoriesResource(Resource):
@staticmethod
def register(api):
api.add_resou... |
#print board
def printBoard(board):
print("---------------------")
for x in range(0, 9):
if x == 3 or x == 6:
print("----------------------")
for y in range(0, 9):
if y == 3 or y == 6:
print("|", end=" ")
print(board[x][y], end=" ")
pri... |
import datetime
import json
import os
import pytest
from datetime import timedelta
from unittest import mock
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.core.management.base import CommandError
from freezegun import freeze_time
from waffle.testutils im... |
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
import sys
from pysnmp.entity.rfc3413 import config
from pysnmp.proto import rfc1905, errind
from pysnmp.proto.api import v2c
from pysnmp.proto.proxy import rfc257... |
# Generated by Django 3.2 on 2021-04-21 01:08
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('genero', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Seri... |
SCREEN_SIZE = (800, 800)
CUSTOMER_COLOR = (255,0,0)
DEPOT_COLOR = (0, 0, 255)
CUSTOMER_SIZE = 5
DEPOT_SIZE = 10
GUI_UPDATE_INTERVAL = 20
ENABLE_GUI = False
T = True
POPULATION_SIZE = 40
DISTANCE_BOUND = 0.13752601101133229
MUTATION_RATE = 0.03
MUTATION_RATE_DECAY = 1#0.999
|
from tamr_unify_client.models.attribute.resource import Attribute
from tamr_unify_client.models.base_collection import BaseCollection
class AttributeCollection(BaseCollection):
"""Collection of :class:`~tamr_unify_client.models.attribute.resource.Attribute` s.
:param client: Client for API call delegation.
... |
from datetime import datetime
from flask import Flask, jsonify
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis', retry_on_timeout=True)
@app.route('/timestamp', methods=['POST'])
def create_timestamp():
timestamp = datetime.now().isoformat()
timestamp_id = redis.incr('TIMESTAMP_ID')
... |
from .version import get_version
__version__ = get_version()
|
"""
Manager and Serializers for Pages.
Pages are markup created and saved by users that can contain Galaxy objects
(such as datasets) and are often used to describe or present an analysis
from within Galaxy.
"""
import logging
from galaxy import model
from galaxy.managers import sharable
log = logging.getLogger(__na... |
# -*- coding: utf-8 -*-
# Scrapy settings for diyifanwen project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/lat... |
import pandas
import matplotlib.pyplot as plt
# inputs
brids_over_time_path = 'all_birds_over_time.csv'
birds = pandas.read_csv(brids_over_time_path)
birds.date = pandas.to_datetime(birds.date, format='%Y-%m-%d %H:%M:%S')
birds.sort_values('date', inplace=True)
for ct, site in enumerate(birds.site.unique()):
sdx... |
import requests
import io
import os
import json
import pathlib
import pathvalidate
import time
from typing import List, Union
from pprint import pprint
chaps = ["0D16B704A478D3FB9C33DC5901307461"]
URL_BASE = "https://www.xuetangx.com"
class SessionInfo:
def __init__(self, session_id: str, sign_id: str):
... |
from enum import IntEnum
class ErrorCode(IntEnum):
Success = 0,
# Common errors
# Caller passed invalid value as param 1 (null, invalid json and etc..)
CommonInvalidParam1 = 100,
# Caller passed invalid value as param 2 (null, invalid json and etc..)
CommonInvalidParam2 = 101,
# Caller... |
#!/usr/bin/env python3
"""
gftools fix-font
Update a font so it conforms to the Google Fonts specification
https://github.com/googlefonts/gf-docs/tree/main/Spec
Usage:
gftools fix-font font.ttf
# Fix font issues that should be fixed in the source files
gftools fix-font font.ttf --include-source-fixes
"""
import arg... |
"""
Implementation of small ints, stored as odd-valued pointers in the
translated PyPy. To enable them, see inttype.py.
"""
from pypy.objspace.std.objspace import *
from pypy.objspace.std.noneobject import W_NoneObject
from pypy.rlib.rarithmetic import ovfcheck, ovfcheck_lshift, LONG_BIT, r_uint
from pypy.objspace.std... |
f1 = open("slurm-3101.out", 'r')
lines = f1.readlines()
count = 0
d = {}
for line in lines:
s = line.split(' + ')
s.remove('\n')
print(s)
count += 1
for x in s:
s1 = x.split('A^')
if (float(s1[0]) != 0 or int(s1[1]) != 0):
print(s1)
res = d.get(int(s1[1]))
... |
# What are the factors of 18?
# factor: an integer which when multiplied with another integer, results in the product 18.
# Hence when 18 is divided by this number, the dividend is an integer and there are no remainders.
num = 18
for i in range(1, num+1):
if num % i == 0: # if remainder after dividing by i is... |
predictions_8ball = ["It is certain.", "It is decidedly so.", "Without a doubt.", "Yes definitely.",
"You may rely on it.",
"As I see it, yes.", "Most likely.", "Outlook good.", "Yes.", "Signs point to yes.",
"Reply hazy, try again.", "Ask again later.", "B... |
# -*- coding: utf-8 -*-
"""
these objects write the results of a select in
various formats
more or less implement an abstract base class
but without the formalism
"""
import HTML
import os
from app_global import AppGlobal
#i#mport html_local
BREAK_LINE = ":====================" # break in "input fil... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('www.urls')),
)
|
from django.conf.urls import include, url, patterns
from . import views
urlpatterns = patterns('',
url(r'^$', views.HomeView.as_view(), name='home'),
url(r'^(?P<short_url>[0-9A-Za-z]{1,30})/$', views.RedirectView.as_view(), name='redirect'),
) |
# Date: 09/01/2018
# Author: Pure-L0G1C
# Description: Execute creator
import os
import sys
import shlex
import shutil
import smtplib
import tempfile
from lib.file import File
from lib.args import Args
try:
from PyInstaller import __main__ as pyi, is_win
except:
print('Please install Pyin... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.hitbtc import hitbtc
import base64
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors imp... |
from typing import Any, Dict
from achi.wallet.key_val_store import KeyValStore
from achi.wallet.settings.default_settings import default_settings
from achi.wallet.settings.settings_objects import BackupInitialized
class UserSettings:
settings: Dict[str, Any]
basic_store: KeyValStore
@staticmethod
as... |
#!/usr/bin/python
# coding=utf-8
################################################################################
import os
import sys
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from test import run_only
from mock import patch
from diamond.collector import Coll... |
import rospy
import copy
import numpy
from smach_based_introspection_framework.configurables import (
dmp_cmd_fields,
)
from birl_skill_management.dmp_management import (
cook_array_from_object_using_postfixs,
)
from birl_skill_management.util import (
get_eval_postfix,
plot_cmd_matrix,
)
from smach_bas... |
from __future__ import absolute_import
import base64
import os
import pathlib
import unittest
import conjur
from OpenSSL import crypto, SSL
CERT_DIR = pathlib.Path('config/https')
SSL_CERT_FILE = 'ca.crt'
CONJUR_CERT_FILE = 'conjur.crt'
CONJUR_KEY_FILE = 'conjur.key'
def generateKey(type, bits):
"""Generates a... |
#!/usr/bin/env python
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Collection of traffic scenarios where the ego vehicle (hero)
is making a left turn
"""
import numpy as np
import py_trees
import carla
from haco.DIDrive_core.utils.planner i... |
# Copyright 2018 Google LLC
#
# 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, ... |
''' Frustum PointNets v2 Model.
'''
from __future__ import print_function
import sys
import os
import tensorflow as tf
import numpy as np
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
import tf_util
... |
import cv2
import os
path = ""
cap = cv2.VideoCapture(0)
print(f'width: {cap.get(3)}')
print(f'height: {cap.get(4)}')
global countFolder
def saveDataFunc():
global countFolder
countFolder = 0
while os.path.exists(path + str(countFolder)):
countFolder += 1
os.makedirs(path + str(countFolder)... |
from __future__ import division
from __future__ import print_function
import os
import time
import tensorflow as tf
import numpy as np
from graphsage.models import SampleAndAggregate, SAGEInfo, Node2VecModel
from graphsage.minibatch import EdgeMinibatchIterator
from graphsage.neigh_samplers import UniformNeighborSamp... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import nose
from numpy.testing.decorators import slow
from datetime import datetime
from numpy import nan
from pandas import date_range,bdate_range, Timestamp
from pandas.core.index import Index, MultiIndex, Int64Index
from pandas.core.api import Categori... |
#!/usr/bin/env python3
# -*- encoding=utf-8 -*-
# description:
# author:jack
# create_time: 2018/1/3
"""
desc:pass
"""
from dueros.Bot import Bot
from dueros.card.TextCard import TextCard
class Bot(Bot):
def launchRequest(self):
'''
打开调用名
'''
self.wait_answer()
card = ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lic... |
import argparse
import os
import traceback
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
from cv2 import cv2
import time
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambd... |
"""shoppers_street URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Cla... |
#!/usr/bin/env python3
def to_base(n: int, base: int) -> str:
""" Convertit un nombre entier dans son écriture dans la base indiquée qui doit être ≤ 36. """
if base > 36 or base < 2:
raise ValueError("to_base() base must be >= 2 and <= 36")
if n == 0:
return "0"
if n < 0:
n ... |
#
# Copyright (c) 2018 Jonathan Weyn <jweyn@uw.edu>
#
# See the file LICENSE for your rights.
#
"""
Methods for formatting predictor data and training scikit-learn models.
"""
from model import *
from predictors import *
from scorers import *
|
"""Tests for lock.py"""
import unittest
from unittest import mock
import re
import asyncio
STR_RGX_REPR = (
r'^<(?P<class>.*?) object at (?P<address>.*?)'
r'\[(?P<extras>'
r'(set|unset|locked|unlocked)(, value:\d)?(, waiters:\d+)?'
r')\]>\Z'
)
RGX_REPR = re.compile(STR_RGX_REPR)
def tearDownModule(... |
# coding: utf-8
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
import re # noqa: F401
import sys # noqa: F401
import nulltype # ... |
# 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.
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the r... |
import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
with open(os.path.join(here, 'CHANGES.txt')) as f:
CHANGES = f.read()
except IOError:
README = CHANGES... |
import concentrate
import sys
from setuptools import setup
if sys.version_info[0] < 3:
sys.exit('python < 3 unsupported.')
requirements = ['yaml'],
setup(
name='concentrate',
version=concentrate.__version__,
packages=['concentrate'],
license=['MIT'],
description='',
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C
import... |
#!/usr/bin/env python3
"""
Experiment to stress Xnet.
This is using the Xnet test driver to benchmark Xnet performance.
"""
import json
import math
import os
import sys
import time
import gflags
from ic.candid import encode
from ic.candid import Types
from ic.principal import Principal
from termcolor import colored
... |
def main(j, args, params, tags, tasklet):
params.merge(args)
import tornado.ioloop
def stop_portal():
ioloop = tornado.ioloop.IOLoop.current()
ioloop.add_callback(lambda x: x.sys.exit(3), tornado.ioloop)
stop_portal()
params.result = ('Portal is reloaded', params.doc)
return... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import sys... |
from .context import inlets
import numpy
import pytest
import os
from shapely.geometry import Polygon
import xarray
DB_NAME = ":memory:"
def data_path(source):
return os.path.join(os.path.dirname(__file__), "..", "data", "netCDF_Data", source)
@pytest.mark.parametrize(
"value,lower,upper",
[
(... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team.
#
# 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... |
"""
Test suite-wide fixtures
Fixtures:
csv_filename
data_and_columns
html_table
"""
import os
from lxml import html
import pytest
from tablify.reader import CSVTableReader
from tablify.renderer import HTMLRenderer
from tablify.ui import UserColumnSettings
from tests.helpers import (
CLASS_NAME,
T... |
import pickle
import numpy as np
arr = np.zeros((1000,2))
with open('rgbs.pkl', 'wb') as f:
pickle.dump([], f) |
from math import sqrt
from random import choice
import pygame as pygame
from pygame.locals import *
pygame.init()
def get_list(l, indexes):
return [l[i] for i in indexes]
def polarity(n):
if n == 0:
return n
return n / abs(n)
def combine_lists(l1, l2, sign):
l1 = list... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import CircuitTestFramework
from test_framework.util import (
asse... |
import sys
import os
import filecmp
path = "D:/OneDrive/Programming/ProgramC/CodeForces/"
def EOF(f):
current_pos = f.tell()
file_size = os.fstat(f.fileno()).st_size
return current_pos >= file_size
def inToAuxFile(auxFile, inputFile, stopKey):
data, normal = [], 0
while (True):
try:
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Dolores Juliana and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
class TestRedashBusinessIntelligence(unittest.TestCase):
pass
|
# Copyright 2021 The Flax 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 applicable law or agreed to in wri... |
from flask_mail import Message
from manage import create_app
from . import mail
from flask import render_template
import os
def send_email(subject, sender, recepients, text_body, html_body):
msg = Message(subject,sender=sender,recipients=recepients)
msg.body = text_body
msg.html = html_body
mail.send(m... |
# Copyright (c) 2013-2018 Steve Milner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistributions of source code must retain the above copyright
# notice, this list of condi... |
# -*- coding: utf-8 -*-
from Slevanda_python_training.Model.group import Group
def test_new_group_address_book(app):
old_groups = app.group.get_group_list()
group = Group(name="Group Name", header="Group header", footer="Group footer")
app.group.create(group)
assert len(old_groups) + 1 == app.group.cou... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import json
from djangocms_text_ckeditor.models import Text
from cms.api import create_page, add_plugin
from cms.constants import PLUGIN_MOVE_ACTION
from cms.models import Page
from cms.models.placeholdermodel import Placeholder
from cms.models.pluginmodel... |
# 密码安全性检查代码
#
# 低级密码要求:
# 1. 密码由单纯的数字或字母组成
# 2. 密码长度小于等于8位
#
# 中级密码要求:
# 1. 密码必须由数字、字母或特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)任意两种组合
# 2. 密码长度不能低于8位
#
# 高级密码要求:
# 1. 密码必须由数字、字母及特殊字符(仅限:~!@#$%^&*()_=-/,.?<>;:[]{}|\)三种组合
# 2. 密码只能由字母开头
# 3. 密码长度不能低于16位
symbols = r' ''~!@#$%^&*()_=-/,.?<>;:[]{}|\... |
from flask import current_app, g, jsonify, request
from flask_cors import cross_origin
from alerta.app import qb
from alerta.auth.decorators import permission
from alerta.exceptions import ApiError
from alerta.models.enums import Scope
from alerta.models.heartbeat import Heartbeat
from alerta.utils.api import assign_c... |
from .config import C, V, PeerToPeerError
import time
import socket
from threading import Lock
class User:
def __init__(self, number, sock, host_port, aeskey, sock_type):
self.name = None
self.client_ver = None
self.network_ver = None
self.p2p_accept = None
self.p2p_udp_acc... |
import numpy as np
def encode_data(obj):
"""
Encodes data before serialization. Basic data-types that can be directly serialized are
returned unchanged. Other data types that cannot be serialized by msgpack, are broken down
and made compatible as well as recognizable. Numpy array are a perfect example... |
# coding=utf-8
# Copyright 2020 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... |
# Copyright 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import tempfile
import unittest
from telemetry.internal.browser import browser_credentials
SIMPLE_CREDENTIALS_STRING = """
{
"google": {
"u... |
from __future__ import absolute_import, division, print_function
import warnings
warnings.warn("The importers module is deprecated and will be removed in "
"version 2.0. Check the `util` module for json imports",
DeprecationWarning)
def import_json():
warnings.warn(
"'import_... |
from __future__ import absolute_import, print_function
import operator
import sys
from collections import defaultdict
from django.core.management.base import BaseCommand, CommandError, make_option
from django.db.models import Q
from six.moves import input, reduce
from sentry.models import Organization, Organization... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Shared fixtures for :mod:`pytest`."""
from __future__ import print_function, absolute_import
import os
try:
from pathlib import Path
except ImportError:
from pathlib2 import Path
import pytest # noqa
import gryaml
import py2neo
import yaml
from py2neo_com... |
import pandas as pd
from geopy.geocoders import Nominatim
from geopy.extra.rate_limiter import RateLimiter
# download data
df = pd.read_csv("https://raw.githubusercontent.com/thessaly/GOSHMap/master/goshmap2.csv")
# clean data
del df['item']
del df['coords']
# Get coords for mapping
geolocator = Nominatim(user_agen... |
import boto
import configparser
import gzip
import os
import re
import subprocess
import xml.etree.ElementTree as ET
from environment_config import (
AWS_CONFIG_PATH,
AWS_PROFILE,
CSS_BUCKET,
IMAGE_BUCKET,
JS_BUCKET,
PREFIX_PATH,
XML_PATH,
JAVA_PATH,
MINIFIER_PATH,
)
def depl... |
# MenuTitle: Guides through all alignment zones
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
# Ricard Garcia - 05.11.2018
# --------------------------
__doc__="""
Sets a global guideline in each alignment zone.
"""
# ---------------------
# Modules
# ------------------... |
import pytest
from src.parsing.postal_code_validator import PostalCodeValidator
from src.parsing.models import Address, City
def get_validator() -> PostalCodeValidator:
return PostalCodeValidator(
config={'postal_code_path': 'test/postal_code_validator_data.csv'},
city_column_name="city"... |
##############################################################################
#
# Unit tests for displacement operations
# Convention: The displacement unitary is fixed to be
# U(\alpha) = \exp(alpha \hat{a}^\dagger - \alpha^* \hat{a})
# where \hat{a}^\dagger is the photon creation operator.
#
########################... |
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from recipe import views
# DefaultRouter - feature that will auto generate the urls for ViewSet
router = DefaultRouter()
router.register('tags', views.TagViewSet)
router.register('ingredients', views.IngredientViewSet)
router.regi... |
from setuptools import setup
setup(
name = 'pygtranslate',
packages = ['pygtranslate'],
version = '0.0.1',
description = 'Pythonic interface to google translate services',
long_description = open('README.md').read(),
long_description_content_type='text/markdown',
author = 'Varun Balupuri',
author_email ... |
from .schema import Report
from .schema import ReportMetadata
__version__ = "0.1.0"
__all__ = ['__version__', 'Report', 'ReportMetadata']
|
""" Utilities to work with html page """
import re
import logging
from cssselect import GenericTranslator
from selenium import webdriver
TS = GenericTranslator()
def to_xpath(selector: str) -> str:
""" Returns css selector for lxml """
return TS.css_to_xpath(selector)
def extract_number(string: str) -> str:
... |
"""AnnouncementExternalFeeds API Version 1.0.
This API client was generated using a template. Make sure this code is valid before using it.
"""
import logging
from datetime import date, datetime
from .base import BaseCanvasAPI
from .base import BaseModel
class AnnouncementExternalFeedsAPI(BaseCanvasAPI):
"""Anno... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
try:
import pydgraph
enabled = True
except ImportError:
enabled = False
from redash.query_runner import BaseQueryRunner, register
from redash.utils import json_dumps
def reduce_item(reduced_item, key, value):
"""From https://github.com/vinay2... |
from psutil import virtual_memory
import pytest
from numpy import around, mean, abs, arange, array, zeros, allclose
from numpy.linalg import norm
from skdh.preprocessing import CalibrateAccelerometer
class TestCalibrateAccelerometer:
@pytest.mark.slow
@pytest.mark.skipif(virtual_memory().available < 90e6, re... |
class Library:
def __init__(self, list_of_books, library_name):
# creating a blank dictionary
self.lend_data = {}
self.list_of_books = list_of_books
self.library_name = library_name
# add book to dictionary
for books in self.list_of_books:
self.lend_data[... |
__version__ = '0.0.61' |
import json
import datetime
from flask import abort, Response
from marshmallow import Schema, fields, validates
from marshmallow.validate import Length, Range
def json_abort(message, status):
abort(Response(json.dumps(message), status))
def check_valid(schema):
if schema:
json_abort(schema, 400)
... |
# -*- coding: utf-8 -*-
"""
test_django-watchman
------------
Tests for `django-watchman` views module.
"""
from __future__ import unicode_literals
import json
import sys
import unittest
from importlib import reload
from unittest.mock import patch
import django
from django.conf import settings
from django.contrib.... |
# encoding=utf-8
"""
@author: xiao nian
@contact: xiaonian030@163.com
@time: 2021-12-30 11:30
"""
import os
from config.config import MODEL_CONFIG
from anchor_kit.tts import TTSExecutor
from anchor_kit.gan import wav2lip
if __name__ == '__main__':
text = '今天的天气不错啊'
TTS = TTSExecutor()
wav_file = TTS.run(te... |
import _plotly_utils.basevalidators
class FramewidthValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="framewidth", parent_name="layout.geo", **kwargs):
super(FramewidthValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name... |
import aiohttp
import asyncio
import logging
import re
import threading
import time
import urllib.parse
import validators
from pysitemap.format_processors.xml import XMLWriter
from pysitemap.format_processors.text import TextWriter
from disk_queue import DiskQueue
class AsyncCrawler():
format_processors = {
... |
import numpy as np
from gym.utils import EzPickle
from pettingzoo import AECEnv
from pettingzoo.utils import agent_selector, wrappers
from pettingzoo.utils.conversions import parallel_wrapper_fn
from .multiwalker_base import MultiWalkerEnv as _env
def env(**kwargs):
env = raw_env(**kwargs)
env = wrappers.Cl... |
class FillPatternTarget(Enum,IComparable,IFormattable,IConvertible):
"""
The type of the fill pattern.
enum FillPatternTarget,values: Drafting (0),Model (1),None (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.