code stringlengths 1 199k |
|---|
import sqlite3
conn = sqlite3.connect('clarity.db', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE TABLE users (gender TEXT, rank INTEGER, username TEXT PRIMARY KEY, password TEXT, name TEXT, voted TEXT, credits INTEGER)''')
c.execute('''CREATE TABLE answers (upvotes INTEGER,
... |
import json
import os
from bson.objectid import ObjectId
from flask import Blueprint, Response, render_template, request
from app import mongo
def mount_web_path(folder):
return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))), folder)
main = Blueprint(
'godinez',
__... |
__author__ = 'James T. Dietrich'
__contact__ = 'james.t.dietrich@dartmouth.edu'
__copyright__ = '(c) James Dietrich 2016'
__license__ = 'MIT'
__date__ = 'Wed Nov 16 11:33:39 2016'
__version__ = '1.0'
__status__ = "initial release"
__url__ = "https://github.com/geojames/..."
"""
Name: Week6-3_Statistics.py
Com... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chills_pos.settings.main")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import sys
import logging
from WordGraph import WordGraph
import networkx as nx
from networkx.readwrite import json_graph
import json
if __name__ == '__main__':
word_graph = WordGraph()
graph = word_graph.get_graph()
# write each line of the dictionary to the json file
with open('output/generated.json',... |
import openpnm as op
import numpy as _np
from numpy.testing import assert_approx_equal
class HydraulicConductanceTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[5, 5, 5], spacing=1.0)
self.geo = op.geometry.GenericGeometry(network=self.net,
... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2016 Alex Forencich
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
... |
import hashlib
from typing import List, Tuple, TYPE_CHECKING, Optional, Union, Sequence
import enum
from enum import IntEnum, Enum
from .util import bfh, bh2u, BitcoinException, assert_bytes, to_bytes, inv_dict, is_hex_str
from . import version
from . import segwit_addr
from . import constants
from . import ecc
from .c... |
"""
Created on Sun Apr 19 19:08:49 2015
@author: Paco
"""
from signalprocessing import *
from fractal import *
from stats import *
from tqdm import tqdm
def dictionaryInitialization():
d = {'fft': list(),
'w0': list(),
'w1': list(),
'w2': list(),
'w3': list(),
'w4': list(),
'w5': list(),
... |
name = input("What is your name? ")
course = input("What class are you in? ")
print()
weight_test = float(input("How much are tests worth in this class (i.e. 0.40 for 40%): "))
test1 = float(input("Enter test score #1: "))
test2 = float(input("Enter test score #2: "))
test3 = float(input("Enter test score #3: "))
print... |
from django.contrib.auth.models import User
from django.core import mail
class BasicBackend:
supports_object_permissions = False
supports_anonymous_user = False
supports_inactive_user = False
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.Do... |
import os
from types import GeneratorType
import pytest
from rss_scrapper.task_factory import create_task
from rss_scrapper.tasks.text import TextTask
TEST_DATA_FOLDER = "tests/test_data"
@pytest.fixture(params={
"lorem_ipsum.txt",
"utf-8.txt",
"cp1252.txt",
})
def test_file_path(request):
return os.pat... |
"""Checker for anything related to the async protocol (PEP 492)."""
import sys
import astroid
from astroid import exceptions
from pylint import checkers
from pylint.checkers import utils as checker_utils
from pylint import interfaces
from pylint import utils
class AsyncChecker(checkers.BaseChecker):
__implements__ ... |
def simple(func):
func.__annotation__ = "Hello"
return func
@simple
def foo():
pass
def complex(msg):
def annotate(func):
func.__annotation__ = msg
return func
return annotate
@complex("Hi")
def bar():
pass
foo
bar
class C(object):
@staticmethod
def smeth(arg0, arg1):
... |
try:
import Tkinter as tk
import ttk
except ImportError:
import tkinter as tk
import tkinter.ttk as ttk
class Base_Form(object):
"""Base class of all forms"""
def __init__(self, widget_class, master, action, hidden_input, kw):
self.action = action
if hidden_input is None:
... |
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import sys, os, glob, re, math
results = {}
def AddRes(name, mem, N, eltime):
global results
results.setdefault(mem, {}).setdefault(name, {})[N] = eltime
def ReadRes(fn):
with open(fn, "rt") as f:
data = f.read()
match = re.searc... |
from os import listdir, rename
from os.path import isfile, isdir, join
import sys
import json
import math
TIMEOUT = 300*1000
def load_json_file(json_path):
f = open(json_path)
content = f.read()
data = json.loads(content)
f.close()
# "purify" the data to a form we care about: (time,
time = int(data["executionTime... |
import json
import os
from functools import partial
import cv2
import numpy as np
from tierpsy.analysis.compress.compressVideo import getROIMask, selectVideoReader, reduceBuffer
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QImage
from PyQt5.QtWidgets import QApplication, QMainWindow, \
QFileDialog, QMess... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class TwitterAccount(models.Model):
"""
Twitter account model that stores the oauth token and secret
for a given user.
"""
user = models.OneToOneField(User, on_del... |
from django.db.models import Q
from rest_framework import filters
class BaseFilter(filters.BaseFilterBackend):
"""Base filter class for django rest framework views
The fields can be mapped to a different filter attribute
by using the mapped fields dictionary, this way we can filter
related models.
"... |
import requests
import pytest
def test_code_changes_by_group(metrics):
response = requests.get('http://localhost:5000/api/unstable/repo-groups/10/code-changes')
data = response.json()
assert response.status_code == 200
assert len(data) >= 1
assert data[0]['commit_count'] > 0
def test_code_changes_by... |
from django.shortcuts import get_object_or_404, render, RequestContext, render_to_response
from repo.forms import UserForm, UserEditForm
from reg.forms import MyRegistrationForm
from reg.models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.views import password_reset
from djang... |
from distutils.core import setup
setup(
name = 'wikiquote',
py_modules = ['wikiquote'],
version = '0.1.1',
description = 'Retrieve quotes from any Wikiquote page.',
author = 'Federico Tedin',
author_email = 'federicotedin@gmail.com',
install_requires = ['lxml'],
url = 'https://github.com/federicotdn/pyt... |
from django.db import transaction
from django.utils import timezone
from autolims.models import (Instruction, Aliquot,Container,
AliquotEffect, Resource)
from transcriptic_tools.inventory import get_transcriptic_inventory
from transcriptic_tools.enums import Reagent
from transcriptic_tools.... |
"""
mixture.py: Classes for estimators for mixture distributions
"""
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
import vampyre.common as common
from vampyre.estim.base import BaseEst
class MixEst(BaseEst):
""" Mixture estimator class
Given a list of est... |
from virtualisation.misc.jsonobject import JSONObject as JOb
from virtualisation.misc.log import Log as L
import os
import psycopg2
import datetime
import json
__author__ = 'Marten Fischer (m.fischer@hs-osnabrueck.de)'
class SQL(object):
datatype_map = {'int': 'INT', 'str': 'VARCHAR', 'float': 'FLOAT', 'datetime.da... |
import cppy.cppy
import os
import fnmatch
import filecmp
def test_file(file):
src = os.path.join('src', file)
dst = os.path.join('dst', file)
ref = os.path.join('ref', file)
cppy.cppy.expand(src, dst, newline='\n')
if filecmp.cmp(dst, ref):
print('Passed: ' + file)
return True
pr... |
import sys
import os
from subprocess import Popen, PIPE, STDOUT
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'
if __name__ == '__main__':
try:
src_dir = sys.argv[1]
new_dir = sys.argv[2]
except IndexError:
print "Usag... |
if __name__ == '__main__' and __package__ is None:
from test_helpers import TestHelpers
helpers=TestHelpers()
helpers.add_relative_path()
from lib.mongo import MongoDB
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans #, MiniBatchKMeans
from sklearn.decomposition... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('groups', '0001_initial'),
('tracker', '0004_auto_20171029_1059'),
]
operations = [
migrations.RemoveField(
... |
count = 0
for index in range(len(s) - 2):
if s[index : index + 3].lower() == 'bob':
count += 1
print count |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import xml.etree.ElementTree as ET
from compas import _iotools
from compas.files._xml.xml_cpython import prettify_string # doesn't need special handling for pre-3.8 so we just import
__all__ = [
'xml_from_f... |
import time
import logging
from flask import request
from flask.ext.restful import Resource, abort
from werkzeug.exceptions import HTTPException
from ..config import Config
from ..utils import udefault
from ..auth import Authentication
from ..dao.mongo.daomongo import DaoMongo
class DspHandler(Resource):
# here bui... |
"""
Sphinx extension for Hades's options
"""
from typing import Any
import sphinx.ext.autodoc
from docutils.parsers.rst.roles import CustomRole, code_role
from sphinx.application import Sphinx
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.roles import XRefRole
fr... |
from openmdao.main.api import VariableTree
from openmdao.main.datatypes.api import Float
class Geometry(VariableTree):
"""Container of variables defining the mixer-ejector geometry"""
length = Float(10.0, units='ft', desc='Ejector width')
width = Float(6.0, units='ft', desc='Ejector width')
Apri = Float... |
"""File containing some simple helper functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def diag(diag_elements):
"""Function to create tensorflow diagonal matrix with input diagonal entries.
Args:
... |
from __future__ import print_function
import sys
import subprocess
import datetime
import time
import string
import argparse
import ConfigParser
from urllib import urlencode
import feedparser
from pyfiglet import Figlet
def clear_console():
'''
Clear previous screen.
'''
subprocess.call(['clear'])
def read_conf... |
import numpy as np
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from matplotlib import animation, cm
from numpy.linalg import inv
from mpl_toolkits.mplot3d import Axes3D
import tables as tb
import subprocess
from scipy.optimize import brentq
import sys
def quick_plot(input_filename=None, filename=None, sta... |
from django.db import models
from filebrowser.fields import FileBrowseField
class CommonSupport(models.Model):
likes = models.IntegerField(u'喜欢', default=0)
unlikes = models.IntegerField(u'不喜欢', default=0)
user = models.ForeignKey('authentication.Account', verbose_name=u'创建人', null=True)
create_at = mod... |
import argparse
import asyncio
import logging
import json
import time
import random
from urllib.parse import urlparse
from .proto import Client
from .exceptions import Draining
from .packets import Inserted
log = logging.getLogger(__name__)
class CallingError(Exception):
"""We tried to put a task, but not sure if i... |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'pandas',
]
setup(name='genedataset',
version='1.0.0a4',
description='Store and access gene expression datasets... |
from __future__ import absolute_import, print_function
import re
from time import time, mktime
import datetime
from .relativedelta import relativedelta
search_re = re.compile(r'^([^-]+)-([^-/]+)(/(.*))?$')
only_int_re = re.compile(r'^\d+$')
any_int_re = re.compile(r'^\d+')
star_or_int_re = re.compile(r'^(\d+|\*)$')
__a... |
import csv
import sys
import urllib
if len(sys.argv) < 1:
print "Usage: %s <inputfile csv>" % sys.argv[0]
sys.exit(1)
PEOPLE_FILE = sys.argv[1]
people = []
headers = []
col_name = 'image_search'
with open(PEOPLE_FILE, 'rb') as f:
rows = csv.reader(f, delimiter=',')
headers = next(rows, None) # remove he... |
"""
Django settings for Internet_store project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_literals
import enviro... |
def is_prime_fast(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
k = 6
while k-1 < n ** 0.5:
if n % (k - 1) == 0 or n % (k+1) == 0:
return False
k += 6
return True |
from webnews import api
class WebnewsObject(object):
"""
This object is the parent object for all webnews objects
"""
def __init__(self, api_val):
"""
init
:param api_val: The api key or api object to use
:return:
"""
if type(api) == api.APINonSingle or ty... |
import numpy as np
from abc import ABCMeta, abstractmethod
from ezclimate.damage_simulation import DamageSimulation
from ezclimate.forcing import Forcing
class Damage(object, metaclass=ABCMeta):
"""Abstract damage class for the EZ-Climate model.
Parameters
----------
tree : `TreeModel` object
provides the tree st... |
import unittest
from os.path import abspath, join, exists
from modipyd.utils import compile_python_source
from modipyd.module import ModuleCode, compile_source, \
collect_module_code, \
read_module_code
from tests import TestCase, FILES_DIR
class TestModipydModuleCo... |
'''
Created by auto_sdk on 2015.09.11
'''
from top.api.base import RestApi
class ItemImgUploadRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.id = None
self.image = None
self.is_major = None
self.num_iid = None
self.position = None
def geta... |
from wiktionaryparser import WiktionaryParser
import sys
import json
parser = WiktionaryParser()
entries = parser.fetch(sys.argv[1], sys.argv[2])
print(json.dumps(entries)) |
class CalendarEntry(object):
def __init__(self, title, description, due_date):
self.entry_title = title
self.entry_description = description
self.entry_due_date = due_date
def __str__(self):
return "\tTitle: " + self.entry_title + "\n\tDescription: " + self.entry_description + "\... |
import pytz
from unittest import mock
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.test import TestCase, RequestFactory
from django.utils import timezone
from snippets.tests.f... |
def is_leap(year):
"""
For a year to be a leap year three things criterias need to be looked at.
1. The year is evenly divisible by four.
2. If the year can be divided by 100 it is not a leap year, unless it can
also be divided by 400.
"""
leap = False
if year % 4 == 0:
leap = True
if year % 4 == 0 and... |
import os
import sys
import vim
def main():
vim_dir = sys.argv[1]
install_dir = os.path.join(vim_dir, 'vimapt/install')
file_list = []
for f in os.listdir(install_dir):
if os.path.isfile(os.path.join(install_dir, f)) and not os.path.basename(f).startswith('.'):
file_list.append(f)
... |
from app.app import create_app
from app.models import Attorney, Organization
import datetime
import pytest
import os
from selenium import webdriver
os.environ["MONGOLAB_URI"] = "mongodb://localhost/honorroll"
def base_url(live_server):
return live_server.url()
@pytest.fixture(scope='session')
def app(request):
... |
import _plotly_utils.basevalidators
class TracerefValidator(_plotly_utils.basevalidators.IntegerValidator):
def __init__(
self, plotly_name="traceref", parent_name="scattergl.error_x", **kwargs
):
super(TracerefValidator, self).__init__(
plotly_name=plotly_name,
parent_na... |
"""Commands supported by the Earth Engine command line interface.
Each command is implemented by extending the Command class. Each class
defines the supported positional and optional arguments, as well as
the actions to be taken when the command is executed.
"""
from __future__ import print_function
from six.moves impo... |
from setuptools import setup
from versioneer import get_cmdclass, get_version
def readme():
with open('README.rst') as f:
return f.read()
setup(name='vibe-analyser',
version=get_version(),
cmdclass=get_cmdclass(),
description='A vibration analysis and data acquisition suite for the rpi',
... |
from django.shortcuts import render,render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from tools.dbcon import *
from online.models import User
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def isflag(req)... |
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
step = [0] * n
visited = [False] * n
nodes = [0]
visited[0] = True
while nodes:
i = nodes[0]
nodes = nodes[1:]... |
"""XML Parsing package
At the moment it's really limited,
but it does the basics, and the rest
is mostly just a matter of fiddling
about with Unicode and CharacterType
support. There is only very minimal
support for Reference types, basically
we note that a Reference exists, but
don't do any further processing of it.
... |
import asynchat
import contextlib
import errno
import glob
import logging
import os
import random
import socket
import sys
import time
import traceback
import warnings
from datetime import datetime
try:
import pwd
import grp
except ImportError:
pwd = grp = None
try:
from OpenSSL import SSL # requires "... |
deps = dict()
deps[('subtype','wind')] = [dict(sector='energy',service='grid',type='wind',basis='weather')]
deps[('subtype','thunder')] = [dict(sector='energy',service='grid',subtype='thunder',basis='weather')]
deps[('subtype','snowstorm')] = [dict(sector='transport',service='roads',type='snowstorm',basis='weather'),
... |
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS ... |
''' Puntuation module '''
from colorama import Fore
from karmaserver.data.models import db
class Puntuation(db.Model):
''' Puntuation class implementation '''
observation_id = db.Column(db.String(64), db.ForeignKey('observation._id'), primary_key=True)
positive = db.Column(db.Integer)
negative = db.Colu... |
from typing import TYPE_CHECKING
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Optional
from azure.core.credentials import TokenCredential
from ._configuration import Custo... |
from django.db import IntegrityError
from django.test import Client
from django.core.urlresolvers import reverse
from base import BaseTestCase
from comments.models import CustomUser, Site, Thread, Comment
class CustomUserManagerTestCase(BaseTestCase):
def test_customusermanager_create_user_succeeds(self):
e... |
"""
Functions that construct stable closed loop control systems. Many of the
methods here are adapted from Digital Control: A State-Space Approach and
accompanying courses at URI.
Requires numpy, scipy, control
"""
from __future__ import print_function
import control_poles
import control
import numpy as np
from numpy i... |
import sys, tempfile, shlex, glob, os
from subprocess import *
from collections import defaultdict
_author="Sebastian Szpakowski"
_date="2011/09/14"
_version="Version 1"
class MothurCommand():
def __init__(self):
self.name = ""
self.input_files = dict()
self.output_files = dict()
self.args = dict()
self.anno... |
import api_utilities
import networkx as nx
import matplotlib.pyplot as plt
def make_group_tree(identifier,idtype='doi',level=0,maxlevel=2):
'''Returns a networkX graph based on papers available in the database.
Give a doi, or a uri if the keyword argument idtype = 'uri'
Example:
-------
import citat... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template("home.html")
@app.route('/about/')
def about():
return render_template("about.html")
if __name__ == '__main__':
app.run() |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-visits',
version='0.1',
packages=['visits'],
include_package_data=True,
license='MIT Li... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='category',
name='index2',
field=models.Inte... |
class AbstractPrinter(object):
def printResults(self, operation):
pass
class ConsolePrinter(AbstractPrinter):
def printResults(self, operation):
operationName = type(operation).__name__
if operationName == 'CountNumberOfElements':
self.CountNumberOfElementsPrinter( operation ... |
from datetime import date
from workalendar.tests import GenericCalendarTest
from workalendar.america import Brazil, BrazilSaoPauloState
from workalendar.america import BrazilSaoPauloCity
from workalendar.america import Colombia
from workalendar.america import Mexico, Chile, Panama
class BrazilTest(GenericCalendarTest):... |
import sys, os
from datetime import datetime
projpath = os.path.abspath('..')
sys.path.append(projpath)
extensions = ['sphinx.ext.autodoc']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = 'django-slow-log'
copyright = u'2010 Jason Moiron'
version = '0.1'
version = None
for line in ... |
"""Implementations of resource abstract base class receivers."""
import abc
class ResourceReceiver:
"""The resource receiver is the consumer supplied interface for receiving notifications pertaining to new, updated or deleted ``Resource`` objects."""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def n... |
"""Module for the Sticky cog."""
import asyncio
import contextlib
import logging
from typing import Any, Dict, Optional, Union
import discord
from redbot.core import Config, checks, commands
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import ReactionPredicate
UNIQUE_ID =... |
from collections import namedtuple
def namedtuplefetchall(cursor):
"""Return all rows from a cursor as a namedtuple"""
desc = cursor.description
nt_result = namedtuple('Result', [col[0] for col in desc])
return [nt_result(*row) for row in cursor.fetchall()] |
"""Handle specific queries.
This module handles questies of type /<collection>/<id> where we respond with a
specific document. We can also respond with a group of document, in the case of
a request to the special keyword 'latest' - /<collection>/latest. These have no
pagination, as the 'latest' items can change quite f... |
from collections import defaultdict
from functools import partial
import unittest
from repeated_test import tup, WithTestClass
from sigtools._util import funcsigs
__all__ = [
'conv_first_posarg',
'transform_exp_sources', 'transform_real_sources',
'SignatureTests', 'Fixtures', 'tup'
]
def conv_first_posa... |
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
from django.template import RequestContext, loader
from django_translate.services import trans as _, transchoice
def hello(request):
return render_to_response("hello.html", context=RequestContext(request))
def apples(reques... |
"""
Example of creating a radar chart (a.k.a. a spider or star chart) [1]_.
Although this example allows a frame of either 'circle' or 'polygon', polygon
frames don't have proper gridlines (the lines are circles instead of polygons).
It's possible to get a polygon grid by setting GRIDLINE_INTERPOLATION_STEPS in
matplot... |
from .added_loss_term import AddedLossTerm
class InducingPointKernelAddedLossTerm(AddedLossTerm):
def __init__(self, variational_dist, prior_dist, likelihood):
self.prior_dist = prior_dist
self.variational_dist = variational_dist
self.likelihood = likelihood
def loss(self, *params):
... |
"""
Runs Bowtie on single-end or paired-end data.
"""
import optparse, os, shutil, sys, tempfile
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
#Parse Command Line
parser = optparse.OptionParser()
parser.add_option('', '--threads', dest='threads', help='The number o... |
import inspect
import os
import re
import textwrap
def remove_indent(text, include_firstline=False):
"""Removes leading whitespace from the provided text.
Removes largest amount of leading whitespaces that is shared amongst all of the selected lines.
Parameters
----------
text : str or list of str
... |
def a_kv(n):
return n*n*(-1)**n
def sumkv(n):
return sum(map(a_kv, range(1, n+1)))
def mysum(n):
if (n % 2) == 0:
k = n / 2
print(2*k*k+k)
else:
k = (n+1) / 2
print(-2*k*k+k)
print(sumkv(1))
print(sumkv(2))
print(sumkv(3))
print(sumkv(4))
mysum(1)
mysum(2)
mysum(3)
mysum(4... |
from __future__ import print_function
import sys
from graph import make
from graph import GraphException
from timer import Timer
def main():
if len(sys.argv) == 4:
try:
filename = str(sys.argv[1])
# print(sys.argv)
timer = Timer()
graph = make(filename)
... |
from numpy import *
def Hasofer(G, u, Tinv, k, delta, sigma, inpt, otpt):
values = [Tinv(u)]
values.extend(pretaylorseries(u, Tinv, delta*sigma, inpt))
out = iter(G(values))
beta_t = out.next()
G2 = lambda x: out.next()
grad_g = taylorseries(G2, u, Tinv, delta*sigma, inpt, otpt).transpose()
... |
from grow.pods import pods
from grow.pods import storage
from grow.testing import testing
import unittest
import webob.exc
class RoutesTest(unittest.TestCase):
def setUp(self):
self.maxDiff = None
self.dir_path = testing.create_test_pod_dir()
self.pod = pods.Pod(self.dir_path, storage=storage.FileStorage)... |
from .linked_service import LinkedService
class AzureStorageLinkedService(LinkedService):
"""The storage account linked service.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param connect_via: Th... |
"""
:mod:`led`
==================
Created by hbldh <henrik.blidh@nedomkull.com>
Created on 2016-04-02
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import time
from pymetawear.client import MetaWearClient
address_1 = 'D1:75:74:0B:59:1F'
address_2 = 'F1:... |
import smtplib
from email.message import EmailMessage
import warnings
import __main__ as main
import os
import traceback
import socket
_username = None
_password = None
_destination = None
def set_credentials(username, password):
if not isinstance(username, str):
raise TypeException("Username must be a stri... |
"""Helper proxy to the state object."""
from flask import current_app
from werkzeug.local import LocalProxy
current_circulation = LocalProxy(
lambda: current_app.extensions['invenio-circulation']
)
"""Helper proxy to circulation state object.""" |
from rest_framework import viewsets
from .serializers import *
from .models import *
class GermanLemmaViewSet(viewsets.ModelViewSet):
queryset = GermanLemma.objects.all()
serializer_class = GermanLemmaSerializer
class ForeignLemmaViewSet(viewsets.ModelViewSet):
queryset = ForeignLemma.objects.all()
seri... |
import abc
import pygame
class AbstractWidget(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self.rect = None
def is_mouse_over(self):
xmouse, ymouse = pygame.mouse.get_pos()
xmouse_over = self.rect.left <= xmouse <= self.rect.right
ymouse_over = self.rect.top <= ym... |
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 SPC values"""
n = Decimal("2000000... |
"""
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk... |
class ThemeManager (object):
def __init__(self):
self.main_background_colour = .85, .85, .85
self.main_text_colour = .31, .31, .31
self.main_bar_colour = .85,.85,.85
self.main_tint_colour = .31,.31,.31
self.main_title_text_colour = .31,.31,.31
self.running_cell_background_colour = .1, .18, 1.0
self.runni... |
import logging
import tornado.escape
import tornado.ioloop
import tornado.web
import os.path
import uuid
from tornado.concurrent import Future
from tornado import gen
from tornado.options import define, options, parse_command_line
define("port", default=8888, help="run on the given port", type=int)
define("debug", defa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.