code stringlengths 1 199k |
|---|
from collections import namedtuple
from enum import IntEnum, Enum
import os
ROOT_DIRECTORY = os.path.abspath(
os.path.join(os.path.dirname(os.path.realpath(__file__)),
os.path.pardir)
)
DATA_DIRECTORY = os.path.join(ROOT_DIRECTORY, 'data')
ANNUAL_FACTOR = 252.0
RETURN_KEY_PRIORITY = ("Settle", "Set... |
from runner.koan import *
class AboutMultipleInheritance(Koan):
class Nameable:
def __init__(self):
self._name = None
def set_name(self, new_name):
self._name = new_name
def here(self):
return "In Nameable class"
class Animal:
def legs(self):
... |
import unittest
from katas.kyu_5.delta_bits import convert_bits
class ConvertBitsTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(convert_bits(31, 14), 2)
def test_equal_2(self):
self.assertEqual(convert_bits(7, 17), 3)
def test_equal_3(self):
self.assertEqual(co... |
import os
import tensorflow as tf
class Network(object):
def __init__(self):
"""
Initialises constants and variables in the Network object
"""
# Parameters
self.batch_size = 64
self.learning_rate = 0.001
self.n_training_epochs = 10
self.display_step = ... |
from supybot.test import *
class DVDTestCase(PluginTestCase):
plugins = ('DVD',) |
"""Collects and renders Python and Flask application evironment and configuration."""
try:
from cgi import escape
except ImportError:
from html import escape
import os
import platform
import socket
import sys
from . import app
optional_modules_list = [
"Cookie",
"mod_wsgi",
"psycopg2",
"zlib",
... |
import wx
import storytext.guishared
class TextLabelFinder(storytext.guishared.TextLabelFinder):
def find(self):
sizer = self.findSizer(self.widget)
return self.findInSizer(sizer) if sizer is not None else ""
def findInSizer(self, sizer):
sizers, widgets = self.findSizerChildren(sizer)
... |
import os
import sys
import django
from django.conf import settings
from django.test.runner import DiscoverRunner
import dj_database_url
from colour_runner.django_runner import ColourRunnerMixin
BASEDIR = os.path.dirname(os.path.dirname(__file__))
PGPFIELDS_PUBLIC_KEY = os.path.abspath(
os.path.join(BASEDIR, 'tests... |
from collections import defaultdict
from django import views
from django.contrib.auth import login
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from app.forms import RegisterForm
from app.models import EventResult, UserProfile
class IndexView(views.generic.TemplateView):
... |
from pathlib import Path
import ezdxf
from ezdxf.math import Vec3
from ezdxf.entities.xdata import XDataUserDict, XDataUserList
DIR = Path("~/Desktop/Outbox").expanduser()
doc = ezdxf.new()
msp = doc.modelspace()
line = msp.add_line((0, 0), (1, 0))
with XDataUserDict.entity(line) as user_dict:
user_dict["CreatedBy"... |
from __future__ import absolute_import
from geocoder.mapzen import Mapzen
from geocoder.location import Location
from geocoder.keys import mapzen_key
class MapzenReverse(Mapzen):
"""
Mapzen REST API
=======================
API Reference
-------------
https://mapzen.com/documentation/search/rever... |
MESSAGES = {
# name -> (message send, expected response)
"find_node request":
(b'd1:ad2:id20:jihgfedcba01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe',
b'^d1:t2:aa1:y1:r1:rd5:nodesl'+
b'26:abcdefghij0123456789\xc0\xa8\xa8\x0f/X'+
b'26:mnopqrstuvwxyz123456\xc0\xa8\xa8\x... |
"""
This file contains the classes for the AST types and the methods to traverse it.
Note that it was adapted from the interpreter by Jay Conrod at http://jayconrod.com/
----------------------------------------------------------------------------
The most important methods defined for the interaction with the solver ar... |
"""
blog-base is an extension for cotidia-cms-base
"""
VERSION = '0.1' |
julia_srpm_builders = ["nightly_srpm"]
srpm_package_scheduler = Nightly(name="Julia SRPM package", builderNames=julia_srpm_builders, branch="master", hour=[0], onlyIfChanged=True)
c['schedulers'].append(srpm_package_scheduler)
julia_srpm_package_factory = BuildFactory()
julia_srpm_package_factory.useProgress = True
ju... |
"""
GNU GENERAL PUBLIC LICENSE Version 2
Created on Mon Oct 13 18:50:34 2014
@author: Wasit
"""
import sys
import pickle
from master import master
from tree import tree
import imp
import numpy as np
import time
import datetime
import os
class log:
def __init__(self,path=""):
self.initTime=time.time()
... |
def song_playlist(songs, max_size):
"""
songs: list of tuples, ('song_name', song_len, song_size)
max_size: float, maximum size of total songs that you can fit
Start with the song first in the 'songs' list, then pick the next
song to be the one with the lowest file size not already picked, repeat
... |
"""
Chunk the MOS text data into easier to search values.
"""
import re
from twisted.internet import reactor
from pyiem.nws import product
from pywwa import common
from pywwa.ldm import bridge
from pywwa.database import get_database
def real_process(txn, data):
"""Go!"""
prod = product.TextProduct(data)
# r... |
from threading import RLock
class Clock(object):
""" A Singlton clock.
Based on [The Singleton](https://goo.gl/T3kxkR)
"""
__instance = None
def __new__(cls):
if Clock.__instance is None:
Clock.__instance = object.__new__(cls)
Clock.__instance.val = int()
... |
import os
import sys
import unittest
sys.path[0:0] = [os.path.join(os.path.dirname(__file__), '..'),]
try:
import json
except ImportError:
import simplejson as json
import flomosa
class TestError(unittest.TestCase):
def setUp(self):
self.headers = {'header1': 'test1'}
self.code = 200
... |
"""
WSGI config for IOThomeinspector project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_... |
from app import db
class Player(db.Model):
__tablename__ = 'tbl_player'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer)
room_id = db.Column(db.Integer)
def __init__(self, user_id=None, room_id=None):
self.user_id = user_id
self.room_id = room_id |
"""105. Construct Binary Tree from Preorder and Inorder Traversal
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder ... |
from __future__ import absolute_import
from __future__ import print_function
from data_utils import load_dialog_task, vectorize_data, load_candidates, \
vectorize_seq2seq_fix, tokenize, vectorize_seq2seq, vectorize_candidates
import metrics
from memn2n import AttentionN2NDialog
import datetime
from itertools import... |
import os
import subprocess
try:
from staticfiles import finders
except ImportError:
from django.contrib.staticfiles import finders # noqa
from pipeline.conf import settings
from pipeline.storage import default_storage
from pipeline.utils import to_class
class Compiler(object):
def __init__(self, storage=de... |
import numpy as np
class Investor():
def __init__(self, π, G, δ, h, m, Y):
self.π = π
self.G = G
self.δ = δ
self.γ = 1-δ
self.h = h
self.m = m
self.Y = Y
# Utility function:
def U(self, C, t):
if self.h(t) <= 0:
return 0
eli... |
"""
update module defines addition and deletion URL operations against backends
"""
import cache
import database
def compose_add_response(status=False):
response = { "status": str(status) }
return response
def update_url(url, hostname, table_name, operation, conf):
"""
add or delete URL from databas... |
class InvalidEmailException(Exception):
pass
class MissingRequiredFieldException(Exception):
pass
resp_status_code_messages = {
400: 'Bad Request - Often missing a required parameter',
401: 'Unauthorized - No valid API key provided',
402: 'Request Failed - Parameters were valid but request failed',
... |
import os
from setuptools import setup, find_packages
base_dir = os.path.dirname(__file__)
setup(
name='mortar',
version='0.2.0.dev0',
author='Chris Withers',
author_email='chris@withers.org',
license='MIT',
description=(
"A dependency injection based web application server framework."
... |
"""Automaton Class."""
from shellcraft.epithets import Name
from random import seed, randint, paretovariate, random
import math
class World(object):
def __init__(self, game, width, height):
self.game = game
self.width, self.height = width, height
self.cache = {}
# Distribute resource... |
"""
Convenience functions for plotting the generated data.
"""
import matplotlib.pyplot as plt
def plot_sa(ts, sas, out_path, *, x_label=None, y_label=None):
"""
Plot the complex survival amplitude as a function of time.
Parameters:
ts: Times.
sas: Vector of complex values corresponding to ts.
... |
import uuid
from unittest.mock import Mock, patch
from app.data_model.answer_store import AnswerStore, Answer
from app.questionnaire.location import Location
from app.questionnaire.questionnaire_schema import QuestionnaireSchema
from app.questionnaire.rules import evaluate_rule, evaluate_goto, evaluate_repeat, \
ev... |
atoms = {
'C': 2,
'H': 5,
}
bonds = {
'C-C': 1,
'C-H': 5,
}
linear = False
externalSymmetry = 1
spinMultiplicity = 2
opticalIsomers = 1
energy = {
'CBS-QB3': GaussianLog('ethyl_cbsqb3.log'),
'Klip_2': -78.98344186,
}
geometry = GaussianLog('ethyl_cbsqb3.log')
frequencies = GaussianLog('ethyl_b3l... |
from past.builtins import map
import threading
from ..config import TIMEOUT_SEC
from ..interfaces import Device
from ..platform import get_provider
from .gatt import CoreBluetoothGattService
from .objc_helpers import cbuuid_to_uuid, nsuuid_to_uuid
from .provider import device_list, service_list, characteristic_list, de... |
"""
Plotting module using matplotlib.
"""
from __future__ import division
import matplotlib
import pymc
import os
from pylab import bar, hist, plot as pyplot, xlabel, ylabel, xlim, ylim, close, savefig
from pylab import figure, subplot, subplots_adjust, gca, scatter, axvline, yticks
from pylab import setp, axis, contou... |
# Copyright Sourav Verma ABV_IIITMG
import requests
from bs4 import BeautifulSoup
url = "http://www.cricbuzz.com/cricket-match/live-scores"
def open_url(url):
return requests.get(url).text # returns html
def get_bsoup_object(html):
return BeautifulSoup(html, "lxml") # returns soup (BeautifulSoup's object)
de... |
from typing import Iterable
NUMBERS = [37107287533902102798797998220837590246510135740250,
46376937677490009712648124896970078050417018260538,
74324986199524741059474233309513058123726617309629,
91942213363574161572522430563301811072406154908250,
23067588207539346171171980310... |
'''
Plots histogram from a desc_merged.txt file.
INPUT: file_path
OUTPUT: *descriptorname.pdf
ARGUMENTS: file_path
USAGE: python pdb2descriptors.py file_path
'''
from enri import Enri
import sys
e = Enri()
filepath = sys.argv[1]
path, name, name_ext = e.path2names(filepath)
data, headers = e.parse_desc_merged_txt(filep... |
"""
Test module to make sure that simple representations of
hyperbolic errors are equivalent to more generalized
expressions.
"""
import numpy as N
from scipy.stats import chi2
from .plot.cov_types.regressions import hyperbola
from ..orientation.test_pca import random_pca
from ..geom.util import dot, augment_tensor, pl... |
from cmspwn.module import pwnfunc
@pwnfunc
def is_silverstripe(cmspwn,response):
identify_strings = ('name="generator" content="SilverStripe', )
for id_string in identify_strings:
if id_string in response.content:
cmspwn.found = True; cmspwn.Framework = 'Silverstripe';cmspwn.site = 'http://w... |
from __future__ import absolute_import
from argparse import ArgumentParser
from aoikproducerconsumerrunner.main.argpsr_const import ARG_CONSUMER_FUNC_URI_F
from aoikproducerconsumerrunner.main.argpsr_const import ARG_CONSUMER_FUNC_URI_H
from aoikproducerconsumerrunner.main.argpsr_const import ARG_CONSUMER_FUNC_URI_K
fr... |
from django.db import models
class Menu(models.Model):
day = models.CharField(max_length=10, blank=False, null=False)
food = models.TextField()
meal = models.CharField(max_length=10, blank=False, null=False)
option = models.IntegerField(null=False)
week = models.IntegerField(null=False)
class Me... |
import re
import requests
import mavri
import pandas as pd
import ray
import time
ray.init()
wiki = 'tr.wikipedia'
xx = mavri.login(wiki, 'Mavrikant Bot')
months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']
@ray.remote
def process(title,text):
if... |
import stomp
import urlparse
import json
import logging
urlparse.uses_netloc.append('tcp')
class ZKillboardStompListener(stomp.listener.ConnectionListener):
def __init__(self, bot):
self.bot = bot
self.conn = None
self.ids = [None for x in range(50)]
def on_error(self, headers, message):... |
from itertools import count
import os
import logging
import warnings
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS
from django.db.backends.base.creation import TEST_DATABASE_PREFIX
from django_extensions.settings import SQLITE_E... |
from collections import Counter
try:
import cPickle as pickle
except:
import pickle
from neural import rectifier_network
class Model:
def save(self, filen=None):
if filen == None:
filen = self.__class__.__name__
with open('{}.pkl'.format(filen), 'w') as f:
pickle.dump... |
"""tests/test_decorators.py.
Tests that class based hug routes interact as expected
Copyright (C) 2016 Timothy Edmund Crosley
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, in... |
from math import atan
from tkinter import *
num = 0
while num <= 3: # Объявляем цикл
num = int(input("Введите 1 для рассчёта G\nВведите 2 для рассчёта F\nВведите 3 для рассчёта Y\nВведите любую другую цифру для выхода\n"))
if num > 3 or num <= 0: # Если num не 1,2,3 - выход из цикла
break
a = float(... |
from module import Module
import numpy as np
class Dropout(Module):
def __init__(self, p=0.5, v1=False, stochastic_inference=False):
super(Dropout, self).__init__()
self.p = p
self.train = True
self.stochastic_inference = stochastic_inference
# version 2 scales output during ... |
"""
pi-timolo - Raspberry Pi Long Duration Timelapse, Motion Tracking,
with Low Light Capability
written by Claude Pageau Jul-2017 (release 7.x)
This release uses OpenCV to do Motion Tracking.
It requires updated config.py
Oct 2020 Added panoramic pantilt option plus other improvements.
"""
from __future__ import print... |
from .chownref import main
main() |
raw_input()
int(string) -> para converter
import re importa regex
Terminal
>>> resultado = re.match('Py', 'Python')
>>> resultado
<_sre.SRE_Match object at 0x104b86ac0>
>>> resultado.group()
'Py'
>>> resultado = re.match('[A-Za-z]y', 'Python') # maiusculo e minusculo
>>> resultado.group()
>>> resultados = re.fi... |
"""
This is the simplest Python GTK+3 Webkit snippet.
WARNING: Debian users have to install the "libwebkitgtk-3.0-dev" package to run
this snippet.
"""
import gi
gi.require_version('WebKit', '3.0')
from gi.repository import Gtk as gtk
from gi.repository import WebKit as webkit
def main():
window = gtk.Wind... |
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import os
import gc
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import T... |
"""
:author: Konrad Podlawski <kpodlawski@kretstudios.pl>
"""
from chatterbot import ChatBot
def nltk_download_corpus(corpus_name):
"""
Download the specified NLTK corpus file
unless it has already been downloaded.
Returns True if the corpus needed to be downloaded.
"""
from nltk.data import fin... |
class Common(object):
TSK_DocumentArchive= 200
TSK_CommandHistory= 201
TSK_CommandGroupArchive= 202
TSK_CommandContainerArchive= 203
TSK_ReplaceAllCommandArchive= 204
TSK_TreeNode= 205
TSK_ProgressiveCommandGroupArchive= 206
TSK_CommandSelectionBehaviorHistoryArchive= 208
TSK_UndoRedoStateCommandSelec... |
import sys
import os
sys.path.append(os.path.abspath('_themes'))
sys.path.append(os.path.abspath('_themes_flask'))
sys.path.append(os.path.abspath('.'))
extensions = [
'sphinx.ext.autodoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'aerofiles'
copyright = u'2014, Tobia... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
'''
this is an interactive tool to explore the profile views
of a given model
'''
def insert_point(point, line):
'''
this method takes in a line and a point, and
updates the line so that the point is o... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='AuthGroup',
fields=[
('id', models.IntegerField(serialize=False, primary_key... |
import argparse
import os
import sys
import ast
import subprocess
import chipset
import reg_access as reg
def parse_file(file):
print('{0:^10s} | {1:^28s} | {2:^10s}'. format('offset', file.name, 'value'))
print('-' * 54)
for line in file:
register = ast.literal_eval(line)
val = reg.read(register[1])
intreg = ... |
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("2000000... |
"""
"""
import logging
import pandas as pd
from .gf import GameFinder
class PlayerGameFinder(GameFinder):
"""
Interactive command line app
"""
prompt = "player_game_finder> "
intro = "Welcome to Player Game Finder! Type ? to list commands"
def do_search(self, inp):
"""
Search for... |
"""
H3HexagonLayer
==============
Plot of values for a particular hex ID in the H3 geohashing scheme.
This example is adapted from the deck.gl documentation.
"""
import pydeck as pdk
import pandas as pd
H3_HEX_DATA = "https://raw.githubusercontent.com/visgl/deck.gl-data/master/website/sf.h3cells.json"
df = pd.read_json... |
import os
import sys
import psycopg2
import json
from bson import json_util
from pymongo import MongoClient
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
def create_app():
app = Flask(__name__)
return app
app = create_app()
MONGODATABASE = "e4"
MONGOSERVER... |
from dssg import db
import base_model
class Message(base_model.BaseModel, db.Model):
__tablename__ = 'message'
id = db.Column(db.Integer, db.Sequence('seq_message'), primary_key=True)
deployment_id = db.Column(db.Integer, db.ForeignKey('deployment.id'))
origin_message_id = db.Column(db.Integer, nullable... |
import sys
import os
import shutil
import random
source = sys.argv[1]
count = int(sys.argv[2])
testset_dir = "ukbench-test"
trainingset_dir = "ukbench-training"
def rand():
return int(random.random() * 10) % 4
fullset = sorted(os.listdir(source))
sampleset = fullset[:count]
testset = ["ukbench%05d.jpg" % (i + rand(... |
from itertools import islice
from nose.tools import raises
from graffiti import util
def test_identity():
assert util.identity(1) == 1
def test_is_dict():
assert util.is_dict({})
assert not util.is_dict([])
def test_fninfo_noargs():
fn = lambda: 1
info = {
"fn": fn,
"args": [],
... |
import os
import matplotlib.pyplot as plt
import cPickle as pickle
import tensorflow as tf
from showattendtell.core.test_solver import CaptioningSolver
from showattendtell.core.model import CaptionGenerator
from showattendtell.core.utils import load_coco_data
from showattendtell.core.bleu import evaluate
dir_path = os.... |
from paramiko import SSHClient, SSHConfig
import os
config = SSHConfig()
abs_path = ('/Users/sabina/.ssh/config')
base_path = os.path.dirname(__file__)
rel_path = os.path.relpath(abs_path)
new_path = (os.path.join(base_path,rel_path))
config.parse(open(new_path,'r'))
o = config.lookup('we')
ssh_client = SSHClient()
ssh... |
""" Test for the slack module. """
import datetime
import os
from unittest import TestCase
from unittest import skipUnless
from unittest.mock import patch
from werkzeug.exceptions import BadRequest
from app import slack
from tests.test_github import FULL_NAME
from tests.test_github import GENERIC_USERNAME
from tests.te... |
import asyncio
import curses
import math
from datetime import datetime
from typing import Any
from .window import BorderedSubWindow
from sortedcontainers import SortedDict
DOWN = 1
UP = -1
class LogSubWindow(BorderedSubWindow):
def __init__(self,
window: Any,
height: int = 0,
... |
'''
Diamond base58 encoding and decoding.
Based on https://diamondtalk.org/index.php?topic=1026.0 (public domain)
'''
import hashlib
class SHA256:
new = hashlib.sha256
if str != bytes:
# Python 3.x
def ord(c):
return c
def chr(n):
return bytes( (n,) )
__b58chars = '123456789ABCDEFGHJKLMN... |
import logging
import unittest
import research_papers.logutils as logutils
from research_papers.tools.crossref_resolver import CrossrefResolver
__author__ = 'robodasha'
__email__ = 'damirah@live.com'
class TestCrossrefResolver(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestCrossrefResolv... |
from __future__ import absolute_import, unicode_literals
import logging
_logger = logging.getLogger('mysqlevp')
_logger.setLevel(logging.INFO)
_ch_handler = logging.StreamHandler()
_ch_handler.setLevel(logging.DEBUG)
_ch_handler.setFormatter(logging.Formatter('%(levelname)s %(asctime)s %(message)s'))
_logger.addHandler... |
from pytelemetrycli.cli import Application
import pytest
from unittest.mock import MagicMock
import cmd
import io
import sys
import queue
class TransportMock:
def __init__(self):
self.q = queue.Queue()
self.canConnect = False
self.counter = 0
def authorizeConnect(self,value):
sel... |
from smtplib import SMTPException
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .forms import *
from .models import... |
"""Test case and runner for :class:`aglyph.component.Component`."""
__author__ = "Matthew Zipay <mattz@ninthtest.info>"
import logging
import unittest
import warnings
from aglyph import AglyphError, __version__
from aglyph.component import Component
from test import assertRaisesWithMessage, dummy
from test.test_Templat... |
import scrapy
class SouqSpider(scrapy.Spider):
name = "festo" # Name of the Spider, required value
start_urls = ["http://www.knowafest.com/college-fests/events"] # The starting url, Scrapy will request this URL in parse
# Entry point for the spider
def parse(self, response):
for href in respon... |
git_refnames = "$Format:%d$"
git_full = "$Format:%H$"
tag_prefix = ""
parentdir_prefix = "m2bk-"
versionfile_source = "m2bk/_version.py"
import os, sys, re, subprocess, errno
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
assert isinstance(commands, list)
p = None
for c in comm... |
class TieBreaking(object):
"""
TieBreaking determines which response should be used in the event
that multiple responses are generated within a logic adapter.
"""
def break_tie(self, statement_list, method):
METHODS = {
"first_response": self.get_first_response,
"rand... |
narcissistic = lambda s: sum(int(x)**len(str(s)) for x in str(s))==s |
"""Production settings and globals."""
from os import environ
import dj_database_url
from .base import *
ALLOWED_HOSTS = []
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = environ.get('EMAIL_HOST', 'smtp.gmail.com')
EMAIL_HOST_PASSWORD = environ.get('EMAIL_HOST_PASSWORD', '')
EMAIL_HOST_USER ... |
class PID:
"""
Discrete PID control
"""
def __init__(self, P=2.0, I=0.0, D=1.0, Derivator=0, Integrator=0, Integrator_max=500, Integrator_min=-500):
self.Kp=P
self.Ki=I
self.Kd=D
self.Derivator=Derivator
self.Integrator=Integrator
self.Integrator_max=Integ... |
from __future__ import with_statement
from __future__ import division
import sys
import os
import time
import numpy as np
import re
import time
import csv
import socket
from matplotlib.mlab import *
from matplotlib.pyplot import *
from scipy import signal as sig
import matplotlib as mpl
from tek3kComms import Tek3kComm... |
"""Generate rnadom story using trigrams from a text file specified by user."""
import io
import random
import sys
def read_file(file):
"""Open and read file input."""
f = io.open(file, 'r', encoding='utf-8')
text = f.read()
f.close()
return text
def strip_d_hyphen(text):
"""Return string without... |
from .most_common import MostCommonHeuristic
from collections import defaultdict
from itertools import product
from gurobipy import GRB, Model, quicksum as sum
import sys
class BendersModelGurobi(object):
'''Benders Decomposition of the original BIP using Gurobi'''
_slug = 'benders-model-gurobi'
def slug(se... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20141223_1124'),
]
operations = [
migrations.AlterField(
model_name='pearl',
name='status',
field=m... |
for _ in range(int(input())):
a=int(input())+int(input())
print(a if a<10**80 else 'overflow') |
from __future__ import print_function
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.layers.core import Activation, Dense, Flatten, Dropout
from keras.optimizers import Adam
from keras.regularizers import l2
from keras import backend as K... |
import os
import sys
import init_multiprocessing
CELLTYPES = os.path.dirname(os.path.dirname(__file__))
sys.path.append(CELLTYPES)
print "Appended to sys path", CELLTYPES # TODO can maybe move this too simetup fn call and call once somewhere else...
SINGLECELL = CELLTYPES + os.sep + "singlecell"
DATADIR = CELLTYPES + ... |
from asposeslides import Settings
from com.aspose.slides import Presentation
from com.aspose.slides import SaveFormat
from com.aspose.slides import XpsOptions
class Properties:
def __init__(self):
# Accessing Built-in Properties
self.get_properties()
# Modifying Built-in Properties
s... |
from Parser.Parser import Parser
from Parser.Data.VariableParser import VariableParser
class VariableDeclarationParser(Parser):
def __init__(self, text, context):
super(VariableDeclarationParser, self).__init__(text, context)
self.internal += [self.parse_declaration]
def parse_declaration(self):... |
""" Implementation of the following grammar for the GIF89a file format
<GIF Data Stream> ::= Header <Logical Screen> <Data>* Trailer
<Logical Screen> ::= Logical Screen Descriptor [Global Color Table]
<Data> ::= <Graphic Block> |
<Special-Purpose Block>
<Graphic Block>... |
from setuptools import setup
with open("README.md", "r") as readme_file:
readme = readme_file.read()
with open("requirements.txt") as reqs:
requirements = reqs.read().split("\n")
setup(
name="peerfinder",
version="2020.09.05",
packages=["peerfinder"],
url="https://github.com/rucarrol/PeerFinder"... |
"""
"**Pycco**" is a Python port of [Docco](http://jashkenas.github.com/docco/):
the original quick-and-dirty, hundred-line-long, literate-programming-style
documentation generator. It produces HTML that displays your comments
alongside your code. Comments are passed through
[Markdown](http://daringfireball.net/project... |
"""
Tool to generate a population of simulated satellite properties.
"""
from collections import OrderedDict as odict
import numpy as np
import pylab
import pandas as pd
import ugali.utils.config
import ugali.utils.projector
import ugali.utils.skymap
import ugali.analysis.kernel
import ugali.observation.catalog
import ... |
import io, sys
from functools import reduce
buffer_size = io.DEFAULT_BUFFER_SIZE * 1024
code_newline = 10
def count_lines(bytes_iter):
return reduce(
lambda buf_counter, elem: buf_counter if elem != code_newline else buf_counter + 1,
bytes_iter,
0
)
if __name__ == "__main... |
"""
Specifications for data objects exposed through a ``provider`` or ``service``.
"""
from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
from enum import Enum
class CloudServiceType(object):
"""
Defines possible service types that are offered by providers.
Providers can... |
from heatmappy.heatmap import Heatmapper,\
GreyHeatMapper,\
PILGreyHeatmapper,\
PySideGreyHeatmapper |
import os
import logging
from . import BaseTask
class TestTask(BaseTask):
helptext_short = "test [test to run]: run the given test or all if no test to run is given."
@classmethod
def run(cls, *args, **kwargs):
test = None
if len(args) >= 1:
test = args[0]
from cactus imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.