content stringlengths 5 1.05M |
|---|
import pytest
from protean import BaseEventSourcedAggregate
from protean.fields import Integer, String
from protean.utils import fully_qualified_name
class User(BaseEventSourcedAggregate):
name = String()
age = Integer()
def test_registering_an_event_sourced_aggregate_manually(test_domain):
try:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from ishell.command import Command
from ishell.console import Console
from ishell.utils import _print
import getpass
class InterfaceConsole(Command):
"""Interface Console.
Parameters:
interface name -- Press tab for options
"""
def args(self):
... |
from app.utils import ServiceSettingsBase
class MongoDBSettings(ServiceSettingsBase):
mongodb_dsn: str
mongodb_min_connections_count: int = 2
mongodb_max_connections_count: int = 8
|
from src.functions.hello import say_hello
def test_say_hello():
assert say_hello('Sample') == 'Hello Sample!'
|
from .models import Bubble, BubbleMenu
from django import forms
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect as redirect, \
HttpResponse as response, Http404
from django.shortcuts import render
from django.template import RequestContext
import json
from wh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Provides robot dynamic transition functions
"""
# TODO: to implement
from pyrobolearn.robots.robot import Robot
from pyrobolearn.dynamics.dynamic import DynamicModel
__author__ = "Brian Delhaisse"
__copyright__ = "Copyright 2019, PyRoboLearn"
__credits__ = ["Brian De... |
import conf
from keras.applications.resnet50 import ResNet50
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.resnet50 import preprocess_input
from keras.applications.resnet50 import decode_predictions
from sys import argv
from pprint import ppr... |
import matplotlib.colors as mcolors
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
def plotly_history(
history,
title=None,
fontsize=14,
yscale=None,
yticks=10,
xticks=10,
ax_width = 515,
ax_height = 450,
width = None,
height = No... |
# Copyright 2011-2013 Colin Scott
# Copyright 2012-2013 Andrew Or
#
# 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... |
from schafkopf.players.mc_tree import MCTree
from schafkopf.players.mc_node import MCNode
from schafkopf.players.nn_player import NNPlayer
from schafkopf.players.uct_player import UCTPlayer
from schafkopf.tournaments.game_states_trick_play import sample_game_states
def main():
sim_player_list = [NNPlayer(game_mo... |
-- Write a query to find the shortest distance between two points in these points.
-- | x |
-- |-----|
-- | -1 |
-- | 0 |
-- | 2 |
-- The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below:
-- | shortest|
-- |---------|
-- | 1 |
# Write your MySQL query... |
"""
analytic_generator.py is a tool for generating logic-tables for random logic-operators
as csv-files for machine learning.
"""
import numpy as np
import itertools
import hashlib
class LogicOperators:
"""LogicOperators.
Attributes
----------
logic operators functions:
1. lg_and
... |
# Copyright (c) 2014-2020 Cloudify Platform 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 b... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""
Handler module for gathering configuration data.
"""
from .env import ENVIRONMENT
CLOWDER_ENABLED = ENVIRONMENT.bool("CLOWDER_ENABLED", default=False)
if CLOWDER_ENABLED:
from app_common_python import ObjectBuckets, LoadedConfig, KafkaTop... |
print('='*5+'10 TERMOS DE UMA PA'+'='*5)
primeiro = int(input('Primeiro termo: '))
razao = int(input('Razão: '))
decimo = primeiro + (10 - 1) * razao
for c in range(primeiro, decimo, razao):
print(f'{c}', end=' ¬ ')
print('Acabou')
|
# -*- coding: utf-8 -*-
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
if len(preorder) == 0 or len(inorder) == 0 or len(preorder) != len(inorder):
return ... |
import uuid
from abc import ABC
from django.core.exceptions import ImproperlyConfigured
from django.forms import BaseFormSet, modelformset_factory, HiddenInput
from django.shortcuts import redirect
from formtools.wizard.views import SessionWizardView
from django.utils.translation import gettext_lazy as _
from django.f... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.stylegan2_generator import *
from models.stylegan2_discriminator import *
from models.pggan_generator import *
from models.pggan_discriminator import *
def stylegan2(path, res):
G = StyleGAN2Generator(resolution = res... |
from urllib import quote
import re
"""
motionless is a library that takes the pain out of generating Google Static Map URLs.
For example code and documentation see:
http://github.com/ryancox/motionless
For details about the GoogleStatic Map API see:
http://code.google.com/apis/maps/docu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
# 时间格式:YYYY-MM-DD hh:mm:ss
def get_date_time():
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# 时间格式:YYYY-MM-DD hh:mm:ss.xxx
def get_ms_date_time():
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y... |
import copy
import itertools
import weakref
from mopidy.models.fields import Field
# Registered models for automatic deserialization
_models = {}
class ImmutableObject:
"""
Superclass for immutable objects whose fields can only be modified via the
constructor.
This version of this class has been re... |
# Copyright The OpenTelemetry 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 ... |
#!/usr/bin/env python
"""
Copyright 2018
author: <scott.wales@unimelb.edu.au>
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 a... |
'''
@File : main.py
@Time : 2020/08/28 11:01:52
@Author : Haowei
@Version : 1.0
@Contact : blackmhw@gmail.com
@Desc :
intput:样本shp目录 (shp文件必须包含class类别,EPSG:3857);
多光谱的影像数据 (EPSG:3857)
output:在输出目录中生成包含label和对应区域的image影像
'''
import argparse
import os.path as osp
import glob
import sys
# s... |
# 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 use ... |
from .c_line_search import CLineSearch
from .c_line_search_bisect import CLineSearchBisect
|
from general_utils import path_checker
import configparser
class ConfigWriter:
"""Class for writing and updating config files.
Arguments:
config_fp {str} -- Path of config file to write/append to
Keyword Arguments:
config_details {dict} -- kwarg keywords will become sections; keys and va... |
# built-in
from math import isclose
# external
import hypothesis
import pytest
# project
import textdistance
ALGS = (
textdistance.bag,
textdistance.hamming,
textdistance.levenshtein,
textdistance.damerau_levenshtein,
textdistance.jaro,
textdistance.jaro_winkler,
textdistance.mlipns,
... |
from pydantic import BaseModel, validator
class IRIncident(BaseModel):
title: str
description: str
location: int
user: int
@validator("title")
def title_length(cls, value):
if not len(value) >= 10:
raise ValueError("title/minimum-10-characters")
return value
@validator("description")
def description_... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
def summarize(filename):
f = open(filename)
file_content = f.readlines()
total_reads = 0
for each_line in file_content:
mapped, unmapped = map(int, each_line.split()[2:])
total_reads += mapped + unmapped
return total_reads
for i in range(1, 25):
if i <10:
file_id = "000... |
################################################################################
# Authors: Brian Schott (Sir Alaran)
# Copyright: Brian Schott (Sir Alaran)
# Date: Oct 20 2009
# License:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p... |
#
# 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 us... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 1999-2017 Alibaba Group Holding Ltd.
#
# 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/LICENS... |
"""
Module: 'tpcalib' on esp32_LoBo
MCU: (sysname='esp32_LoBo', nodename='esp32_LoBo', release='3.2.24', version='ESP32_LoBo_v3.2.24 on 2018-09-06', machine='ESP32 board with ESP32')
Stubber: 1.0.0 - updated
"""
from typing import Any
class Calibrate:
""""""
def calibError(self, *args) -> Any:
pass
... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# An instance of a class is called an object. It's creating by calling the
# class itself as if it were a function.
# There's a special class method name called init, with double underscores
# before and after, so those are two underscore characters. O... |
import psycopg2
import math
from subprocess import call, Popen
import pandas as pd
import numpy as np
from mpmath import mp
import matplotlib.pyplot as plt
import matplotlib
from geopy import Point
from geopy.distance import distance, VincentyDistance
from sqlalchemy import create_engine
import itertools as it
df = ... |
"""
Example of classification
-------------------------
Figure 4.5.
An example of a simple classification problem between two Gaussian
distributions. Given a value of x, we need to assign that measurement to one
of the two distributions (background vs. source). The cut at xc = 120 leads
to very few Type II errors (i.e... |
# zipbackup copia uma pasta toda e seu conteúdo para um arquivo ZIP cujo nome seja incrementado
import zipfile
import os
def backupzip(folder):
"""Faz backup de todos os arquivos de folder para um zip
:param folder:
:return:
"""
folder = os.path.abspath(folder) # garante que o folder é um path abs... |
from django.conf.urls import patterns, url
from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^objednavka/pridat/$', views.PegastudioOrderCreate.as_view(), name='objedn_list'),
]
|
import json
import logging
import multiprocessing
import unittest
from datetime import timedelta, datetime
from multiprocessing import Process
from unittest import mock
from unittest.mock import call
import pika
import pika.exceptions
from freezegun import freeze_time
from parameterized import parameterized
from src.... |
# -*- coding: utf-8 -*-
'''
@Author : lance
@Email : wangyl306@163.com
'''
from sklearn import metrics
from keras.models import load_model
from keras_preprocessing.image import ImageDataGenerator
import numpy as np
import keras
import keras.backend as K
#%%加载模型
#model_cx=load_model("myweights/... |
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QGridLayout, QSlider, QSpinBox, QWidget
from hexrd.ui.hexrd_config import HexrdConfig
class ImageSeriesToolbar(QWidget):
def __init__(self, name, parent=None):
super(ImageSeriesToolbar, self).__init__(parent)
self.ims = HexrdConfig().i... |
import os
import pandas as pd
import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
class ConfusionMatrixGenerater(object):
def __init__(self, image_data, csvfile):
self.image_data = image_data
self.csvfile = csvfile
self.df = pd.re... |
#!/usr/bin/env python
"""
Downloads files to temp locations. This script is invoked by the Transfer
Manager (galaxy.jobs.transfer_manager) and should not normally be invoked by
hand.
"""
import ConfigParser
import json
import logging
import optparse
import os
import random
import SocketServer
import sys
import tempfil... |
import sys
if sys.version_info[0] == 2:
from .society2 import core_value_decode, core_value_encode
else:
from .society3 import core_value_encode, core_value_decode
|
if __name__ == '__main__':
import os
import config
from components.send_backup import send_backup
from components.sort_backups import sort_backups
from utils import utils
from utils.run_system_cmd import run_system_cmd
from utils.send_mail import send_mail
utils.create_folders()
run... |
import os
import re
from wok import logger
from wok.config.data import Data
from wok.core.flow.loader import FlowLoader
_LOGGER_NAME = "wok.projects"
class ProjectManager(object):
FLOW_URI_RE = re.compile(r"^(?:([^\:]+)\:)?([^\/]+)(?:\/(.+))?$")
def __init__(self, conf, base_path=None):
self.conf = conf
sel... |
import argparse
import logging
import os
import time
import numpy as np
import torch
import torch.nn as nn
from data_cleaning import ParkingDataLoader
from torch.utils.data import TensorDataset, DataLoader
parser = argparse.ArgumentParser()
parser.add_argument('--network', type=str, choices=['resnet', 'odenet'], defa... |
from .interpolateopacity import InterpolatingOpacity
import pickle
import numpy as np
import pathlib
from taurex.mpi import allocate_as_shared
class HDF5Opacity(InterpolatingOpacity):
"""
This is the base class for computing opactities
"""
@classmethod
def priority(cls):
return 5
@cl... |
# -*- coding: utf-8 -*-
"""Set classifier function."""
__author__ = ["TonyBagnall"]
from sktime.clustering import TimeSeriesKMeans, TimeSeriesKMedoids
def set_clusterer(cls, resample_id=None):
"""Construct a clusterer.
Basic way of creating the clusterer to build using the default settings. This
set up... |
class MatrixFormatter:
def __init__(self, matrix):
self.matrix = matrix
def pretty_print(self):
""" Make the matrix look pretty """
out = ""
rows,cols = self.matrix.shape
for row in range(0,rows):
out += "["
for col in range(0,cols):
... |
import git
import skbio
import pandas as pd
import numpy as np
import os
# Find home directory for repo
repo = git.Repo("./", search_parent_directories=True)
homedir = repo.working_dir
# Define data directory
datadir = f"{homedir}/data/processed_sequencing/"
# List all fastq.gz files
fastq_file = datadir + "efflux_... |
#!/usr/bin/python3
from influxdb import InfluxDBClient
class Influxdb:
def __init__(self, host, port):
self.host = host #8086
self.port = port
def connect(self, db):
self.client = InfluxDBClient(host=self.host, port=self.port)
self.client.switch_database(db)
def write(se... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class GetPollutionInfoData(Model):
"""NOTE: This class is auto generated by th... |
from lxml import html
from typing import NamedTuple
import requests
class BootEntity(NamedTuple):
""" 书本信息 """
title: str
price: float
link: str
store: str
def __str__(self):
return '价格: {self.price} ;名称:{self.title} ; 购买链接:{self.link} 店铺:{self.store}'.format(self=self)
class MySpi... |
#! python 3
import http.client
import sys
import os
import string
import re
from urllib.request import urlopen
class Display () :
def read_input_file() :
print ("Please enter the path and name of the file you would like to open")
userInput = input("Path and file name: ")
if Display.file_exists( userInput ) ==... |
"""The ``resilient_exporters`` package provides data exporters designed to be
resilient to peak utilisation and Internet connection disruptions.
Install:
$ pip install resilient-exporters
"""
import logging
from .exporters import *
from .exceptions import *
# With NullHandler we enable logging only the user... |
from pyquilted.quilted.iconify import Iconify
class Detail:
def serialize(self):
name = self.__class__.__name__ + '-detail'
detail = dict()
detail[name.lower()] = vars(self)
return detail
class Location(Detail, Iconify):
def __init__(self, location=None, via=None, **kwargs):
... |
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result
from nornir.core.task import Result
import argparse
import sys
from pathlib import Path
from datetime import datetime, timedelta
import yaml
# Nornir Tool
#
# -c "comma... |
"""Available Commands:
.moon
.smoon
.tmoon"""
from telethon import events
import asyncio
from collections import deque
@borg.on(events.NewMessage(pattern=r"\.tmoon", outgoing=True))
async def _(event):
if event.fwd_from:
return
deq = deque(list("🌗🌘🌑🌒🌓🌔🌕🌖"))
for _ in range(32):
await... |
import itertools
import collections
from . import parser
from .utils import to_string
class FeatureFactory(object):
def __init__(self, feature_classes):
self.parser = parser.Parser()
self.feature_classes = feature_classes
self.feature_dict = {f.name: f for f in self.feature_classes}
... |
from .GloVeModel import GloVeModel
from .Word2vecGoogleModel import Word2vecGoogleModel
|
from flask import Flask, request
from flask_restful import Resource
from .models import Order, orders
class OrderDetals(Resource):
def get(self, id):
order = Order().get_order_by_id(id)
if not order:
return {"message":"Order not found"}, 404
return {"order": ord... |
"""Python command-line script for managing CKAN user accounts.
This script can only create or update a user account. It does not
manage memberships in groups or roles.
The base URL for the API to use (without the trailing "/api/action" text)
can be specified in an environment variable named 'CKAN_URL'. The value f... |
# X10 is so slow...
# I ran a web server to let me control X10 lights through a CM11A gateway.
# there's nearly a second of latency per command! on top of that, it just
# wasn't very reliable (some commands would go, some wouldn't).
# I'm not using this code anymore, but left it here if it's helpful to you
import logg... |
"""Test haddock3-cfg client."""
import pytest
from haddock import config_expert_levels
from haddock.clis import cli_cfg
from haddock.modules import modules_category
@pytest.fixture(params=config_expert_levels + ("all",))
def config_level(request):
"""Haddock3 config levels."""
return request.param
@pytest.... |
################################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) ... |
from base import Error
class Integrity(Error):
def __init__(self):
super().__init__(401, 'integrity isn\'t valid')
|
# -*- coding: utf-8 -*-
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from bs4 import BeautifulSoup
import time
class ETA:
def __init__(self):
self.path = r'D:\PythonProjects\Personal\python-sandbox\drivers' \
r'\chromedriver.exe'
self.options ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declared_attr
from ziggurat_foundations.models.base import BaseModel
__all__ = ["GroupMixin"]
class GroupMixin(BaseModel):
""" Mixin for Group model """
__table_args__ = {"mysql_... |
#!/usr/bin/env python
# Copyright 2018 D-Wave Systems 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 ... |
# Package pyarmor
import logging
import sys
import os
sys.path.append(os.path.dirname(__file__))
def main():
from pyarmor2 import main as main_entry
logging.basicConfig(
level=logging.INFO,
format='%(levelname)-8s %(message)s',
)
main_entry(sys.argv[1:])
|
#!/usr/bin/python
# -*- coding: utf8 -*-
from datetime import datetime
from Crypto.Cipher import AES
import time
import random
import socket
import threading
import parser
import struct
version = "1.1.3"
def gendevice(devtype , host, mac,name=None, cloud=None,update_interval = 0):
#print format(devtype,'02x')
##We... |
from setuptools import setup
long_description = '''
Python package for numerai
'''
setup(
name='jax_tools',
version='0.0.1',
description='lib build on top of JAX to make it easier for code reuse and fast implementation',
long_description=long_description,
author='Clement Jambou',
packages=["j... |
# Defines class items handling a dataset.
class TrackingDataset:
def __init__(self, train_file, valid_file, folder_prefix):
# self.train_list = open(train_file, 'r').read().splitlines() #读取每个图片的文件名?
# self.valid_list = open(valid_file, 'r').read().splitlines()
# self.train_images = [folder_prefix + '/Ref/' + tra... |
### Data to pickle
import os, sys, pickle
### DEF ###
def openMyJarOfPickles():
if os.path.exists( pickleFile ):
picklesFromMyJar = open( pickleFile, 'rb')
else:
out = chngCurrentUser()
picklesFromMyJar = open( pickleFile, 'rb')
return picklesFromMyJar
def readFromPickle():... |
#!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(12, GPIO.OUT)
class Led_publish(object):
def __init__(self):
self.pub_control = rospy.Publisher("~led_test_control", Int32, queue_size=1)
self.controlBox()
def controlBox(self):
p = G... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class Complex(object):
''' Simple Complex Number Class for pytorch '''
def __init__(self, real, imag=None):
''' if imag is none we divide real --> [re, im]'''
if imag is no... |
# ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... |
"""
Script to upload IOTile Device Streamer Reports (containing stream data)
"""
import argparse
import datetime
import getpass
import json
import logging
import os
import sys
from pprint import pprint
import pytz
from iotile_cloud.api.connection import Api
from iotile_cloud.api.exceptions import HttpClientError
PR... |
import sys
import asyncio
import logging
import grpc
import app_pb2
import app_pb2_grpc
PORT = 50052
async def run() -> None:
async with grpc.aio.insecure_channel(f"localhost:{PORT}") as channel:
stub = app_pb2_grpc.GreeterStub(channel)
response = await stub.SayHello(
app_pb2.HelloRe... |
"""
Description:
"""
__author__ = "James Banting, Darren Wiens, Jonathan Healy"
|
__author__ = "Sanju Sci"
__email__ = "sanju.sci9@gmail.com"
__copyright__ = "Copyright 2019"
from nltk import pos_tag, ne_chunk
from nltk.tokenize import word_tokenize
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
class NamedEntityRecognization(object):
def __init__(self... |
import typing as t
import sys
from .app import app, SECRET_KEY
from .config import APP_CONFIGS
def debug():
print(f"SECRET_KEY: {SECRET_KEY}")
app.run(**APP_CONFIGS)
COMMANDS: t.Dict[str, t.Callable] = {
"debug": debug,
"production": lambda: print("Not done yet")
}
def main(args: t.List[str]) -> i... |
import logging
from tensorflow import keras
from tensorflow.keras import losses
from tensorflow.keras import regularizers
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers ... |
"""Tests for degredations."""
from prysm import degredations
def test_smear():
sm = degredations.Smear(1, 1)
assert sm.analytic_ft(0, 0) == 1 / sm.width
def test_jitter():
jt = degredations.Jitter(1)
assert jt.analytic_ft(0, 0) == 1
|
import pandas as pd
import tweepy
import time
import pickle
key = {
"consumer_key": ,# key
"consumer_secret": , # secret
"access_token": , # Token
"access_token_secret": # Token secret
}
#Twitter API credentials
consumer_key = key["consumer_key"]
consumer_secret = key["consumer_secret"]
access_key = key[... |
import example
# Create the Circle object
r = 2;
print " Creating circle (radium: %d) :" % r
c = example.Circle(r)
# Set the location of the object
c.x = 20
c.y = 30
print " Here is its current position:"
print " Circle = (%f, %f)" % (c.x,c.y)
# ----- Call some methods -----
print "\n Here are some propert... |
import concurrent.futures as cf
import subprocess
import os
def run_processes(commands, worker_count=4):
with cf.ProcessPoolExecutor(max_workers=worker_count) as executer:
for c in commands:
executer.submit(run_batch, command=c)
def run_batch(command):
subprocess.call([command], stdout=... |
from typing import List
from flask import jsonify, request
from flask_accepts import accepts, responds
from flask_cors import cross_origin
from flask_restx import Namespace, Resource, abort
from flask_jwt_extended import get_jwt_claims, jwt_required
from .interface import IPup
from .model import Pup
from .schema impo... |
def test(x):
foo = None
if x is True:
def foo():
print('yes')
elif not x:
def foo():
print('no')
return foo
print(test(1))
test(True)()
test(False)()
|
def factorial(n):
fat = 1
while n > 0:
fat = fat * n
n = n - 1
return fat
def main():
num = 1
print("Bem-vindo a sua calculadora de fatoriais em série! Para parar a execução digite um valor negativo")
while num >=0:
num = int(input("Digite o número que deseja o fatorial:... |
"""
Tools for creating a DC/OS cluster.
"""
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import click
from docker.models.networks import Network
from docker.types import Mount
from dcos_e2e.backends import Docker
from dcos_e2e.distributions import Distribution
from dcos_e2e.docker_sto... |
from pathlib import Path
from dogebuild import dependencies, doge, directory
from dogebuild_protobuf import proto_mode, ProtobufPlugin
proto_mode()
dependencies(doge(directory("../dependency"), tasks=["proto-sources"],))
ProtobufPlugin(src=Path("src").glob("**/*.proto"),)
|
import avalon.api
from maya import cmds
class SelectSubset(avalon.api.InventoryAction):
label = "Select Subset"
icon = "hand-o-down"
color = "#d8d8d8"
order = 99
def process(self, containers):
groups = list()
for container in containers:
if container.get("loader") =... |
import pymysql.cursors
import csv
import json
from datetime import date, datetime
import dateutil.parser
# JSON serializer for objects not serializable by default json code
def json_serial(obj):
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % ... |
"""
Created by yan on 2018/9/26 16:31
"""
import json
from flask import request, jsonify, flash
from app.models import db
from app.libs.helper import get_book_info
from app.models.book import Book
from app.models.user import User
from app.web import web
__author__ = 'yan'
@web.route('/addbook',methods = ["POST" ]... |
"""The Concat Implementation."""
from concat.transpile import transpile
import concat.astutils
import concat.level1.typecheck
import concat.level2.stdlib.repl
import concat.level2.execute
import argparse
import os.path
import sys
import io
from typing import Callable, IO, AnyStr, TextIO
filename = '<stdin>'
def f... |
from ..midinote import MidiNote
from ...constants import EVENT_NOTE, EVENT_AMPLITUDE, EVENT_DURATION, EVENT_GATE
from ...pattern import PSequence
import mido
import logging
log = logging.getLogger(__name__)
class MidiFileInputDevice:
""" Read events from a MIDI file.
Requires mido. """
def __init__(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.