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 |
|---|---|---|---|---|---|
"""
metakit.py -- Utility code for the Python interface to Metakit
$Id: metakit.py 1669 2007-06-16 00:23:25Z jcw $
This is part of Metakit, see http://www.equi4.com/metakit.html
This wraps the raw Mk4py compiled extension interface.
To use Metakit through this interface, simply do:
import metakit
After that, things ... | electric-cloud/metakit | python/metakit.py | Python | mit | 2,471 |
import tensorflow as tf
from networks.network import Network
from fcn.config import cfg
zero_out_module = tf.load_op_library('lib/triplet_flow_loss/triplet_flow_loss.so')
class custom_network(Network):
def __init__(self):
self.inputs = cfg.INPUT
# self.input_format = input_format
self.num... | daweim0/Just-some-image-features | lib/networks/net_labeled_concat_features_shallower.py | Python | mit | 12,807 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import platform
import re
import unittest
import warnings
import random
import sys
from pymatgen import SETTINGS, __version__ as pmg_version
from pymatgen.ext.matproj import MPRester, MPRestError, TaskType
from ... | gVallverdu/pymatgen | pymatgen/ext/tests/test_matproj.py | Python | mit | 21,960 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Triangle Project Code.
# Triangle analyzes the lengths of the sides of a triangle
# (represented by a, b and c) and returns the type of triangle.
#
# It returns:
# 'equilateral' if all sides are equal
# 'isosceles' if exactly 2 sides are equal
# 'scalene' ... | MichaelSEA/python_koans | python3/koans/triangle.py | Python | mit | 1,017 |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# sliding window
max_len = 0
li = 0
ri = 0
l = 0
inserted = False
for ri, rval in enumerate(nums):
if rval =... | daicang/Leetcode-solutions | 487-max-consecutive-ones-ii.py | Python | mit | 773 |
# # # # #
# armoreServer.py
#
# This file is used to serve up
# RESTful links that can be
# consumed by a frontend system
#
# University of Illinois/NCSA Open Source License
# Copyright (c) 2015 Information Trust Institute
# All rights reserved.
#
# Developed by:
#
# Information Trust Institute
# University of Illinois... | GridProtectionAlliance/ARMORE | source/webServer/armoreServer.py | Python | mit | 6,634 |
# -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from apm.buildout.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of apm.buildout into Plone."""
def setUp(self):
"""Custom shared utility setup for tests.""... | a25kk/apm | src/apm.sitetheme/apm/sitetheme/tests/test_setup.py | Python | mit | 1,143 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-29 06:36
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('books', '0005_book_tags'),
]
operations = [
migrations.AlterModelOptions(
... | djangogirlstaipei/eshop | bookshop/books/migrations/0006_auto_20161129_0636.py | Python | mit | 747 |
#!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the scantxoutset rpc call."""
from test_framework.test_framework import BitcoinTestFramework
from ... | nikkitan/bitcoin | test/functional/rpc_scantxoutset.py | Python | mit | 13,144 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-08-01 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import jsonfield.fields
import proso.django.models
class Migration(migrations.Migration):
initial = True
dependencies = [... | adaptive-learning/proso-apps | proso_tasks/migrations/0001_initial.py | Python | mit | 4,601 |
import sys
import os
import argparse
import tqdm
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from keras.models import load_model
from vis.visualization.saliency import visualize_cam
from train import DataGenerator
from visualize import plot_row_item
def get_model_predict... | yujanshrestha/pre-trained-keras-example | cam_animation.py | Python | mit | 3,666 |
import numpy as np
import keras
from keras.datasets import mnist
from keras.models import Model, Sequential
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.layers import Flatten, Reshape
from keras import regularizers
from plotly import offline as py
import plotly.graph_objs as go
... | Christoph/tag-connect | keyvis_add/ml.py | Python | mit | 2,394 |
from django.db import models
class Person(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=45, blank=False, null=False)
lastname = models.CharField(max_length=45, blank=False, null=False)
genre = models.CharField(max_length=1, blank=True, null=True)
alive... | gnzandrs/opencare | src/server/api/Opencare/person/models.py | Python | mit | 495 |
# -*- coding: utf-8 -*-
import random
import string
from django.db import models
from django.utils import timezone
from django.conf import settings
def random_string(n=100):
return ''.join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(n)
)
class AuthT... | Kriegspiel/ks-python-api | kriegspiel_api_server/api/models/auth_token.py | Python | mit | 539 |
import logging
import os
from tempfile import mkdtemp
from .repositories import Repository, AuthenticatedRepository
log = logging.getLogger(__name__)
class RepoManager(object):
"""
Manages creation and deletion of `Repository` objects.
"""
to_cleanup = {}
def __init__(self, authenticated=False,... | richtier/imhotep | imhotep/repomanagers.py | Python | mit | 4,477 |
from time import sleep
import sys
import os
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
p1 = 14
p2 = 15
GPIO.setup(p1, GPIO.OUT)
GPIO.setup(p2, GPIO.OUT)
class Quit(Exception): pass
def green(duration):
GPIO.output(p1, False)
GPIO.output(p2, True)
sleep(duration)
GPIO.output(p2, False)
def red(duration):
... | Nilpo/RPi-Samples | metronome_led.py | Python | mit | 1,233 |
from .base import *
from .local import *
FB_APP_ID = "557603244304943" | amol-mandhane/konnactivity | settings/__init__.py | Python | mit | 71 |
from utils.property import cached_property
from utils.dict import mget,kwargs_str
from utils.list import sort
from giftwrap import Auth, Exchange, JsonExchange
from .webinar import Webinar
from .session import Session
from sanetime import time,delta
API_TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
DEFAULT_HISTORY_DELTA = delta... | prior/gtwpy | gtw/organizer.py | Python | mit | 3,650 |
# -*- coding: utf-8 -*-
import logging
import random
from collections import (
namedtuple,
defaultdict,
)
from itertools import repeat
import cachetools
import gevent
from gevent.event import (
_AbstractLinkable,
AsyncResult,
Event,
)
from ethereum import slogging
from raiden.exceptions import (
... | tomashaber/raiden | raiden/network/protocol.py | Python | mit | 24,753 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
# Url Patterns from the root.
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^aboutme/', 'blog.views.aboutme'),
url(r'^contact/', 'blog.views.contact'),
url(r'^$', 'blog.views.index'),
... | vikrampriya/portfolio | portfolio/urls.py | Python | mit | 372 |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Frappe Technologies and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
import frappe.desk.form.document_follow as document_follow
class TestDocumentFollow(unittest.TestCase):
def test_document_follow(self):
user = g... | saurabh6790/frappe | frappe/email/doctype/document_follow/test_document_follow.py | Python | mit | 1,735 |
"""
utilities.py
"""
from flask import url_for
def _get_project_path():
""" Return absolute path to planet_express, without trailing slash"""
# Assumes that the project folder is one up from here, at ./..
import sys, os
my_folder = os.path.dirname(os.path.realpath(__file__))
parent_folder = os.pa... | MarlboroCollegeComputerScience/flask_sql_planet_express | src/utilities.py | Python | mit | 503 |
import csv
import collections
import itertools
def evaluateDuplicates(found_dupes, true_dupes):
true_positives = found_dupes.intersection(true_dupes)
false_positives = found_dupes.difference(true_dupes)
uncovered_dupes = true_dupes.difference(found_dupes)
print('found duplicate')
print(len(found_d... | dedupeio/dedupe-examples | patent_example/patent_evaluation.py | Python | mit | 1,311 |
from vmupdate.config import config
from vmupdate.errors import UpdateError
from vmupdate.pkgmgr import get_pkgmgrs, run_pkgmgr
from vmupdate.vm import VM
from tests.case import TestCase
from tests.constants import *
from tests.context import get_data_path, mock
from tests.mocks import get_mock_virtualizer, get_mock_ss... | CorwinTanner/vmupdate | tests/test_pkgmgr.py | Python | mit | 1,900 |
import sys
import math
from PyQt4 import QtGui, QtCore, uic
from PyQt4.QtCore import Qt, QObject, QEvent, pyqtSignal
from PyQt4.QtCore import QPoint, QRect, QSize
##----------------------------------------------------------------##
def _getModulePath( path ):
import os.path
return os.path.dirname( __file__ ) + '/' +... | tommo/gii | lib/gii/qt/controls/GraphicsView/TimelineWidget.py | Python | mit | 25,976 |
#!/usr/bin/env python
"""
fla.gr user model
Given a userID or a username or a email, return the users couchc.database ORM
http://xkcd.com/353/
Josh Ashby
2013
http://joshashby.com
joshuaashby@joshashby.com
"""
from couchdb.mapping import Document, TextField, DateTimeField, \
BooleanField, IntegerField
impor... | JoshAshby/Fla.gr | app/models/couch/user/userModel.py | Python | mit | 3,412 |
"""
Django settings for rivannastreamwatch project.
Generated by 'django-admin startproject' using Django 1.11.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
... | erinspace/rivannastreamwatch_api | rivannastreamwatch/settings.py | Python | mit | 3,277 |
#!/usr/bin/env python
import argparse
import email
import bisect
try:
from imapclient import IMAPClient
except ImportError:
import sys
print >>sys.stderr, """This script requires IMAPClient, a convenient Python IMAP library.
http://imapclient.freshfoo.com/
You can install it using PyPI:
(sudo) pip in... | praus/Label-Big-Mail | big_mail_labeler.py | Python | mit | 3,890 |
import os
import sys
#import feedparser
#from bs4 import BeautifulStoneSoup
from bs4 import BeautifulSoup
#from nltk import clean_html
import urllib
import re
import json
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field
from ... | koneman/NGOpycrawl | NGOcrawler/spiders/spider_base.py | Python | mit | 5,932 |
# cloudscope.utils.timez
# Time string utilities for ensuring that the timezone is properly handled.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Tue Nov 24 17:35:49 2015 -0500
#
# Copyright (C) 2015 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: timez.py [d0f0ca1] benjamin@bengf... | bbengfort/cloudscope | cloudscope/utils/timez.py | Python | mit | 3,309 |
import hypergan as hg
from hypergan.layer_shape import LayerShape
from . import Operation
class Mul(Operation):
"""
---
description: 'layer mul for configurable component'
---
# mul layer
Multiplies two or more layers together. Accepts nested layer definitions.
##... | 255BITS/HyperGAN | hypergan/layers/mul.py | Python | mit | 702 |
#!/usr/bin/env python3
from datetime import datetime
import psutil
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('direction', type=str,
choices=['left', 'right'])
args = parser.parse_args()
status = ''
if args.direction == 'left':
status = '<fc=#B27AEB><fn... | bamos/dotfiles | .xmonad/xmobar.py | Python | mit | 655 |
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
Builder.load_file('toolbox.kv')
Builder.load_file('generaloptions.kv')
Builder.load_file('statusbar.kv')
Builder.load_file('drawingspace.kv')
class ComicCreator(AnchorLayout):
pass
class ComicCreatorApp(App):
... | pimier15/PyGUI | Kivy/Kivy/Bk_Interractive/My/C1/Proj_ComicBook/comiccreator.py | Python | mit | 434 |
#!/usr/bin/python
# use ogr to make a new shapefile with select by attributes
# note that 'ogr2ogr -sql' is way awesomer
# this script was nearly written by http://gis.stackexchange.com/ user Luke: http://gis.stackexchange.com/questions/68650/ogr-how-to-save-layer-from-attributefilter-to-a-shape-filter
# example use: ... | albert-decatur/gis-utils | selectByAttributes.py | Python | mit | 909 |
import os
import warnings
from static_precompiler import exceptions, utils
from . import base
__all__ = (
"Babel",
)
class Babel(base.BaseCompiler):
name = "babel"
input_extension = "es6"
output_extension = "js"
def __init__(self, executable="babel", sourcemap_enabled=False, modules=None, plu... | liumengjun/django-static-precompiler | static_precompiler/compilers/babel.py | Python | mit | 2,171 |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... | rogerscristo/BotFWD | env/lib/python3.6/site-packages/pytests/test_inlinequeryresultlocation.py | Python | mit | 5,366 |
# -*- coding: utf-8 -*-
"""Contains a quick-and-dirty client for talking to a Razor server.
Rather than enumerating an API that has lots of warning labels and stickers
cautioning that the API might change frequently, I'm letting the razor server
drive. This class will, when given a host and port, ask razor for its API... | fhats/py_razor_client | py_razor_client/razor_client.py | Python | mit | 4,490 |
"""app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... | matokeotz/matokeo-api | app/app/urls.py | Python | mit | 1,219 |
# -*- encoding: utf-8 -*-
from supriya.tools.ugentools.WidthFirstUGen import WidthFirstUGen
class IFFT(WidthFirstUGen):
r'''An inverse fast Fourier transform.
::
>>> pv_chain = ugentools.LocalBuf(2048)
>>> ifft = ugentools.IFFT.ar(
... pv_chain=pv_chain,
... window_si... | andrewyoung1991/supriya | supriya/tools/ugentools/IFFT.py | Python | mit | 4,524 |
import subprocess
import unittest
import os
class TestCmdLine(unittest.TestCase):
"""
Those tests are against the lwp command lines
"""
def test_01_generate_secret(self):
assert not os.path.exists('/etc/lwp/session_secret')
assert not os.path.exists('/etc/lwp/lwp.conf')
subpr... | claudyus/LXC-Web-Panel | tests/utils.py | Python | mit | 755 |
import os
import pytest
from click.testing import CliRunner
from verta._cli import cli
from verta._internal_utils import _config_utils
pytest.skip("repository sub-CLI has been disabled", allow_module_level=True)
class TestInit:
def test_init(self):
runner = CliRunner()
with runner.isolated_fil... | mitdbg/modeldb | client/verta/tests/test_cli/test_repository.py | Python | mit | 3,580 |
sum = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
print sum
| huangshenno1/algo | project_euler/1.py | Python | mit | 84 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import os
import json
SPLIT_CHAR = '#'
MSG_SPLIT_CHAR = '@'
MIN_BETWEEN_BEFORE_AFTER = 1
if len(sys.argv) < 3:
print "引数が足りない(<infile1> <infile2>)"
sys.exit(1)
in_file_1 = sys.argv[1]
in_file_2 = sys.argv[2]
out_file = "combined_file.txt"
wf = open(out... | supertask/ChainX | server/websocket/recorded_operations/combiner.py | Python | mit | 1,425 |
"""empty message
Revision ID: f719fe7c700a
Revises: b8fa640ec739
Create Date: 2017-02-15 19:55:55.163798
"""
# revision identifiers, used by Alembic.
revision = 'f719fe7c700a'
down_revision = 'b8fa640ec739'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... | indonoso/small-Inventory | migrations/versions/f719fe7c700a_.py | Python | mit | 1,179 |
"""
==============================================
The :mod:`mpi_array.globale_ufunc_test` Module
==============================================
Module defining :mod:`mpi_array.globale` unit-tests.
Execute as::
python -m mpi_array.globale_ufunc_test
and with parallelism::
mpirun -n 2 python -m mpi_array.glob... | mpi-array/mpi_array | mpi_array/globale_ufunc_test.py | Python | mit | 33,737 |
"""
Wrappers to make file-like objects cooperative.
.. class:: FileObject
The main entry point to the file-like gevent-compatible behaviour. It will be defined
to be the best available implementation.
There are two main implementations of ``FileObject``. On all systems,
there is :class:`FileObjectThread` which... | burzillibus/RobHome | venv/lib/python2.7/site-packages/gevent/fileobject.py | Python | mit | 7,896 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import model_utils.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODE... | slafs/dibs | src/dibs/migrations/0001_initial.py | Python | mit | 1,831 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from celery import shared_task
from celery.utils.log import get_task_logger
from django.contrib.auth import get_user_model
logger = get_task_logger(__name__)
@shared_task
def notify(sender, to, topic=None, post=None):
from niji.models import Notific... | ericls/niji | niji/tasks.py | Python | mit | 984 |
"""State class definition."""
from . import get_db
db = get_db()
class State(db.Model):
"""State class.
Extends Model of 'Flask-SQLAlchemy'.
"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(32), nullable=False)
value = db.Column(db.Integer, unique=True, nullable=F... | mmktomato/zenmai-bts | web/models/state.py | Python | mit | 690 |
from datetime import datetime
from datetime import timezone
import singer
import urllib.request
def my_ip():
now = datetime.now(timezone.utc).isoformat()
schema = {
'properties': {
'ip': {'type': 'string'},
'timestamp': {'type': 'string', 'format': 'date-time'},
},
... | karantan/singer-getting-started | src/main.py | Python | mit | 617 |
# coding: utf-8
"""FETCH parser tests."""
from __future__ import print_function
import unittest
import six
from modoboa_webmail.lib.fetch_parser import FetchResponseParser
from . import data
def dump_bodystructure(fp, bs, depth=0):
"""Dump a parsed BODYSTRUCTURE."""
indentation = " " * (depth * 4)
f... | modoboa/modoboa-webmail | modoboa_webmail/tests/test_fetch_parser.py | Python | mit | 3,016 |
from collections import defaultdict
import fileinput
mem = defaultdict(int)
s1 = -100000
s2 = -100000
def condition(line):
global mem
l = line[-3:]
if l[1] == "==":
if mem[l[0]] == int(l[2]): return True
else: return False
elif l[1] == "<":
if mem[l[0]] < int(l[2]): return Tru... | zigapk/adventofcode | 2017/8/main.py | Python | mit | 1,081 |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
import logging
import optparse
import os
import sys
import shutil
import te... | bitdeal/bitdeal | qa/rpc-tests/test_framework/test_framework.py | Python | mit | 7,473 |
from allauth.account.forms import *
class MyLoginForm(LoginForm):
def __init__(self, *args, **kwargs):
super(MyLoginForm, self).__init__(*args, **kwargs)
self.fields['login'].label = "이메일"
self.fields['password'].label = "비밀번호"
self.fields['remember'].label = "로그인 상태 유지"
#... | yeongseon/django_beautifulseodang | home/forms.py | Python | mit | 899 |
from django.template import Library
from django.utils.functional import Promise
import json
register = Library()
@register.filter
def json_dumps(json_object):
if isinstance(json_object, Promise):
json_object = dict(json_object)
return json.dumps(json_object)
@register.filter
def json_dumps_pretty(js... | DylanMcCall/stuartmccall.ca | common/templatetags/json_tools.py | Python | mit | 482 |
import sys
from captcha import get_version as get_captcha_version
from setuptools import find_packages, setup
from setuptools.command.test import test as test_command
class Tox(test_command):
user_options = [("tox-args=", "a", "Arguments to pass to tox")]
def initialize_options(self):
test_command.i... | mbi/django-simple-captcha | setup.py | Python | mit | 2,125 |
__author__ = 'briannelson'
from SID.Utilities import ConfigUtility
from SIDClient.Controllers import SendToSidWatchServerController
config = ConfigUtility.load('./Config/sidwatch.cfg')
controller = SendToSidWatchServerController(config)
controller.start()
| SidWatch/pySIDWatch | Source/SendToSidWatchServer.py | Python | mit | 261 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from powerpages.settings import app_settings
class NamedURL(object):
"""Wrapper over named URLs to provide lazy reversion"""
def __init__(self, name, *args, **kwargs):
self.name = name
... | Open-E-WEB/django-powerpages | powerpages/sitemap_config.py | Python | mit | 3,800 |
# -*- coding:utf8 -*-
# File : progress.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 2/26/17
#
# This file is part of TensorArtist.
from tartist.core.utils.thirdparty import get_tqdm_defaults
import tqdm
import numpy as np
def enable_epoch_progress(trainer):
pbar = None
def epoch_... | vacancy/TensorArtist | tartist/plugins/trainer_enhancer/progress.py | Python | mit | 1,402 |
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from CustomUser.models import PSUCustomUser
# Register your models here.
class UserChangeForm(forms.ModelForm):
class Meta:
model = PSUCustomUser
f... | hhauer/myinfo | CustomUser/admin.py | Python | mit | 1,737 |
from theano.tensor.shared_randomstreams import RandomStreams
from ..initializer import Xavier, Zero, Initializer
from params import ParamStore, Param
__author__ = 'victor'
import numpy as np
from theano import tensor as T, function, shared, config
class Layer(dict):
count = 0
def __init__(self, *args, **kwa... | vzhong/pystacks | pystacks/layers/common.py | Python | mit | 3,933 |
# -*- coding: utf-8 -*-
"""
Included class for human interaction via console.
Prints position and takes move written in algebraic notation as string input
Copyright © 2016 Aubhro Sengupta. All rights reserved.
"""
from chess_py.core.algebraic import converter
from chess_py.players.player import Player
try:
inpu... | LordDarkula/chess_py | chess_py/players/human.py | Python | mit | 994 |
'''
Authors: Donnie Marino, Kostas Stamatiou
Contact: dmarino@digitalglobe.com
Unit tests for the gbdxtools.Catalog class
'''
from gbdxtools import Interface
from gbdxtools.catalog import Catalog
from auth_mock import get_mock_gbdx_session
import vcr
import unittest
"""
How to use the mock_gbdx_session and vcr to cr... | michaelconnor00/gbdxtools | tests/unit/test_catalog.py | Python | mit | 9,207 |
"""This module includes objects that store parameter specfications and
efficiently convert between parameter dictionaries and parameter vectors
necessary for fitting algorithms. There are submodules for parameter priors,
common parameter transformations, and pre-defined sets of parameter
specifications.
"""
from .sed... | bd-j/prospector | prospect/models/__init__.py | Python | mit | 518 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.api.app_identity.app_identity import get_default_gcs_bucket_name
from google.appengine.ext.blobstore import blobstore
from blob_app import blob_facade
from config.template_middleware import TemplateResponse
from gaec... | renzon/appengineepython | backend/appengine/routes/updown/home.py | Python | mit | 1,716 |
from django.contrib import admin, messages
from .tasks import import_areas_from_kml_file
from .models import Area, AreaMap, DataMap, AreaBin
class AreaAdmin(admin.ModelAdmin):
list_display = ("id", "name", "area_type")
class AreaMapAdmin(admin.ModelAdmin):
list_display = ("id", "name", "data_source", "da... | matthewoconnor/maps | map/admin.py | Python | mit | 975 |
# -*- coding: utf-8 -*-
"""
sphinx.ext.pngmath
~~~~~~~~~~~~~~~~~~
Render math in HTML via dvipng. This extension has been deprecated; please
use sphinx.ext.imgmath instead.
:copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
i... | neerajvashistha/pa-dude | lib/python2.7/site-packages/sphinx/ext/pngmath.py | Python | mit | 9,187 |
"""
@name: Modules/families/UPB/UPB_data.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Aug 6, 2014
@summary: This module is for communicating with UPB controllers.
"""
__updated__ = '2020-02-17'
# ... | DBrianKimmel/PyHouse | Project/src/Modules/House/Family/Upb/upb_data.py | Python | mit | 787 |
"""Class to perform under-sampling based on one-sided selection method."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
from collections import Counter
import numpy as np
from sklearn.base import clone
from sklearn.neighbors import KNeighborsClassifier
from sklear... | scikit-learn-contrib/imbalanced-learn | imblearn/under_sampling/_prototype_selection/_one_sided_selection.py | Python | mit | 7,093 |
import unittest
import logging
from harmoniccontext.harmonic_context import HarmonicContext
from harmoniccontext.harmonic_context_track import HarmonicContextTrack
from harmonicmodel.secondary_chord_template import SecondaryChordTemplate
from harmonicmodel.tertian_chord_template import TertianChordTemplate
from struc... | dpazel/music_rep | tests/transformation_tests/reflection_tests/test_t_chromatic_reflection.py | Python | mit | 7,963 |
"""File holds the three classes Bit, DigitProduct, and PartialProduct."""
class Bit:
"""Class Bit represents a single bit of a digit-product."""
def __init__(self, identifier, absolute, relative):
self.identifier = identifier
self.absolute = absolute
self.relative = relative
def s... | Koppermann/mod-mul-mersenne | mod_mul_mersenne/classes.py | Python | mit | 2,433 |
#!/usr/bin/env python
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
# TODO: put package requireme... | bstinsonmhk/python-template | {{cookiecutter.project_repo}}/setup.py | Python | mit | 1,796 |
from maze_builder.sewer import MadLibs, Choice
from maze_builder.lost_text.text_decorations import fix_sentence
negative_status_sentence = MadLibs({
'{NEGATIVE_STATUS INTENSIFIED SENTENCE FIXED}': 1,
'{NEGATIVE_STATUS SENTENCE FIXED}': 1,
},
FIXED=fix_sentence,
SENTENCE={
'{}.': 30... | kcsaff/maze-builder | maze_builder/lost_text/negative_status.py | Python | mit | 5,360 |
# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from editor.models import Source, Format, Category
class Command(BaseCommand):
help = 'Adds root category for Source, Format and Category models.'
def _change_root(self, model_class, verbosity=1):
ROOT_NAME = '!ROOT!'
... | CivicKnowledge/metaeditor | editor/management/commands/create_roots.py | Python | mit | 1,850 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-26 13:33
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('annotations', '0007_auto_20170826_1446'),
]
def... | bit-bots/imagetagger | src/imagetagger/annotations/migrations/0008_auto_20170826_1533.py | Python | mit | 1,648 |
#!/usr/bin/env python2
import i3ipc
import subprocess
# process all windows on this workspace. hide when leaving and show when entering
# because chrome/ium doesnt consider itself hidden when on an invisible workspace
# this script drops my cpu usage when listening to google music from ~10% to ~3%
# I'm just putting... | lbeckman314/dotfiles | i3/musicwatcher.py | Python | mit | 1,595 |
def checkPrime(primes, test):
i = 0
isPrime = True
while(i<= len(primes) and primes[i]<= int(test ** (1/2))):
if(test % primes[i] == 0):
isPrime = False
break
i+=1
return isPrime
primes = [2]
i = 3
lastTest = int((2 * (10**9))**(1/2)) #Square Root of 2 * 10 ^9
#build an array of primes up t... | clemus90/competitive-programming | hackerRank/crackingTheCodingInterview/time_complexity_primality.py | Python | mit | 622 |
#!flask/bin/python
from migrate.versioning import api
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
api.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
v = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)
print('Current database version: ' + str(v))
| Sanjurjo7/microblog | db_upgrade.py | Python | mit | 317 |
from fabric.colors import *
from fabric.contrib.console import confirm
from contextlib import contextmanager
from fabric.api import *
from fabric.contrib.project import rsync_project
from fabric.contrib.files import exists
import os
env.user = "root"
env.hosts = ['__var_pooled_server_ip__']
env.key_filename = '__var_s... | zinglax/SPA-BoilerPlate2017 | app/stock/spa/fabfile.py | Python | mit | 2,980 |
"""
Passing arguments to decorators
------------------------------
Looking back at the example before the one above, you can notice how
redundant the decorators in the example are. 3 decorators(div_decorate,
p_decorate, strong_decorate) each with the same functionality but wrapping
the string with different tags. We ca... | spradeepv/dive-into-python | decorators/passing_args_to_decorators.py | Python | mit | 753 |
from PyQt5.QtCore import pyqtSignal, QObject
from core.baseSocket import BaseSocket
from core.upload import Upload
from core.download import Download
from core.config import Settings
from core.cryptogram import Cryptogram
from core import utils
class Signal(QObject):
# def __init__(self):
# super(UploadSig... | yxwzaxns/cowry | client/core/ftpClient.py | Python | mit | 11,520 |
import unittest
import os
import json
import time
from os import environ
from ConfigParser import ConfigParser
from pprint import pprint
from biokbase.workspace.client import Workspace as workspaceService
from MyContigFilter.MyContigFilterImpl import MyContigFilter
class MyContigFilterTest(unittest.TestCase):
... | briehl/wjr_sdk_test | test/MyContigFilter_server_test.py | Python | mit | 4,171 |
def fizzbuzz(x):
return 'fizzbuzz' if x % 15 == 0 else 'fizz' if x % 3 == 0 else 'buzz' if x % 5 == 0 else x
for y in [fizzbuzz(x) for x in range(1, 101)]:
print y
| orende/intro-till-python | ex5d.py | Python | mit | 173 |
from vkapp.bot.models import Blogger, News, AdminReview, Publication
from .usersDAO import get_or_create_blogger
from datetime import datetime, timedelta, time
def new_news(link, media, uid, pic):
blogger = get_or_create_blogger(uid)
news = News(link=link, blogger=blogger, media=media, pic=pic)
news.save(... | ParuninPavel/lenta4_hack | vkapp/bot/dao/newsDAO.py | Python | mit | 1,222 |
"""Visualizes top 5 power lines by variance"""
import sys
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
sys.path.append("../")
from utils.utils import *
interval = '1D'
def d_resample(df):
if interval:
return df.resample(interval).mean()
else:
return df
sca... | alex-bauer/kelvin-power-challenge | src/viz/power_analysis.py | Python | mit | 708 |
from box.models import *
gold = ThingsType(title="Золото", kind=2, color="Жёлтый")
gold.save()
ferrum = ThingsType(title="Железо", kind=2, color="Чёрный")
ferrum.save()
ring = Thing(title="Кольцо", things_type=gold)
ring.save()
hammer = Thing(title="Молоток", things_type=ferrum)
hammer.save()
| h4/fuit-webdev | examples/lesson5/pandora_data.py | Python | mit | 335 |
# coding=utf-8
from django.db import models
from tests.testapp.constants import ModelState
from tximmutability.models import MutableModel
from tximmutability.rule import MutabilityRule
class AbstractImmutableModel(MutableModel):
name = models.CharField(
null=False, max_length=50, default='Immutable Mode... | txerpa/dj-tximmutability | tests/testapp/models.py | Python | mit | 3,872 |
# Alien Blaster
# Demonstrates object interaction
class Player(object):
""" A player in a shooter game. """
def blast(self, enemy):
print("The player blasts an enemy.\n")
enemy.die()
class Alien(object):
""" An alien in a shooter game. """
def die(self):
print("The alien gasps ... | bohdan-shramko/learning-python | source/chapter09/alien_blaster.py | Python | mit | 656 |
import binascii
import socket
import struct
import sys
def ten_digit_to_comma_format(badge):
"""Returns the comma-format RFID number (without the comma) from the
10-digit RFID number.
Explanation:
*On an EM4100/4001 spec RFID card, there will generally be two sets of
numbers like this: 0015362878... | pawl/Chinese-RFID-Access-Control-Library | rfid.py | Python | mit | 9,417 |
import six
from django.conf import settings
from .utils import load_path_attr
STRIPE_PUBLIC_KEY = settings.STRIPE_PUBLIC_KEY
INVOICE_FROM_EMAIL = getattr(
settings,
"PAYMENTS_INVOICE_FROM_EMAIL",
"billing@example.com"
)
PAYMENTS_PLANS = getattr(settings, "PAYMENTS_PLANS", {})
PLAN_CHOICES = [
(plan, ... | aibon/django-stripe-payments | payments/settings.py | Python | mit | 1,269 |
# -*- coding: utf-8 -*-
# author: Alfred
from db2charts.settings import analysis_db_modules
from django.db import models as django_models
class AnalysisBase(object):
def __init__(self):
super(AnalysisBase, self).__init__()
self.modules = analysis_db_modules
def get_dbs(self):
return s... | Alfredx/django-db2charts | db2charts/analysis/base.py | Python | mit | 1,025 |
text = 'this is a sample file\nnew line'
savefile = open('newtext', 'w')
savefile.write(text)
savefile.close()
| Faraaz54/python_training_problems | basic_python/write_file.py | Python | mit | 123 |
from fractions import gcd
def greatest_common_divisor(*args):
args = list(args)
a, b = args.pop(), args.pop()
gcd_local = gcd(a, b)
while len(args):
gcd_local = gcd(gcd_local, args.pop())
return gcd_local
def test_function():
assert greatest_common_divisor(6, 10, 15) == 1, "12"
a... | denisbalyko/checkio-solution | gcd.py | Python | mit | 635 |
import boto
import argparse
try:
import urllib2
except ImportError: # Python 3
import urllib.request as urllib2
from awsutil.logger import logger
def set_public_record():
parser = argparse.ArgumentParser(description="Updates DNS records")
parser.add_argument(
"--address",
default=url... | opalmer/aws | awsutil/dns.py | Python | mit | 1,168 |
"""
A simple sample of using a wx.Overlay to draw a rubberband effect
"""
import wx
print(wx.version())
class TestPanel(wx.Panel):
def __init__(self, *args, **kw):
wx.Panel.__init__(self, *args, **kw)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
... | dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/samples/overlay/overlay.py | Python | mit | 2,662 |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
import os
import json
from glob import iglob
from decimal import Decimal, InvalidOperation
try:
from collections import OrderedDict
except ImportError:
# Fallback for python 2.6
from ordereddict import OrderedDict
... | python-febraban/cnab240 | cnab240/registro.py | Python | mit | 6,950 |
# ============================================================================
# FILE: make.py
# AUTHOR: Johannes Ziegenbalg <Johannes dot Ziegenbalg at gmail.com>
# License: MIT license
# ============================================================================
import re
import shlex
import os, sys, stat
from os i... | JoZie/denite-make | rplugin/python3/denite/source/make.py | Python | mit | 5,366 |
from historyemergent import app
# Comment out the line below if you are using something other than the built-in
# Flask development server
app.run(host='127.0.0.1', port=5000, debug=True) | kylewmoser/HistoryEmergent | run.py | Python | mit | 187 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db.models import F, Func, Value
class AlphabeticalPaginationMixin(object):
alphabetical_pagination_field = 'name'
def get_alphabetical_pagination_field(self):
return self.alphabetical_pagination_field
def get_selected_l... | sha-red/django-shared-utils | shared/utils/views/alphabetical_pagination.py | Python | mit | 1,768 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('exhibitors', '0002_auto_20160409_2110'),
]
operations = [
migrations.AlterField(
model_name='exhibitorlistplugin... | modelbrouwers/modelbouwdag.nl | src/modelbouwdag/exhibitors/migrations/0003_auto_20160409_2153.py | Python | mit | 448 |