content stringlengths 5 1.05M |
|---|
import os
import inspect
src = inspect.getsource(os)
print(src) |
__app_name__ = "hetzner-control"
__version__ = "0.3.0"
|
class Solution:
def numSquares(self, n: int) -> int:
squar_nums = [x * x for x in range(1, 101) if x * x <= n]
dp = [0] * (n + 1)
for num in range(1, n+1):
min_ = 10
for squar_num in squar_nums:
if squar_num > num:
break
... |
"""
Scheme obtained by gluing two other schemes
"""
#*******************************************************************************
# Copyright (C) 2006 William Stein
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#******************************... |
# Generated by Django 3.0.7 on 2020-06-12 19:58
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authorization', '0005_user_banned'),
('comment', '0004_auto_20200529_2044'),
]
operations = [
migrat... |
import picamera
import picamera.array
import png
import math
from pixel_object import PixelObject
"""
Image processor that can find the edges in a PNG image captured by a PiCamera.
"""
class ImageProcessor:
def __init__(self, res_width=96, res_height=96):
self.camera = picamera.PiCamera(resolution=(res_... |
#-------------------------------------------------------------------------------
# elftools: elf/notes.py
#
# ELF notes
#
# Eli Bendersky (eliben@gmail.com)
# This code is in the public domain
#-------------------------------------------------------------------------------
from ..common.py3compat import bytes2hex, byte... |
# -*- encoding: utf-8 -*-
import argparse
import getpass
import json
import math
import sys
from tabulate import tabulate
from ..consts import PER_PAGE
from ..libs.config import Config
def user_input(text='', hide_input=False):
""" Nice little function to read text inputs from stdin """
try:
if hide_... |
"""A setuptools based setup module.
See:
https://packaging.python.org/guides/distributing-packages-using-setuptools/
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
import pathlib
here = pathlib.Path(__file__).parent
# Get the long descr... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from pulp import LpProblem, LpStatus, lpSum, LpVariable, GLPK, LpMinimize
OBJ_EPSILON = 1e-12
class Game(object):
def __init__(self, config, env, random_seed=1000):
self.random... |
from tensorflow.keras.models import Sequential
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Flatten, Conv2D, Concatenate, Input
class EncoderNetwork:
def __init__(self, carrier_shape=(32, 32, 3), payload_shape=(32, 32, 1)):
# super(EncoderModel, self).__init__()
... |
"""
Created on Mar 30, 2018
@author: lubo
"""
import pytest
from dae.utils.regions import Region
@pytest.mark.parametrize(
"region,count,ref_freq,alt_freq",
[
(Region("1", 11501, 11501), 1, 75.0, 25.0),
(Region("1", 11503, 11503), 1, 75.0, 25.0),
(Region("1", 11511, 11511), 1, 50.0, ... |
class Icecream:
def eat(self) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-08-16 03:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('doctorwho', '0002_auto_20190815_2148'),
]
operations = [
migrations.RenameField(
... |
from cryptofield.fieldpolynom import *
from cryptofield.fieldmatrix import *
def PolynomEquilid(F, x, y):
if (x.deg() < y.deg()):
f = y.copy()
g = x.copy()
else:
f = x.copy()
g = y.copy()
polNull = FPolynom(F, [0])
if g == polNull:
return f
while True:
r = f % g
if r ... |
"""
Wiki templates based intents
"""
from .football import FootballPlayerFactIntent
from .qa_wiki import AnswersWikiIntent
|
import logging
import os
import re
from urllib.parse import urlsplit, urlunsplit
import requests
IAP_CLIENT_ID = "IAP_CLIENT_ID"
DEX_USERNAME = "DEX_USERNAME"
DEX_PASSWORD = "DEX_PASSWORD"
class AuthHandler(object):
log = logging.getLogger(__name__)
def obtain_id_token(self):
from google.auth.exce... |
#
# 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
# ... |
import base64
try:
import cryptography
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
HAS_CRYPTO = True
except:
HA... |
"""Tests for random geometric graphs"""
import Box2D.b2 as b2
import shapely.geometry
import metis
from metis.factored_random_geometric_graphs import (
FactoredRandomGeometricGraph, NoObjectContactBlacklist)
from metis.debug import graphical_debug, draw_polygon, draw_polygons
def example_world():
"""Create ... |
from __future__ import division, print_function
import unittest
import mock
from smqtk.algorithms.nn_index.lsh.functors import \
LshFunctor, get_lsh_functor_impls
class TestLshFunctorImplGetter (unittest.TestCase):
@mock.patch('smqtk.algorithms.nn_index.lsh.functors.plugin.get_plugins')
def test_get_ls... |
# -*- coding: utf-8 -*-
import sys
import numpy
from utils import *
class LogisticRegression(object):
def __init__(self, input, label, n_in, n_out):
self.x = input
self.y = label
self.W = numpy.zeros((n_in, n_out)) # initialize W 0
self.b = numpy.zeros(n_out) # initialize bias ... |
from typing import List
import stweet as st
def _scrap_tweets_with_count_assert(count: int):
phrase = '#koronawirus'
search_tweets_task = st.SearchTweetsTask(
all_words=phrase,
tweets_limit=count
)
tweets_collector = st.CollectorTweetOutput()
st.TweetSearchRunner(
search_t... |
import tensorflow_datasets as tfds
import tensorflow as tf
import time
import numpy as np
import matplotlib.pyplot as plt
def create_padding_mask(seq):
seq = tf.cast(tf.math.equal(seq,0), tf.float32)
return seq[:,tf.newaxis,tf.newaxis,:]
def create_look_ahead_mask(size):
mask = 1 - tf.linalg.band_part(tf.o... |
import pygame
from . import ColorPicker, Transform
from UI import Button
class PropertyPanel:
def __init__(self, x,y, properties, UIManager, selected_obj):
self.x, self.y = x,y
self.w, self.h = 320,10
self.properties_obj = {}
self.padding = 10
self.linking = False
... |
from django.urls import path
from naccbisapp.views import LeaderboardView, TeamOffenseView
urlpatterns = [
path('leaders/batters', LeaderboardView.as_view()),
path('leaders/team_offense', TeamOffenseView.as_view()),
]
|
# Convert arrays into sets so I can use 'in'
try recursion in version 2
# Find all possible markings
def all_possible_markings:
max_size = 25
possible_markings[1] = [0, 1]
for current_size in range(2, max_size):
for possible_marking in possible_markings[current_size - 1]:
possible_markings[current_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-11 14:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('repositories', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
import os
import tempfile
import shutil
import string
import random
from unittest import TestCase
from urltomd import Content, Mapper
class BaseTestCase(TestCase):
"""
Will automatically create a random, empty directory so that the
tests have a place to work with files. Will also clean and
... |
import os
from pathlib import Path
def build_manifest():
if not os.path.exists("MANIFEST.in"):
Path("MANIFEST.in").touch() |
def convert_answers_to_payload_0_0_2(answer_store, schema, routing_path):
"""
Convert answers into the data format below
'data': [
{
'value': 'Joe Bloggs',
'answer_id': 'household-full-name',
'group_instance': 0,
'answer_instance': 0
},
... |
from dataclasses import dataclass
from typing import Callable
from rxbp.init.initsubscription import init_subscription
from rxbp.mixins.flowablemixin import FlowableMixin
from rxbp.observables.fromsingleelementobservable import FromSingleElementObservable
from rxbp.subscriber import Subscriber
from rxbp.subscription i... |
import pandas as pd
import numpy as np
import os
import re
import requests
import time
source = 'https://services1.arcgis.com/vdNDkVykv9vEWFX4/arcgis/rest/services/Child_Nutrition/FeatureServer'
in_path = source + '/0/query?outFields=*&where=1%3D1&f=geojson'
out_dir = 'food-data/Cleaned_data_files'
out_path = os.path.... |
'''define the config file for cityscapes and bisenetv2fp16'''
import os
from .base_cfg import *
# modify dataset config
DATASET_CFG = DATASET_CFG.copy()
DATASET_CFG.update({
'type': 'cityscapes',
'rootdir': os.path.join(os.getcwd(), 'CityScapes'),
})
DATASET_CFG['train']['aug_opts'] = [
('Resize', {'outpu... |
# import datetime
# import os
# import unittest
# from decompy.DataGathering.FileGetter import FileGetter
# import shutil
# import json
#
#
# class GitHubScraperTest(unittest.TestCase):
#
# def test_repo_vc_1_download_config_META_create_and_update(self):
# """
# Tests if the repo.json download time ... |
from rltorch.algs.PPOLSTM.agent import PPOLSTMAgent
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--env_name", type=str, default='CartPole-v0')
parser.add_argument("--hidden_size", type=int, default=32)
parser.add_argument("--actor_lr", type=flo... |
# Copyright 2019 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 unittest
from .composition_parts import Component
from .composition_parts import Identifier
from .make_copy import make_copy
class MakeCopyTest(uni... |
import discord
from discord.ext import commands
import random
class EightBall(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['8ball', '8Ball'])
async def _8ball(self, ctx, *, question):
responses =['It is certain.','It is decidedly so.','Without... |
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from std_msgs.msg import ColorRGBA
class RobotShapesContainer:
def __init__(self):
self.shapes = {}
self.positions = {}
self.last_markers = {}
def robot_ids(self):
return [id for id in self... |
import subprocess
import unittest
from threading import Timer
class ApplicationTest(unittest.TestCase):
PROMPT = "> "
TIMEOUT = 2
def setUp(self):
self.proc = subprocess.Popen(
["python", "-m", "task_list"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
... |
# -*- coding: utf-8 -*-
"""
py_vollib.ref_python.black.implied_volatility
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A library for option pricing, implied volatility, and
greek calculation. py_vollib is based on lets_be_rational,
a Python wrapper for LetsBeRational by Peter Jaeckel as
described below.
:copyright... |
import pygame
from model.Bar import Bar
from model.BarVertical import BarVertical
class BarRight(BarVertical):
def __init__(self, screen_size, max_speed):
BarVertical.__init__(self, screen_size, max_speed)
self.surface = pygame.image.load('imgs/bar_right.png')
self.rect = self.surface.get... |
# -*- coding: utf-8 -*-
import pandas as pd
import csv
dataset_file1 = open('survey_sample.csv','r')
dataset = pd.read_csv(dataset_file1)
#dataset = dataset.loc[:,['question_id','answer','question_entity_label','question_relation_label']]
dataset['triple'] = ""
for index, row in dataset.iterrows():
triple = "<"... |
import json
import pkgutil
import os
import logging
import logging.config
import yaml
global Z_CLOUDS, DEBUG_DEFAULT, MAX_FQDN_LEN, MAX_PSK_LEN, REQUEST_TIMEOUTS
DEBUG_DEFAULT = False
MAX_FQDN_LEN = 255
Z_CLOUDS = {
'zscaler': 'https://admin.zscaler.net/',
'zscloud': 'https://admin.zscloud.net/',
'zsca... |
from django import forms
from equipment.models import Item
class CreateItemForm(forms.ModelForm):
class Meta:
model = Item
fields = [
"kind",
"person",
"code",
"brand",
"specifications",
"series_number",
"state",
... |
# Code taken from: https://explore-flask.readthedocs.io/en/latest/views.html
# Specify part of the URL to be converted into Python List of Integer
from werkzeug.routing import BaseConverter
class ListConverter(BaseConverter):
def to_python(self, value):
return list(map(int, value.split('+')))
def t... |
from flask import render_template, request
def index():
return render_template(
'index.html', email=request.cookies.get('email')
)
|
# -*- coding: utf-8 -*-
def includeme(config):
# Register the transform_annotation subscriber so that nipsa fields are
# written into annotations on save.
config.add_subscriber('h.nipsa.subscribers.transform_annotation',
'h.events.AnnotationTransformEvent')
# Register an add... |
c=0
for i in range(1,10):
#print(i)
#if c==i%(y=int(z) for z in range(2,10)):
if 0==i%z: for z in range(3,i-1))
#print(i%z)
print(i)
else:
pass
|
"""
Usage example for the decode_video python op.
"""
from __future__ import absolute_import
from __future__ import print_function
import time
import argparse
import numpy as np
import tensorflow as tf
from py_ops import decode_video
def _parse_arguments():
parser = argparse.ArgumentParser('Test decode_video ... |
# Copyright 2020 Huawei Technologies Co., Ltd.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 ap... |
#!/usr/bin/env python3
import numpy as np
import pickle
from scipy.spatial.transform import Rotation
def load_poses(path):
f = open(path + '/ep_data.pkl', 'rb')
data = pickle.load(f)
gt_mat = np.zeros([0, 4, 4])
gt_obj_pose_mat = np.eye(4)
quat = data['obj_world_pose'][3:]
quat[0], quat[1], q... |
from functools import partial
from collections import Sequence
import os
from pathlib import Path
import random
from ..utils import _norm_path
from menpo.base import menpo_src_dir_path, LazyList
from menpo.visualize import print_progress
def data_dir_path():
r"""A path to the Menpo built in ./data folder on this ... |
# encoding:utf-8
import requests
import base64
import json
filename = 'res.json'
request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
f = open('./res.jpg', 'rb')
img = base64.b64encode(f.read())
params = {"image": img}
access_token = 'your own access_token'
request_url = request_url +... |
#!/usr/bin/env python
# coding=UTF-8
# BSD 2-Clause License
# Copyright (c) 2021, Yury Demidenko (Beigesoft™)
# All rights reserved.
# See the LICENSE in the root source folder
#Classify NIST data - train (900 samples) and test (the rest 100) files
#NIST data from http://www.cis.jhu.edu/~sachin/digit/digit.html 1000 ... |
import pandas as pd
from pickle import dump
from typing import List, Tuple
from sklearn.preprocessing import MinMaxScaler
def extract_features_from_dataset(data: pd.DataFrame) -> pd.DataFrame:
"""
Extract features from dataset.
Parameters
----------
data: pd.DataFrame
Market chart data.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sudo i2cdetect -y 1
from __future__ import print_function
import time
from led_matrix import LEDDisplay
from pygecko.multiprocessing import geckopy
def got_msg(t, m):
# want to do something if message arrives
pass
def matrix(**kwargs):
geckopy.init_node... |
"""
InfluxDB-related functionality
------------------------------
Include `hadmin-stats-influxd`.
"""
import argparse
import hadmin.system
import requests
from requests.auth import HTTPBasicAuth
import sys
import time
SEC_TO_NANOSEC = 10**9
class WriteBody:
def __init__(self):
self.body = []
def... |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
import json
from scrape_utils import parse_macro
with webdriver.Chrome() as driver:
wait = WebDriverWait(driver, 10)
driver.get('https://eu4.paradoxwikis.com/Modifier_list')
r... |
import json
'''
Immutable object representing the current gaming status.
'''
class Status:
def __init__(self, gaming_status):
if not isinstance(gaming_status, bool):
raise ValueError("Specified gaming status must be of type bool!")
self.__gaming_status = gaming_status
def get_gam... |
# Generated by Django 3.0.5 on 2020-04-24 17:40
from django.db import migrations, models
import paint.validators
class Migration(migrations.Migration):
dependencies = [
('paint', '0015_auto_20200424_2227'),
]
operations = [
migrations.AlterField(
model_name='pu... |
from unittest import TestCase
class TestTransaction(TestCase):
pass
|
"""
AVCaesar API class wrapper
"""
import json
import sys
import logging
try:
import requests
except ImportError as err:
print("[!] error, missing %s" % (err))
sys.exit()
class CaesarAPI():
'''
API wrapper for AV Caesar
Docs: https://avcaesar.malware.lu/docs/api
'''
def __init__(self, ... |
"""
Test all getters and setters in the Character class
Includes all methods that set and retrieve data
"""
import npc
from npc.character import Character
import pytest
class TestTypeKey:
def test_casing(self):
"""Type key should always be lower case"""
char = Character(type=['Fish', 'Great Ape']... |
# Generated by Django 2.0.4 on 2018-06-12 01:18
from django.db import migrations
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20180410_1101'),
]
operations = [
migrations.AlterField(
model_name='product',
... |
import numpy as np
from scipy import linalg
from pressio4py import logger, solvers, ode
class MySys1:
def createResidual(self):
return np.zeros(5)
def createJacobian(self):
return np.zeros((5,5))
def residual(self, stateIn, R):
for i in range(5):
R[i] = float(i)
def jacobian(self, stateIn... |
from flask import render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_admin.contrib.sqla import ModelView
from . forms import PostForm, CommentForm, SubscribersForm
from .import main
from .. import db, basic_auth
import markdown2
from .email import mail_message
fro... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import Client, TestCase
from ..models import Group
class TestGroupsViews(TestCase):
"""
TestCase class to test the groups views.
"""
def setUp(self):
# This client will be logged in, admin & subsc... |
from soad import AsymmetricData as asyd
import matplotlib.pyplot as plt
# This script is prepared for calculating the difference between
# PDFs (Probability Density Function) of two variable.
a = asyd(20.0, 1.6007810593582121, 1.6007810593582121,N=50000)
b = asyd(20.27602675930529, 1.521759265471423, 1.916585620152... |
import random
import uuid
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, RequestFactory
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.contrib.messages.storage.fallback import FallbackStorage
... |
#!/usr/bin/python3
import unicodedata
FILENAME = 'xwordlist.dict'
def strip_accents(s):
"""String accents from a string"""
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
def read():
parsed = []
used_words = set()
with open(FILENAME... |
from citc.aws import AwsNode
from citc.cloud import NodeState
from citc.slurm import SlurmNode
from citc.watchdog import crosscheck
def test_crosscheck_empty():
slurm_nodes = []
cloud_nodes = []
res = crosscheck(slurm_nodes, cloud_nodes)
res = list(res)
assert not res
def test_crosscheck_one_ma... |
"""Reader file to parse Seward Electric Association 15-minute
meter data provided by Chugach Electric.
"""
from io import StringIO
import csv
from .base_reader import BaseReader
class Reader(BaseReader):
def read_header(self, fobj, file_name):
# There is one header line
return [fobj.readline()... |
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
return self.nQueensHelper([-1] * n, 0)
def nQueensHelper(self, array, count):
length = len(array)
if count == length:
return 1
... |
# coding: utf-8
import pytest
from scraper.src.config.config_loader import ConfigLoader
from .abstract import config
from .mocked_init import MockedInit
class TestGetExtraFacets:
def test_extra_facets_should_be_empty_by_default(self):
c = config()
actual = ConfigLoader(c)
assert actual.g... |
import networkx as nx
import graph
def test_check_shortest_path():
# load data
graph_data = graph.graph_loader('data.txt')
# create graph
nx_graph = graph.get_nx_graph(graph_data)
my_graph = graph.get_my_graph(graph_data)
# get shortest_path
expected_path = nx.shortest_path(nx_graph, sou... |
from kazoo.client import KazooClient
from kazoo.exceptions import CancelledError
import gevent
from gevent import Greenlet
from consistent_hash import ConsistentHash
import logging
""" Partition Library
This library provides functionality to implement partition sharing between
cluster nodes
"""
class PartitionClient... |
"""
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2.
Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Source - https://leetcode.com/problems/count-square-sum-triples/
"""
"""
Time Complexity - O(n^2)
Space Complexity - O(1)
"""
class Solution:
... |
from syft.spdz.interface import (
base_interface,
distributed_interface,
grid_client_interface,
grid_worker_interface,
)
s = str(base_interface)
s += str(distributed_interface)
s += str(grid_client_interface)
s += str(grid_worker_interface)
|
from pypise import Pypise, TestCase, TestRunner
from parameterized import parameterized
class BaiduTest(TestCase):
"""Baidu serach test case"""
@classmethod
def setUpClass(cls):
""" Setting browser driver, Using chrome by default."""
cls.driver = Pypise("chrome")
cls.timeout = 15 ... |
import urllib.request
import json
def _get_and_parse_json(url):
# print(url)
req = urllib.request.Request(url,
headers={'Content-type': 'application/json',
'Accept': 'application/json'})
f = urllib.request.urlopen(req)
parsed =... |
from django.conf.urls import url
from . import views
from django.conf import settings
urlpatterns=[
url('^$',views.index,name = 'index'),
url('^create/profile$',views.update_profile,name='profile'),
url(r'^post/create',views.post,name = 'posthood'),
url(r'^business/create',views.business,name = 'postbu... |
# 変数宣言
name = 'NerdApe'
twitter_id = '12345'
faceBook = 1234
# 整数型、文字型、浮動小数点型
# int()型、str()型、float()型
numbers = 12345
strings = 'NerdELu'
strings_02 = "KustomApe"
recommend = 'single'
special_strings = "I don't think that is right thing to do."
syosu = 1.23
syosu_02 = 4.56
# 関数
print(name)
|
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import inspect
import textwrap
from pyiron.base.job.generic import GenericJob
"""
The GenericMaster is the template cla... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 11:25:39 2021
@author: alann
"""
import requests
from datetime import datetime
apiKey = '65837ca6772c3e676cacc80f5428'
def filterByCountry(partners) -> dict():
"""
This can be done on the fly but I felt like it would be too much nesting.
"""
countries... |
"""Shows plugins that are loaded"""
import colors
import common
import logger
import plugin_api
_logger = logger.LOGGER
class Plugin(plugin_api.LocalPlugin):
"""Plugin to show loaded plugins"""
@property
def enabled(self):
"""ALWAYS ENABLED!"""
return True
async def on_message(self... |
# Text to speech toolkits
import speech_recognition as sr
import pyttsx3
from pydub import AudioSegment
from pydub.utils import make_chunks
import wave
import pyaudio
# Generator Natural Langugae Tool Kit
import nltk
from nltk.data import load
from nltk import CFG
from nltk.grammar import is_nonterminal
from nltk.collo... |
BASE_URL = "https://financialmodelingprep.com/api"
INDEX_PREFIX = "^"
SUPPORTED_INTERVALS = ["1min","5min","15min","30min","1hour","4hour"]
SUPPORTED_CATEGORIES = [
'profile',
'quote',
'quote-short',
'quotes',
'search',
'search-ticker',
'income-statement',
'balance-sheet-statement',
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import seaborn as sns
from torchvision import datasets, transforms, models
import argparse
import json
from PIL import Image
import time
import argparse
def ... |
from redis import Redis
import time
import threading
def notrans():
conn = Redis("127.0.0.1",6379)
print conn.incr('notrans:')
time.sleep(.1)
conn.incr('notrans:',-1)
def __main__():
for i in xrange(3):
threading.Thread(target=notrans).start()
time.sleep(.5) |
import argparse
import os
from pd_mesh_net.utils import BaseTrainingJob
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--f',
type=str,
help="Path to the folder containing the pretrained model to evaluate "
"and the training parameters.",
... |
"""empty message
Revision ID: bbb6eae59947
Revises: 11d65b51ea1d
Create Date: 2020-08-15 21:51:23.925183
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bbb6eae59947'
down_revision = '11d65b51ea1d'
branch_labels = None
depends_on = None
def upgrade():
# ... |
import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from . import networks
from util.metrics import PSNR, roll_2
import pytorch_msssim
from util.util import fft2, ifft2
from util.hfen import hfen
class DLMRIModel(BaseModel):
def name(self):
re... |
import pytest
from copy import deepcopy
from string import printable
from optimization.utilities.random_values import generate_random_int, generate_random_float, choose_random_value, \
choose_random_values, shuffle, shuffled, choose_random_value_with_weights
class TestRandomFunctions:
"""
Tests for rando... |
#!/usr/bin/env python
"""
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")... |
import os
import random
import string
from bs4 import BeautifulSoup
import pytest
from uaaextras.clients import UAAClient
from .integration_test import IntegrationTestClient
@pytest.fixture
def config():
config = {}
urls = {}
urls["uaa"] = os.environ["UAA_URL"]
urls["extras"] = os.environ["EXTRAS_UR... |
from pyvsr53dl.vsr53dl import PyVSR53DL
from pyvsr53dl.DisplayModes import Units as Units
from pyvsr53dl.DisplayModes import Orientation as Orientation
from pyvsr53dl.logger import log
import logging
if __name__ == '__main__':
from pyvsr53dl.sys import dev_tty
log.setLevel(logging.INFO)
sensor_address = 1
... |
default_app_config = "my_wallet.wallets.apps.WalletsConfig"
|
##########################################################################
#
# CUDA code generator
#
# This routine is called by op2 which parses the input files
#
# It produces a file xxx_kernel.cu for each kernel,
# plus a master kernel file
#
##########################################################################... |
from SBaaS_base.postgresql_orm_base import *
class data_stage01_isotopomer_averages(Base):
__tablename__ = 'data_stage01_isotopomer_averages'
#id = Column(Integer, Sequence('data_stage01_isotopomer_averages_id_seq'), primary_key=True)
experiment_id = Column(String(50))
sample_name_abbreviation = Column(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.