code stringlengths 2 1.05M | repo_name stringlengths 5 104 | path stringlengths 4 251 | language stringclasses 1
value | license stringclasses 15
values | size int32 2 1.05M |
|---|---|---|---|---|---|
import math
import theano.tensor as T
# ----------------------------------------------------------------------------
# this is all taken from the parmesan lib
c = - 0.5 * math.log(2*math.pi)
def log_bernoulli(x, p, eps=1e-5):
"""
Compute log pdf of a Bernoulli distribution with success probability p, at valu... | kuleshov/deep-learning-models | models/distributions/distributions.py | Python | mit | 2,861 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-06-27 07:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('posts', '0020_auto_20160627_0139'),
]
operations = [
migrations.RemoveFi... | iharsh234/eElectronics | posts/migrations/0021_auto_20160627_1326.py | Python | mit | 580 |
import time
from multiprocessing import Value
import pytest
from dash import Dash, Input, Output, State, callback_context, html, dcc, dash_table
from dash.exceptions import PreventUpdate
def test_cbmt001_called_multiple_times_and_out_of_order(dash_duo):
app = Dash(__name__)
app.layout = html.Div([html.Butto... | plotly/dash | tests/integration/callbacks/test_multiple_callbacks.py | Python | mit | 18,497 |
import unittest
from os import path
class RepoFiles(unittest.TestCase):
FILES = [
['./Dockerfile', './docker/Dockerfile'],
['./docker-compose.yml', './docker/docker-compose.yml'],
['./.env_sample'],
['./.gitignore'],
['./CHANGELOG.md'],
['./CODE_OF_CONDUCT.md'],
... | sendgrid/python-http-client | tests/test_repofiles.py | Python | mit | 1,039 |
def get_service(context):
return context.services["emulator"]
def get_data(context):
return get_service(context).data
def get_search(context):
return get_service(context).data.search
def get_system(key, context):
return get_service(context).data.systems[key]
def get_systems(context):
return ... | dstenb/pylaunchr-emulator | emulator/utils.py | Python | mit | 600 |
"""
Module for adding stimulations to networks
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from numbers import Number
try:
basestrin... | Neurosim-lab/netpyne | netpyne/network/stim.py | Python | mit | 10,067 |
import src.executor as executor
import src.dqn as dqn
import src.game_data as game_data
import src.graph as graph
import src.environment as environment
import numpy as np
import unittest
class TestIntegration(unittest.TestCase):
def setUp(self):
self.executor = executor.Executor()
self.dqn = dqn.... | escoboard/dqn | test/test_integration.py | Python | mit | 2,279 |
# -*- coding: utf-8 -*-
'''
canteen model tests
~~~~~~~~~~~~~~~~~~~
tests canteen's data modelling layer.
:author: Sam Gammon <sam@keen.io>
:copyright: (c) Keen IO, 2013
:license: This software makes use of the MIT Open Source License.
A copy of this license is included as ``LICENSE.md`` in
... | mindis/canteen | canteen_tests/test_model/__init__.py | Python | mit | 1,361 |
from bibliopixel import *
from bibliopixel.animation import BaseAnimation, AnimationQueue, OffAnim
from util import *
from static_objects import *
import loader
import config
import status
import traceback
import globals
class BPManager:
def __init__(self, off_timeout):
self.driver = []
... | ManiacalLabs/PixelWeb | pixelweb/bpmanager.py | Python | mit | 11,336 |
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class TModel(models.Model):
name = models.CharField(max_length=200)
test = models.OneToOneField(
'self',
null=True,
blank=True,
related_name='related_test_mo... | shubhamdipt/django-autocomplete-light | test_project/select2_one_to_one/models.py | Python | mit | 647 |
import pytest
from aiohttp_json_api.common import JSONAPI_CONTENT_TYPE
class TestDocumentStructure:
"""Document Structure"""
@pytest.mark.parametrize(
'resource_type',
('authors', 'books', 'chapters', 'photos', 'stores')
)
async def test_response_by_json_schema(self, fantasy_client,
... | vovanbo/aiohttp_json_api | tests/integration/test_document_structure.py | Python | mit | 587 |
from collections import defaultdict
from collections import namedtuple
from itertools import izip
from enum import Enum
from tilequeue.process import Source
def namedtuple_with_defaults(name, props, defaults):
t = namedtuple(name, props)
t.__new__.__defaults__ = defaults
return t
class LayerInfo(named... | tilezen/tilequeue | tilequeue/query/common.py | Python | mit | 15,803 |
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
__all__ = ["book", "book_builder", "elements", "util"]
| m-wichmann/LimeTusk | limetusk/__init__.py | Python | mit | 148 |
import requests
from pprint import pprint
r = requests.get("http://pokeapi.co/api/v2/pokedex/1")
#pprint(r.json()["pokemon_entries"])
regpath = "regular/"
shinypath = "shiny/"
import os
for pkmn in r.json()["pokemon_entries"]:
id = str(pkmn["entry_number"])
name = pkmn["pokemon_species"]["name"]
for file in os.lis... | MarkSpencerTan/pokemaster_bot | img/pokemon/image_rename.py | Python | mit | 559 |
"""
Script that trains Sklearn singletask models on GDB7 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from sklearn.kernel_ridge impo... | ktaneishi/deepchem | examples/qm7/qm7_sklearn.py | Python | mit | 1,271 |
# Copyright (c) 2010-2014 Bo Lin
# Copyright (c) 2010-2014 Yanhong Annie Liu
# Copyright (c) 2010-2014 Stony Brook University
# Copyright (c) 2010-2014 The Research Foundation of SUNY
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
#... | mayli/DistAlgo | da/endpoint.py | Python | mit | 14,912 |
import qor
from scripts import ctf
class Mod(qor.Mod):
def __init__(self):
# set up specific things that engine needs to know about the mod
# possibly setting up customized gui, background music, theming, etc.
# include possible selections of things, and which customizations to
# en... | flipcoder/qor | bin/mods/example/__init__.py | Python | mit | 1,487 |
from __future__ import absolute_import, print_function, division
import operator
from petl.compat import text_type
from petl.util.base import Table, asindices, itervalues
from petl.transform.sorts import sort
def duplicates(table, key=None, presorted=False, buffersize=None, tempdir=None,
cache=Tru... | alimanfoo/petl | petl/transform/dedup.py | Python | mit | 15,217 |
from composite import *
from ensemble import *
from metrics import *
# from parametrization import *
from pdf import *
from utils import *
| aimalz/qp | qp/__init__.py | Python | mit | 145 |
from sqlalchemy import Column, ForeignKey, UniqueConstraint, String, Text
from sqlalchemy.orm import relationship
from sqlalchemy.orm import column_property, relationship, validates
from frt_server.common import CommonColumns
import frt_server.config
import hashlib
import string
import random
import os
from itsdange... | HPI-SWA-Lab/BP2016H1 | frt_server/user.py | Python | mit | 3,794 |
#!/usr/bin/env python
import sys
import os
import argparse
import h5py
import numpy
import shutil
import logging
import json
from skimage import morphology as skmorph
from scipy.ndimage import label
import traceback
from . import imio, agglo, morpho, classify, evaluate, app_logger, \
session_manager, pixel, feat... | jni/ray | ray/segmentation_pipeline.py | Python | mit | 18,742 |
# Generic tests for data structures
import builtins
import itertools as itools
import unittest
KEY_RANGE = range(10)
VALUE_RANGE = range(1000)
# Some random (key, value) pairs
map_data = (
(0, 764),
(3, 448),
(8, 760),
(7, 648),
(4, 307),
(9, 384),
(7, 682),
(5, 841),
(1, 152),
... | afbarnard/glowing-broccoli | src/tests.py | Python | mit | 10,294 |
'''
Created on Oct 31, 2011
@author: robertsj
'''
import abc
class Bundle(object):
'''
An abstract base class for representing bundles.
'''
__metaclass__ = abs.ABCMeta
def __init__(self):
'''
Constructor
'''
| robertsj/poropy | poropy/bundletools/bundle.py | Python | mit | 264 |
"""
Support for installing and building the "wheel" binary package format.
"""
from __future__ import absolute_import
import compileall
import csv
import errno
import functools
import hashlib
import logging
import os
import os.path
import re
import shutil
import stat
import sys
import tempfile
import warnings
from ba... | James-Firth/pip | pip/wheel.py | Python | mit | 31,114 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Roles in this namespace are meant to provide `Nginx <http://wiki.nginx.org/Main>`_ web server utility methods for Debian distributions.
'''
from provy.core import Role
from provy.more.debian.package.aptitude import AptitudeRole
class NginxRole(Role):
'''
This ro... | python-provy/provy | provy/more/debian/web/nginx.py | Python | mit | 7,202 |
from django.core.exceptions import ValidationError
from django.forms import UUIDField
import six
from django.utils.module_loading import import_string
from django.utils.translation import ugettext_lazy as _
from django_smalluuid import settings
class ShortUUIDField(UUIDField):
default_error_messages = {
... | adamcharnock/django-smalluuid | django_smalluuid/forms.py | Python | mit | 1,158 |
from collections import OrderedDict
from conans.paths import SimplePaths
from conans.client.output import Color
from conans.model.ref import ConanFileReference
from conans.model.ref import PackageReference
from conans.client.installer import build_id
import fnmatch
class Printer(object):
""" Print some specific... | mropert/conan | conans/client/printer.py | Python | mit | 12,165 |
import logging
import ConfigParser
from collections import namedtuple
# User Configuration Handler
class ConfigHandler:
# Some Config Constants
FILE_NAME = 'app.cfg'
FILE_MODE = 'wb'
CONSUMER_SECTION = 'Consumer Info'
ACCESS_SECTION = 'Access Info'
MENTION_SECTION = 'Mention Info'
CONSUMER_KEY = '... | Th3BFG/hex-note | HexNote/confighandler.py | Python | mit | 1,649 |
def ReadLines(filename):
content = []
with open(filename) as f:
content = [x.rstrip() for x in f.readlines()]
return content
| aawc/cryptopals | sets/1/challenges/common/read_lines.py | Python | mit | 136 |
from wdom.server import start
from wdom.document import set_app
from wdom.tag import Div, H1, Input
class MyElement(Div):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.h1 = H1(parent=self)
self.h1.textContent = 'Hello, WDOM'
self.input = Input(parent=se... | miyakogi/wdom | docs/guide/samples/wdom2.py | Python | mit | 526 |
#!/bin/python3
import sys
time = input().strip()
# 12AM = 00:00
# 12PM = 12:00
# 01PM = 13:00
meridian = time[-2:]
time = time[:-2]
hour, minute, second = time.split(":")
hour = int(hour, 10)
if meridian == "PM":
if hour != 12:
hour += 12
else:
if hour == 12:
hour = 0
print("{:0>2d}:{}:{}"... | costincaraivan/hackerrank | algorithms/warmup/python3/time_conversion.py | Python | mit | 351 |
""" Test suite for the cppext library.
The script can be executed on its own or incorporated into a larger test suite.
However the tests are run, be aware of which version of the package is actually
being tested. If the package is installed in site-packages, that version takes
precedence over the version in this proje... | mdklatt/cppext-python | test/test_cppext.py | Python | mit | 1,176 |
# flake8: noqa
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.is_published'
db.add_column('event_rsvp_event', 'is_published',
... | bitmazk/django-event-rsvp | event_rsvp/migrations/0008_auto__add_field_event_is_published.py | Python | mit | 7,470 |
# coding: utf-8
from numpy import matrix
from oneVsAll import oneVsAll
from numpy import loadtxt, savetxt
from predictOneVsAll import predictOneVsAll
def train():
num_labels = 34
print '... Training'
X = matrix(loadtxt('X.dat')) / 255.0
y = matrix(loadtxt('y.dat')).transpose()
the_lambda = 0.1
... | skyduy/zfverify | Verify-Manual-python/train/core/train.py | Python | mit | 950 |
#!/usr/bin/env python
import queue
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.size = 1
self.self_count = 1
def treeBuilder(nodeString):
nodeList = nodeString[1:-1].split(',')
nodeQueue = queue.Queue()
if nodeList... | eroicaleo/LearningPython | interview/leet/tree.py | Python | mit | 2,092 |
def tsvread(filename, delimiter = "\t", endline = "\n", **kwargs):
""" Parses tsv file to an iterable of dicts.
Args:
filename (str):
File to read. First line is considered header.
delimiter (str, Optional):
String used to mark fields in file. Defaults to '\\t'
... | btoth/utility | tsvio.py | Python | mit | 1,931 |
"""
Django settings for ProgrammerCompetencyMatrix project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.joi... | FiaDot/programmer-competency-matrix | ProgrammerCompetencyMatrix/settings.py | Python | mit | 2,486 |
"""Common settings and globals."""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
from os import environ
# Normally you should not import ANYTHING from Django directly
# into your settings, but ImproperlyConfigured is an exception.
from django.core.exceptions import ImproperlyConf... | gfavre/beyondthewall.ch | beyondthewall/beyondthewall/settings/base.py | Python | mit | 7,931 |
from wodcraft.api import resources
# Routing
def map_routes(api):
api.add_resource(resources.Activity,
'/api/v1.0/activities/<int:id>',
endpoint='activity')
api.add_resource(resources.Activities,
'/api/v1.0/activities',
endpoi... | the-gigi/wod-craft-server | wodcraft/api/routes.py | Python | mit | 1,064 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Filename : video.py
# Author : Kim K
# Created : Fri, 29 Jan 2016
# Last Modified : Sun, 31 Jan 2016
from sys import exit as Die
try:
import sys
import cv2
from colordetection import ColorDetector
except ImportError as err:
Die(err)
... | muts/qbr | src/video.py | Python | mit | 4,872 |
#!/usr/bin/python
"""
Author: Mohamed K. Eid (mohamedkeid@gmail.com)
Description: stylizes an image using a generative model trained on a particular style
Args:
--input: path to the input image you'd like to apply a style to
--style: name of style (found in 'lib/generators') to apply to th... | mohamedkeid/Feed-Forward-Style-Transfer | src/test.py | Python | mit | 3,177 |
"""Implementations of locale abstract base class objects."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and include no... | mitsei/dlkit | dlkit/abstract_osid/locale/objects.py | Python | mit | 32,414 |
from django.contrib import admin
from feedhoos.worker.models.entry import EntryModel
from feedhoos.finder.models.feed import FeedModel
from feedhoos.reader.models.bookmark import BookmarkModel
from feedhoos.folder.models.folder import FolderModel
class EntryModelAdmin(admin.ModelAdmin):
list_display = ('id', "fee... | 38elements/feedhoos | feedhoos/worker/admin.py | Python | mit | 894 |
########
"""
This code is open source under the MIT license.
Its purpose is to help create special motion graphics
with effector controls inspired by Cinema 4D.
Example usage:
https://www.youtube.com/watch?v=BYXmV7fObOc
Notes to self:
Create a simialr, lower poly contorl handle and
perhaps auto enable x-ray/bounding... | kmeirlaen/Blender_Effectors | effector.py | Python | mit | 18,791 |
#! /usr/bin/env python
import flickr_api, pprint, os, sys,argparse,json,csv
flickr_api.set_keys(api_key = '52182e4e29c243689f8a8f45ee2939ae', api_secret = 'a6238b15052797dc')
def DownloadSource(SourceList, PhotosetTitle):
for url in SourceList:
os.system("wget --append-output=download... | sharathchandra92/flickrapi_downloadfavorites | flickrdownload.py | Python | mit | 3,886 |
import sigopt.cli.commands.cluster
import sigopt.cli.commands.config
import sigopt.cli.commands.experiment
import sigopt.cli.commands.init
import sigopt.cli.commands.local
import sigopt.cli.commands.version
import sigopt.cli.commands.training_run
from .base import sigopt_cli
| sigopt/sigopt-python | sigopt/cli/commands/__init__.py | Python | mit | 277 |
import json
from sqlalchemy import create_engine, inspect, Table, Column
import pandas as pd
from ilxutils.args_reader import read_args
from ilxutils.scicrunch_client import scicrunch
import sys
import time
from ilxutils.interlex_sql import interlex_sql
import re
from collections import defaultdict
import requests as r... | tgbugs/pyontutils | ilxutils/tests/elastic_test.py | Python | mit | 2,991 |
#!/bin/python
"""Fixes some common spelling errors. Might I add that this is one of the
reasons why having a website is useful?
"""
import os
import sys
def levenshtein_ratio(s1, s2, cutoff=None):
max_len = max(len(s1), len(s2))
if cutoff is not None:
cutoff = int(math.ceil((1.0 - cutoff) * max_len) +... | bskari/park-stamper | parks/scripts/initialize_db/fix_spelling.py | Python | mit | 5,292 |
"""
Tahmatassu Web Server
~~~~~~~~~~~~~~~~~~~~~
HTTP-status codes containing module
:copyright: (c) 2014 by Teemu Puukko.
:license: MIT, see LICENSE for more details.
"""
from werkzeug.wsgi import LimitedStream
class StreamConsumingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(se... | puumuki/tahmatassu-api | tahmatassu-server/middlewares.py | Python | mit | 813 |
from setuptools import setup
readme = open('README.md').read()
setup(name='HDFserver',
version='0.1',
author='Yohannes Libanos',
license='MIT',
description='REST service for HDF5 data stores',
py_modules=['HDFserver'],
long_description=readme,) | yohannesHL/HDFserver | setup.py | Python | mit | 281 |
import copy
class ArtifactEmulator:
def __init__(self, random_str, ctx, base_url):
self._random_str = random_str
self._ctx = ctx
self._artifacts = {}
self._artifacts_by_id = {}
self._files = {}
self._base_url = base_url
self._portfolio_links = {}
def cr... | wandb/client | tests/utils/artifact_emu.py | Python | mit | 5,987 |
import warnings
from collections import defaultdict
from queryset import QuerySet, QuerySetManager
from queryset import DoesNotExist, MultipleObjectsReturned
from queryset import DO_NOTHING
from mongoengine import signals
import sys
import pymongo
from bson import ObjectId
import operator
from functools import part... | newvem/mongoengine | mongoengine/base.py | Python | mit | 50,511 |
import os
import sys
import numpy as np
import properties
svm = properties.svm_path
model = properties.svm_model_path
output = properties.svm_output_path
config = []
config.append("bsvm-train.exe")
config.append("bsvm-predict.exe")
t = " -t 1 "
c = " -c 1 "
m = " -m 1024 "
w0 = " -w0 0.0384 "
w1 = " -w1 1.136 "
w2 = "... | sureshbvn/nlpProject | SVM_A/svm.py | Python | mit | 891 |
import pandas as pd
import os
import subprocess as sub
import re
import sys
from Bio import SeqUtils
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER_RELEASE69/genbank')
# ['DbxRefs','Description','FeaturesNum','GenomicID','Genomi... | sergpolly/Thermal_adapt_scripts | composition_analysis_Thermo.py | Python | mit | 11,114 |
import pandas as pd
df_ab = pd.DataFrame({'a': ['a_1', 'a_2', 'a_3'], 'b': ['b_1', 'b_2', 'b_3']})
df_ac = pd.DataFrame({'a': ['a_1', 'a_2', 'a_4'], 'c': ['c_1', 'c_2', 'c_4']})
print(df_ab)
# a b
# 0 a_1 b_1
# 1 a_2 b_2
# 2 a_3 b_3
print(df_ac)
# a c
# 0 a_1 c_1
# 1 a_2 c_2
# 2 a_4 c_4
... | nkmk/python-snippets | notebook/pandas_merge_join.py | Python | mit | 5,590 |
'''
Created on Apr 28, 2011
@author: Bartosz Alchimowicz
'''
############################
# Collection #
############################
class ScreenSpec(object):
def __init__(self):
self.children = []
def append(self, screen):
assert isinstance(screen, Screen)
self.children.append(screen)
re... | perfidia/screensketch | src/screensketch/screenspec/model.py | Python | mit | 7,161 |
try:
__version__ = __import__('pkg_resources').require('booleanOperations')[0].version
except Exception:
__version__ = 'unknown'
| moyogo/booleanoperations | Lib/booleanOperations/version.py | Python | mit | 137 |
import numpy
import chainer
from chainer.backends import cuda
from chainer import function_node
from chainer.utils import type_check
def _as_mat(x):
if x.ndim == 2:
return x
return x.reshape(len(x), -1)
def _ij_ik_il_to_jkl(a, b, c):
ab = chainer.functions.matmul(a[:, :, None], b[:, None, :]) ... | rezoo/chainer | chainer/functions/connection/bilinear.py | Python | mit | 8,648 |
__author__ = 'Emil E Nielsen'
start = 1
end = 17
for i in range (8):
for x in range(start, end):
print chr(x),
if x >= 128:
break
print "\n"
start = end + 1
end = start + 16 | EENielsen/school-python | ascii-tabel.py | Python | mit | 222 |
# A simple DOC file parser based on pyole
import os
import struct
import logging
import datetime
from pyole import *
class FIBBase(OLEBase):
wIdent = 0
nFib = 0
unused = 0
lid = 0
pnNext = 0
Flags1 = 0
fDot = 0
fGlsy = 0
fComplex = 0
fHasPic = 0
cQuickSaves = 0
fEncry... | z3r0zh0u/pyole | pydoc.py | Python | mit | 14,460 |
from setuptools import setup
from os.path import join as join_path
from os import walk
def files_in(package, directory):
paths = []
for root, dirs, files in walk(join_path(package, directory)):
for file in files:
paths.append(join_path(root, file)[(len(package) + 1):])
return paths
a... | LuRsT/datdash | setup.py | Python | mit | 825 |
import json
import os
from collections import OrderedDict
from difflib import unified_diff
import pytest
from dash.development._py_components_generation import generate_class
from dash.development.component_generator import reserved_words
from . import _dir, expected_table_component_doc
@pytest.fixture
def componen... | plotly/dash | tests/unit/development/test_generate_class.py | Python | mit | 4,761 |
# ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without rest... | diplomacy/research | diplomacy_research/models/policy/order_based/model.py | Python | mit | 28,290 |
"""
Django settings for sippa project.
Generated by 'django-admin startproject' using Django 1.10.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
i... | luissiqueira/sippa-no-api | sippa/settings.py | Python | mit | 4,223 |
# encoding: utf-8
from views import dogs, breeds, users
urls = [
('/dogs/', dogs.DogAPI.as_view('dog_api')),
('/user_dogs/', dogs.UserDogsAPI.as_view('user_dogs_api')),
('/breeds/', breeds.BreedAPI.as_view('breed_api')),
('/breed_dogs/', breeds.BreedDogsAPI.as_view('breed_dogs_api')),
('/users/', u... | gabrielecker/DogAdoption-Backend | project/urls.py | Python | mit | 467 |
import json
from unittest import TestCase
from mock import Mock, patch, create_autospec
class CommandTestCase(TestCase):
"""A TestCase for unit testing bot requests and responses.
To use it:
* provide your bot in *bot_class* (and optionally a config).
* use self.send_message inside your test ca... | venmo/slouch | slouch/testing.py | Python | mit | 1,912 |
import datetime
import requests
import numpy as np
import pandas as pd
import sys
# August 3, 2015: Updated the getNipa() method to accomodate possible differences in data availability for series in tables.
# Cleaned up and organized the code substantially.
class initialize:
def __init__(self,a... | letsgoexploring/beapy-package | beapy.py | Python | mit | 25,953 |
# vim:ts=4:sts=4:sw=4:expandtab
"""The public API of satori.events.
"""
import hashlib
import random
import traceback
from satori.objects import Object
from satori.events.misc import Namespace
from .dispatcher import Dispatcher
from .protocol import KeepAlive, Disconnect, Attach, Detach, Map, Unmap, Send, Receive
... | zielmicha/satori | satori.events/satori/events/api.py | Python | mit | 2,752 |
# Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
from types import StringType
from Bio.Alphabet import ProteinAlphabet
from Bio.Seq import... | NirBenTalLab/proorigami-cde-package | cde-root/usr/lib64/python2.4/site-packages/Bio/PDB/Polypeptide.py | Python | mit | 11,950 |
# This is an example of adding a custom plugin to Projeny
# If you uncomment this then initialize a new project (for eg. "prj -p MyProject -bf")
# Then after that completes there should be a new file at UnityProjects/MyProject/MyP-win/MyExampleFile.txt
#import mtm.ioc.Container as Container
#from mtm.ioc.Inject impor... | modesttree/Projeny | Source/prj/plugins/ExamplePlugin.py | Python | mit | 745 |
####
#
# This module allows for easy integration with Slack (https://slack.com/). The
# messages are sent via JSON over plaintext, so don't use them for transmitting
# anything sensitive.
#
####
## Imports
import json
import urllib2
####
#
# API Description
#
# These are all of the Slack API fields supported in this ... | univ-of-utah-marriott-library-apple/management_tools | management_tools/slack.py | Python | mit | 10,760 |
from __future__ import division
def run () :
import libtbx.load_env # import dependency
for module in libtbx.env.module_list :
print module.name
if (__name__ == "__main__") :
run()
| hickerson/bbn | fable/fable_sources/libtbx/command_line/list_modules.py | Python | mit | 194 |
from django.core.management.base import BaseCommand
from openkamer.verslagao import create_verslagen_algemeen_overleg
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('year', nargs='+', type=int)
parser.add_argument('--max', type=int, help='The max number of docum... | openkamer/openkamer | openkamer/management/commands/create_verslagen_ao.py | Python | mit | 553 |
"""group_mod tests."""
from unittest import TestCase
from pyof.v0x04.controller2switch.group_mod import GroupMod
from pyof.v0x04.common.action import (
ActionExperimenter, ActionSetField, ListOfActions)
from pyof.v0x04.common.flow_match import OxmClass, OxmOfbMatchField, OxmTLV
from pyof.v0x04.common.port import P... | kytos/python-openflow | tests/unit/v0x04/test_controller2switch/test_group_mod.py | Python | mit | 6,137 |
#-*- coding: utf-8 -*-
""" EOSS catalog system
Implementation of urthecast catalog access
https://developers.urthecast.com/sign-in
"""
__author__ = "Thilo Wehrmann, Steffen Gebhardt"
__copyright__ = "Copyright 2016, EOSS GmbH"
__credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"]
__license__ = "GPL"
__version__ = "1.0... | eoss-cloud/madxxx_catalog_api | catalog/manage/urthecastcatalog.py | Python | mit | 2,226 |
import sqlalchemy
class Connection(object):
def __init__(self, auth):
url = self._build_url(auth)
self.engine = sqlalchemy.create_engine(url, convert_unicode=True)
self.connection = None
self.transaction = None
def connect(self):
self.connection = self.engine.conn... | trackingwire/witchcraft | witchcraft/connection.py | Python | mit | 2,023 |
#dice guideline
from random import randint
#FOR program module
moduleName="Dice Module"
#moduleName="The Lusty Orc Dice Module"
#FOR dice rolls
#mulligan_yes_or_no=True not implemented
the_lowest_possible_roll=1
the_number_of_sides_on_a_die=6
the_number_of_rolls_in_a_set=4
reroll_if_equal_or_less=0
number_of_lowest_... | RZMC/dndCharGen | dice guideline.py | Python | mit | 7,477 |
import os,sys
#import ez_setup
#ez_setup.use_setuptools()
from setuptools import setup, find_packages
import numpy
from Cython.Build import cythonize
# not compatible with distribute
#from distutils.extension import Extension
#from Cython.Distutils import build_ext
version = '0.7.0'
README = os.path.join(os.path.di... | mizuy/seqtool | setup.py | Python | mit | 2,123 |
import _plotly_utils.basevalidators
class BgcolorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(self, plotly_name="bgcolor", parent_name="pie.hoverlabel", **kwargs):
super(BgcolorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/pie/hoverlabel/_bgcolor.py | Python | mit | 499 |
###############
### imports ###
###############
from fabric.api import cd, env, lcd, put, prompt, local, sudo
from fabric.contrib.files import exists
##############
### config ###
##############
local_app_dir = './flask_project'
local_config_dir = './config'
remote_app_dir = '/home/www'
remote_git_dir = '/home/git... | kaiocesar/automation-fab | fabfile.py | Python | mit | 4,325 |
from django.contrib import admin
from api_boilerplate.models import ApiKey
admin.site.register(ApiKey)
| kippt/django-api-boilerplate | api_boilerplate/admin.py | Python | mit | 105 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-24 22:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('samples', '0004_sample'),
]
operations = [
m... | gcrsaldanha/fiocruz | samples/migrations/0005_auto_20170424_1903.py | Python | mit | 1,172 |
# -*- coding:utf-8 -*-
import os
def split_screen():
val = os.system("xrandr --output HDMI1 --right-of VGA1 --auto")
def run_sensorcmd_web():
path = "/home/suyf/swork/git/sensorcmd-web/web/"
os.chdir(path)
val = os.system("./apprun.py")
def run_cas():
path = "/home/suyf/swork/git/cas/web/"
os.chdir(path)
val = ... | myyyy/wiki | shell/work_start.py | Python | mit | 791 |
"""
from https://codelab.interviewbit.com/problems/symmetry/
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def isSymm... | JuanCTorres/interview-prep-solutions | codelab/symmetric_trees.py | Python | mit | 694 |
from PyQt4 import QtGui, QtCore
from PyQt4 import uic
form_class = uic.loadUiType('logWindow.ui')[0]
class LogWindow(QtGui.QDialog, form_class):
def __init__(self, parent=None):
super(LogWindow, self).__init__(parent)
self.setup_ui()
def setup_ui(self):
self.setupUi(self)
se... | RaynoldKim/MyTrade | LogWindow.py | Python | mit | 394 |
import _plotly_utils.basevalidators
class DataValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="data", parent_name="layout.template", **kwargs):
super(DataValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/layout/template/_data.py | Python | mit | 8,076 |
from apscheduler.schedulers.blocking import BlockingScheduler
from manage import update_live_points, update_for_gw, update_test, update_epl_players
from tweetbot import TweetBot
sched = BlockingScheduler()
# @sched.scheduled_job('cron', day_of_week='wed-sun', hour='22', minute='50-59/1', timezone='America/New_York')
... | code247/FPL_FFC | jobs.py | Python | mit | 1,124 |
from __future__ import absolute_import, division, print_function
import warnings
import re
import py
import pytest
from _pytest.recwarn import WarningsRecorder
def test_recwarn_functional(testdir):
reprec = testdir.inline_runsource("""
import warnings
def test_method(recwarn):
warning... | MichaelAquilina/pytest | testing/test_recwarn.py | Python | mit | 10,978 |
from scudcloud.resources import Resources
from PyQt5 import QtCore
from PyQt5.QtCore import QUrl
from PyQt5.QtWebKit import QWebSettings
from PyQt5.QtWebKitWidgets import QWebView
class LeftPane(QWebView):
def __init__(self, window):
QWebView.__init__(self)
self.window = window
with open(... | raelgc/scudcloud | scudcloud/leftpane.py | Python | mit | 2,425 |
import urllib
import urllib2
import string
import json
import websocket
import thread
import time
#// Grab hitbox ip and socket id //////////////////#
site = "http://api.hitbox.tv/chat/servers.json?redis=true"
lines = json.load(urllib2.urlopen(site))#.read()
for line in lines:
ip = ".".join(line['server_ip'].sp... | cgwennap/pyHitBot | testsocket.py | Python | mit | 3,056 |
from octopy.utils import *
from ru.parallel.octotron.core.logic import Response
from ru.parallel.octotron.generators.tmpl import ReactionTemplate
from ru.parallel.octotron.generators.tmpl import ReactionAction as Reaction
def ReactsFromDict(reactions_dict):
res = []
for name, reaction in reactions_dict.items():
... | srcc-msu/octotron | octopy/react_wrapper.py | Python | mit | 1,761 |
import sys, os
from Grafo import Grafo
if __name__ == '__main__':
try:
arquivo = open('grafo_teste_listar.txt', 'r')
arquivo_saida = open('teste_listar.txt', 'w')
except IOError:
sys.stderr.write('Erro ao tentar ler ou criar o arquivo, verifique se estão válidos.\n')
sys.exit()... | Razborges/algGrafos | TrabalhoFinal/testes/teste_listar.py | Python | mit | 573 |
import mock
from st2tests.base import BaseActionTestCase
from runfolder_service import ArteriaRunfolderServiceAction
from tests.pack_test_utils import FakeResponse
class RunfolderServiceServiceTest(BaseActionTestCase):
action_cls = ArteriaRunfolderServiceAction
def test_get_state(self):
expected... | arteria-project/arteria-packs | tests/test_action_runfolder_service.py | Python | mit | 1,239 |
from keras_code import predict, models
import numpy as np
import os
import math
from PIL import Image
from keras import backend as K
from utilities.logging import print_n_log
import utilities.paths as paths
DRIVE = paths.get_drive()
def build_img(array):
array = np.squeeze(array)
# In Pixels
padding = 5
... | HaydenFaulkner/phd | visualisations/networks/activations.py | Python | mit | 3,664 |
import asyncio
from arq import create_pool
from arq.connections import RedisSettings
async def the_task(ctx):
print('running the task with id', ctx['job_id'])
async def main():
redis = await create_pool(RedisSettings())
# no id, random id will be generated
job1 = await redis.enqueue_job('the_task')
... | samuelcolvin/arq | docs/examples/job_ids.py | Python | mit | 1,073 |
from django.conf.urls import url
from Overlay import views
urlpatterns = [
url(r'^$',
views.main,
name='main'),
url(r'^checks/$',
views.checks,
name='checks'),
url(r'^results/$',
views.results,
name='results'),
url(r'^upload/$',
views.upload,
... | DalenWBrauner/FloridaDataOverlay | Website/Florida_Data_Overlay/Overlay/urls.py | Python | mit | 344 |
import itertools as it
from conference_scheduler.resources import Shape, Constraint
from conference_scheduler.lp_problem import utils as lpu
def _schedule_all_events(events, slots, X, summation_type=None, **kwargs):
shape = Shape(len(events), len(slots))
summation = lpu.summation_functions[summation_type]
... | PyconUK/ConferenceScheduler | src/conference_scheduler/lp_problem/constraints.py | Python | mit | 3,874 |
# 倒序排
a = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
print(a)
# 按成绩从高到低排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score)
print(L2)
# [('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)] | longze/my-cellar | web/articles/python/demo/09-sort.py | Python | mit | 322 |
from util import *
@responses.activate
def test_getters(client, dummy_data):
assert client.host() == dummy_data.host
assert client.api_host() == dummy_data.api_host
@responses.activate
def test_setters(client, dummy_data):
try:
client.host('host.nexmo.com')
client.api_host('host.nexmo.com'... | Nexmo/nexmo-python | tests/test_getters_setters.py | Python | mit | 627 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tracking', '0007_auto_20160313_1725'),
]
operations = [
migrations.AddField(
model_name='organization',
... | Heteroskedastic/Dr-referral-tracker | tracking/migrations/0008_adding_creation_modification_time.py | Python | mit | 1,984 |