content stringlengths 5 1.05M |
|---|
try:
from graphql_example.model import Author, Book
except ModuleNotFoundError:
from model import Author, Book
from mimesis import Generic
# fake data generator
generate = Generic('en')
def author_factory(**replace):
kwargs = dict(
first_name=generate.personal.name(),
last_name=generate.... |
# Copyright (c) 2020 - 2021 Persanix LLC. All rights reserved.
#
# 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 ... |
from fparser.Fortran2003 import *
from fparser.api import get_reader
from nose.tools import assert_equal
def assertRaises(exc, cls, s):
try:
cls(s)
raise AssertionError('Expected %s but got nothing' % exc)
except exc:
pass
#############################################################... |
import importlib
def DetourBackend(filename, data_fallback=None, base_address=None, try_pdf_removal=True, replace_note_segment=False, try_without_cfg=False, variant=None):
with open(filename, "rb") as f:
start_bytes = f.read(0x14)
if start_bytes.startswith(b"\x7fCGC"):
detourbackendclas... |
# Python program to generate WordCloud
# importing all necessery modules
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
import pandas as pd
# Reads 'Youtube04-Eminem.csv' file
df = pd.read_csv("wc_test.csv", encoding ="utf-8", delimiter=' ')
comment_words = ''
stopwords = ... |
import torch
from jet20.backend.const import LINEAR,QUADRATIC
class LeConstraitConflict(Exception):
pass
class EqConstraitConflict(Exception):
pass
class Constraints(object):
def __call__(self,x):
raise NotImplementedError("")
def validate(self,x,*args,**kwargs):
raise N... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 16:44:37 2017
@author: Usman
"""
import random,time,numpy as np,threading
from matplotlib import pyplot as plt
def multiply(rows,columns,matrix,matrix2,matrix3):
for i in range(0,int(rows),1):
for j in range(0,int(columns),1):
value... |
import os
import re
import smtplib
import ssl
from contextlib import contextmanager
from datetime import datetime
from email.headerregistry import Address
from email.message import EmailMessage
from email.utils import format_datetime, make_msgid
from typing import Any, Dict, Generator, List, Optional, Tuple, Union
fro... |
from __future__ import annotations
import datetime
import inspect
from typing import Any, ClassVar, Optional
from basic_notion.base import NotionItemBaseMetaclass, NotionItemBase
from basic_notion.schema import Schema
from basic_notion.property_schema import PropertySchema, TextListSchema
from basic_notion.attr impor... |
# Copyright (c) 2014 Dark Secret Software 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 agree... |
from pathlib import Path
from datetime import datetime
from Players.BasePlayers import BaseExItPlayer
from keras.models import load_model as load_keras_model
from Games.GameLogic import GameResult
from tqdm import tqdm, trange
import os.path
import re
from copy import deepcopy
# ******************** GENERAL ********... |
import numpy as np
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.core.cache import cache
from django.views.decorators.cache import cache_page
import django
from svweb.models import LebOrigin
from svweb.plotting_utils import view_wave
from m... |
from utils import *
from ImageSplit import *
from keras.utils.np_utils import to_categorical
from keras.applications import InceptionV3
from keras import models, layers
#Normalize (Rescale data to same range)
X_train, X_test = X_train/255, X_test/255
#one hot encode the labels
y_train = to_categorical(y_train, num_cl... |
#filename show.py
#coding:utf-8
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
import datetime
from django.utils.translation import ugettext
import urllib
from xml.dom import minidom
def... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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... |
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
print(sqlalchemy.__version__ ) |
#!/usr/bin/env python
#coding:utf-8
"""
Author: coreyjones --<>
Purpose: Download YouTube Audio and Video Files.
Created: 12/12/2018
"""
import os, pafy, logging
url = "https://www.youtube.com/watch?v=SLsTskih7_I" #YouTube Video Link
dlcheck = False #dlcheck - Set to "True" to download - Set to "False for dr... |
# An empty __init__ file to get pytest to detect this as a valid test folder.
pass
|
import argparse, yaml, os
from PyBenchFCN import Factory
from CuckooSearch import evolve
os.makedirs("./tmp", exist_ok=True)
parser = argparse.ArgumentParser()
parser.add_argument('prob', type=argparse.FileType('r'))
parser.add_argument('prof', type=argparse.FileType('r'))
args = parser.parse_args()
problems = yaml.... |
from __future__ import absolute_import
from duo_client.https_wrapper import CertValidatingHTTPSConnection
import unittest
import mock
import ssl
class TestSSLContextCreation(unittest.TestCase):
""" Test that the SSL context used to wrap sockets is configured correctly """
def test_no_ca_certs(self):
co... |
# Here we choose which app implementation to use by exporting it as `app`
from app.examples.library.app import app
|
"""Constants used by the legacy Nest component."""
DOMAIN = "nest"
DATA_NEST = "nest"
DATA_NEST_CONFIG = "nest_config"
SIGNAL_NEST_UPDATE = "nest_update"
|
from ..core import Field, SystemObject
from ..core.api.special_values import Autogenerate
from ..core.bindings import RelatedObjectBinding
from ..core.translators_and_types import MunchType
class Plugin(SystemObject):
FIELDS = [
Field("id", type=int, is_identity=True, is_filterable=True, is_sortable=True)... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 05 23:55:12 2018
@author: Kazushige Okayasu, Hirokatsu Kataoka
"""
import datetime
import os
import random
import time
import torch
import torchvision
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.models as model... |
"""Mono-objective available algorithms
"""
# main imports
import logging
# module imports
from macop.algorithms.base import Algorithm
class HillClimberFirstImprovment(Algorithm):
"""Hill Climber First Improvment used as quick exploration optimisation algorithm
- First, this algorithm do a neighborhood expl... |
print("this a line of error")
print("this is a second line")
exit(1) |
from __future__ import unicode_literals
from math import sqrt
import subprocess
import time
import os
import logging
import codecs
from collections import defaultdict
from functools import partial
#from traceback import print_exc
from lxml import etree
import enchant
from py4j.java_gateway import JavaGateway
from djang... |
#!/usr/bin/env python2
import unittest
from hypothesis import given
from hypothesis.strategies import text
from comp_ui import _PromptLen
class PromptTest(unittest.TestCase):
@given(text())
def testNeverPanics(self, s):
self.assertIs(_PromptLen(s) >= 0, True)
if __name__ == '__main__':
unittest... |
from __future__ import annotations
import logging
import re
from abc import ABC, abstractmethod
from typing import Sequence
from home_connect_async import Appliance, Events
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import DOMAIN
... |
import FWCore.ParameterSet.Config as cms
dqmXMLFileGetter=cms.EDAnalyzer("DQMXMLFileEventSetupAnalyzer",
labelToGet = cms.string('GenericXML')
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, ... |
#-*-coding: utf-8-*-
#todo p.246 ~ p.249
#todo code 6-1 ~ code 6-4
#todo 6.1.1 단어와 문자의 원-핫 인코딩
# 단어 수준의 원-핫 인코딩하기
import numpy as np
samples = ['The cat sat on the mat.', 'The dog ate my homework.']
token_index = {}
for sample in samples:
for word in sample.split():
if word not in token_index:
... |
import sys
import json
from facebook_scraper import get_posts
post = next(get_posts(post_urls=[sys.argv[1]], cookies="src/services/cookies.txt"))
post.pop('time')
print(json.dumps(post)) |
import cv2
import numpy as np
import socket
import SocketServer
# KERAS stuff
from keras.layers import Dense, Activation
from keras.models import Sequential
import keras.models
SIGMA = 0.25
class NeuralNetwork(object):
def __init__(self):
self.model = keras.models.load_model('nn_h5/nn.h5')
def pre... |
import json
import time
from pprint import pprint
import keyboard
# with open('bindings.json') as f:
# data = json.load(f)
#
# action = data['spaceship_general']['v_exit']
# pprint(action)
def run():
self_destruct()
eject()
def self_destruct():
for i in range(3):
keyboard.press('alt+backs... |
from random import randint
import time
for i in range(1, 60):
print('')
s = ''
for i in range(1, 1000):
count = randint(1, 500)
while count > 0:
s += ' '
count -= 1
if i % 10 == 0:
print(s + 'Happy New Year')
elif i % 91 == 0:
print(s + 'Merry Chritmas')
else:
rand = ... |
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from dsGameSolver.gameSolver import dsSolve
alpha = 0.25 ## productivity parameter
beta = 0.95 ## discount factor
gamma = 2 ## relative risk aversion
delta = 0 ## capital depreciation
## utility function
def u(c):
return ... |
# Copyright The PyTorch Lightning 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 law or agreed to i... |
import cv2
import numpy as np
import Queue
class Digit(object):
'''
Extracts the digit from a cell.
Implements the classic `Largest connected component` algorithm.
'''
def __init__(self, image):
self.graph = image.copy()
self.W, self.H = self.graph.shape
self.visited = [[F... |
#!/usr/bin/python
'''
NAMEGEN.PY V1.0
Got it working, generating the names from one or many of several databases,
being Goblin, Western (m+f), Elf (m+f), Orc, and Greek Gods. Also is cross-
platform (only checks for which backslash it should use), which should save time
between two files. Currently the names are genera... |
test = { 'name': 'q3a',
'points': 3,
'suites': [ { 'cases': [ { 'code': '>>> '
'print(np.mean(train_scores,axis=1).round(3))\n'
'[0.954 0.958 0.959 0.962 0.963 '
... |
import os
import time
import socket
import struct
import hashlib
from pathlib import Path
from enum import Enum
import numpy as np
class OP(Enum):
RRQ = 1
WRQ = 2
DAT = 3
ACK = 4
ERR = 5
class TFTPClient:
def __init__(self, remote, basedir):
self.remote = remote
self.basedir ... |
EPICS_enabled = True
description = 'Sample slits vert. gap'
prefix = '14IDB:m27'
target = 0.070125 |
from __future__ import absolute_import, division, print_function
import numpy as np
import pandas as pd
import dask.dataframe as dd
from dask.array import Array
from xarray import DataArray
from collections import OrderedDict
from .utils import Dispatcher, ngjit, calc_res, calc_bbox, orient_array, compute_coords, get... |
# importing modules
import helper
import random
import pathlib
import json
# setup
root = pathlib.Path(__file__).parent.parent.resolve()
with open( root / "config/quotes.json", 'r') as filehandle:
random_quote = random.choice(json.load(filehandle))
random_quote = random_quote.replace("-","<br/> -")
# processin... |
from .data import *
from .core import *
from .cam import *
from .models.inception_time import * |
from django.conf import settings
from django.core import management
from django.core.management.base import BaseCommand
from playlists.management import playlist
from playlists.models import Playlist
from talks.models import Talk
from youtube_data_api3.video import get_video_youtube_url
from youtube_data_api3.playlis... |
import random
import time
from flask import Flask, request, abort
from imgurpython import ImgurClient
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
import tempfile, os
from config import client_id, client_secret, album_... |
#!/bin/python3
import requests
import argparse
from html.parser import HTMLParser
class WFarm():
class CustomHTMLParser(HTMLParser):
def __init__(self, nextUrls, url, args, wordsFound):
HTMLParser.__init__(self)
self.nextUrls = nextUrls
self.url = url
sel... |
# 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, software
# distributed under the... |
from flask import *
from flask_bootstrap import *
from flask_moment import Moment
from datetime import datetime
from flask_mail import *
import os
localpass = "admin"
app = Flask(__name__)
Bootstrap(app)
Moment(app)
print('no yeet')
app.config['SECRET_KEY'] = "SomeSecretText"
users = {"kairan.quazi@gmail.com": {'first_... |
#!/usr/bin/env python3
import time
import sys
import threading
import copy
import random
from optparse import OptionParser
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QInputDialog
from PyQt5.QtWidgets import QLabel, QTextEdit, QFrame
from PyQt5.QtWidgets import ... |
#!/usr/bin/env python
import sys, os
import numpy as np
import torch
import matplotlib.pyplot as plt
plt.style.use('seaborn-paper')
import yaml
import glob
fields = ['coll_intensity', 'gp_mse', 'in_collision', 'max_penetration', 'num_iters', 'ext_cost_per_iter', 'task_loss_per_iter',
'constraint_violation']
... |
from django.conf import settings
class NoDefault:
pass
JWT_DEFAULT_SETTINGS = {
'JWT_CLIENT.RENAME_ATTRIBUTES': {},
'JWT_CLIENT.DEFAULT_ATTRIBUTES': {},
'JWT_CLIENT.CREATE_USER': False,
'JWT_CLIENT.COOKIE_NAME': 'id_token',
'JWT_SERVER.JWK_EXPIRATION_TIME': 3600,
'JWT_SERVER... |
from datetime import datetime
class PriceOfferTransformPipeline(object):
def process_item(self, item, spider):
if item['price']:
item['price'] = float(item['price'])
# Optional attributes
if 'discounted_price' in item and item['discounted_price']:
item['discounte... |
"""Solution to Project Euler Problem 1
https://projecteuler.net/problem=1
"""
NUMBERS = 3, 5
MAXIMUM = 1000
def compute(*numbers, maximum=MAXIMUM):
"""Compute the sum of the multiples of `numbers` below `maximum`."""
if not numbers:
numbers = NUMBERS
multiples = tuple(set(range(0, maximum, numb... |
from objects.modulebase import ModuleBase
from objects.permissions import PermissionKickMembers
from utils.funcs import find_user, request_reaction_confirmation
class Module(ModuleBase):
usage_doc = '{prefix}{aliases} <user> [reason]'
short_doc = 'Kick user from server'
name = 'kick'
aliases = (nam... |
from java.awt.geom import AffineTransform
from org.geotools.referencing.operation.matrix import AffineTransform2D
from org.geotools.data import WorldFileReader, WorldFileWriter
from geoscript import util
class WorldFile(object):
"""
World file reader and writer.
"""
def __init__(self, file):
self.fil... |
from ipykernel.kernelbase import Kernel
from iarm.arm import Arm
import re
import warnings
import iarm.exceptions
class ArmKernel(Kernel):
implementation = 'IArm'
implementation_version = '0.1.0'
language = 'ARM'
language_version = iarm.__version__
language_info = {
'name': 'ARM Coretex M0... |
from astropy.table import QTable
from astropy.table import Table
from astropy.io import ascii
import numpy as np
import os
def savetable_S3(filename, time, wave_1d, stdspec, stdvar, optspec, opterr):
"""
Saves data in an event as .txt using astropy
Parameters
----------
event : An Event... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... |
from django.test import TestCase
# Create your tests here.
from django.urls import reverse
from licornes.models import Licorne
from licornes.models import User
from licornes.models import Etape
from django.conf import settings
from bs4 import BeautifulSoup
import re
import os
class IndexViewTest(TestCase):
@cl... |
print('======= DESAFIO 11 =======')
l = float(input('Largura da parede (m): '))
h = float(input('Altura da parede (m): '))
a = l * h
tinta = a/2
print('Para pintar uma parede de área igual a {} m², será(ão) necessário(s) {} L de tinta!'.format(a, tinta))
|
#####################################################################
##### IMPORT STANDARD MODULES
#####################################################################
from __future__ import print_function
from ..data import DataBlock
from ..preprocess import PreProcess
import pandas as pd
import numpy as np
from... |
# 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 u... |
#!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
number = 0
for i in range(x):
try:
print("{}".format(my_list[i]), end="")
number += 1
except IndexError:
print("")
return number
print("")
return number
|
import logging
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import NearestNeighbors
import anatomist.api as anatomist
from soma import aims
import colorado as cld
"""Inspired from lightly https://docs.lightly.ai/tutorials/package/tutorial_simclr_clothing.html
"""
log = logging.getLogger(... |
HANZI_BREAKER_MAP = {
'卧': ('臣', '卜'),
'项': ('工', '页'),
'功': ('工', '力'),
'攻': ('工', '攵'),
'荆': ('茾', '刂'),
'邪': ('牙', '阝'),
'雅': ('牙', '隹'),
'期': ('其', '月'),
'欺': ('其', '欠'),
'斯': ('其', '斤'),
'鞭': ('革', '便'),
'勒': ('革', '力'),
'划': ('戈', '刂'),
'敬': ('苟', '攵'),
... |
from pytorch_lightning.loggers import NeptuneLogger as _NeptuneLogger
from pytorch_lightning.loggers import CSVLogger as _CSVLogger
class Logger:
def log_metrics(self, metric_dict, step, save=False):
pass
def log_hparams(self, hparams_dict):
pass
class CSVLogger(Logger):
def __init__... |
import nanome
from nanome.util import Logs
from nanome.util import Color
from nanome.api.ui import Dropdown, DropdownItem
from functools import partial
import pathlib
import os
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
IMG_REFRESH_PATH = os.path.join(BASE_PATH, 'icons', 'refresh.png')
class K... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import xarray as xr
sns.set()
def plot_range(xlabel, ylabel, title, x, values):
"""x and values should have the same size"""
plt.plot(x, values, 'r-', linewidth=2)
plt.gcf().set_size_inches(8, 2)
plt.title(title)
plt.xlabel(... |
import numpy as np
def bbox2feat_grid(bbox, stride_H, stride_W, feat_H, feat_W):
x1, y1, w, h = bbox
x2 = x1 + w - 1
y2 = y1 + h - 1
# map the bbox coordinates to feature grid
x1 = x1 * 1. / stride_W - 0.5
y1 = y1 * 1. / stride_H - 0.5
x2 = x2 * 1. / stride_W - 0.5
y2 = y2 * 1. / strid... |
from django import forms
from categoria.models import Categoria
class CategoriaFormulario(forms.ModelForm):
class Meta:
model = Categoria
# el atributo de categoria que no quiero que aprezca en la view
exclude = ('user',)
# todos los atributos de la clase Categoria
fields... |
import json
import os
import csv
# Rename the data files to start with "indicator_".
"""
for filename in os.listdir('data'):
if filename.endswith(".csv") and not filename.startswith('indicator_'):
path_from = os.path.join('data', filename)
path_to = os.path.join('data', 'indicator_' + filename)
... |
import random
import exrex as ex
import numpy as np
def transponiraj(a1, a2):
vnos = np.array([a1, a2])
vnos = np.transpose(vnos)
return vnos
#----MODEL---------
capList = [50, 100, 150, 200, 300]
tezaList = [10, 12, 20, 20, 23]
vnosModel = transponiraj(capList, tezaList)
def napolniTabeloModel(vnos):
... |
from django.db import models
from django.db.models import CharField
from django_mysql.models import ListCharField #This is a custom field that requires mysql
# Create your models here.
class Excursion(models.Model):
Active = 'active'
Inactive = 'inactive'
Excursion_status = [
(Active, 'active'),
(Inactiv... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... |
class Mem(object):
def __init__(self, addr, size, isUsed):
self.addr = addr
self.size = size
self.isUsed = isUsed
class Function(object):
argc = 0
testcases = (
(None, None),
)
def __init__(self, emu, startEa, endEa):
self.emu = emu
self.startEa = st... |
"""
Author: Andrew Harris
Python Version: Python3.8.3
"""
import argparse
from pathlib import Path
from gevent import monkey
monkey.patch_all()
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from gevent.pywsgi import WSGIServer
from thex.app import a... |
# Copyright 2021 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, ... |
"""main entry for langlab command-line interface"""
def main():
from langlab import Langlab
ret, fwds = Langlab().run_command()
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""Tests for PySnoo components."""
|
# -*- coding: utf-8 -*-
import requests
import re
import urllib
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
def binary_word_search(string, data):
"""A simple binary search algorithm to check if string ex... |
#!/usr/bin/env python
# encoding: utf-8
"""Common utilities."""
import logging as lg
import os
import os.path as osp
from contextlib import contextmanager
from shutil import rmtree
from tempfile import mkstemp
from threading import Thread
from six.moves.queue import Queue
_logger = lg.getLogger(__name__)
class Hd... |
from floodsystem.analysis import polyfit
from floodsystem.stationdata import build_station_list, update_water_levels
from floodsystem.datafetcher import fetch_measure_levels
import datetime
import numpy
def test_polyfit():
stations = build_station_list()
update_water_levels(stations)
#find the polynomia... |
# -*- coding: utf-8 -*-
"""
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
"""
import time
impo... |
"""
Tests for the Keys endpoint.
"""
import pytest
PROJECT_ID = "454087345e09f3e7e7eae3.57891254"
KEY_ID = 34089721
@pytest.mark.vcr
def test_keys(client):
"""Tests fetching of all keys
"""
keys = client.keys(PROJECT_ID, {
"page": 2,
"limit": 3,
"disable_references": "1",
... |
import asyncio
import pytest
import cryptocom.exchange as cro
@pytest.mark.asyncio
async def test_account_get_balance(account: cro.Account):
balances = await account.get_balance()
assert balances[cro.Coin.CRO].available > 1
assert balances[cro.Coin.USDT].available > 1
for coin in cro.Coin:
a... |
l = float(input('Entre a largura da parede em metros.: '))
a = float(input('Entre a altura da parede em metros..: '))
area = l * a
tinta = (area / 2)
print()
print('Área da parede......: {:.3f} m²'.format(area))
print('Quantidade de tinta.: {} litros'.format(tinta))
input()
|
""" Forms for searching """
from flask_wtf import FlaskForm
from wtforms import SubmitField, TextField, validators
from wtforms.fields import StringField
from wtforms.widgets import TextArea
class SearchForm(FlaskForm):
""" Form to search an ingredient """
name = TextField("Name", [validators.Length(min=1, m... |
# Generated by Django 3.1.7 on 2021-04-09 07:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('polls', '0002_question_ip_address'),
]
operations = [
migrations.CreateModel(
name='User',
... |
import os
import discord
import asyncio
print("Discord Version: {} ".format(discord.__version__))
class App(discord.Client):
async def on_ready(self):
print("Logged in as {} with ID {}".format(self.user.name, self.user.id))
async def on_message(self, message):
print("{}: {}: {}: {}".format(me... |
"""
Import all gentoo based modules.
All manually entered modules can be placed in the following import section.
Portage_Gen based projects will be generated automatically as soon as we
can find an index generated by portage info.
"""
import logging
import os
from benchbuild.settings import CFG
from . import (autopo... |
#!/usr/bin/env python
# stack_landsat.py
# Lawrence Dudley 4/2/2017
''' This script takes a landsat MTL.txt file as input, along with a list
of desired bands to stack (optional) and creates a geotiff image containing
these image bands.
'''
from osgeo import gdal, gdal_array
import numpy as np
import glob
import argp... |
'''
this code is for transforming real data obtained from unicom to experimental data
'''
import pandas as pd
import numpy as np
file = 'huawei3G'
df = pd.read_csv('..\data\\' + file + '.csv')
mu, sigma = 0, 1
min_num_capacity, max_num_capacity = 5, 10
x_provider = np.round(df['Lon'].values, 2)
y_provider = n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import gc
import glob
import pathlib
import warnings
from pathlib import Path
from random import shuffle, random
import torch
import torch.nn.functional as F
import yaml
from PIL import Image, ImageOps
from pynvml import *
from tqdm import tqdm
from col... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import Command, setup
import batch_requests
class PyTest(Command):
'''
A command handler for setup.py test.
'''
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
... |
import unittest
from bseg.morphology import Morphology
from bseg.bunsetsu import Bunsetsu
class TestBunsetsu(unittest.TestCase):
def setUp(self):
morp1 = Morphology("天気 名詞,一般,*,*,*,*,天気,テンキ,テンキ")
morp2 = Morphology("が 助詞,格助詞,一般,*,*,*,が,ガ,ガ")
self.bnst1 = Bunsetsu([morp1, morp2])
m... |
"""
Code taken from https://raw.githubusercontent.com/hma02/thesne/master/model/tsne.py
And then modified.
"""
import os, sys
import theano.tensor as T
import theano
import numpy as np
from utils import dist2hy
import theano.sandbox.rng_mrg as RNG_MRG
import theano.tensor.shared_randomstreams as RNG_TRG
from thean... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division, with_statement
import phonetics
import history
import culture
import speed
import beauty
import internet
import meaning
weights = (
("phonetics-spellability", phonetics.spellability, 40),
("phonetics-pronounceability", phonetics.pronou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.