content stringlengths 5 1.05M |
|---|
"""
sevenbridges-python
~~~~~~~~~~~~~~~~~~~
:copyright: 2018 Seven Bridges Genomics Inc.
:license: Apache 2.0
"""
import ssl
import logging
__version__ = "0.23.0"
from sevenbridges.api import Api
from sevenbridges.config import Config
from sevenbridges.models.invoice import Invoice
from sevenbridges.models.billing_g... |
# Copyright 2021 Huawei Technologies Co., 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
from flask_wtf import FlaskForm
from wtforms import SubmitField, StringField
from wtforms.validators import DataRequired
class PostSearchForm(FlaskForm):
text = StringField("Search")
submit = SubmitField('Search')
|
def get_sql(cte, params, company, conn, ledger_id, source_codes):
common = f"""
(
SELECT b.source_code, SUM(a.tran_day) AS tran_day
FROM {company}.ar_totals a
JOIN {company}.gl_source_codes b ON b.row_id = a.source_code_id
WHERE a.deleted_id = 0 AND a.tran_date = dates.date
... |
"""
setup.py for auth-service.
For reference see
https://packaging.python.org/guides/distributing-packages-using-setuptools/
"""
from pathlib import Path
from setuptools import setup, find_packages
HERE = Path(__file__).parent.absolute()
with (HERE / 'README.md').open('rt') as fh:
LONG_DESCRIPTION = fh.read().s... |
# Copyright 2020 Miljenko Šuflaj
#
# 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 a... |
#!/usr/bin/env python3
"""
Telegram message listener that launches commands
Usage::
./mthook.py api_id api_hash session "chat_id,command,regex" "chat_id,command,regex" ...
"""
import re
import requests
import subprocess
import sys
from datetime import datetime
from pyrogram import Client, filters
def handle(fs, m... |
from django.conf.urls import url, include
from django.contrib import admin
from liq_ytdl import views as liq_ytdl_views
from liq_ffmpeg import views as liq_ffmpeg_views
from liq_scdl import views as liq_scdl_views
from liq_wget import views as liq_wget_views
from liquid import views as liquid_views
"""
ALL URLS CONVEN... |
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
return ["<h1 style='color:blue'>Hello There!</h1>"]
|
# -*- coding: utf-8 -*-
{
'\n\nThank you!': '\n\nThank you!',
'\n\nWe will wait and let you know when your payment is confirmed.': '\n\nWe will wait and let you know when your payment is confirmed.',
'\n- %s from %s to %s': '\n- %s from %s to %s',
'\nAmount: R$%.2f': '\nAmount: R$%.2f',
"\nSomething happened and we cou... |
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./data.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=F... |
# -*- coding: utf-8 -*-
import os
from server import icityServer
ROOT_PATH = os.path.abspath(os.path.dirname(__file__))
# Need to import all resources
from workspaces.home.controller import HomeRoutes
from workspaces.dashboard.controller import DashRoutes
# Register all Blueprint
icityServer.icity_app.register_bluep... |
print('Testing Lin v Log')
test=2
if test==1:
import astropy.table as table
import numpy as np
from defcuts import *
from defflags import *
from halflight_first import *
from def_get_mags import *
from def_halflight_math import *
bands=['g', 'r', 'i','z', 'y']
daperture=[1.01,1.51,2.02,3.02,4.03,5.71,8.40... |
from .tensors import *
|
import os
import torch
import random
import scipy.io
import typing as t
import numpy as np
import torchio as tio
from glob import glob
from functools import partial
from torch.utils.data import DataLoader
def get_scan_shape(filename: str):
extension = filename[:-3]
if extension == 'mat':
data = scipy.io.loadm... |
'''
Reporters output information about the state and progress of the program to
the user. They handle information about the formatting of this output, as
well as any additional processing which is required to support it, such as
comunicating with a web or email server, for example.
They are derived from the Base_Repo... |
from telegram.ext import (Updater, CommandHandler, MessageHandler,
Filters ,ConversationHandler,RegexHandler)
import apiai, json
import sqlite3
updater = Updater(token='')
print("Connection to Telegram established; starting bot.")
dispatcher = updater.dispatcher
import telegram as tg
i... |
"""
Write a function to find the longest common prefix string amongst an array of
strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"] Output: "fl"
IDEA:
take the 1st word as a prefix, then decrease the len... |
from collections import defaultdict
NO_DEFAULT = object()
class Observable:
"""
:class: Observables are properties that one can bind methods to.
Notes
-----
We store method names instead of methods themselves. This so we can dynamically patch methods on widgets and the new
method will be ca... |
from django.contrib import admin
from .models import contact,SlideShowItem
# Register your models here.
admin.site.register(contact)
# Registered the model
admin.site.register(SlideShowItem)
|
from unicodedata import name
from django.shortcuts import redirect, render
from django.http import Http404, HttpResponse
import datetime as dt
from .models import Image
# Create your views here.
def test(request):
return HttpResponse('testing gallery')
def show_all_images(request):
images = Image.get_im... |
import logging
from fastapi import FastAPI
from starlette.requests import Request
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import JSONResponse
from controllers.health.status import health_router
from controllers.v1.conference import conference_router
from contr... |
from typing import Callable
from typing import List
from typing import Union
import torch
from cata import constants
from cata.teachers import base_teacher
from cata.utils import threshold_functions
class ClassificationTeacher(base_teacher.BaseTeacher):
"""Classification - threshold output"""
def __init__(
... |
import base64
import requests_mock
from app.clients.freshdesk import Freshdesk
def test_create_ticket(notify_api):
def match_json(request):
expected = {
'product_id': 42,
'subject': 'Ask a question',
'description': 'my message',
'email': 'test@example.com'... |
#!/usr/bin/env python
import numpy as np
import math
import matplotlib.pyplot as plt
from pylab import *
import h5py
from matplotlib.colors import LogNorm
## Set the Zero
zero = 1.0e-20
## Set the maximum size of xenon
maxSize = 1000001
## Create plots
fig = plt.figure()
title = 'Xenon Distribution'
fig.supti... |
from pathlib import Path
from typing import Set
from datetime import datetime
from dataclasses import dataclass
from rich.progress import track
from rich import print
import csv
import requests
lat = 47.350
lon = 8.100
rssiFilePath = Path("/Users/eliabieri/Downloads/rssi.csv")
appId = "262b0bd7ac5cf100bd4198648434b2... |
# img2epub
__version__ = "0.3.0"
|
"""Test the R2C Module""" |
from DB import SQLite as sql
from languages import lang as lang_P
def admin(param):
fct = param["fct"]
arg2 = param["arg2"]
arg3 = param["arg3"]
arg4 = param["arg4"]
msg = []
if fct == "playerid":
if arg2 == "None":
platform = param["name_pl"]
else:
plat... |
from django.conf import settings
GET_CREATE_LOCATION_FUNCTION = getattr(settings, 'GET_CREATE_LOCATION_FUNCTION', None)
APP_NAME = getattr(settings, 'APP_NAME', 'Untitled')
COMPILE_MEDIA = getattr(settings, 'COMPILE_MEDIA', False) |
from django import forms
from .models import *
class NewsLetterForm(forms.Form):
your_name = forms.CharField(label='First Name', max_length=30)
email = forms.EmailField(label='Email')
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
exclude = ['poster', 'imagecommented']
c... |
"""
Código para o calculo de quaernions em python.
"""
from __future__ import print_function
from math import pi, sin, cos, asin, acos, atan2, sqrt
def _check_close(a, b, error=0.0001):
if isinstance(a, (tuple, list)):
assert isinstance(b, (tuple, list))
assert len(a) == len(b)
for a1, b1... |
import simplyencrypt as en
keys = en.new_random_password(1024)
line = "Let's encrypt this line"
print("Unenceypted line: " + line)
cipher_text = en.encrypt(keys, line)
try:
print("Encrypted line: " + str(cipher_text))
except:
print("Encrypted: ", end=" ")
for c in cipher_text:
c = str(ord(c))
print(c, end=", "... |
# Copyright 2014 The Oppia Authors. 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 applicable ... |
from .base import *
# security enforcement
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = env('DJANGO_SECURE_SSL_REDIRECT', True)
SESSION_COOKIE_SECURE = env('DJANGO_SESSION_COOKIE_SECURE', True)
# uncomment for cross-domain cookies
# SESSION_COOKIE_DOMAIN = '.{}'.format(env('DJA... |
import numpy as np
import scipy.sparse as sp
import networkx as nx
from sklearn.gaussian_process.kernels import RBF
from sklearn.preprocessing import StandardScaler
# Cora
def encode_onehot(labels):
classes = set(labels)
classes_dict = {c: np.identity(len(classes))[i, :] for i, c in
enum... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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 restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
# -*- coding: utf-8 -*-
import sys
import cv2
import glob
import os
from matplotlib.pyplot import imread
from tqdm import tqdm
import numpy as np
import math
from multiprocessing import Pool
import matplotlib.pyplot as plt
import argparse
args = argparse.ArgumentParser(description='the option of the evaluation')
arg... |
import json
import os
import shutil
from pathlib import Path
from typing import Callable
from github import Github
from .deck_exporter import DeckExporter
from ..anki.adapters.anki_deck import AnkiDeck
from ..representation import deck_initializer
from ..representation.deck import Deck
from ..utils.constants import ... |
s = float(input('\033[1;30mDigite seu salário: R$'))
a = s+(s*15/100)
print(f'\033[1;32mSeu novo salário com um aumento de 15% vai ficar \033[36mR${a:.2f}') |
#!/usr/bin/env python3
# coding: utf-8
"""
Utility which help preparing data in view of parallel or distributed computing, in a dask-oriented view.
Usage:
daskutils.py partition --config-file=<cf> --nb-partitions=<p> [--log-file=<f> --verbose]
Options:
--config-file=<cf> json configuration dict specifying v... |
#! /usr/bin/python3
"""Extracts the reghdfe sections from the output logs as markdown."""
import re
import sys
def ExtractReghdfes(lines):
section = []
in_section = False
for line in lines:
# Stata logs every command as ". some_command" so lines that start with
# ". " indicate a new section. Close off ... |
#!/usr/bin/python
import grizzly.numpy_weld as npw
import numpy as np
import unittest
class NumPyWeldTestMethods(unittest.TestCase):
# TODO: Add more tests here
def test_div(self):
input = npw.NumpyArrayWeld(
np.array([3, 6, 12, 15, 14], dtype=np.int32), npw.WeldInt())
self.asser... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import math
class Linkedin:
def __init__(self):
linkprofile = webdriver.FirefoxProfile('')
self.driver = webdriver.Firefox(linkprofile)
#self.driver.get('https://www.linkedin.com/mynetwork/')
... |
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from corehq.apps.sso.models import IdentityProvider, AuthenticatedEmailDomain
from corehq.apps.sso.utils.user_helpers import get_email_domain_from_username
class SsoBackend(ModelBackend):
"""
Authenticates again... |
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense
size_of_image = 96
model = Sequential()
model.add(Convolution2D(8, (3, 3), activation='relu', input_shape=(size_of_image,size_of_image,1)))
model.add(MaxPooling2D(pool_size... |
# vim:tw=50
"""Classes are Types
Let's move on to **classes**. We've been using
them already without directly talking about it, so
let's get down to what they really are.
In general, you can think of a class as a
**type**. This is, of course, merely a useful
fiction because it hides subtlety, but it is still
a great... |
import torch
import argparse
import os
import numpy as np
from torch.backends import cudnn
from config.config import cfg, cfg_from_file, cfg_from_list
import data.transforms as T
import sys
import pprint
import random
from solver.solver import Solver
from model import segmentation as SegNet
from model.domain_bn import ... |
import bpy
from collections import OrderedDict
from mathutils import Vector, Matrix
import math
import json
from functools import reduce
import os
def vec2array( _vector ):
return [ _vector.x, _vector.z, -_vector.y ]
def unit(vec):
vec_sq = [x for x in map(lambda x:x*x, vec)]
length = math.sqrt(reduce(lam... |
YACHT = lambda dice: 50 if len(set(dice)) == 1 else 0
ONES = lambda dice: sum(x for x in dice if x == 1)
TWOS = lambda dice: sum(x for x in dice if x == 2)
THREES = lambda dice: sum(x for x in dice if x == 3)
FOURS = lambda dice: sum(x for x in dice if x == 4)
FIVES = lambda dice: sum(x for x in dice if x == 5)
SIXES =... |
from pandas import Series
from pandas import DataFrame
inde = ['x1', 'x2', 'x3', 'x4', 'x5']
oneSer = Series(data=[1, 2, 3, 4, 5], index=inde)
twoSer = Series(data=[2, 4, 6, 8, 10], index=inde)
threeSer = Series(data=[1, 3, 5, 7, 9], index=inde)
x1 = DataFrame([oneSer, twoSer, threeSer])
print(x1)
inde2 = ['y1', 'y... |
# ------------------------------------------------------------------------------ #
# Basic Input-Output pada Python #
# ------------------------------------------------------------------------------ #
# OUTPUT : #
# 1.) Untuk print/menampilkan pada stdout (layar) : #
# - pri... |
INOUTDOOR_LABELS = ['person'] |
from dolfin import *
from xii.meshing.make_mesh_cpp import make_mesh
from xii.assembler.average_matrix import curve_average_matrix
from xii.assembler.average_shape import Square
from xii import EmbeddedMesh
import numpy as np
surface_average_matrix = lambda V, TV, bdry_curve: curve_average_matrix(V, TV, bdry_curve, w... |
#!/usr/bin/env python
# coding:utf-8
"""
# @Time : 2020-08-26 20:39
# @Author : Zhangyu
# @Email : zhangycqupt@163.com
# @File : gaode_interface.py
# @Software : PyCharm
# @Desc :
"""
import json
import requests
from math import radians, cos, sin, asin, sqrt
from geopy.distance import geodesic
def ... |
import sys
import asyncio
import os
import types
import functools
from collections import namedtuple
from collections.abc import Iterator
import abc
from typing import List, Union, NamedTuple
import uuid
import yaml
import logging
log = logging.getLogger(__name__)
Fire = NamedTuple('Fire', [('rate', int), ('duratio... |
# Generated by Django 2.0.3 on 2018-04-06 18:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('entrance', '0063_selectenrollmenttypeentrancestep_text_on_moderation'),
]
operations = [
migrations.AlterField(
model_name='sele... |
observations["eventDate"] = pd.to_datetime(observations[["year", "month", "day"]])
observations |
'''Train CIFAR10 with PyTorch.'''
import torch.optim as optim
import torch.cuda
import torch.backends.cudnn as cudnn
import torch.utils.data
from models.codinet import *
from utils.dataloader import get_data
import os
from utils.argument import get_args
from utils.metric import *
from utils.loss import *
from utils.met... |
"""The ``i2c`` module lets you communicate with devices connected to your board
using the I²C bus protocol. There can be multiple slave devices connected at
the same time, and each one has its own unique address, that is either fixed
for the device or configured set_power_on it. Your board acts as the I²C master.
We u... |
import unittest
import mock
from main import check_util
from main import Common
from StringIO import StringIO
import console_logger
class TestCheckUtil(unittest.TestCase):
""" unit tests for functions in the check_util module """
def setUp(self):
self.logger = console_logger.ConsoleLogger()
s... |
#!Python 3
import csv
with open("test.csv") as csvfileA:
reader = csv.DictReader(csvfileA)
test = len(list(reader))
|
# Copyright (c) 2020, Ahmed M. Alaa
# Licensed under the BSD 3-clause license (see LICENSE.txt)
# ---------------------------------------------------------
# Helper functions and utilities for deep learning models
# ---------------------------------------------------------
import numpy as np
from matplotlib import ... |
import os
import sys
from os import listdir
from os.path import isfile, join
DIR_TASK = os.path.basename(os.getcwd())
DIR_LIB = os.path.abspath(os.path.join(os.path.dirname(__file__),"../"))
DIR_TASK = os.path.dirname(os.path.abspath(__file__))
import json, csv, time, string, itertools, copy, yaml
import numpy as np... |
# python3
# coding: utf-8
import argparse
import warnings
from collections import Counter
from sklearn.metrics import classification_report, f1_score
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import cross_validate
from sklearn.dumm... |
import numpy as np
from numpy import linalg
from abc import abstractmethod
import pandas as pd
import math
pd.options.display.float_format = '{:,.6f}'.format
np.set_printoptions(suppress=True, precision=6)
TOR = pow(10.0, -5)
TRUE_X = np.array([0.5, 0, -0.5235988])
class SteepestDescentMethod(object):
def __in... |
from __future__ import print_function
import pandas as pd
def fetch_training_molecules():
smiles_list = []
count = 0
for i in range(10):
data_file = '../../datasets/keck_pria/fold_{}.csv'.format(i)
df = pd.read_csv(data_file)
smiles_list.extend(df['rdkit SMILES'].tolist... |
# MIT License
#
# Copyright (c) 2021 Julien Gossa
#
# 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 restriction, including without limitation the rights
# to use, copy, modify, merge,... |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2020 OSGeo
#
# 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 ... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
from . import constants
class MilterMessage(object):
def __init__(self, cmd, data=None):
if cmd not in constants.VALID_CMDS:
raise ValueError('invalid command %s' % cmd)
self.cmd = cmd
self.data = data or {}
def __str__(self):
return '%s<%s, %s>' % (self.__class__.... |
import utime
def toI8(byte, scaling):
return float((byte + 2 ** 7) % 2 ** 8 - 2 ** 7) * scaling
def log(string):
#dateArray = utime.localtime()
#ts = "%02d-%02d-%02d %02d:%02d:%02d" % (
# dateArray[0], dateArray[1], dateArray[2], dateArray[3], dateArray[4], dateArray[5])
print("%s : %s" % (u... |
"""
Created on Dec 14, 2018
@author: Yuedong Chen
"""
from .base_solver import BaseSolver
from sklearn.metrics import confusion_matrix, accuracy_score
import time
import os
import torch
import numpy as np
class ResFaceClsSolver(BaseSolver):
"""docstring for ResFaceClsSolver"""
def __init__(self):
s... |
from . import utils
from . import settings
from . import exceptions
from .resource import (
ResourceConstant,
get_resource_repository,
GroupResourceRepository,
IndexedResourceRepository,
IndexedGroupResourceRepository,
ResourceRepository,
GroupHistoryDataRepository,
IndexedHistoryDataRep... |
import asyncio
import json
import urllib.request
from typing import Any, Callable
from urllib.error import HTTPError
from urllib.parse import urlencode
BASE_URL = "http://127.0.0.1:8000"
async def exec_as_aio(blocking_fn: Callable[..., Any], *args: Any) -> Any:
"""Asyncronously run blocking functions.
Args:... |
from setuptools import setup
meta = {}
with open("bladex/meta.py") as fp:
exec(fp.read(), meta)
# Package meta-data.
NAME = meta['__title__']
DESCRIPTION = 'Python Blade Morphing'
URL = 'https://github.com/mathLab/BladeX'
MAIL = meta['__mail__']
AUTHOR = meta['__author__']
VERSION = meta['__version__']
KEYWORDS =... |
"""
Task 6
@author: Alexandr Mazanik
"""
import time
import turtle
n = int(input('enter the number of legs - '))
alpha = 360 / n
length = 150
turtle.shape('turtle')
turtle.speed(5)
for i in range(n):
turtle.forward(length)
turtle.stamp()
turtle.left(180)
turtle.forward(length)
turtle.left(180)
... |
# Copyright (c) 2010 Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests to ensure all attributes of L{twisted.internet.gtkreactor} are
deprecated.
"""
import sys
from twisted.trial.unittest import TestCase
class GtkReactorDeprecation(TestCase):
"""
Tests to ensure all attributes of L{twiste... |
#!/usr/bin/env python3
import os
import sys
import json
import subprocess
import shutil
import datetime
os.environ["DEBIAN_FRONTEND"] = "noninteractive"
DISTRIBUTION=sys.argv[1]
NOW=datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")
SCRIPT_DIR=os.path.dirname(os.path.abspath(__file__))
METAPACKAGES_DIR=os.path.ab... |
# Author: Arash Nemati Hayati
# 14 Feb 2019
# HPCC Brandeis
#This code will
#1) All files inside a given path that have not been accessed/modified/group_changed in the last threshod days
#2) Create a report of user owners and their deleted files
import os, time, datetime
import pwd
import sys
clear = lambda: os.s... |
import os
import importlib
import simplejson as json
import click
from flask import current_app
import pandas as pd
import numpy as np
from sqlalchemy import Table
import datetime as dt
DATE_FORMAT = '%Y-%m-%d'
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S'
class Error(Exception):
"""Based class for exceptions in this mo... |
# The following list comprehension exercises will make use of the
# defined Human class.
import pdb
class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"<Human: {self.name}, {self.age}>"
humans = [
Human("Alice", 29),
Human... |
import execjs
import requests
class Google:
def __init__(self):
self.api = "https://translate.google.cn/translate_a/single"
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 = 3293161072;
var jd = ".";
var $b ... |
from logging import Logger
from typing import NoReturn, Callable, Dict, Optional, Tuple
from discord_webhook import DiscordWebhook
from telegram import Bot, Chat
from .models import FormatFunction, NotificationSettings
class NotificationBase:
def __init__(self, name: str) -> NoReturn:
self.name = name
... |
# coding: utf-8
"""
Camunda BPM REST API
OpenApi Spec for Camunda BPM REST API. # noqa: E501
The version of the OpenAPI document: 7.13.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
clas... |
import gc
import numpy as np
import argparse
import sys
import itertools
import librosa
import scipy
from scipy.signal import stft, istft
# use CQT based on nonstationary gabor transform
from nsgt import NSGT_sliced, MelScale, LogScale, BarkScale, VQLogScale
if __name__ == '__main__':
parser = argparse.ArgumentP... |
import unittest
import pinion
from pinion import parse_hosts, create_packet
class BaseTestCase(unittest.TestCase):
def test_parse_hosts(self):
expected = [("127.0.0.1", 4730)]
self.assertEqual(parse_hosts([("127.0.0.1", "4730")]), expected)
self.assertEqual(parse_hosts(["127.0.0.1"]), ex... |
from .nanopublication import Nanopublication
from .nanopublication_manager import NanopublicationManager
|
Import("env", "projenv")
import serial;
import time;
import io
def after_upload(source, target, env):
print("Start reset.")
ser = serial.Serial("COM3", 115200, serial.EIGHTBITS, serial.PARITY_NONE, serial.STOPBITS_ONE, xonxoff=0, rtscts=0)
#if(ser.isOpen()):
# print("It was previously open so clo... |
from rest_framework.exceptions import APIException
class UsernameUnavailableException(APIException):
status_code = 200
default_detail = 'This username is unavailable.'
default_code = 'username_unavailable'
class EmailInUseException(APIException):
status_code = 200
default_detail = 'This email is... |
import logging
from django.db.models import Count, Sum
from django.conf import settings
from django.core.management.base import NoArgsCommand
from pycon.finaid.models import FinancialAidApplication
from pycon.finaid.utils import send_email_message
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
... |
#! /usr/bin/env python
import os.path
import sys
import sift_pyx12.error_handler
import sift_pyx12.map_if
from sift_pyx12.params import params
import sift_pyx12.segment
def donode(node):
print((node.get_path()))
for child in node.children:
if child.is_loop() or child.is_segment():
donode... |
#!/usr/bin/python
# Copyright 2018 gRPC 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 ag... |
# -*- coding: utf-8 -*-
import enigma.core as core
import enigma.rotors as rotors
import enigma.reflectors as reflectors
if __name__ == '__main__':
main() |
__version__ = '0.1.0'
API_PREFIX = '/v1' |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
import cProfile
import pstats
import time
from functools import wraps
import hfut
from .log import logger
def term_range(major_name, max_term_number):
start_year = int(major_name[:4])
start = (start_year - 2001) * 2 - 1
end = start + 7
... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class AuthConfig(AppConfig):
name = "blapp.auth"
label = "blapp_auth"
verbose_name = _("Authentication and authorization")
|
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import LabelEncoder
df = pd.read_csv('train.csv')
dfi = df.set_index('PassengerId')
dfi.shape
dfi.columns
dfi.describe()
dfi.info()
#Write a program that calculates the number of survi... |
"""
Package: service
Package for the application models and service routes
This module creates and configures the Flask app and sets up the logging
"""
import importlib
import logging
import os
from flask import Flask
# Create Flask application
app = Flask(__name__)
app.config.from_object("config")
# Import the rout... |
# Copyright 2021, 2022 Cambridge Quantum Computing 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/LICENSE-2.0
#
# Unless required by applicable la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.