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 |
|---|---|---|---|---|---|
"""db migration
Revision ID: 373a21295ab
Revises: 21f5b2d3905d
Create Date: 2015-05-05 15:42:33.474470
"""
# revision identifiers, used by Alembic.
revision = '373a21295ab'
down_revision = '21f5b2d3905d'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
op.dr... | Mytho/groceries-api | db/versions/20150505_154233_373a21295ab_db_migration.py | Python | mit | 1,244 |
from flask import *
import os
from decorators import validate_account_and_region
from aws import connect
from sgaudit import get_reports, add_description
from app.models import IPWhitelist
elastatus = Blueprint('elastatus', __name__)
@elastatus.route('/')
def index():
default_account = current_app.config['CONFI... | PercussiveRepair/elastatus | app/views.py | Python | mit | 6,380 |
##################################################################
# Copyright 2018 Open Source Geospatial Foundation and others #
# licensed under MIT, Please consult LICENSE.txt for details #
##################################################################
import unittest
import pytest
from pywps import xml... | geopython/pywps | tests/test_execute.py | Python | mit | 30,624 |
import random
import time
from flask import (Flask, flash, redirect, render_template, request, session,
url_for)
from flask_admin import Admin
from flask_babelex import Babel
from flask_wtf import Form
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from wtforms import v... | Stark-Mountain/meetup-facebook-bot | meetup_facebook_bot/server.py | Python | mit | 4,314 |
"""
WSGI config for Incubator 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`... | gmartinvela/Incubator | Incubator/wsgi.py | Python | mit | 1,428 |
""" Class to handle date-parsing and formatting """
# Workaround for http://bugs.python.org/issue8098
import _strptime # pylint: disable=unused-import
from datetime import datetime
import time
class DateUtils(object):
""" Class to handle date-parsing and formatting """
date_format = '%Y-%m-%dT%H:%M:%SZ'
... | sebastian-steinmann/kodi-repo | src/service.library.video/resources/lib/date_utils.py | Python | mit | 1,538 |
import sys
from tornado import gen, ioloop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.queues import Queue
class Scraper():
def __init__(
self,
destinations=None,
transform=None,
headers={},
max_clients=5... | andres-de-castro/scraping | scraper.py | Python | mit | 2,725 |
import sys
import time
import traceback
from StringIO import StringIO
from copy import copy
from lxml import etree
from sfa.trust.sfaticket import SfaTicket
from sfa.trust.credential import Credential
from sfa.util.sfalogging import logger
from sfa.util.xrn import Xrn, urn_to_hrn
from sfa.util.version import version_... | yippeecw/sfa | sfa/managers/slice_manager.py | Python | mit | 23,958 |
# -*- coding: utf-8 -*-
import os
from mock import Mock, patch
from maidchan.translate import get_trans_language_prediction, get_translation
SCRIPT_PATH = os.path.abspath(os.path.dirname(__file__))
def _get_response(name):
path = os.path.join(SCRIPT_PATH, 'data', name)
with open(path) as f:
return ... | freedomofkeima/messenger-maid-chan | tests/test_translate.py | Python | mit | 1,946 |
class Items(object):
def __init__(self, item='item type', durability=0, gain=0,
materials=0, id=0):
self.item = item
self.durability = durability
self.gain = gain
self.materials = materials
self.id = id
def item_id(self, id):
self.wood = 'wood'
... | kevin2314/TextGame | game/itemlib.py | Python | mit | 956 |
"""Automatic keyboard layout switcher"""
import functools
import logging
import subprocess
from typing import Iterable
from typing import Set
import xkbgroup
import swytcher.settings as settings
import swytcher.xwindow as xwindow
from swytcher.util import suppress_err
log = logging.getLogger(__name__) # pylint: dis... | eddie-dunn/swytcher | swytcher/swytcher.py | Python | mit | 3,436 |
# # a=1
# # b=a
# # print(a,b)
# #
# # for i in range(1,10,2):
# # print(i)
#
# def fun():
# a=10
# print(a)
# return a +100
#
# sun = fun()
# # sun + 100
#
# print(fun())
# print(sun)
file = open('my file.txt','r') #以读文件的形式打开文件
# content = file.readline() 仅读取第一行
content = file.readlines() #读取所有行,并以列表形... | 1065865483/0python_script | Python/01.py | Python | mit | 415 |
import math
class RaceApproximator:
def timeToBeat(self, d1, t1, d2, t2, raceDistance):
time = t1 * math.exp( math.log(float(t2)/t1) * math.log(float(d1)/raceDistance) / math.log(float(d1)/d2) )
time = int(time)
hours = time / 3600
minutes = (time - hours * 3600) / 60
... | mikefeneley/topcoder | src/SRM-184/race_approximator.py | Python | mit | 716 |
import os
import tempfile
import numpy.testing as test
import numpy as np
from unittest import TestCase
from datetime import datetime
from dateutil.relativedelta import relativedelta
from PyFVCOM.preproc import Model
from PyFVCOM.grid import write_sms_mesh
from PyFVCOM.utilities.time import date_range
class PrePro... | pwcazenave/PyFVCOM | tests/preproc.py | Python | mit | 9,048 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
#!/usr/bin/env python
from __future__ import division, unicode_literals
"""
#TODO: Write module doc.
"""
__author__ = 'Shyue Ping Ong'
__copyright__ = 'Copyright 2013, The Materials Virtual Lab'
__version__ =... | Bismarrck/pymatgen | pymatgen/io/aseio.py | Python | mit | 594 |
"""Console functionality for command line tools."""
from __future__ import print_function, unicode_literals
import codecs
import getpass
import shutil
import sys
import textwrap
from django.core.exceptions import ValidationError
from django.core.management.color import color_style, no_style
from django.utils import ... | chipx86/reviewboard | reviewboard/cmdline/utils/console.py | Python | mit | 20,318 |
import sys
import libsinan.sinexceptions
"""
The stream oriented parser produces a series of events that describe the structure currently being parsed. These events are then consumed by the calling application in some manner. The actual mechanism of consumption will vary from language type to language type though a few... | asceth/sinan | client/libsinan/jsax.py | Python | mit | 11,711 |
#!/usr/bin/env python3
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Copyright (c) 2015-2017 The Bitcoin Unlimited developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import test_framework.loginit
#
# Test pruning ... | BitcoinUnlimited/BitcoinUnlimited | qa/rpc-tests/pruning.py | Python | mit | 18,143 |
import os
from nanopore.analyses.abstractAnalysis import AbstractAnalysis
from nanopore.analyses.utils import AlignedPair, getFastaDictionary, getFastqDictionary, samIterator
import xml.etree.cElementTree as ET
from jobTree.src.bioio import *
class Hmm(AbstractAnalysis):
"""Calculates stats on indels.
"""
... | mitenjain/nanopore | nanopore/analyses/hmm.py | Python | mit | 4,792 |
"""
Django settings for alex project.
Generated by 'django-admin startproject' using Django 1.10.7.
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
#... | xualex/DjangoTutorial | alex/alex/settings.py | Python | mit | 3,153 |
# DJANGO 1.10.5 LOCAL SETTINGS
# https://docs.djangoproject.com/en/1.10/topics/settings/
# ==================================================================================================
from .base import *
DEBUG = True
# APP CONFIGURATION
# https://docs.djangoproject.com/en/1.10/ref/applications
# =============... | justinmnoor/geodjangotemplate | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings/local.py | Python | mit | 457 |
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup
setup(name='ReddWall',
version='0.2',
description='Get random wallpapers from Reddit',
author='Matthew Bauer',
author_email='mjbauer95@gmail.com',
url='http://github.com/matthewbauer/reddwall',
ins... | matthewbauer/reddwall | setup.py | Python | mit | 447 |
import code
import datetime
import os
import os.path
def PrintReceipt(receipt, time_string):
return_string = ""
return_string=return_string+"-------------------------------------\n"
return_string=return_string+"MY GROCERY STORE\n"
return_string=return_string+"-------------------------------------\n"
... | MarcBarakat/nyu-python-marcbarkat | shopping_cart.py | Python | mit | 5,047 |
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
import typing
from ... import exc
from ... import util
from ...sql import coercions
from ...sql impo... | sqlalchemy/sqlalchemy | lib/sqlalchemy/dialects/mysql/expression.py | Python | mit | 4,164 |
import urwid
from pipeinspector.widgets import BlobWidget, BlobBrowser
from pipeinspector.settings import UI
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM3NeT collaboration."
__credits__ = []
__license__ = "MIT"
__maintainer__ = "Tamas Gal"
__email__ = "tgal@km3net.de"
__status__ = "D... | tamasgal/km3pipe | pipeinspector/gui.py | Python | mit | 1,923 |
# I made some modifications to termcolor so you can pass HEX colors to
# the colored function. It then chooses the nearest xterm 256 color to
# that HEX color. This requires some color functions that I have added
# in my python path.
#
# 2015/02/16
#
#
# coding: utf-8
# Copyright (c) 2008-2011 Volvox Development Team
... | marchdf/dotfiles | mypython/mypython/mytermcolor.py | Python | mit | 5,928 |
def get_current_phase(tag):
sdu = getvar('#stimDisplayUpdate')
for item in sdu:
if item['name'] == tag:
return '%.2f' % -item['current_phase']
return ''
| mworks/mworks | examples/Tests/Stimulus/DriftingGrating/StartingPhase/get_current_phase.py | Python | mit | 185 |
#!/usr/bin/env python
# Jonas Schnelli, 2013
# make sure the TakeiCoin-Qt.app contains the right plist (including the right version)
# fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267)
from string import Template
from datetime import date
bitcoinDir = "./";
i... | takeicoin/takeicoin | share/qt/clean_mac_info_plist.py | Python | mit | 898 |
#from .vnctpmd import MdApi
from .vnoestd import TdApi
from .vnoesmd import MdApi
from .oes_constant import * | bigdig/vnpy | vnpy/api/oes/__init__.py | Python | mit | 109 |
#!/usr/bin/env python
# IMPORT NECESSARY LIBRARIES
import RPi.GPIO as GPIO
import time
# INITIALIZE THE GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26,GPIO.OUT)
# TURN ON RELAY 1
GPIO.output(26,0)
# CLEAN UP GPIO
# GPIO.cleanup()
| CamoFPV/Relay-Website-with-Raspberry-Pi | py/14on.py | Python | mit | 254 |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 The DigiByte Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test account RPCs.
RPCs tested are:
- getaccountaddress
- getaddressesbyaccount
- listadd... | digibyte/digibyte | test/functional/wallet_accounts.py | Python | mit | 8,572 |
import base64
from os.path import abspath, dirname, join
import sys, os
import uuid
import shutil
import untangle
import subprocess, threading
# missing module fix
sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'], 'wsgi'))
virtenv = os.environ['APPDIR']+'/virtenv'
os.environ['PYTHON_EGG_CACHE']... | pacbard/clsipy | wsgi/clsi.py | Python | mit | 4,642 |
# orm/attributes.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Defines instrumentation for class attributes and their interaction
with instanc... | ThiefMaster/sqlalchemy | lib/sqlalchemy/orm/attributes.py | Python | mit | 57,173 |
from pyramid.response import Response
from pyramid.view import view_config
from sqlalchemy.exc import DBAPIError
from .models import (
DBSession,
MyModel,
)
@view_config(route_name='home', renderer='templates/mytemplate.pt')
def my_view(request):
try:
one = DBSession.query(MyModel).filter(My... | Akagi201/learning-python | pyramid/misc/MyProject/myproject/views.py | Python | mit | 1,090 |
from firebase import firebase
import os
import datetime
import json
import logging
from boto.s3.connection import S3Connection
from boto.s3.key import Key
## FIREBASE ACCESS INFO ##
firebase_url = 'https://your-app.firebaseio.com/' #Or get from environment variable
firebase_secret = os.environ['FIREBASE_SECRET']
fireb... | designed27/firebase-backup-s3-python | backup-firebase.py | Python | mit | 1,486 |
# coding: utf-8
# pylint: disable=wildcard-import
"""Loads all routes and their functions"""
from .user_api import *
from .position_api import *
from .feedback_api import *
from .auth_api import *
from .config_api import *
from .generate_db_api import *
| Huijari/gae_test | main/api/v1/__init__.py | Python | mit | 255 |
from django.db import models
from mongoengine.queryset import QuerySet
class GCMMessageMixin(object):
def send_message(self, message, **kwargs):
if self:
from instapush.libs.gcm import gcm_send_bulk_message
data = kwargs.pop("extra", {})
if message is not None:
... | amyth/django-instapush | instapush/models/querysets.py | Python | mit | 1,414 |
import itertools
import struct
def ip4_to_int32(str_ip, order='>'):
return struct.unpack(order+"I",struct.pack("BBBB",*map(int,str_ip.split("."))))[0]
def int32_to_ip4(big_int, order='>'):
return '.'.join(map(str, struct.unpack("BBBB",struct.pack(order+"I",big_int))))
def gen_get_n_bit(data, bit=1):
mask = 1 <... | k3idii/pykpyk | datatools.py | Python | mit | 955 |
# -*- coding: utf-8 -*-
from dp_tornado.engine.controller import Controller
class TimestampController(Controller):
def get(self):
backup_zone = self.model.tests.helper_test.datetime.switch_timezone('Asia/Seoul')
assert_tuple = self.model.tests.assert_tuple
tzx_seoul = 'Asia/Seoul'
... | why2pac/dp-tornado | example/controller/tests/helper/datetime/timestamp.py | Python | mit | 3,271 |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Identifies key events related to user satisfaction.
Several lenses are defined, for example FirstTextPaintLens and
FirstSignificantPaintLens.
"""
import ... | junhuac/MQUIC | src/tools/android/loading/user_satisfied_lens.py | Python | mit | 5,080 |
# vim: set fileencoding=utf-8
# Pavel Odvody <podvody@redhat.com>
#
# HICA - Host integrated container applications
#
# MIT License (C) 2015
import os, sys
from json import loads
from base.hica_base import *
library_path='/usr/lib64'
class LibraryInjector(HicaInjector):
def _get_libs(self):
return sorted(loads... | shaded-enmity/docker-hica | injectors/libs.py | Python | mit | 1,615 |
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
X_DOMAINS = '*'
X_HEADERS = ['Content-Type']
CACHE_CONTROL = 'no-cache'
CACHE_EXPIRES = 0
IF_MATCH = False
RESOURCE_METHODS = ['GET', 'POST', 'DELETE']
ITEM_METHODS = ['GET', 'PATCH', 'PUT', 'DELETE']
XML = False
EMBEDDING = True
## ## ## ## ##
## animes definition
## ## ... | Haellsigh/yawl | settings.py | Python | mit | 3,170 |
#!/usr/bin/python
# Written by Stjepan Horvat
# ( zvanstefan@gmail.com )
# by the exercises from David Lucal Burge - Perfect Pitch Ear Traning Supercourse
# Thanks to Wojciech M. Zabolotny ( wzab@ise.pw.edu.pl ) for snd-virmidi example
# ( wzab@ise.pw.edu.pl )
import random
import time
import sys
import re
fname="/de... | schef/schef.github.io | source/11/mc-11-05-sk-mt.py | Python | mit | 3,429 |
ldata=[]
ldata=a_data
nr=len(ldata)
atmsel1 = []
atmsel2 = []
sidechain1 = []
sidechain2 = []
if(nr==0):
print "No saltbridges found"
cmd.hide('lines', '%s'%modelName)
cmd.show('cartoon', '%s'%modelName)
cmd.util.cbc(selection='%s'%modelName,first_color=7,quiet=1,legacy=0,_self=cmd)
cmd.hide('cartoon'... | S-John-S/MAT | sb_temp_script.py | Python | mit | 2,698 |
import biopsy
import bifa_server
import base64, threading , os, socket
from sslUserCheck import CheckUserEngine
from soaplib.wsgi_soap import WSGISoapApp
from soaplib.wsgi_soap import SoapServiceBase
from soaplib.service import soapmethod
from soaplib.client import make_service_client
from soaplib.serializers.primitiv... | JohnReid/biopsy | Python/bio_server/main_server.py | Python | mit | 11,092 |
import unittest
from integration.thrift.test_thrift import ThriftTestCase
from scales.thriftmux import ThriftMux
class ThriftMuxTestCase(ThriftTestCase):
BUILDER = ThriftMux
if __name__ == '__main__':
unittest.main()
| steveniemitz/scales | test/integration/thrift/test_mux.py | Python | mit | 224 |
# This file is autogenerated. Do not edit it manually.
# If you want change the content of this file, edit
#
# spec/fixtures/responses/whois.nic.bj/status_registered
#
# and regenerate the tests with the following script
#
# $ scripts/generate_tests.py
#
from nose.tools import *
from dateutil.parser import parse ... | huyphan/pyyawhois | test/record/parser/test_response_whois_nic_bj_status_registered.py | Python | mit | 3,633 |
def descriptor(rcut=4, desc_type='se_ar', mneiba=150):
smth_frac = 0.85
if desc_type == 'se_ar':
rmult = 1.5
mneibr = 500
ar_smth = rcut*smth_frac
desc = {
'type': 'se_ar',
'a': {
'sel': [mneiba],
'rcut_smth': ar_smth,
'rcut': rcut,
'neuron': [10, 20, 40],... | Paul-St-Young/solid_hydrogen | qharv_db/dpmd_train.py | Python | mit | 2,815 |
#!/usr/bin/env python
# encoding: utf-8
"""
crawler.py
~~~~~~~~~~~~~
主要模块,爬虫的具体实现。
"""
import re
import time
import logging
import threading
import traceback
from hashlib import md5
from bs4 import BeautifulSoup
from datetime import datetime
from collections import deque
from locale import getdefaultlocale
from urlpar... | zhkzyth/a-super-fast-crawler | crawler.py | Python | mit | 9,133 |
"""
Boolean Operations
~~~~~~~~~~~~~~~~~~
Perform boolean operations with closed surfaces (intersect, cut, etc.).
Boolean/topological operations (intersect, cut, etc.) methods are implemented
for :class:`pyvista.PolyData` mesh types only and are accessible directly from
any :class:`pyvista.PolyData` mesh. Check out :... | akaszynski/vtkInterface | examples/01-filter/boolean-operations.py | Python | mit | 3,395 |
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
#class FlexSlidersApp(CMSApp):
# name = _("FlexSlider")
# urls = ["flexslider.urls"]
# app_name = "flexslider"
#
#apphook_pool.register(FlexSlidersApp) # register your app
| ForumDev/djangocms-flexslider | flexslider/cms_app.py | Python | mit | 317 |
#!/usr/bin/env python
"""Unit test for nbawebstats.
Presently this test is very basic, only checking that the module imports
without error. Module functionality is checked by the test located at
tests/functional/test-requests.py.
"""
import unittest
import nbawebstats
class TestInterface(unittest.TestCase):
def... | agirardeaudale/nbawebstats | tests/test-nbawebstats.py | Python | mit | 476 |
from skidl import SKIDL, TEMPLATE, Part, Pin, SchLib
SKIDL_lib_version = '0.0.1'
analog_devices = SchLib(tool=SKIDL).add_parts(*[
Part(name='AD623AN',dest=TEMPLATE,tool=SKIDL,keywords='ad623 instumentation amplifier dip-8',description='Single Supply, Rail to Rail, Instumentation Amplifier, RoHS, DIP-8',ref_pr... | xesscorp/skidl | skidl/libs/analog_devices_sklib.py | Python | mit | 14,637 |
#!/usr/bin/env python
import argparse
import datetime
import pandas as pd
import yaml
from pytrthree import TRTH
from pytrthree.utils import retry
def make_request(daterange, criteria):
request = api.factory.LargeRequestSpec(**template)
short_dates = sorted([x.replace('-', '') for x in daterange.values()])
... | plugaai/pytrthree | tools/request_sender.py | Python | mit | 2,685 |
# dev settings
from .base import *
DEBUG = os.getenv("DEBUG", False)
| OpenSourceHelpCommunity/OpenSourceHelpCommunity.github.io | oshc/oshc/settings/dev.py | Python | mit | 71 |
from .downloader_base import DownloaderBase
from ... import logger
log = logger.get(__name__)
import traceback
import json
from urllib import request, error
try:
import ssl
SSL = True
except ImportError:
SSL = False
def is_available():
return SSL
class UrllibDownloader(DownloaderBase):
"""Down... | blopker/Color-Switch | colorswitch/http/downloaders/urllib.py | Python | mit | 1,149 |
import pipes
from fabric.api import settings, task, local, hide
from fabric.contrib.console import confirm
def is_working_tree_clean():
with settings(hide('everything'), warn_only=True):
local('git update-index -q --ignore-submodules --refresh')
unstaged = local('git diff-files --quiet --ignore-s... | GaretJax/ppc | fabfile.py | Python | mit | 2,432 |
#!/usr/bin/env python
# -*- coding: utf8 -*-
class Time:
def ums(i, ignoreZero=True):
i = float(i)
hours = int(i / 3600)
rest = i % 3600
minutes = int(rest / 60)
seconds = int(rest % 60)
if hours < 10:
hours = "0" + str(hours)
if minutes < 10:
... | lucienimmink/scanner.py | scanner/_utils.py | Python | mit | 1,322 |
import dataset
from pdl_scraper import settings
def db_connect():
"""
Performs database connection using database settings from settings.py.
Returns sqlalchemy engine instance
:param test: if test is True then create an empty test database
"""
database_name = settings.DATABASE['database']
... | proyectosdeley/proyectos_de_ley | proyectos_de_ley/pdl_scraper/models.py | Python | mit | 631 |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import yo_payments
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Yo Payments'
copyright = u'2013, James M... | JamesMura/yo_payments | docs/conf.py | Python | mit | 978 |
import h5py
import numpy as np
import matplotlib.pyplot as plt
import my_pytools.my_matplotlib.colors as colors
with h5py.File('out.h5', 'r') as f:
d = f["monitors/volume_monitor/vol/dft"][...]
Er = d['real']
Ei = d['imag']
I = Er**2 + Ei**2
I = I.squeeze()
phase = np.arctan2(Ei,Er).squeeze()... | johnaparker/Qbox | tests/dynamics/plot.py | Python | mit | 471 |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from qiniuyun.backend import QiniuPush
from qiniuyun.models import ImageAtQiniu
from .indexView import ImgList
from DJangoHotel.models import RoomInfo
def roomInfo(request):
rooms=RoomInfo.objects.all()
imgObjs=ImageAtQiniu.objects.all()
imgUrls=... | williezh/hotelbooksystem | DJangoHotel/viewspackage/roomInfoView.py | Python | mit | 584 |
# 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 'SliderItemTitle.is_published'
db.add_column('hero_slider_slideritemtitle', 'i... | bitmazk/django-hero-slider | hero_slider/south_migrations/0002_auto__add_field_slideritemtitle_is_published.py | Python | mit | 8,315 |
import matplotlib.pyplot as plt
from matplotlib import cm
import pywt
import scipy
import numpy as np
import time
import random
import math
import sys
import kplr
import wavelet_funcs
data = np.loadtxt("KIC_7874976_llc.dat")
data.shape # (60020,4)
# From Montet:
# Columns are time, raw-flux, detrended-flux, uncertai... | pdbaines/KepleR | python/wavelets.py | Python | mit | 3,443 |
from django.conf import settings
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello")
| rochacbruno/dynaconf | example/django_pure/polls/views.py | Python | mit | 125 |
from .. import Provider as PersonProvider
class Provider(PersonProvider):
formats_female = (
"{{first_name_female}} {{last_name}}",
"{{first_name_unisex}} {{last_name}}",
"{{prefix_female}} {{first_name_unisex}} {{last_name}}",
"{{prefix_female}} {{first_name_female}} {{last_name}}... | joke2k/faker | faker/providers/person/or_IN/__init__.py | Python | mit | 35,828 |
import csv
from giantcellsim_trial import giantcellsim_trial
import itertools
import numpy
def flatten(items, seqtypes=(list, tuple)): # used for flattening lists
for i, x in enumerate(items):
while isinstance(items[i], seqtypes):
items[i:i+1] = items[i]
return items
def giantcellsim_moti... | kins912/giantcellsim | giantcellsim_motifoutput.py | Python | mit | 3,105 |
import collections
class Solution:
def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
table = collections.defaultdict(list)
for i, m in enumerate(manager):
table[m].append(i)
Q = collections.deque([(headID, 0)])
min... | jiadaizhao/LeetCode | 1301-1400/1376-Time Needed to Inform All Employees/1376-Time Needed to Inform All Employees.py | Python | mit | 524 |
#! /usr/bin/env python
# import os
import pygame
import random
from highscore import is_high_score_and_save
# it is better to have an extra variable, than an extremely long line.
player_img_path = 'player.png'
pill_img_path = 'pill.png'
boost_img_path = 'boost.png'
background = pygame.image.load("space.jpg")
# creat... | dojojon/pygame | week5/spawn5.py | Python | mit | 4,613 |
#!/usr/bin/env python
"""PIQS: Permutational Invariant Quantum Solver
PIQS is an open-source Python solver to study the exact Lindbladian
dynamics of open quantum systems consisting of identical qubits.
"""
DOCLINES = __doc__.split('\n')
CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science... | nathanshammah/pim | setup.py | Python | mit | 3,679 |
import abc
import pickle
from hashlib import sha1
from .. import utils
from .. import version
class Base(object):
''' An abstract base class for backends for the Sass cache.
Any key-value store can act as such a backend;
it just needs to implement the
\{#_store} and \{#_retrieve} methods.
To use a cache sto... | OiNutter/sasspy | sasspy/cache_stores/base.py | Python | mit | 1,732 |
#!/usr/bin/env python
# Based on previous work by
# Charles Menguy (see: http://stackoverflow.com/questions/10217067/implementing-a-full-python-unix-style-daemon-process)
# and Sander Marechal (see: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/)
# Adapted by M.Hendrix [2015] (deprecated)... | Mausy5043/ubundiagd | daemon15.py | Python | mit | 4,996 |
__author__ = 'Hans-Werner Roitzsch'
from datetime import datetime
import sched
import cv2 as opencv
import numpy as np
from config import *
from processor.SensorDataProcessor import SensorDataProcessor
from model.ProcessedCameraData import ProcessedCameraData
from writer.ImageFileWriter import ImageFileWriter
cl... | hwroitzsch/BikersLifeSaver | src/bike_module/processor/CameraDataProcessor.py | Python | mit | 5,814 |
#!/usr/bin/env python3
#
# This file is part of the MicroPython project, http://micropython.org/
#
# The MIT License (MIT)
#
# Copyright (c) 2020 Damien P. George
# Copyright (c) 2020 Jim Mussared
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated document... | pfalcon/micropython | tools/codeformat.py | Python | mit | 6,422 |
datafile1 = "./problem18data.txt"
datafile2 = "./problem67data.txt"
def getdata(filename):
l = []
with open(filename, 'r') as f:
for line in f:
row = [int(s.strip()) for s in line.split(" ")]
l.append(row)
return l
def read_data_test():
l = getdata(datafile)
print l
def longest_path(filename):
l = get... | hubenjm/Project-Euler | problem18.py | Python | mit | 992 |
# File: setup.py
# Version: 3
# Description: Setup for SHA2017 badge
# License: MIT
# Authors: Renze Nicolai <renze@rnplus.nl>
# Thomas Roos <?>
import ugfx, badge, appglue, dialogs, easydraw, time
def asked_nickname(value):
if value:
badge.nvs_set_str("owner", "name", value)
# Do the ... | SHA2017-badge/micropython-esp32 | esp32/modules/setup.py | Python | mit | 894 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
import json
from model_mommy import mommy
from io import BytesIO
from PIL import Image
from tiny_rest.tests import Client
import s... | allisson/django-tiny-rest | testproject/blog/tests/test_views.py | Python | mit | 10,142 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools import setup, find_packages
from pip.req import parse_requirements
import pip
install_reqs = reqs = [str(ir.req) for ir in parse_requirements('requirements.txt',
session=pip.download.PipSession())]
dev_reqs = [str(ir.req) ... | HEP-DL/proton_decay_study | setup.py | Python | mit | 1,937 |
# 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 may ... | Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_04_01/aio/operations/_load_balancer_network_interfaces_operations.py | Python | mit | 5,642 |
from django.conf.urls import patterns, url
from landingpage import views
urlpatterns = patterns('', url(r'^$', views.index, name='landingpage'))
| mewwts/bandpage | landingpage/urls.py | Python | mit | 146 |
# coding:utf-8
import logging
import numpy as np
from scipy.linalg import svd
from mla.base import BaseEstimator
np.random.seed(1000)
class PCA(BaseEstimator):
y_required = False
def __init__(self, n_components, solver="svd"):
"""Principal component analysis (PCA) implementation.
Transfor... | rushter/MLAlgorithms | mla/pca.py | Python | mit | 1,758 |
"""
.. module:: configs.common.django
:synopsis: Django settings file.
Django settings for django_core_models project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and the... | ajaniv/django-core-models | configs/common/django.py | Python | mit | 3,872 |
# -*- coding: utf-8 -*-
import pytest
import numpy as np
import tensorflow as tf
from inferbeddings.models.training import pairwise_losses
def test_additive_walk_embedding():
pos_scores = tf.Variable(np.array([.9]), name='pos_scores')
neg_scores = tf.Variable(np.array([.1]), name='neg_scores')
init_op... | uclmr/inferbeddings | tests/inferbeddings/model/training/test_objectives.py | Python | mit | 658 |
import unittest
from lib.earthquake import Parser
class ParserTestCase(unittest.TestCase):
def setUp(self):
self.parser = Parser()
def test_parser_contains_a_parse_method(self):
self.assertTrue(callable(getattr(self.parser, "parse")), "Parser contains a parse method")
def test_parse_method_... | domenicosolazzo/Earthquake | tests/tests_earthquake_parser.py | Python | mit | 585 |
"""
Test the integrators.
"""
import os
# Third-party
import pytest
import numpy as np
# Project
from .. import (
LeapfrogIntegrator,
RK5Integrator,
DOPRI853Integrator,
Ruth4Integrator,
)
from gala.tests.optional_deps import HAS_TQDM
# Integrators to test
integrator_list = [
RK5Integrator,
... | adrn/gala | gala/integrate/tests/test_pyintegrators.py | Python | mit | 3,454 |
import enum
import numpy as np
from . import base
from spych.utils import array
class SpliceStage(base.ProcessingStage):
def __init__(self, splice_size=4, splice_step=1):
self.splice_size = splice_size
self.splice_step = splice_step
def process(self, feature_matrix):
processed = arr... | ynop/spych | spych/data/features/pipeline/splicing.py | Python | mit | 1,313 |
#coding:utf-8
import os, sys, io
import shutil
import struct
_DELTA = 0x9E3779B9
def _long2str(v, w):
n = (len(v) - 1) << 2
if w:
m = v[-1]
if (m < n - 3) or (m > n): return ''
n = m
s = struct.pack('<%iL' % len(v), *v)
if w :
return s[0:n]
else :
return s... | helloztq/helloztq.github.io | _drafts/encrypt.py | Python | mit | 2,578 |
#! /usr/bin/env python
# coding:utf-8
from __future__ import division, print_function
import itertools
class NgramException(Exception):
pass
def ngram(sentences, n):
s_len = len(sentences)
if s_len < n:
raise NgramException("the sentences length is not enough:\
len(... | kenkov/smt | smt/langmodel/ngram.py | Python | mit | 551 |
import os
import traceback
from threading import Thread, Event
from common.models.task import TaskInfo
from common.models.state import TaskState
from worker.backend import WorkerBackend
from worker.executor import ExecutionEnded, Executors
from worker.resource import Resources
class TaskExecution(Thread):
def __... | LuckyGeck/dedalus | worker/engine.py | Python | mit | 5,052 |
# -*- coding:utf-8 -*-
# Created by Vaayne at 2016/09/04 09:49
from gevent.monkey import patch_all
patch_all()
from gevent.pool import Pool
import logging
import coloredlogs
from .wx_iwgc import WxWGC
from .smzdm import Smzdm
from .fly import FlyerTea
import os
import sys
import time
log = logging.getLogger(__file__... | Vaayne/vaayne.com | app/func/spider/run.py | Python | mit | 997 |
#!/usr/bin/env python
import os.path
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def ge... | avinassh/learning-tornado | tornado-book/extending-templates/basic_templates/main.py | Python | mit | 1,328 |
#!/usr/bin/env python3
#
# idfix.py
#
# Copyright (C) 2013, Jian-Long Huang
# Licensed under The MIT License
# http://opensource.org/licenses/MIT
#
# Author: Jian-Long Huang (jianlong@ntu.edu.tw)
# Version: 0.1
# Created: 2013.1.7
#
# Usage: idfix.py <idmap> <fasta> <output>
import sys
def main():
with open(sys.... | jlhg/bdorpy | bdorpy/idfix.py | Python | mit | 912 |
#! /usr/bin/env python3
# Copyright 2017 John Hanley.
#
# 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, copy, modify, m... | jhanley634/testing-tools | problem/powerset/permutations.py | Python | mit | 3,632 |
"""
[2016-02-17] Challenge #254 [Intermediate] Finding Legal Reversi Moves
https://www.reddit.com/r/dailyprogrammer/comments/468pvf/20160217_challenge_254_intermediate_finding_legal/
# Description
The game of Reversi (or Othello) is a color flipping strategy game played between two players. It's played on an 8x8
unch... | DayGitH/Python-Challenges | DailyProgrammer/DP20160217B.py | Python | mit | 2,571 |
'''
Created on 13-09-2013
@author: kamil
'''
from django.contrib import admin
from officetune.models import Song, Vote
admin.site.register(Vote)
admin.site.register(Song)
| karolmajta/officetune | server/src/officetune/officetune/admin.py | Python | mit | 175 |
import npc
from mako.template import Template
def template_output(sectioner):
template_path = str(npc.settings.InternalSettings().get('listing.templates.markdown.sections.simple'))
section_template = Template(filename=template_path)
return section_template.render(sectioner=sectioner)
def test_generates_ha... | aurule/npc | tests/commands/listing/templates/sections/test_simple_section_md.py | Python | mit | 991 |
# Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import os
import pytest
import random
from ezdxf import recover
from ezdxf.audit import AuditError
from ezdxf.lldxf.tagger import tag_compiler, ascii_tags_loader
BASEDIR = os.path.dirname(__file__)
DATADIR = "data"
RECOVER1 = "recover01.dxf"
RECOVER2 = "rec... | mozman/ezdxf | integration_tests/test_recover.py | Python | mit | 4,960 |
"""
Semiconducting Materials from Analogy and Chemical Theory
A collection of fast screening tools from elemental data
"""
# get correct path for datafiles when called from another directory
from builtins import filter
from builtins import map
from builtins import range
from builtins import object
from os ... | WMD-group/SMACT | smact/__init__.py | Python | mit | 14,679 |
from django.conf import settings
DEFAULTS = {
'SOCIAL_CONTENT_TYPES': (
'Facebook',
'Twitter',
'Instagram',
),
'SOCIAL_CONTENT_MAX_POSTS': None,
# Facebook
'FACEBOOK_APP_ID': None,
'FACEBOOK_APP_SECRET': None,
# Twitter
'TWITTER_CONSUMER_KEY': None,
'TW... | chrisforrette/django-social-content | social_content/conf.py | Python | mit | 814 |
# Generated by Django 2.0.8 on 2018-08-14 10:45
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Banner',
fields=[
('id', models.AutoField(a... | sussexstudent/falmer | falmer/banners/migrations/0001_initial.py | Python | mit | 924 |