repo_name
stringlengths
5
104
path
stringlengths
4
248
content
stringlengths
102
99.9k
amol-/depot
tests/base_ming.py
from __future__ import absolute_import import os import ming from ming import Session from ming.odm import ThreadLocalODMSession from ming import create_datastore from depot.fields.ming import DepotExtension mainsession = Session() DBSession = ThreadLocalODMSession(mainsession, extensions=(DepotExtension, )) database...
ztane/jaspyx
jaspyx/visitor/binop.py
from __future__ import absolute_import, division, print_function import ast from jaspyx.ast_util import ast_load, ast_call from jaspyx.visitor import BaseVisitor class BinOp(BaseVisitor): def visit_BinOp(self, node): attr = getattr(self, 'BinOp_%s' % node.op.__class__.__name__, None) attr(node.lef...
TheAspiringHacker/Asparserations
bootstrap/parser_gen.py
#!/usr/bin/python3 import argparse import collections import json import string import sys header_template = """ #ifndef ASPARSERATIONS_GENERATED_${class_name}_H_ #define ASPARSERATIONS_GENERATED_${class_name}_H_ #include <array> #include <map> #include <memory> #include <set> #include <utility> #include <vector> $h...
OpenBazaar/openbazaar-go
qa/smtp_notification.py
import requests import json import time import subprocess import re import os from collections import OrderedDict from test_framework.test_framework import OpenBazaarTestFramework, TestFailure from test_framework.smtp_server import SMTP_DUMPFILE class SMTPTest(OpenBazaarTestFramework): def __init__(self): ...
sourlows/pyagricola
src/field/node_item.py
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(s...
MahjongRepository/mahjong
mahjong/hand_calculating/yaku.py
import warnings class Yaku: yaku_id = None tenhou_id = None name = None han_open = None han_closed = None is_yakuman = None def __init__(self, yaku_id=None): self.tenhou_id = None self.yaku_id = yaku_id self.set_attributes() def __str__(self): return ...
jyi/ITSP
prophet-gpl/tools/libtiff-prepare-test.py
# Copyright (C) 2016 Fan Long, Martin Rianrd and MIT CSAIL # Prophet # # This file is part of Prophet. # # Prophet is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at y...
jgreener64/pdb-benchmarks
checkwholepdb/checkwholepdb.py
# Test which PDB entries error on PDB/mmCIF parsers # Writes output to a file labelled with the week import os from datetime import datetime from math import ceil from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser start = datetime.now() basedir = "." pdbl =...
hcrlab/access_teleop
cse481wi18/perception/src/perception/mock_camera.py
import rosbag from sensor_msgs.msg import PointCloud2 def pc_filter(topic, datatype, md5sum, msg_def, header): if datatype == 'sensor_msgs/PointCloud2': return True return False class MockCamera(object): """A MockCamera reads saved point clouds. """ def __init__(self): pass ...
eccles/lnxproc
lnxproc/vmstat.py
''' Contains Vmstat() class Typical contents of vmstat file:: nr_free_pages 1757414 nr_inactive_anon 2604 nr_active_anon 528697 nr_inactive_file 841209 nr_active_file 382447 nr_unevictable 7836 nr_mlock 7837 nr_anon_pages 534070 nr_mapped 76013 nr_file_pages 1228693 nr_dirty 21 nr_...
chrisdjscott/Atoman
atoman/gui/outputDialog.py
# -*- coding: utf-8 -*- """ The output tab for the main toolbar @author: Chris Scott """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import shutil import subprocess import copy import logging import math import functools import dateti...
pschanely/gunicorn
gunicorn/app/pasterapp.py
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import logging import os import pkg_resources import sys import ConfigParser from paste.deploy import loadapp, loadwsgi SERVER = loadwsgi.SERVER from gunicorn.app.base import Application fr...
mattiasgiese/squeezie
app/master.py
#!/usr/bin/env python from flask import Flask, jsonify, request, abort, render_template app = Flask(__name__) @app.route("/",methods=['GET']) def index(): if request.method == 'GET': return render_template('index.html') else: abort(400) @app.route("/devices",methods=['GET']) def devices(): if request.m...
nashby/sublime_config
new_file_syntax.py
''' Stores syntax file from last activated view and reuses this for a new view. @author: Oktay Acikalin <ok@ryotic.de> @license: MIT (http://www.opensource.org/licenses/mit-license.php) @since: 2011-03-05 @todo: Remove odd workaround below when/if "on_deactivated", "on_new" and "on_activated" events get fire...
adexin/Python-Machine-Learning-Samples
Other_samples/Gradient_check/gradient_check.py
import numpy as np from Other_samples.testCases import * from Other_samples.Gradient_check.gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, \ gradients_to_vector def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(...
wright-group/WrightTools
WrightTools/data/_axis.py
"""Axis class and associated.""" # --- import -------------------------------------------------------------------------------------- import re import numexpr import operator import functools import numpy as np from .. import exceptions as wt_exceptions from .. import kit as wt_kit from .. import units as wt_units...
itsmemattchung/speedcurve.py
docs/conf.py
# -*- coding: utf-8 -*- # # Speedcurve.py documentation build configuration file, created by # sphinx-quickstart on Mon Nov 16 12:29:28 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file....
lbryio/lbry
lbry/lbry/extras/daemon/analytics.py
import asyncio import collections import logging import aiohttp import typing from lbry import utils from lbry.conf import Config from lbry.extras import system_info ANALYTICS_ENDPOINT = 'https://api.segment.io/v1' ANALYTICS_TOKEN = 'Ax5LZzR1o3q3Z3WjATASDwR5rKyHH0qOIRIbLmMXn2H=' # Things We Track SERVER_STARTUP = 'Se...
akrherz/iem
htdocs/plotting/auto/scripts200/p215.py
"""KDE of Temps.""" import calendar from datetime import date, datetime import pandas as pd from pyiem.plot.util import fitbox from pyiem.plot import figure from pyiem.util import get_autoplot_context, get_sqlalchemy_conn from pyiem.exceptions import NoDataFound from matplotlib.ticker import MaxNLocator from scipy.sta...
inducer/codery
pieces/admin.py
from django.contrib import admin from pieces.models import ( PieceTag, Piece, Venue, Study, Keyword, PieceToStudyAssociation) # {{{ studies class KeywordInline(admin.TabularInline): model = Keyword extra = 10 class StudyAdmin(admin.ModelAdmin): list_display = ("id", "name", "st...
mburakergenc/Malware-Detection-using-Machine-Learning
cuckoo/modules/processing/platform/linux.py
# Copyright (C) 2010-2013 Claudio Guarnieri. # Copyright (C) 2014-2016 Cuckoo Foundation. # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. import os import logging import datetime import re import dateutil.parser from lib.cuckoo.common.abstrac...
tmetsch/suricate
suricate/ui/api.py
# coding=utf-8 """ An API used by the UI and RESTful API. """ from bson import ObjectId __author__ = 'tmetsch' import collections import json import pika import pika.exceptions as pikaex import uuid from suricate.data import object_store from suricate.data import streaming TEMPLATE = ''' % if len(error.strip()) >...
lucianp/dotfiles
link/.vim/ftplugin/orgmode/plugins/Todo.py
# -*- coding: utf-8 -*- import vim import itertools as it from orgmode._vim import echom, ORGMODE, apply_count, repeat, realign_tags from orgmode import settings from orgmode.liborgmode.base import Direction from orgmode.menu import Submenu, ActionEntry from orgmode.keybinding import Keybinding, Plug from orgmode.exc...
GarlandDA/bad-boids
bad_boids/test/test_boids.py
import yaml import os from ..boids import Boids from nose.tools import assert_equal import random import numpy as np from unittest.mock import patch import unittest.mock as mock def test_Boids(): flock = Boids(boid_number=10,move_to_middle_strength=0.1,alert_distance=100,formation_flying_distance=900,formation_fly...
TangentMicroServices/BuildService
buildservice/urls.py
from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from api.views import router urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), url(r'^ui/', include('ui.urls', namespace...
perfectsearch/sandman
test/buildscripts/textui_prompt_test.py
# # $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $ # # Proprietary and confidential. # Copyright $Date:: 2011#$ Perfect Search Corporation. # All rights reserved. # import unittest, os, sys, StringIO from textui.prompt import * from nose.tools import istest, nottest from nose.plugins.attrib import...
beallej/event-detection
WebApp/EventDetectionWeb.py
import sys; import os sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) from flask import Flask, render_template, request, redirect import subprocess from Utils import subprocess_helpers from Utils.DataSource import * app = Flask(__name__) dataSource = DataSource() def launch_prepr...
naomi-/exploration
Enemy.py
import pygame from pygame.locals import * import constants as c class Enemy: def __init__(self, x, y, health, movement_pattern, direction, img): self.x = x self.y = y self.health = health self.movement_pattern = movement_pattern self.direction = direction ...
Lothiraldan/ZeroServices
tests/utils.py
import asyncio try: from unittest.mock import Mock, create_autospec except ImportError: from mock import Mock, create_autospec from uuid import uuid4 from functools import wraps from copy import copy from unittest import TestCase as unittestTestCase from zeroservices.exceptions import ServiceUnavailable from...
sprymix/parsing
parsing/ast.py
""" The classes `Token` and `Nonterm` can be subclassed and enriched with docstrings indicating the intended grammar, and will then be used in the parsing as part of the abstract syntax tree that is constructed in the process. """ from __future__ import annotations class Symbol: pass class Nonterm(Symbol): ...
kollad/turbo-ninja
tools/bootstrap.py
from distutils.dir_util import copy_tree, remove_tree import os import shutil def _copy_function(source, destination): print('Bootstrapping project at %s' % destination) copy_tree(source, destination) def create_app(): cwd = os.getcwd() game_logic_path = os.path.join(cwd, 'game_logic') game_app_...
levilucio/SyVOLT
t_core/main.py
from tc_python.arule import ARule from t_core.messages import Packet from HA import HA from HAb import HAb from HTopClass2TableLHS import HTopClass2TableLHS from HTopClass2TableRHS import HTopClass2TableRHS r1 = ARule(HTopClass2TableLHS(), HTopClass2TableRHS()) p = Packet() p.graph = HA() p1 = r1.packet_in(p...
tysonholub/twilio-python
twilio/rest/video/v1/room/room_participant/room_participant_subscribed_track.py
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base...
MaciCrowell/TCGA_DataScience
glm.py
"""Interface to rpy2.glm Copyright 2012 Allen B. Downey License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html """ import rpy2.robjects as robjects r = robjects.r def linear_model(model, print_flag=True): """Submits model to r.lm and returns the result.""" model = r(model) res = r.lm(model) if print...
thonkify/thonkify
src/lib/future/backports/html/__init__.py
""" General functions for HTML manipulation, backported from Py3. Note that this uses Python 2.7 code with the corresponding Python 3 module names and locations. """ from __future__ import unicode_literals _escape_map = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;'} _escape_map_full = {ord('&'): '&amp;', or...
renatopp/psi-robotics
psi/engine/camera.py
# ============================================================================= # Federal University of Rio Grande do Sul (UFRGS) # Connectionist Artificial Intelligence Laboratory (LIAC) # Renato de Pontes Pereira - renato.ppontes@gmail.com # ============================================================================...
joedeller/pymine
forloop.py
#! /usr/bin/python # Joe Deller 2014 # Using for loops # Level : Beginner # Uses : Libraries, variables, operators, loops # Loops are a very important part of programming # The for loop is a very common loop # It counts from a starting number to a finishing number # It normally counts up in ones, but you can count u...
BoboTiG/python-mss
mss/factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) ->...
jiadaizhao/LeetCode
0301-0400/0394-Decode String/0394-Decode String.py
class Solution: def decodeString(self, s: str) -> str: St = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '[': St.append([num, curr]) num = 0 curr = '' ...
pombredanne/metamorphosys-desktop
metamorphosys/META/src/Python27Packages/py_modelica/py_modelica/modelica_simulation_tools/tool_base.py
# Copyright (C) 2013-2015 MetaMorph Software, Inc # Permission is hereby granted, free of charge, to any person obtaining a # copy of this data, including any software or models in source or binary # form, as well as any drawings, specifications, and documentation # (collectively "the Data"), to deal in the Data ...
chilleo/ALPHA
raxmlOutputWindows/matplotlibCustomBackend/customFormlayout.py
# -*- coding: utf-8 -*- """ formlayout ========== Module creating Qt form dialogs/layouts to edit various type of parameters formlayout License Agreement (MIT License) ------------------------------------------ Copyright (c) 2009 Pierre Raybaut Permission is hereby granted, free of charge, to any person obtaining ...
ma1co/fwtool.py
fwtool/archive/axfs.py
"""A parser for axfs file system images""" from stat import * import zlib from . import * from ..io import * from ..util import * AxfsHeader = Struct('AxfsHeader', [ ('magic', Struct.STR % 4), ('signature', Struct.STR % 16), ('digest', Struct.STR % 40), ('blockSize', Struct.INT32), ('files', Struct.INT64), ('s...
Sispheor/piclodio3
back/tests/test_views/test_web_radio_views/test_get_details.py
from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APITestCase from restapi.models.web_radio import WebRadio class TestGetDetails(APITestCase): def setUp(self): super(TestGetDetails, self).setUp() self.webradio = WebRadio.objects.create(n...
oy-vey/algorithms-and-data-structures
5-AdvancedAlgorithmsAndComplexity/Week1/evacuation/evacuation.py
# python3 import queue class Edge: def __init__(self, u, v, capacity): self.u = u self.v = v self.capacity = capacity self.flow = 0 # This class implements a bit unusual scheme for storing edges of the graph, # in order to retrieve the backward edge for a given edge quickly. clas...
dotsonlab/AWSC-Toilet
flow.py
''' David Rodriguez Goal: Continuously looping while to perform valve actions at specified times, introduce substance at a specific ratio based on flow data, recording and saving flow data, and actuating a flush at a specified time. Inputs: A schedule of events based on entered times. Outputs: Sequence of e...
jimmyshen/sunset
sunset/parser.py
import re import datetime import logging log = logging.getLogger(__name__) class Marker(object): __slots__ = ['line_start', 'line_end', 'expires'] def __init__(self, lineno): self.line_start = lineno self.line_end = lineno self.expires = None def __str__(self): if self.l...
yipyip/Qurawl
qurawl/qurawl.py
# -*- coding: utf-8 -*- """Qurawl Main""" #### from __future__ import absolute_import from __future__ import unicode_literals import itertools as it import random as rand import difflib as diff #### import common.debugit as debugit import qurawl.regparse as rp from qurawl.level import * from qurawl.items import * ...
rubbenrc/uip-prog3
parcial/presupuesto_parcial.py
#------------------------------------------------------------------------------- # Name: presupuesto parcial#1 # Author: programar # # Creado: 12/11/2015 # Copyright: (c) programar 2015 # Licence: <your licence 1.1> #------------------------------------------------------------------------------- im...
mbodenhamer/fmap
docs/conf.py
# -*- coding: utf-8 -*- # # fmap documentation build configuration file, created by # sphinx-quickstart on Mon Apr 11 21:30:39 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All ...
ayziao/niascape
niascape/usecase/postcount.py
""" niascape.usecase.postcount 投稿件数ユースケース """ import niascape from niascape.repository import postcount from niascape.utility.database import get_db def day(option: dict) -> list: with get_db(niascape.ini['database']) as db: # type: ignore # XXX セクションぶっこむとmypyさんにおこられ 辞書化すべきか return postcount.day(db, **option) ...
jorisvanzundert/sfsf
sfsf/epub_to_txt_parser.py
import sys, getopt import errno import os.path import epub import lxml from bs4 import BeautifulSoup class EPubToTxtParser: # Epub parsing specific code def get_linear_items_data( self, in_file_name ): book_items = [] book = epub.open_epub( in_file_name ) for item_id, linear in book.op...
pcmagic/stokes_flow
try_code/contourAnimation.py
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np # from sympy import * from src import jeffery_model as jm DoubleletStrength = np.array((1, 0, 0)) alpha = 1 B = np.array((0, 1, 0)) lbd = (alpha ** 2 - 1) / (alpha ** 2 + 1) x, y = np.meshgrid(np.linspace(-1, 1, 100), np.linspa...
ufjfeng/leetcode-jf-soln
python/211_add_and_search_word-data_structure_design.py
""" Design a data structure that supports the following two operations: void addWord(word) bool search(word) search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter. For example: addWord("bad") addWord("dad") ...
su27/qcloud_cos_py3
docs/source/conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Qcloud COS SDK for Python 3 documentation build configuration file, created by # cookiecutter pipproject # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autog...
andre487/news487
collector/rss/reader.py
import feedparser import logging from rss import sources from util import date, dict_tool, tags log = logging.getLogger('app') def parse_feed_by_name(name): feed_params = sources.get_source(name) if not feed_params: raise ValueError('There is no feed with name %s' % name) source_name = feed_par...
Bluejudy/bluejudyd
lib/broadcast.py
#! /usr/bin/python3 """ Broadcast a message, with or without a price. Multiple messages per block are allowed. Bets are be made on the 'timestamp' field, and not the block index. An address is a feed of broadcasts. Feeds may be locked with a broadcast whose text field is identical to ‘lock’ (case insensitive). Bets ...
allisson/django-tiny-rest
tiny_rest/tests/test_authorization.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase, RequestFactory from django.contrib.auth import get_user_model, authenticate from django.contrib.auth.models import AnonymousUser import json import status from tiny_rest.views import APIView from tiny_rest.authorization ...
AutorestCI/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/operations/availability_sets_operations.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
LMescheder/AdversarialVariationalBayes
avb/inputs.py
import numpy as np import tensorflow as tf import os def get_inputs(split, config): split_dir = config['split_dir'] data_dir = config['data_dir'] dataset = config['dataset'] split_file = os.path.join(split_dir, dataset, split + '.lst') filename_queue = get_filename_queue(split_file, os.path.join(d...
mven/gonzo.py
gonzo.py
# GONZO: A PYTHON SCRIPT TO RECORD PHP ERRORS INTO MONGO # Michael Vendivel - vendivel@gmail.com import subprocess import datetime from pymongo import MongoClient # where's the log file filename = '/path/to/php/logs.log' # set up mongo client client = MongoClient('mongo.server.address', 27017) # which DB db = clien...
akshaykurmi/reinforcement-learning
atari_breakout/per.py
import os import pickle import numpy as np from tqdm import tqdm class SumTree: def __init__(self, capacity): self.capacity = capacity self.tree = np.zeros(2 * capacity - 1, dtype=np.float32) self.data = np.empty(capacity, dtype=object) self.head = 0 @property def total_p...
ambimanus/appsim
analyze-headless.py
import sys import os import csv from datetime import datetime, timedelta import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.dates import drange from matplotlib.patches import Rectangle import scenario_factory # http://www.javascripter.net/faq/hextorgb.htm PRIM...
leanix/leanix-sdk-python
src/leanix/models/ServiceHasResource.py
#!/usr/bin/env python """ The MIT License (MIT) Copyright (c) 2017 LeanIX GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use,...
meine-stadt-transparent/meine-stadt-transparent
mainapp/migrations/0023_auto_20190405_0911.py
# Generated by Django 2.1.8 on 2019-04-05 07:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mainapp', '0022_auto_20190404_1605'), ] operations = [ migrations.AlterField( model_name='historicalpaper', name='ref...
phihes/sds-models
sdsModels/models.py
import sklearn.cross_validation as cv import sklearn.dummy as dummy from sklearn.mixture import GMM from sklearn.hmm import GMMHMM from sklearn import linear_model, naive_bayes import collections import itertools import pandas as pd from testResults import TestResults from counters import * import utils as utils cla...
stiell/hyde
hyde/ext/plugins/folders.py
# -*- coding: utf-8 -*- """ Plugins related to folders and paths """ from hyde.plugin import Plugin from hyde.fs import Folder class FlattenerPlugin(Plugin): """ The plugin class for flattening nested folders. """ def __init__(self, site): super(FlattenerPlugin, self).__init__(site) def b...
frigg/frigg-hq
frigg/builds/migrations/0011_auto_20150223_0442.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('builds', '0010_merge'), ] operations = [ migrations.AlterField( model_name='project', name='approved...
pseudomuto/kazurator
kazurator/read_write_lock.py
from kazoo.exceptions import NoNodeError from sys import maxsize from .mutex import Mutex from .internals import LockDriver from .utils import lazyproperty READ_LOCK_NAME = "__READ__" WRITE_LOCK_NAME = "__WRIT__" class _LockDriver(LockDriver): def sort_key(self, string, _lock_name): string = super(_LockD...
coingraham/codefights
python/fileNaming/fileNaming.py
""" You are given an array of desired filenames in the order of their creation. Since two files cannot have equal names, the one which comes later will have an addition to its name in a form of (k), where k is the smallest positive integer such that the obtained name is not used yet. Return an array of names that will...
brosner/nip
setup.py
from distutils.core import setup setup( name = "nip", version = "0.1a1", py_modules = [ "nip", ], scripts = [ "bin/nip", ], author = "Brian Rosner", author_email = "brosner@gmail.com", description = "nip is environment isolation and installation for Node.js", lo...
pheanex/xpython
exercises/allergies/allergies_test.py
import unittest from allergies import Allergies # Python 2/3 compatibility if not hasattr(unittest.TestCase, 'assertCountEqual'): unittest.TestCase.assertCountEqual = unittest.TestCase.assertItemsEqual # Tests adapted from `problem-specifications//canonical-data.json` @ v1.0.0 class AllergiesTests(unittest.Tes...
RocketScienceAbteilung/git-grid
experiments/buttons.py
import numpy import argparse import time import mido import colorsys import gitgrid.gridcontroller import gitgrid.utils.utils args = gitgrid.utils.utils.controller_args() tmp = gitgrid.gridcontroller.create(args.controller, args.input, args.output) def toggle(x, y, Message): curr = tmp.lights[x, y, :] / 255. ...
emgreen33/easy_bake
oven.py
import RPi.GPIO as gpio from datetime import datetime import time import controller gpio.setmode(gpio.BOARD) # switch_pins = [10, 40, 38] switch = 10 gpio.setup(switch, gpio.OUT, initial=False) # gpio.setup(switch_pins, gpio.OUT, initial=False) def switch_on(): gpio.output(switch, True) print "Oven switched ON a...
yeleman/snisi
snisi_trachoma/views.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.http import Http404 from django.shortcuts import render from django.contrib.auth.decorators import login...
c4fcm/DataBasic
databasic/logic/tfidfanalysis.py
import os import codecs, re, time, string, logging, math from operator import itemgetter from nltk import FreqDist from nltk.corpus import stopwords import textmining from scipy import spatial from . import filehandler def most_frequent_terms(*args): tdm = textmining.TermDocumentMatrix(simple_tokenize_remove_our_s...
de-vri-es/qtile
setup.py
#!/usr/bin/env python # Copyright (c) 2008 Aldo Cortesi # Copyright (c) 2011 Mounier Florian # Copyright (c) 2012 dmpayton # Copyright (c) 2014 Sean Vig # Copyright (c) 2014 roger # Copyright (c) 2014 Pedro Algarvio # Copyright (c) 2014-2015 Tycho Andersen # # Permission is hereby granted, free of charge, to any perso...
28harishkumar/Social-website-django
user/migrations/0003_auto_20150703_0843.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('user', '0002_auto_20150703_0836'), ] operations = [ migrations.AlterField( mode...
sebastian-code/jsonb-test
jsonb/emporium/models.py
from django.db import models from django.contrib.postgres.fields.jsonb import JSONField class Supplier(models.Model): name = models.CharField(max_length=50) tax_id = models.CharField(max_length=10) def __str__(self): return self.name class Bargain(models.Model): sku = models.CharField(max_l...
sajaldebnath/vrops-metric-collection
metric-collection.py
# !/usr/bin python """ # # data-collect.py contain the python program to gather Metrics from vROps. Before you run this script # set-config.py should be run once to set the environment # Author Sajal Debnath <sdebnath@vmware.com> # """ # Importing the Modules import nagini import requests #import pprint import json ...
Ishydo/miot
miot/forms.py
from mapwidgets.widgets import GooglePointFieldWidget from miot.models import PointOfInterest, Page, Profile from django import forms class PointOfInterestForm(forms.ModelForm): '''The form for a point of interest.''' class Meta: model = PointOfInterest fields = ("name", "featured_image", "posi...
practo/r5d4
r5d4/publisher.py
from __future__ import absolute_import from werkzeug.exceptions import ServiceUnavailable, NotFound from r5d4.flask_redis import get_conf_db def publish_transaction(channel, tr_type, payload): conf_db = get_conf_db() if tr_type not in ["insert", "delete"]: raise ValueError("Unknown transaction type", ...
mattvonrocketstein/smash
smashlib/ipy3x/utils/encoding.py
# coding: utf-8 """ Utilities for dealing with text encodings """ #----------------------------------------------------------------------------- # Copyright (C) 2008-2012 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING, distributed as part...
astronomeralex/morphology-software
morphology.py
import numpy as np import scipy.interpolate as interp import warnings from astropy.io import fits def concentration(radii, phot, eta_radius=0.2, eta_radius_factor=1.5, interp_kind='linear', add_zero=False): """ Calculates the concentration parameter C = 5 * log10(r_80 / r2_0) Inputs: radii -- 1d a...
ngageoint/gamification-server
gamification/core/migrations/0007_auto__add_field_project_url.py
# -*- 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 'Project.url' db.add_column(u'core_project', 'url', self.gf('django.db....
Uberlearner/uberlearner
uberlearner/courses/admin.py
from django.contrib import admin from courses.models import Course, Instructor, Page, Enrollment class CourseAdmin(admin.ModelAdmin): list_display = ['title', 'instructor', 'language', 'popularity', 'is_public', 'deleted'] prepopulated_fields = { 'slug': ('title', ) } def queryset(self, request...
mitsei/dlkit
dlkit/json_/relationship/searches.py
"""JSON implementations of relationship searches.""" # pylint: disable=no-init # Numerous classes don't require __init__. # pylint: disable=too-many-public-methods,too-few-public-methods # Number of methods are defined in specification # pylint: disable=protected-access # Access to protected methods allowe...
sorz/isi
store/category/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(pri...
Kotaimen/stonemason
stonemason/service/tileserver/themes/views.py
# -*- encoding: utf-8 -*- __author__ = 'ray' __date__ = '2/27/15' from flask import jsonify, abort from flask.views import MethodView from ..models import ThemeModel class ThemeView(MethodView): """ Theme View Retrieve description of a list of available themes. :param theme_model: A theme model that ...
urfonline/api
config/wsgi.py
""" WSGI config for api project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` sett...
coll-gate/collgate
server/accession/fixtures/sequences.py
# -*- coding: utf-8; -*- # # @file sequences # @brief collgate # @author Frédéric SCHERMA (INRA UMR1095) # @date 2018-01-09 # @copyright Copyright (c) 2018 INRA/CIRAD # @license MIT (see LICENSE file) # @details def fixture(fixture_manager, factory_manager): acc_seq = "CREATE SEQUENCE IF NOT EXISTS accession_n...
mozillazg/lark
lark/lark/settings_dev.py
""" Django settings for lark 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 .base import * # Build paths inside the project like this: os.path.join...
sahlinet/fastapp
fastapp/migrations/0011_thread_updated.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('fastapp', '0010_auto_20150910_2010'), ] operations = [ migrations.AddField( model_name='thread', nam...
wesleykendall/django-issue
issue/tests/model_tests.py
from datetime import datetime, timedelta import json from django.contrib.contenttypes.models import ContentType from django.test import TestCase from django_dynamic_fixture import G, N from freezegun import freeze_time from mock import patch from issue.models import ( Assertion, ExtendedEnum, Issue, IssueAction, ...
cbelth/pyMusic
pydub/exceptions.py
class TooManyMissingFrames(Exception): pass class InvalidDuration(Exception): pass class InvalidTag(Exception): pass class InvalidID3TagVersion(Exception): pass class CouldntDecodeError(Exception): pass
dtnaylor/web-profiler
tools/test.py
#! /usr/bin/env python import os import sys import shutil import logging import argparse import tempfile sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from webloader.phantomjs_loader import PhantomJSLoader from webloader.curl_loader import CurlLoader from webloader.pythonrequests_loader import Python...
DistrictDataLabs/topicmaps
topics/serializers.py
# topics.serializers # Serializers for the topic and voting models. # # Author: Benjamin Bengfort <bbengfort@districtdatalabs.com> # Created: Wed Sep 09 09:34:46 2015 -0400 # # Copyright (C) 2015 District Data Labs # For license information, see LICENSE.txt # # ID: serializers.py [] benjamin@bengfort.com $ """ Seri...
n3011/deeprl
dataset/replay_v2.py
import random import numpy as np class ReplayBuffer(object): def __init__(self, max_size): self.max_size = max_size self.cur_size = 0 self.buffer = {} self.init_length = 0 def __len__(self): return self.cur_size def seed_buffer(self, episodes): self.init_...
corcra/UMLS
parse_metamap.py
#!/bin/python # The purpose of this script is to take the *machine-readable* output of UMLS # MetaMap and convert it to something that looks like a sentence of UMLS CUIs, # if possible. Ideally there would be an option in MetaMap to do this, assuming # it is sensible. import re import sys #INTERACTIVE = True INTERA...
spthm/glio
snapshot.py
from copy import copy import numpy as np from .fortranio import FortranFile from .snapview import SnapshotView class SnapshotIOException(Exception): """Base class for exceptions in the the snapshot module.""" def __init__(self, message): super(SnapshotIOException, self).__init__(message) class Snaps...
pyhmsa/pyhmsa
pyhmsa/fileformat/exporter/raw.py
""" Export to RAW/RPL file format Based on: http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm """ # Standard library modules. import os # Third party modules. # Local modules. from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread from pyhmsa.spec.datum.analysislist import A...