code stringlengths 6 947k | repo_name stringlengths 5 100 | path stringlengths 4 226 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k |
|---|---|---|---|---|---|
#!/usr/bin/env python
#
# Copyright (c) 2013, NLnet Labs. All rights reserved.
#
# This software is open source.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must reta... | ncanceill/atlas-dnssec | atlas.py | Python | mit | 6,681 |
"""
"""
import sys
from abc import ABC, abstractmethod
from typing import Any, Sequence, Dict, List, Optional, Callable
from copy import copy,deepcopy
from logging import INFO, DEBUG, ERROR
from datetime import datetime
from vnpy.event import Event, EventEngine
from .event import (
EVENT_TICK,
EVENT_BAR,
... | msincenselee/vnpy | vnpy/trader/gateway.py | Python | mit | 29,138 |
import os
import pytest
import constantstest
@pytest.fixture(scope='session')
def session_test_dir():
return create_dir(os.path.join(constantstest.TEST_RUN_DIR))
@pytest.fixture(scope='module')
def module_test_dir(request):
return create_dir(os.path.join(constantstest.TEST_RUN_DIR, request.module.__name__... | samuel-phan/mssh-copy-id | tests/func-tests/filetest.py | Python | mit | 988 |
from fastapi.testclient import TestClient
from docs_src.path_operation_configuration.tutorial005 import app
client = TestClient(app)
openapi_schema = {
"openapi": "3.0.2",
"info": {"title": "FastAPI", "version": "0.1.0"},
"paths": {
"/items/": {
"post": {
"responses": ... | tiangolo/fastapi | tests/test_tutorial/test_path_operation_configurations/test_tutorial005.py | Python | mit | 4,083 |
# testing configuration
DEBUG = True
TESTING = True
SECRET_KEY = "dummy"
CACHE_NO_NULL_WARNING = True
SQLALCHEMY_DATABASE_URI = "postgres://localhost/seamless_karma_test"
| singingwolfboy/seamless-karma | seamless_karma/config/test_postgres.py | Python | mit | 172 |
from InstagramAPI.src.http.Response.Objects.Comment import Comment
from .Objects.User import User
from .Response import Response
class MediaInfoResponse(Response):
def __init__(self, response):
self.taken_at = None
self.image_url = None
self.like_count = None
self.likers = None
... | danleyb2/Instagram-API | InstagramAPI/src/http/Response/MediaInfoResponse.py | Python | mit | 1,452 |
"""
Copyright (c) 2012 Casey Dunham <casey.dunham@gmail.com>
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, merg... | caseydunham/tweet-dump | tweet-dump.py | Python | mit | 5,740 |
def scale(w, h, x, y, maximum=True):
nw = y * w / h
nh = x * h / w
if maximum ^ (nw >= x):
return nw or 1, y
return x, nh or 1
| ActiveState/code | recipes/Python/577575_scale_rectangle_while_keeping_aspect/recipe-577575.py | Python | mit | 175 |
# *** BFS Graph Solver ***
# (c) Krzysztof Kondrak (at) gmail (dot) com
import sys
import os
import itertools
import getopt
import pickle
from graph import *
from pathFinding import *
from tools import ProgressBar, usage, processGraphFile
sys.path.append(os.getcwd())
SILENT_MODE = False
def Message(msg):
if no... | kondrak/graph_bfs_solver | solver.py | Python | mit | 7,116 |
import random
class Zoo:
noOfAnimals = 0
noOfZoos = 0
def __init__(self, animals, ticketPrice):
Zoo.noOfAnimals += len(animals)
Zoo.noOfZoos += 1
self.ticketPrice = ticketPrice
self.animals = animals
def __iter__(self):
for animal in self.animals:
... | developerQuinnZ/this_will_work | student-work/JacobJanak/class_lessons/zoo.py | Python | mit | 1,060 |
'''Data preparation / preprocessing algorithms.'''
import numpy as np
def scale(x, new_range=(0., 1.), eps=1e-9):
'''Changes the scale of an array
Parameters
----------
x : ndarray
1D array to change the scale (remains unchanged)
new_range : tuple (float, float)
Desired range of ... | atjacobs/PeakUtils | peakutils/prepare.py | Python | mit | 970 |
class fixFileReader:
def __init__(self, inputFilename, myFixParser):
self.myFixParser = myFixParser
self.inputFile = open(inputFilename)
self.securities={}
def __del__(self):
self.inputFile.close()
def updateOrderBookWithNextLine(self):
# Mark the entire order book as not updated
for secu... | benofben/implier | implierWorkspace/Implier/src/fix/fixFileReader.py | Python | mit | 4,271 |
#!/usr/bin/python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of ... | SRombauts/LoggerCpp | cpplint.py | Python | mit | 160,846 |
from __future__ import print_function
import datetime
from couchdbkit import *
from couchdbkit.designer import push
from docs import initvars
import config as cfg
import sys
import json
# Wrap sys.stdout into a StreamWriter to allow writing unicode.
import codecs
import locale
sys.stdout = codecs.getwriter(locale.... | SandStormHoldings/ScratchDocs | couchdb_delviews.py | Python | mit | 530 |
import json
import re
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3 import Retry
URL_TEMPLATE = "https://itunes.apple.com/lookup?id=%s&entity=podcast"
def id_from_url(url):
"""
Extract ID from iTunes podcast URL
:param url (str)
:return: (str)
"""
m... | wotaen/itunes_podcast_rss | extract.py | Python | mit | 1,768 |
"""m_play URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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-base... | bysreg/m_play | src/m_play/m_play/urls.py | Python | mit | 814 |
from mapofinnovation.tests import *
class TestAdminfuncController(TestController):
def test_index(self):
response = self.app.get(url(controller='adminfunc', action='index'))
# Test response...
| AnanseGroup/map-of-innovation | mapofinnovation/tests/functional/test_adminfunc.py | Python | mit | 215 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from os.path import abspath, dirname, join
FIXTURE_ROOT_PATH = abspath(dirname(__file__))
def read_fixture(name):
with open(join(FIXTURE_ROOT_PATH, name), 'r') as fixture:
return fixture.read()
| heynemann/shamester | shamester_api/tests/fixtures/__init__.py | Python | mit | 256 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('editorial', '0062_auto_20171202_1413'),
]
operations = [
migrations.AddField(
model_name='assignment',
... | ProjectFacet/facet | project/editorial/migrations/0063_assignment_complete.py | Python | mit | 453 |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import importlib # noqa
import logging # noqa
import os # noqa
import signal # noqa
import sys # noqa
from . import env
# Setup the environment before loading anything else from the application
#... | christianmemije/kolibri | kolibri/utils/cli.py | Python | mit | 20,522 |
from cStringIO import StringIO
import sys
import cgi
import urllib
import urlparse
import re
import textwrap
from Cookie import BaseCookie
from rfc822 import parsedate_tz, mktime_tz, formatdate
from datetime import datetime, date, timedelta, tzinfo
import time
import calendar
import tempfile
import warnings
from webob.... | sizzlelab/pysmsd | extras/webob/__init__.py | Python | mit | 82,534 |
#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module who manage the log of the script'''
import os
class Log:
'''class who manage the log of the script
there is to log:
the file where is save the log at each new line,
the string who is print eache time that the standart output is erase'''
def __init__(self, star... | CaptainDesAstres/Blender-Render-Manager | log.py | Python | mit | 2,242 |
#!/usr/bin/env python
"""
Extract minor planet orbital elements and discovery dates to json.
Orbital elements are extracted from the file MPCORB.DAT:
https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT
Discovery dates are extracted from the file NumberedMPs.txt:
https://minorplanetcenter.net/iau/lists/NumberedMPs.txt
... | sn3p/Orrery | data/data_to_json.py | Python | mit | 4,117 |
import json, hashlib, os, os.path, shutil
from collections import defaultdict
from datetime import datetime
from typing import List, Dict, Any, cast
from typing_extensions import TypedDict
import shttpfs3.common as sfs
from shttpfs3.storage.server_db import get_server_db_instance_for_thread
import pprint
#++++++++... | robehickman/simple-http-file-sync | shttpfs3/storage/versioned_storage.py | Python | mit | 21,979 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tools/modelbase.py
#
#
# MODEL DEFINITION:
# 1. create a subclass.
# 2. set each definitions as below in the subclass.
#
# __structure__ = {} # define keys and the data type
# __required_fields__ = [] # lists required keys
# __default_values__ = {} # set def... | kazukiotsuka/mongobase | mongobase/modelbase.py | Python | mit | 5,018 |
from django.core.management.base import BaseCommand
from cassandra.cluster import Cluster, NoHostAvailable
class Command(BaseCommand):
#http://datastax.github.io/python-driver/getting_started.html
def handle(self, *args, **options):
print "Running Cassandra Initialize"
cluster = Cluster(['12... | WilliamQLiu/django-cassandra-prototype | cass-prototype/reddit/management/commands/cassandra_initialize.py | Python | mit | 522 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('devices', '0012_auto_20140925_1540'),
]
operations = [
migrations.AlterField(
model_name='ap',
name=... | lindseypack/NIM | devices/migrations/0013_auto_20140925_1616.py | Python | mit | 981 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-13 20:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('kriegspiel', '0003_auto_20170113_2035'),
]
operations ... | Kriegspiel/ks-python-api | kriegspiel_api_server/kriegspiel/migrations/0004_move_created_at.py | Python | mit | 507 |
# coding: utf-8
from sqlalchemy import Column, DateTime, Index, Integer, String, Text, text, \
ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class RedmineToDriveMapping(Base):
__tablename_... | rockdreamer/redmine-docs-to-drive | model.py | Python | mit | 12,096 |
from uchan.lib.tasks import post_task
from uchan.lib.tasks import report_task
| Floens/uchan | uchan/lib/tasks/__init__.py | Python | mit | 78 |
'''
Main learner class.
@author: anze.vavpetic@ijs.si
'''
from collections import defaultdict
from hedwig.core import UnaryPredicate, Rule, Example
from hedwig.core.settings import logger
from hedwig.stats.significance import is_redundant
from hedwig.stats.scorefunctions import interesting
class BottomUpLearner:
... | anzev/hedwig | hedwig/learners/bottomup.py | Python | mit | 2,529 |
"""
Glue for interfacing with a farm object
"""
import os
import ast
from .constants import HealthStatus
def imagesAndStatuses(outputDir):
"""
Return a dictionary of images and corresponding human assigned statuses from output.
"""
controlPath = os.path.join(outputDir, 'controls', 'HealthImageryControl... | ForeverWintr/ImageClassipy | clouds/util/farmglue.py | Python | mit | 2,342 |
import datetime
import hashlib
import copy
import httplib, urllib, urlparse
import collections
__author__ = 'peter.liu@xiaoi.com'
class AskParams:
def __init__(self, platform="", user_id="", url="", response_format="json"):
self.platform = platform
self.user_id = user_id
self.url = url
... | pengzhangdev/slackbot | slackbot/plugins/ibotcloud.py | Python | mit | 6,471 |
import re
from django.test import TestCase
from django.db.utils import IntegrityError
from smartfields.models import SmartfieldsModelMixin
from test_app.models import TextTesting
from test_suite.test_files import add_base
class TextTestCase(TestCase):
def strip(self, text):
return re.sub('( +|\t+|\n+)'... | un33k/django-smartfields | tests/test_suite/test_text.py | Python | mit | 4,733 |
"""
given a BST, find the two nodes that sums up to a value and are the farthest apart.
"""
class Tree:
def __init__(self, val):
self.val = val
self.left = self.right = None
def __repr__(self):
return '[ %d ]' % self.val
def get_tree():
def build_tree(vals):
if not vals:
... | Shaunwei/shua-shua-shua | G_farthest_BST_sum.py | Python | mit | 2,599 |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 26 19:32:49 2018
@author: JinJheng
"""
x,y=map(int,input().split(','))
m,n=map(int,input().split(','))
if n > y:
greater = n
else:
greater = y
while(True):
if((greater % n == 0) and (greater % y == 0)):
q = greater
break
... | KuKuKai/104asiajava | 509.py | Python | mit | 712 |
import datetime
from Tkinter import *
import tkMessageBox
import tkFileDialog
import random
import time
import share
class App(object):
'''Controls the running of the app'''
def __init__(self, master = None):
'''A controller class that runs the app
Constructor: Controller(object)'''
#... | jaric-thorning/ProjectCapital | GUI.py | Python | mit | 6,637 |
#!/usr/bin/env python
import sys
import optparse
import socket
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
if sys.platform == 'win32':
HEADER... | nootropics/propane | propane.py | Python | mit | 3,698 |
from typing import Any
from typing import List
from typing import Optional
from typing import Union
import bpy
import compas_blender
from compas.artists import PrimitiveArtist
from compas.geometry import Line
from compas.colors import Color
from compas_blender.artists import BlenderArtist
class LineArtist(BlenderAr... | compas-dev/compas | src/compas_blender/artists/lineartist.py | Python | mit | 2,962 |
import caffe
import numpy as np
import pdb
class MyLossLayer(caffe.Layer):
"""Layer of Efficient Siamese loss function."""
def setup(self, bottom, top):
self.margin = 10
print '*********************** SETTING UP'
pass
def forward(self, bottom, top):
"""The parameters here ... | xialeiliu/RankIQA | src/MyLossLayer/netloss_tid2013.py | Python | mit | 1,910 |
from builtin import builtin
import constants
import pyphp.phparray as phparray
#import re
WARN_NOT_PCRE = False
USING_PCRE = False
if USING_PCRE:
try:
import pcre as re
USING_PCRE = True
except ImportError, ie:
USING_PCRE = False
if USING_PCRE:
def parse_regex(pat):
... | g-i-o-/pyphp | pyphp/phpbuiltins/regex.py | Python | mit | 2,865 |
# project/models.py
from project import db
from project.uuid_gen import id_column
class Payment(db.Model):
id = id_column()
email = db.Column(db.String(255), unique=False, nullable=False)
names = db.Column(db.String(255), unique=False, nullable=False)
cardNumber = db.Column(db.String(255), unique=Fals... | fiston/abaganga | project/payment/models.py | Python | mit | 932 |
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os","bs4","urllib.request","requests","lxml"], "excludes": ["tkinter"], "include_files":["style.css"]}
# GUI applications require a different base on Wi... | gsidhu/Pretty_Parser | setup.py | Python | mit | 683 |
import itertools
import shutil
from typing import IO, Optional, Union
import click
from mitmproxy import contentviews
from mitmproxy import ctx
from mitmproxy import exceptions
from mitmproxy import flowfilter
from mitmproxy import http
from mitmproxy import flow
from mitmproxy.tcp import TCPFlow, TCPMessage
from mit... | mhils/mitmproxy | mitmproxy/addons/dumper.py | Python | mit | 11,666 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct
import socket
from netlink import *
NETLINK_ROUTE = 0
NETLINK_UNUSED = 1
NETLINK_USERSOCK = 2
NETLINK_FIREWALL = 3
NETLINK_SOCK_DIAG = 4
NETLINK_NFLOG = 5
NETLINK_XFRM = 6
NETLINK_SELINUX ... | tijko/IO-Mon | lib/taskstats/controller.py | Python | mit | 3,616 |
#sum of ascii values of characters in a string
str = raw_input('enter the string:')
ascii_numbers = [ord(c) for c in str]
print ascii_numbers
print sum(ascii_numbers)
| ganesh-95/python-programs | thoughtworks/ascii.py | Python | mit | 197 |
# https://projecteuler.net/problem=20
#
# n! means n × (n − 1) × ... × 3 × 2 × 1
#
# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
#
# Find the sum of the digits in the number 100!
def preCalcFactSum(limit):
ary = [1]
f = 1
... | rahulsrma26/code-gems | ProjectEuler/Problems/problem001_025/Solution020.py | Python | mit | 528 |
from OpenGLCffi.GL import params
@params(api='gl', prms=['n', 'ids'])
def glCreateTransformFeedbacks(n, ids):
pass
@params(api='gl', prms=['xfb', 'index', 'buffer'])
def glTransformFeedbackBufferBase(xfb, index, buffer):
pass
@params(api='gl', prms=['xfb', 'index', 'buffer', 'offset', 'size'])
def glTransformFeed... | cydenix/OpenGLCffi | OpenGLCffi/GL/EXT/ARB/direct_state_access.py | Python | mit | 13,788 |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 4 09:07:22 2016
Vectors and Qvectors use the same metric i.e. the
xyz vector and corresponding ivm vector always have
the same length.
In contrast, the tetravolume.py modules in some cases
assumes that volume and area use R-edge cubes and triangles
for XYZ units resp... | 4dsolutions/Python5 | qrays.py | Python | mit | 11,110 |
import unittest
RESOURCE_NAME = 'Test_Resource'
class BaseEndpointTest(unittest.TestCase):
def setUp(self):
self.endpoint = None
self.resources = {}
self.template = {
'Resources': self.resources
}
def test_resource_name(self):
if self.endpoint:
... | pebble/spacel-provision | src/test/provision/app/alarm/endpoint/__init__.py | Python | mit | 688 |
from scapy.all import *
from termcolor import colored
def pkthandler(pkt):
try:
ip = pkt[IP]
except IndexError:
pass
try:
src = ip.src
dst = ip.dst
except UnboundLocalError:
pass
if pkt.haslayer(DNS):
dns = pkt[DNS]
query = dns[DNSQR]
qtype = dnsqtypes.g... | Dylan-halls/Network-Exploitation-Toolkit | Unpacking/DNS.py | Python | mit | 1,603 |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Kooka-Counter
#Problem level: 7 kyu
from itertools import groupby
def kooka_counter(laughing):
return len([key for key,_ in groupby(laughing.split('a')[:-1])])
| Kunalpod/codewars | kooka-counter.py | Python | mit | 216 |
"""
@brief test log(time=1s)
"""
import unittest
import itertools
from ensae_teaching_cs.td_1a.construction_classique import enumerate_permutations_recursive, enumerate_permutations
class TestClassiquesPermutation(unittest.TestCase):
def test_permutation(self):
self.maxDiff = None
ens = list... | sdpython/ensae_teaching_cs | _unittests/ut_td_1a/test_classique_permutation.py | Python | mit | 794 |
from __future__ import absolute_import, division, print_function
'''
From https://github.com/fchollet/deep-learning-models
'''
import json
from keras.utils.data_utils import get_file
from keras import backend as K
import numpy as np
CLASS_INDEX = None
CLASS_INDEX_PATH = 'https://s3.amazonaws.com/deep-learning-m... | keplr-io/quiver | quiver_engine/imagenet_utils.py | Python | mit | 2,049 |
#!/usr/bin/env python2.7
import argparse,sys
import time as t
parser = argparse.ArgumentParser()
parser.add_argument("--inTSV", help="")
parser.add_argument("--outVCF", help="")
args = parser.parse_args()
def toVCF(TSV, VCF):
'''
:param TSV:
:param VCF:
:return:
'''
out = open(VCF, 'w')
f... | grbot/agd | mamana/templates/TSVtoVCF.py | Python | mit | 950 |
from .mapper import find_mapper, IncompatibleGridError
from .celltopoint import CellToPoint
from .pointtopoint import NearestVal
from .pointtocell import PointToCell
__all__ = [
"find_mapper",
"IncompatibleGridError",
"CellToPoint",
"NearestVal",
"PointToCell",
]
| csdms/coupling | pymt/mappers/__init__.py | Python | mit | 285 |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, "X-Cache")
| cflq3/getcms | plugins/jiasule_cloudsec.py | Python | mit | 126 |
#!/usr/bin/env python
import os
import sys
from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr
from readSettings import ReadSettings
from mkvtomp4 import MkvtoMp4
from deluge_client import DelugeRPCClient
import logging
from logging.config import fileConfig
logpath = '/var/log/sic... | Filechaser/sickbeard_mp4_automator | delugePostProcess.py | Python | mit | 5,303 |
x = 2
print "salam!"
for i in range(10):
print x,
x = x * 2
| amiraliakbari/sharif-mabani-python | by-session/ta-921/j1/turtle7.py | Python | mit | 73 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import division
import logging
import time
from quant import config
from quant.brokers import broker_factory
from .basicbot import BasicBot
from quant.common import log
MESSAGE_TRY_AGAIN = 'Please try again'
class T_Bithumb(BasicBot):
"""
bch:
... | doubleDragon/QuantBot | quant/observers/t_bithumb.py | Python | mit | 40,197 |
import os
import subprocess
import requests
import time
from urlparse import urlparse
from config import config
class Server(object):
"""
Simple helper to start/stop and interact with a tests server
TODO: add method to check what request has been send last by browser
might need this for connect-src ... | ilyanesterov/browser-csp-compatibility | utils/server.py | Python | mit | 4,620 |
"""
Unit tests for the module.
Thomas Ogden <t@ogden.eu>
"""
import os
import unittest
import numpy as np
from maxwellbloch import mb_solve, t_funcs, spectral, utility
# Absolute path of tests/json directory, so that tests can be called from
# different directories.
JSON_DIR = os.path.abspath(os.path.join(__file... | tommyogden/maxwellbloch | maxwellbloch/tests/test_mb_solve.py | Python | mit | 12,255 |
# MIT licensed
# Copyright (c) 2019 lilydjwg <lilydjwg@gmail.com>, et al.
from nvchecker.api import GetVersionError
API_URL = 'https://repology.org/api/v1/project/{}'
async def get_version(name, conf, *, cache, **kwargs):
project = conf.get('repology') or name
repo = conf.get('repo')
subrepo = conf.get('subrep... | lilydjwg/nvchecker | nvchecker_source/repology.py | Python | mit | 896 |
#! /usr/bin/env python3
# This script is for running peru directly from the repo, mainly for
# development. This isn't what gets installed when you install peru. That would
# be a script generated by setup.py, which calls peru.main.main().
import os
import sys
repo_root = os.path.dirname(os.path.realpath(__file__))
... | buildinspace/peru | peru.py | Python | mit | 411 |
# -*- coding: UTF-8 -*-
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models, controller
try:
db.session.add(models.validFields())
db.session.commit()
except:
pass
| cirno-baka/Flask_auth_example | app/__init__.py | Python | mit | 301 |
from recipe_scrapers.innit import Innit
from tests import ScraperTest
class TestInnitScraper(ScraperTest):
scraper_class = Innit
def test_host(self):
self.assertEqual("innit.com", self.harvester_class.host())
def test_title(self):
self.assertEqual(
"Tofu Mixed Greens Salad w... | hhursev/recipe-scraper | tests/test_innit.py | Python | mit | 3,331 |
import plivo, plivoxml
auth_id = "MAODU4MTK1MDC0NTBMMM"
auth_token = "MWVkNWNlZWFlYjRmYmViNDBiZDAwNjA0NjA5OTQz"
p = plivo.RestAPI(auth_id, auth_token)
params = {
'to': '14153163136', # The phone numer to which the all has to be placed
'from' : '1111111111', # The phone number to be used as the caller id
... | lucyzee/plivo_apps | outbound_call.py | Python | mit | 871 |
from app import app
from flask import render_template, make_response, redirect
# Route decorators to referance urls
@app.route('/')
def index():
user = {'nickname': 'Kemal'} # fake user
posts = [ # fake array of posts
{
'author': {'nickname': 'John'},
'body': 'Beautiful day in... | NAU-CFL/CFL_Website | app/views.py | Python | mit | 1,376 |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import unittest
from bs4 import BeautifulSoup
from compute.code import CodeExtractor
logging.basicConfig(level=logging.INFO, format="%(message)s")
class ExtractCodeTest(unittest.TestCase):
def setUp(self):
... | andrewhead/Package-Qualifiers | tests/compute/test_compute_code.py | Python | mit | 4,317 |
import numpy as np
from collections import OrderedDict
import os.path as path
import gzip
# Author: David Qixiang Chen
# email: qixiang.chen@gmail.com
#
# utility nrrd header reader for .nhdr
class NrrdHeader:
def fromNiftiHeader(nifti_header):
header = NrrdHeader()
aff = nifti_header.get_best_affi... | sinkpoint/pynrrd | pynrrd/nrrd.py | Python | mit | 11,390 |
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4
"""Tests window.py for vimiv's test suite."""
import os
from unittest import main, skipUnless
from gi import require_version
require_version('Gtk', '3.0')
from gi.repository import Gdk
from vimiv_testcase import VimivTestCase, refresh_gui
class WindowTest(VimivTest... | karlch/vimiv | tests/window_test.py | Python | mit | 1,521 |
#Defaults - overridable via. pypayd.conf or command-line arguments
DEFAULT_KEYPATH = '0/0/1'
DEFAULT_TICKER = 'dummy'
DEFAULT_CURRENCY = 'USD'
DEFAULT_WALLET_FILE = 'wallet.txt'
DEFAULT_WALLET_PASSWORD = "foobar"
DEFAULT_MNEMONIC_TYPE = "electrumseed"
DB = None
DEFAULT_DB = "pypayd.db"
DEFAULT_TESTNET_DB = "pypayd_tes... | pik/pypayd | pypayd/config.py | Python | mit | 1,595 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Python Word Sense Disambiguation (pyWSD): WSD function tests
#
# Copyright (C) 2014-2015 alvations
# URL:
# For license information, see LICENSE.md
bank_sents = ['I went to the bank to deposit my money',
'The river bank was full of dead fishes']
plant_sents = ['The w... | alvations/pywsd | test_wsd.py | Python | mit | 4,733 |
import os
import jug.backends.redis_store
import jug.backends.file_store
import jug.backends.dict_store
from jug.backends.redis_store import redis
import pytest
if not os.getenv('TEST_REDIS'):
redis = None
try:
redisConnectionError = redis.ConnectionError
except:
redisConnectionError = SystemError
@pytes... | luispedro/jug | jug/tests/test_store.py | Python | mit | 3,891 |
# -*- coding: utf-8 -*-
"""
Created on Wed May 18 18:22:12 2016
@author: ajaver
"""
import os
import cv2
import tables
import numpy as np
from tierpsy.helper.params import read_fps
from tierpsy.helper.misc import TimeCounter, print_flush
def getSubSampleVidName(masked_image_file):
#used by AnalysisPoints.py an... | ver228/tierpsy-tracker | tierpsy/analysis/vid_subsample/createSampleVideo.py | Python | mit | 4,145 |
from canvasapi.canvas_object import CanvasObject
from canvasapi.exceptions import RequiredFieldMissing
from canvasapi.util import combine_kwargs
class QuizGroup(CanvasObject):
def __str__(self):
return "{} ({})".format(self.name, self.id)
def delete(self, **kwargs):
"""
Get details of... | ucfopen/canvasapi | canvasapi/quiz_group.py | Python | mit | 4,094 |
#!/usr/bin/python
"""
Bulk Uploader - Controllers
A simple loader for GIS files in CSV format. Developed primarily for loading Administrative Areas for Haiti.
LICENSE:
This source file is subject to LGPL license that is available
through the world-wide-web at the following URI:
http://www.gn... | luisibanez/SahanaEden | controllers/bulk_gis.py | Python | mit | 8,554 |
# Copyright (c) 2014 The Ekwicoin Core developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Helpful routines for regression testing
#
# Add python-ekwicoinrpc to module search path:
import os
import sys
sys.path.appe... | KaSt/ekwicoin | qa/rpc-tests/util.py | Python | mit | 10,605 |
from django.http import HttpResponseRedirect
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
from re import compile
EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMP... | forestdussault/olc_webportalv2 | olc_webportalv2/users/middleware.py | Python | mit | 1,413 |
from kamo import Template
template = Template("""
%for x in range(1, N):
%if x % 15 == 0:
"fizzbuzz"
%elif x % 3 == 0:
"fizz"
%elif x % 5 == 0:
"buzz"
%else:
${x}
%endif
%endfor
""")
print(template.render(N=100))
| podhmo/kamo | demo/fizzbuzz.py | Python | mit | 224 |
import unittest
from mox import MoxTestBase, IsA, IgnoreArg
import gevent
from gevent.socket import create_connection
from gevent.ssl import SSLSocket
from slimta.edge.smtp import SmtpEdge, SmtpSession
from slimta.envelope import Envelope
from slimta.queue import QueueError
from slimta.smtp.reply import Reply
from sli... | slimta/python-slimta | test/test_slimta_edge_smtp.py | Python | mit | 5,342 |
import versioneer
import os
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
with open('requirements-optional.txt') as f:
optionals = f.read().splitlines()
reqs = []
for ir in required:
if ir[0:3] == 'git':
name = ir.split('/')[-1]
... | opesci/devito | setup.py | Python | mit | 1,948 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""Tests for `dparse.parser`"""
from dparse.parser import parse, Parser
from dparse import filetypes
from packaging.specifiers import SpecifierSet
def test_requirements_with_invalid_requirement():
content = "in=vali===d{}{}{"
... | pyupio/dparse | tests/test_parse.py | Python | mit | 10,268 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('dataset', '0009_remove_selection_model'),
]
operations = [
migrations.AlterField(
model_name='dataset',
... | michaelbrooks/uw-message-coding | message_coding/apps/dataset/migrations/0010_auto_20150619_2106.py | Python | mit | 419 |
"""
WSGI config for common project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os,sys
sys.path.append('/var/www/portal/')
sys.path.append('/var/www/portal/common')
os.env... | Ilyushin/PortalDjango | common/wsgi.py | Python | mit | 469 |
# -*- coding: utf-8 -*-
#
# Blend documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 24 14:11:43 2012.
#
# 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 c... | azavea/blend | docs/conf.py | Python | mit | 7,745 |
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug':('title',)}
list_display = ('title', 'author', 'created_date',)
admin.site.register(Post, PostAdmin)
| JoshAddington/contributr | contributr/contriblog/admin.py | Python | mit | 237 |
"""
Django settings for template 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/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
i... | moshthepitt/answers | template/settings.py | Python | mit | 6,081 |
"""
Mongo database connection class
use mongodb to store/retrive data
"""
from AbstractDb import AbstractDb
class Mongodb(AbstractDb):
pass
| DrewMeyersCUboulder/UPOD_Bridge | Server/Mongodb.py | Python | mit | 147 |
import boto3
from decEncoder import *
from DynamoTable import *
def handler(event, context):
"""Dynamo resource"""
buildingTable = DynamoTable('Buildings')
return getBuildingId(event, buildingTable)
"""Lambda handler function for /buildings/{buildingId} API call
Returns building with the buildingId spe... | jcolekaplan/WNCYC | src/main/api/getBuildingId.py | Python | mit | 1,479 |
'''
Run a variety of turbulent statistics on the full M33 cube.
This will use a TON of memory. Recommend running on a cluster.
File structure setup to work on cedar in scratch space.
Saves the outputs for later use
'''
from spectral_cube import SpectralCube
from astropy.io import fits
from os.path import join as o... | e-koch/VLA_Lband | 14B-088/HI/turbulence/M33_turbstats.py | Python | mit | 5,008 |
try:
from setuptools import setup, Extension
from setuptools.command import install_lib as _install_lib
except ImportError:
from distutils.core import setup, Extension
from distutils.command import install_lib as _install_lib
from codecs import open
from os import path
from os import environ
from sys import pla... | jruizgit/rules | setup.py | Python | mit | 2,665 |
"""
WSGI config for freedoge project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "freedoge.settings")
from dj_static i... | craigatron/freedoge | freedoge/wsgi.py | Python | mit | 426 |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import super
from future import standard_library
standard_library.install_aliases()
from vcfx.field.nodes import Field
class Categories(Field):
KEY = "C... | Pholey/vcfx | vcfx/field/explanatory/nodes.py | Python | mit | 1,485 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RailReservation.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| KeshavSeth/RailwayReservationSystem | src/manage.py | Python | mit | 258 |
#!/usr/bin/env python
def get_yz_vals(x):
b = -1
yVals = []
while x ** 2 + 1 > b * x and b != x:
a = (x ** 2) - (b * x) + 1
if a % b == 0:
yVals.append((b - x, a / b))
b -= 1
return yVals
if __name__ == '__main__':
count = 0
x = -1
answers = []
while... | dcjohnson/Project-Euler | 221/221.py | Python | mit | 554 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-08-19 19:46
from __future__ import unicode_literals
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Cr... | Dybov/real_estate_agency | real_estate_agency/applications/migrations/0001_initial.py | Python | mit | 1,441 |
import numpy as np
import random
class NeuralNetwork():
def __init__(self, sizes):
# sizes is an array with the number of units in each layer
# [2,3,1] means w neurons of input, 3 in the hidden layer and 1 as output
self.num_layers = len(sizes)
self.sizes = sizes
# the syn... | guilhermefloriani/signature-recognition | network.py | Python | mit | 4,512 |
from rpython.annotator import model as annmodel
from rpython.rlib import jit
from rpython.rtyper import rint
from rpython.rtyper.error import TyperError
from rpython.rtyper.lltypesystem.lltype import Signed, Bool, Void, UniChar
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.rmodel import IteratorRep... | oblique-labs/pyVM | rpython/rtyper/rstr.py | Python | mit | 35,786 |
import re
################################################################################
# Human Command Protocol
################################################################################
class HumanCommandProtocol:
def __init__(self):
self.commands = (('^help', self.help),)
def help(s... | michaeldove/abode | chat/protocol.py | Python | mit | 735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.