content stringlengths 5 1.05M |
|---|
import deepfilter as df
import numpy as np
import pickle as pkl
import os
#temps = np.concatenate(([0.1], np.arange(0.5, 10.5, 0.5)))
temps = [10.0]
#compare_temps = [0.1, 0.5, 1.0, 5.0, 10.0]
N = 100
train_path = '/home/az396/project/deepfiltering/training/checkpoints'
train_date = '210604'
train_dset = '210602_df1_... |
"""
Module with classes for rendering specifications and object hierarchies
"""
from hdmf.spec.spec import AttributeSpec, LinkSpec
from hdmf.spec import GroupSpec
from hdmf.spec import DatasetSpec
from hdmf.utils import docval, getargs
import warnings
class HierarchyDescription(dict):
"""
Dictionary data stru... |
import csv
from time import time
from time import sleep
def test_reader():
ts = time()
with open('csvreader.csv', 'r') as f:
reader = csv.reader(f)
for line in reader:
continue
te = time()
print(f'Python csv.reader parses {reader.line_num} lines '
f'in {(te-ts)... |
def pytest_addoption(parser):
parser.addoption('--aws', action='store_true', dest="aws",
default=False, help="enable tests needing aws lambda")
def pytest_configure(config):
if not config.option.aws:
setattr(config.option, 'markexpr', 'not aws')
|
###***********************************###
'''
Grade Notifier
File: initializegn.py
Author: Ehud Adler
Core Maintainers: Ehud Adler, Akiva Sherman,
Yehuda Moskovits
Copyright: Copyright 2019, Ehud Adler
License: MIT
'''
###***********************************###
from os import sys, path
sys.path.append(path.dirname(path... |
from models.model_group import Group
import random
def test_modify_some_group(app, db, check_ui):
if len(db.get_group_list()) == 0:
app.group.create_new_group(Group(group_name='a', group_header='b', group_footer='c'))
old_groups = db.get_group_list()
group = random.choice(old_groups)
new_group... |
from __future__ import division
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import tensorflow as tf
import numpy as np
import sys
sys.path.append('utils')
slim = tf.contrib.slim
from utils.model import deform_model
from utils.mnist_gen import get_gen
batch_size... |
# functions that work with the tracking data ....
import pandas as pd
import numpy as np
import math
from scipy.signal import savgol_filter
from scipy.ndimage.filters import gaussian_filter1d
from scipy.stats import circmean,circvar
import cv2
import sys
def pos_make_df(data_pos,box_size_cm,timebase_pos,time_stamps_s... |
# Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
from builton_sdk.api_models import Company
def test_rest_decorators():
company = Company("request", "props")
assert hasattr(company, "get")
assert hasattr(company, "refresh")
def test_init_sets_api_path():
company = Company("request", "props")
assert company.api_path == "companies"
|
from observer2 import Publisher, SubscriberOne, SubscriberTwo
pub = Publisher()
bob = SubscriberOne('Bob')
alice = SubscriberTwo('Alice')
john = SubscriberOne('John')
pub.register(bob, bob.update)
pub.register(alice, alice.receive)
pub.register(john)
pub.dispatch("It's lunchtime!")
pub.unregister(john)
pub.dispatch(... |
# Copyright (c) Hu Zhiming 2021/04/22 jimmyhu@pku.edu.cn All Rights Reserved.
import sys
sys.path.append('../')
from utils import LoadTrainingData, LoadTestData, RemakeDir, MakeDir, SeedTorch
from models import weight_init
from models.EHTaskModels import *
import torch
import torch.nn as nn
import torch.utils.data as ... |
#!/usr/bin/python
import sys
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
from HOG_detector import HOGDetector
class HOG:
def __init__(self, topic):
print topic
self.hog = HOGDetector()
self.bridge = CvBridge()
self.image_... |
import sys
version = sys.argv[1]
if version.startswith('http'):
print(version)
else:
next_version = version[:-1] + '%d' % (int(version[-1]) + 1)
print('Django>=%s,<%s' % (version, next_version))
|
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
from utils import add_homework_path
add_homework_path(__file__)
|
# @yifan
# 2021.01.12
#
import numpy as np
from sklearn import cluster
class myKMeans():
def __init__(self, n_clusters=-1, trunc=-1):
self.KM = cluster.KMeans( n_clusters=n_clusters, n_init=11 )
self.cent = []
self.trunc = trunc
def truncate(self, X):
i... |
import cv2
import numpy as np
import glob
import pdb
fps = 30.0
#raspi_ids = [0,1]#[2,3,4]#range(2)
raspi_ids = [4]
#dataDir = '/Users/philipp/Documents/theater/push_up/tv_project/'
dataDir = '/home/pmueller/pushup/'
imgInDir = dataDir+'images_raw/'
videoInDir = dataDir+'videos_raw/'
#outDir = dataDir+'videos_out/'
... |
import functools
import numpy as np
from scipy.ndimage import map_coordinates
def uv_meshgrid(w, h):
uv = np.stack(np.meshgrid(range(w), range(h)), axis=-1)
uv = uv.astype(np.float64)
uv[..., 0] = ((uv[..., 0] + 0.5) / w - 0.5) * 2 * np.pi
uv[..., 1] = ((uv[..., 1] + 0.5) / h - 0.5) * np.pi
return... |
from rest_framework import serializers
from play.models import Simulation
class SimulationSerializer(serializers.Serializer):
runs = serializers.IntegerField(min_value=1)
user_hand = serializers.ListField(
child=serializers.CharField(max_length=3, min_length=2, allow_blank=True),
min_length... |
import numpy as np
def voc_ap(rec, prec, use_07_metric=False):
""" ap = voc_ap(rec, prec, [use_07_metric])
Compute VOC AP given precision and recall.
If use_07_metric is true, uses the
VOC 07 11 point method (default:False).
Adopted from https://github.com/rbgirshick/py-faster-rcnn/blob/master/li... |
#!/usr/bin/python
START_DELAY = 2 # seconds
REFRESH_FREQ = 0.5 # seconds
NUMPIXELS = 30 # number of pixels, must match with arduino
import urllib
import json
import serial
import time
import random
# Sets active pixel counter to 0
counter = 0
# Opens serial port
ser = serial.Serial('/dev/ttyACM0', 9600)
# Delay to... |
import pytest
import re
import numpy as np
import pandas as pd
from formulae.matrices import design_matrices
from formulae.parser import ParseError
# TODO: See interaction names.. they don't always work as expected
@pytest.fixture(scope="module")
def data():
np.random.seed(1234)
size = 20
data = pd.DataF... |
# -*- coding: utf-8 -*-
########################################################################
#
# Copyright (c) 2019 Baidu.com, Inc. All Rights Reserved
#
########################################################################
import math
from region import error
from region import geometry as mygeo
from gene... |
import unittest
import http.client
import urllib.parse
class TestMongoDB(unittest.TestCase):
host = "localhost"
port = 80
#resource = "/test-classes/test.html"
def test_post(self):
params = urllib.parse.urlencode({'text':'lorem ipsum'})
headers = {"Content-type": "application/x-www-fo... |
#!/usr/bin/env python2
import urllib
import urllib2
import os.path
import utils
"""A Python script to help download a series of Isochrone files from
an OpenTripPlanner server"""
def buildRequestStringRaster(server_url, routing_params, date, time, lon_lat,
img_bbox, raster_res, otp_router_id=None):
reqSt... |
"""Utility functions used by signals to attach Ratings to Comments"""
try:
from django.contrib.comments.models import Comment
except ImportError:
from django_comments.models import Comment
from django.contrib.sites.models import Site
from django.core import urlresolvers
from django.utils.encoding import smart_s... |
import copy
from PyQt5 import QtCore
from PyQt5.QtWidgets import QCheckBox, QDialog, QDoubleSpinBox, QGridLayout, QLabel, QMessageBox, QPushButton, QSizePolicy, QSpinBox
class EditModifierDialog(QDialog):
def __init__(self, Parent, CharacterWindow, StatModifier, StatModifierDescription="Stat Modifier"):
... |
#!/usr/bin/env python3
import rospy
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
import math
import time
from std_srvs.srv import Empty
X = 0.0
Y = 0.0
yaw = 0.0
def pose_callback(pose):
global X, Y, yaw
rospy.loginfo("X=%f, Y=%f\n", pose.x, pose.y)
X = pose.x
Y = pose.y
ya... |
import sys
from twisted.python import usage
from twisted.internet import reactor
from twisted.internet.defer import (
maybeDeferred, Deferred, DeferredQueue, inlineCallbacks, returnValue)
from twisted.internet.task import deferLater
from vumi.service import Worker, WorkerCreator
from vumi.servicemaker import VumiOp... |
from ..mockingjay.hubconf import mockingjay_local as audio_albert_local
from ..mockingjay.hubconf import mockingjay_gdriveid as audio_albert_gdriveid
def audio_albert(refresh=False, *args, **kwargs):
"""
The default model
refresh (bool): whether to download ckpt/config again if existed
"""
... |
# Generated by Django 3.2.5 on 2021-07-18 23:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Config',
fields=[
... |
# Project libraries
from . import BaseResource
from .app import App
from .build import Build
class PostDeploy(BaseResource):
_strs = ["output"]
_ints = ["exit_code"]
def __init__(self):
super(PostDeploy, self).__init__()
class AppSetup(BaseResource):
_strs = ["id", "failure_message", "postd... |
print("hello, directory 1")i
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import xml.dom.minidom
from python.Log import *
class XmlFileUtil:
'android strings.xml file util'
@staticmethod
def writeToFile(keys, values, directory, filename):
if not os.path.exists(directory):
os.makedirs(directory)
... |
"""Convex hull tester."""
from itertools import tee
import cv2
import convexhull
COLOR = (0, 0, 255) #BGR
def pairwise(iterable):
"""Return paired items from iterable object as such
s -> (s0,s1), (s1,s2), (s2, s3), ...
Parameters
----------
iterable : iterable object
object to ite... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:mgboy time:2020/8/2
import win32api
import win32con, winreg, os, sys
def Judge_Key(key_name=None,
reg_root=win32con.HKEY_CURRENT_USER, # 根节点
reg_path=r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", # 键的路径
abspath=Non... |
"""
A simple factory.
"""
import logger
class Factory(object):
def __init__(self):
self._reg = {}
self.log = logger.get()
pass
def register(self, name, cls):
if name not in self._reg:
self.log.info('Registering class "{}"'.format(name), verbose=2)
sel... |
# source: https://github.com/TheAILearner/Snake-Game-using-OpenCV-Python/blob/master/snake_game_using_opencv.ipynb
import numpy as np
import cv2
import random
import time
def collision_with_apple(apple_position, score):
apple_position = [random.randrange(1,50)*10,random.randrange(1,50)*10]
score += 1
return apple_p... |
import argparse, subprocess, os, sys, glob, re
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--video_file', nargs = '?',
help = 'The relative path(s) to the video file(s). Default is all files in the current directory that end in .mov or .mp4.')
parser.add_argument('-o', '--output_file', nargs = '?'... |
"""
[2015-08-19] Challenge #228 [Intermediate] Use a Web Service to Find Bitcoin Prices
https://www.reddit.com/r/dailyprogrammer/comments/3hj4o2/20150819_challenge_228_intermediate_use_a_web/
# Desciption
Modern web services are the core of the net. One website can leverage 1 or more other sites for rich data and mas... |
import sys
import pandas as pd
import numpy as np
import pickle
from sqlalchemy import create_engine
# import tokenize_function
from models.tokenizer_function import Tokenizer
# import sklearn
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransforme... |
# -*- coding: utf-8 -*-
"""05_Groupby.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Y4LOqH8fPH5Ez3UYmoRzw86G7wcBfeNe
# Introduction to Pandas

n_samples = np.random.randint(40,200,size=n_component)
n_dimension=np.random.randint(2,51)
random_mu=100*np.random.random((n_component,n_dimension))
random_sigma=10*np.random.random((n_component,n_dimension))
X=np.zeros((0,n... |
from tokenizers import BertWordPieceTokenizer
def train(data):
tokenizer = BertWordPieceTokenizer()
tokenizer.train(files=data, vocab_size=52_000, min_frequency=2)
return tokenizer
if __name__ == "__main__":
import argparse
import sys
import os
command_line = " ".join(sys.argv[1:])
... |
import tempfile
from otoole.visualise import create_res
url = "tests/fixtures/simplicity-v0.2.1.zip"
def test_create_res():
_, path_to_resfile = tempfile.mkstemp(suffix=".pdf")
create_res(url, path_to_resfile)
|
# Copyright the Karmabot authors and contributors.
# All rights reserved. See AUTHORS.
#
# This file is part of 'karmabot' and is distributed under the BSD license.
# See LICENSE for more details.
import re
from karmabot.core import storage
# TODO: regular expressions in this module should be
# replaced with somethi... |
from board import boards
# Error handling
def get_input_int(string):
for i in range(5):
for attempt in range(10):
try:
return int(input(string))
except:
print('Invalid Input')
else:
break
else:
print('To... |
class FinancialSession(object):
''' The main entry point of the API.
'''
def begin(self):
pass
def list_accounts(self):
pass
def list_transactions(self, account):
pass
def end(self):
pass
class Account(object):
''' An account objec... |
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation
# 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/LICE... |
# Generated by Django 3.2.5 on 2021-09-14 10:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('participant_profile', '0032_participantcert_verified'),
]
operations = [
migrations.RemoveField(
model_name='participantcert',
... |
import os
import pytest
from dagster import (
PipelineDefinition,
ModeDefinition,
execute_pipeline,
ResourceDefinition,
DagsterInvalidDefinitionError,
)
from dagster_aws.s3.resources import S3Resource
from dagster.core.storage.file_cache import fs_file_cache, LocalFileHandle
from dagster.seven imp... |
from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class ChatmapCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "DBChatmap"
chatmapBaseUrl = "https://chatmap.raptorpo... |
import glob
import json
import optparse
import os
import matplotlib.pyplot as plt
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import StandardScaler
from common.utils import DATA_DIR
def count_min_posts(folder, min_posts):
json_pattern = os.path.join('..', DATA_DIR, 'pos_tags_{}_emb... |
# -*- coding: utf-8 -*-
"""Ultralight math notebook.
Auto-print top-level expressions, auto-assign last result as _.
"""
# This is the kind of thing thinking with macros does to your program. ;)
from ast import Expr
from macropy.core.quotes import macros, q, ast_literal
def nb(body, args):
p = args[0] if args ... |
import timeit
class Runtime:
def __init__(self, report_name, meter):
self.report_name = report_name
self.meter = meter
def __call__(self, fn):
def wrapper_bench(*args, **kwargs):
start = timeit.timeit()
result = fn(*args, **kwargs)
end = timeit.time... |
import dash_carbon_components as dca
import dash_html_components as html
from ... import LOA_REPO_URL, REPO_URL
landing_layout = dca.Grid(
style={
'padding': '16px',
'height': 'calc(100% - 75px)',
'overflow': 'auto',
'width': '75%'
},
className='bx--grid--narrow bx--grid--f... |
# Generated by Django 3.1.5 on 2021-03-05 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0015_post_header_image'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='bio',
... |
"""
Plot the relationship (mean of heads) for global Transformer.
Plot the relationship of local-transformer and global-transformer.
python3 plot_relation2.py --id 26 --point_id 10 --stage 0 --save
"""
import argparse
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random
import os
import n... |
#
# Input: {4, 2, -3, 1, 6}
# Output: true
# Input: {4, 2, 0, 1, 6}
# Output: true
# Input: {-3, 2, 3, 1, 6}
# Output: false
#given a list return true if zero sum is achievable with any of the elements from the list
#return false if not achievable
def zerosum(inputlist):
seen_nums = []
curr_collect = []
... |
"""
This module takes care of starting the API Server, Loading the DB and Adding the endpoints
"""
import os
from flask import Flask, request, jsonify, url_for, send_from_directory
from flask_migrate import Migrate
from flask_swagger import swagger
from flask_cors import CORS
from api.utils import APIException, generat... |
from app import db
class Note(db.Model):
id_ = db.Column(db.String(16), primary_key=True)
text = db.Column(db.Text)
response = db.Column(db.String(100))
created_at = db.Column(db.DateTime)
read_at = db.Column(db.DateTime)
password = db.Column(db.String(64))
|
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #
import libmeme as ml
import libmeme_engine as engine
# * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #
class my_script(ml.script_object):
def __init__(self, **kwargs):
return s... |
# 4.https://the-internet.herokuapp.com/dropdown
# si pe pagina de heruko selectezi o optiune si apoi verifici ca e selectata cea care trebuie
# cu un asert
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
def test_drop_d... |
"""A machine learning model to recognize the centers of circles.
The general outline is that we can create arbitrary circles and pass them into
a tensorflow model which will locate their centers. This should be a relatively
simple task, since at first at least there will be no partial circles (meaning
that the entire ... |
# -*- coding: utf-8 -*-
"""
(c) 2019 - Copyright Red Hat Inc
Authors:
Michal Konecny <mkonecny@redhat.com>
"""
from __future__ import unicode_literals, absolute_import
import unittest
import sys
import os
import json
from mock import patch, MagicMock
sys.path.insert(
0, os.path.join(os.path.dirname(os.p... |
# Copyright (c) 2019 Yubico AB
# Copyright (c) 2019 Oleg Moiseenko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
... |
import sys
def mapper():
for line in sys.stdin:
# your code here
if line.startswith(','): #skip header
continue
data = line.split(',')
print "{0}\t{1}".format(data[1], data[6])
mapper() |
SECRET_KEY = 'UJenkeiWSQpF3X5_KO3g9A' |
import os,sys
import argparse
from chinn.models import PartialDeepSeaModel, NNClassifier
from chinn import train
import torch
def get_args():
parser = argparse.ArgumentParser(description="Train distance matched models")
parser.add_argument('data_name', help='The prefix of the data (without _[train|valid|test]... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class H5bench(CMakePackage):
"""A benchmark suite for measuring HDF5 performance."""
... |
# Generated by Django 3.0.7 on 2020-10-26 02:42
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0018_auto_20201024_1557'),
]
operations = [
migrations.AddField(
model_name='empresa',
name='descripcion',
... |
import torch
from functools import reduce
from torchtext import data
from tqdm.autonotebook import tqdm
from abc import ABC, abstractmethod
import logging
import os.path
import json
import csv
from transformers import BertTokenizer, BertModel
logging.basicConfig(level=logging.DEBUG)
module_logger = logging.getLogger('... |
# Copyright 2014-2015 ARM Limited
#
# 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 w... |
import datetime
import os
import random
from pathlib import Path
import discord
from discord.ext import commands
from util import post_stats_log
from util.var import website, get_blacklist_servers
class BotEvents(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.posting = post_stats_lo... |
from matplotlib import pyplot as plt
__author__ = 'tonnpa'
class Oddball:
def __init__(self, graph):
self._graph = graph
self._egonetworks = dict((node, {}) for node in graph.nodes())
self._run()
@property
def egonetworks(self):
return self._egonetworks
@prope... |
def rank(numbers):
### Kodunuzu rank fonksiyonun blogu icerisinde girintilemeye dikkat ederek yaziniz.
### Asagidaki satirlari kodunuzu test etmek icin kullanabilirsiniz.
print(rank([21, 4, 13, 5, 8, 17, 23, 6, 22]))
print(rank([21, 4, 13, 5, 8, 17, 22, 6, 23]))
|
# some calculations about corona values
# start date somewhen in 3/2020
# added multiprocessing in 6/2020
import pandas as pd
import matplotlib.pyplot as plt
from multiprocessing import Process
# process files with these suffixes
localSuffixes = ["BW", "BY", "GER", "WORLD", "US"]
# flexinterval
flexInt = 7
def p... |
# -*- coding: utf-8 -*
from urllib.request import Request, urlopen
import json
Coin=("adzcoin", "auroracoin-qubit", "bitcoin", "bitcoin-cash", "bitcoin-gold", "dash", "digibyte-groestl",
"digibyte-qubit", "digibyte-skein", "electroneum", "ethereum", "ethereum-classic", "expanse", "feathercoin",
"gamecred... |
# -*- coding: utf-8 -*-
import logging
import click
from ..hello import HelloBase, HelloHTML
@click.command()
@click.option(
"-f",
"--format",
"output_format",
type=click.Choice(
["plain", "html"],
case_sensitive=False
),
help=(
"Select output format, default to 'plai... |
import os
from subprocess import PIPE, Popen
from time import sleep
from mininet.net import Mininet
from mininet.log import setLogLevel, info
from mininet.cli import CLI
from p4_mininet import P4Switch, P4Host
from p4runtime_switch import P4RuntimeSwitch
import conf
from topology import Topology
from compile_switch i... |
'''
Multithreaded realtime detection uses a VideoStream class
For some reason, inference time is slower than gstreamer.
'''
from edgetpu.detection.engine import DetectionEngine
from PIL import Image
import argparse
import imutils
from threading import Thread
from queue import LifoQueue
import time
import cv2
# default... |
class Flower:
color = 'unknown'
rose = Flower()
rose.color = "red"
violet = Flower()
violet.color = "green"
this_pun_is_for_you = "I don't sleep at night cause I'm thinking of you"
print("Roses are {},".format(rose.color))
print("violets are {},".format(violet.color))
print(this_pun_is_for_you)
#A class repres... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('media', '0003_file_alt_text'),
]
operations = [
migrations.AlterModelOptions(
name='file',
options={'ordering': ['title']},
),
... |
# Documentation can be found via
# https://microbit-micropython.readthedocs.io
# Load routines that allow us to use the microbit
from microbit import *
# load radio library if we need it
# import radio
# load neopixel library if we need it
# import neopixel
def forever():
"""
Code to run again and again
... |
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column
class DemoForm(forms.Form):
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'E-mail address'}))
def __init__(self, *args, **kwargs):
super().__init__(*args, ... |
"""
Audio decoder implemented with BASS dll.
"""
import ctypes
import ctypes.util
from typing import io
import numpy
BASS = ctypes.cdll.LoadLibrary(ctypes.util.find_library('bass'))
class AudioProcessError(Exception):
"""
Error occurred during audio processing.
"""
pass
def decode_audio(audi... |
import numpy as np
import jsonpickle
class NumpyHandler(jsonpickle.handlers.BaseHandler):
"""
Automatic conversion of numpy float to python floats
Required for jsonpickle to work correctly
"""
def flatten(self, obj, data):
data['repr'] = repr(obj)
return data
def restore(self... |
import typing
import jk_prettyprintobj
from .MWPageContent import MWPageContent
from .MWTimestamp import MWTimestamp
from .MWPageRevision import MWPageRevision
from .MWNamespaceInfo import MWNamespaceInfo
class MWPage(jk_prettyprintobj.DumpMixin):
def __init__(self, title:str, searchTitle:typing.Union[str,No... |
# Generated by Django 3.0.5 on 2020-05-16 10:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stock', '0040_stockitemtestresult'),
]
operations = [
migrations.AddField(
model_name='stockitemtestresult',
name='n... |
from unittest import TestCase
__author__ = 'pdoren'
__project__ = 'DeepEnsemble'
class TestITLFunctions(TestCase):
# noinspection PyStringFormat,PyTypeChecker
def test_cross_information_potential(self):
from deepensemble.utils.utils_functions import ITLFunctions
import numpy as np
N ... |
"""The venstar component."""
import logging
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
)
from homeassistant.const import STATE_ON
DOMAIN = "venstar"
ATTR_FAN_STATE = "fan_state"
ATTR_HVAC_STATE = "hvac_mode"
CONF_HUMIDIFIER = "... |
'''
TODO user test cases
'''
import asyncio
from fastapi import status
from fastapi.testclient import TestClient
from requests.auth import HTTPBasicAuth
from app.tests.fixtures import client, event_loop # noqa: F401
from app.schemas.user import UserInput
from app.repositories.user import UserRepository
from app.use... |
import os
from gym.envs.registration import register
register(
id='heist-auto-unpool-v0',
entry_point='gym_autoencoder.heist.envs:AutoencoderUnpoolEnv',
)
register(
id='heist-auto-maxpool-v0',
entry_point='gym_autoencoder.heist.envs:AutoencoderMaxPoolEnv',
)
register(
id='heist-auto-maxpool-big-v... |
import numpy as np
from nnmnkwii.io import hts
from os.path import join
from glob import glob
from tqdm import tqdm
paths = sorted(glob(join('../data/basic5000', "label_phone_align", "*.lab")))
for i, filepath in tqdm(enumerate(paths)):
label = hts.load(filepath)
end_times_ = label.end_times
end_times ... |
from explainer.real_time.pytorch_fixes import SaliencyModel
from explainer.real_time.resnet_encoder import resnet50encoder
import torch.nn.functional as F
from torch.autograd import Variable
def get_pretrained_saliency_fn(model_dir, cuda=True, return_classification_logits=False):
''' returns a saliency function t... |
import torch
from torch.autograd import Variable as V
import torchvision.models as models
from torchvision import transforms as trn
from torch.nn import Linear, Conv2d, BatchNorm1d, BatchNorm2d, PReLU, Sequential, Module, ModuleList, LogSoftmax, Softmax, functional as F
import os
from PIL import Image
import numpy as n... |
"""
Milestone 3 Code (P7 & P8) - Batch User Interface
Team 64: Py Eaters
Team Leader: Bardia Parmoun
Team Members: Hao Lin
Benjamin Richards
Ian Holmes
Authors: Benjamin Richards and Hao Lin
Submitted on 02/04/2020
"""
# Libraries
from Cimpl import (copy,... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class CommonConfig(AppConfig):
name = 'geotrek.common'
verbose_name = _("Common")
def ready(self):
import geotrek.common.lookups # NOQA
|
import os
from pymongo import MongoClient
import time
import uuid
import web
# Global variables
import os
here = os.path.dirname(__file__)
filedir = os.path.join(here, 'static/pub') # File storage directory
class DBManager():
def __init__(self):
self.client = MongoClient()
self.db = self.client.n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.