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 |
|---|---|---|---|---|---|
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'students.views.home', name='home'),
# url(r'^students/', include('students.foo.urls')),
... | pkuhad/django-student | students/urls.py | Python | mit | 684 |
"""Wrapper for running Freebayes.
"""
import collections
import errno
import fileinput
import glob
import tempfile
import os
import shutil
import subprocess
import vcf
from celery import task
from django.conf import settings
from main.models import Dataset
from main.model_utils import get_dataset_with_type
from pipe... | woodymit/millstone | genome_designer/pipeline/variant_calling/freebayes.py | Python | mit | 10,343 |
"""
Module to translate various names (unicode, LaTeX & other text) for characters to encodings in the Symbol font standard encodings.
Also, provide grace markup strings for them.
It recognizes unicode names for the greek alphabet and most of the useful symbols in the Symbol font.
Marcus Mendenhall, Vanderbilt Univer... | bt3gl/Plotting-in-Linux | grace/src/symbol_mapping.py | Python | mit | 8,291 |
#! /usr/bin/env python
from __future__ import print_function
import os
import sys
import logging
import argparse
sys.path.append(
os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..")))
from mykatlas.version import __version__
from mykatlas.base import ArgumentParserWi... | Phelimb/atlas | mykatlas/atlas_main.py | Python | mit | 8,067 |
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Frank Scholz <coherence@beebits.net>
"""
Test cases for L{dbus_service}
"""
import os
from twisted.trial import unittest
from twisted.internet import reactor
from twisted.internet.defer impor... | unintended/Cohen | tests/test_dbus.py | Python | mit | 3,086 |
import os
import django
from django.contrib.auth import get_user_model
os.environ['DJANGO_SETTINGS_MODULE'] = os.getenv('DJANGO_SETTINGS_MODULE')
django.setup()
username = os.getenv('DJANGO_OSMAXX_CONVERSION_SERVICE_USERNAME')
password = os.getenv('DJANGO_OSMAXX_CONVERSION_SERVICE_PASSWORD')
def create_user(user_na... | geometalab/osmaxx-frontend | docker_entrypoint/osmaxx/conversion_service/create_user_entrypoint.py | Python | mit | 958 |
"""Defines exceptions specific to this project"""
class CryptoBaseException(Exception):
"""Base exception to be inherited by other exceptions"""
def __init__(self, value):
"""Set the exception's message and cause"""
self.value = value
def __str__(self):
"""Return a string represe... | FreakJoe/cryptolockpy | cryptolock/exceptions.py | Python | mit | 1,180 |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from electrum_gui.kivy.i18n import _
Builder.load_string('''
<FeeDialog@Popup>
id: popup
title: _('Transaction Fees')
size_hint: 0.8, 0.8
pos_hint: {'top':0.9}
method:... | kyuupichan/electrum | gui/kivy/uix/dialogs/fee_dialog.py | Python | mit | 4,529 |
from .private_keychain import PrivateKeychain
from .public_keychain import PublicKeychain
| blockstack/keychain-manager-py | keychain/__init__.py | Python | mit | 90 |
__author__ = 'Daniel'
from UserData import config
def get_integer_input(query="", default=None):
"""
Takes a query and gets an input from the user
:param query:
:param default:
:return:
"""
res = ""
while not str.isnumeric(res):
res = input(query)
if res == "" and defau... | daniellowtw/MentalMaths | utility.py | Python | mit | 472 |
# coding: utf-8
# 文字列は""でも''でもいいよ
print "hello" + ' world'
print u"ほげ" * 5
print u"明日も\tきっと\tハレルヤ\n\"\\\\あははは。\""
# 複数行に渡るときは"を3回続ければいい
print u"""
今日も
いい
天気
です
ね
"""
| TomckySan/python-training | string.py | Python | mit | 278 |
"""
Brewery Example - merge multiple CSV files
Input: Multiple CSV files with different fields, but with common subset of
fields.
Output: Single CSV file with all fields from all files and with additional
column with origin file name
Run:
$ python merge_multiple_files.py
Afterwards display ... | Stiivi/brewery | examples/merge_multiple_files/merge_multiple_files.py | Python | mit | 2,107 |
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 u... | gnmiller/craig-bot | craig-bot/lib/python3.6/site-packages/discord/colour.py | Python | mit | 7,005 |
from redis import Redis
from runserver import host
# rethink config
RDB_HOST = 'localhost'
RDB_PORT = 28015
TODO_DB = 'knuth'
rds = Redis()
DEFAULT_PIC = 'https://github.com/identicons/'
FB_APP_ID = 122742198082740
FB_APP_SECRET = "8474009531f56532cf1e194df6afd53d"
CAPTCHA_SECRET = '6LesFgwTAAAAAIy1YjMlYaWJ27QbqXP4... | nirmitgoyal/longclaw | config.py | Python | mit | 427 |
import clr
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
def t... | dimven/SpringNodes | py/Element.IsCut.py | Python | mit | 932 |
from django.shortcuts import render, render_to_response
from django.contrib import auth
from django.core.context_processors import csrf
from django.contrib.auth.decorators import login_required
from .models import Ticket, UserProfile, Order, TicketType, OrderType
from django.core.mail import send_mail
from django.templ... | abogeorge/simpleTicket | simpleTicket/siteEngine/views.py | Python | mit | 15,240 |
#!/usr/bin/env/python
"""
We treat each silica atom as its own residue. As a consequence,
we have more than 10000 residues in the system.
The silly PDB format only allows up to 9999 residues. We solve
this issue by manually creating a .gro file, which allows for
up to 99999 residues
"""
from __future__ import print_f... | jmborr/confinedBSA | simulation/silica/cristobalite/confineBSA/poretop/nobonds/adaptPDB.py | Python | mit | 1,589 |
from datetime import timedelta
from math import copysign
def is_workingday(input_date):
return input_date.isoweekday() < 6
def add(datestart, days):
sign = lambda x: int(copysign(1, x))
dateend = datestart
while days:
dateend = dateend + timedelta(days=sign(days))
if is_workingday(date... | baxeico/pyworkingdays | workingdays/__init__.py | Python | mit | 947 |
#--coding: utf8--
from django.shortcuts import render
from templated_docs import fill_template
from templated_docs.http import FileResponse
from invoices.forms import InvoiceForm
def invoice_view(request):
form = InvoiceForm(request.POST or None)
if form.is_valid():
doctype = form.cleaned_data['fo... | alexmorozov/templated-docs | example/invoices/views.py | Python | mit | 643 |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import json
import logging
import struct
import sys
class IODIMetadata(object):
# This needs to match the defin... | facebook/redex | tools/python/symbolicator/iodi.py | Python | mit | 3,369 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os
import ldap
import time
import paramiko
import traceback
import codecs
import subprocess
from cgi import escape
from vmchecker import paths, update_db, penalty, submissions, submit, coursedb
from vmchecker.coursedb import ... | calin-iorgulescu/vmchecker | vmchecker/websutil.py | Python | mit | 27,704 |
"""
Current FlexGet version.
This is contained in a separate file so that it can be easily read by setup.py, and easily edited and committed by
release scripts in continuous integration. Should (almost) never be set manually.
The version should always be set to the <next release version>.dev
The jenkins release job wi... | antivirtel/Flexget | flexget/_version.py | Python | mit | 453 |
from django.db import models
# Create your models here.
from django.db.models import TextField, BooleanField, ImageField
class Product(models.Model):
photo = ImageField(upload_to='products')
class Meta:
abstract = True
class Blind(Product):
name = TextField()
child_safe = BooleanField()
... | CloudNcodeInc/silk | tests/example_app/models.py | Python | mit | 367 |
from typing import TYPE_CHECKING, List, Optional
import strawberry
from api.languages.types import Language
from api.submissions.types import Submission
from api.users.types import User
from strawberry.types.datetime import DateTime
if TYPE_CHECKING: # pragma: no cover
from api.conferences.types import Conferenc... | patrick91/pycon | backend/api/schedule/types.py | Python | mit | 1,130 |
#!/usr/bin/env priithon
import os, sys
import six
import wx, wx.lib.scrolledpanel as scrolled
import wx.lib.agw.aui as aui # from wxpython4.0, wx.aui does not work well, use this instead
try:
from ..Priithon import histogram, useful as U
from ..PriCommon import guiFuncs as G ,microscope, imgResample
... | macronucleus/chromagnon | Chromagnon/ndviewer/main.py | Python | mit | 43,167 |
" Userman: Dump the database into a JSON file."
import json
import tarfile
from cStringIO import StringIO
from userman import utils
from userman import constants
def dump(db, filename):
"""Dump contents of the database to a tar file, optionally compressed.
Return the number of items, and the number of attac... | pekrau/userman | userman/dump.py | Python | mit | 3,017 |
#!/usr/bin/env python3
class Solution():
def numSubarrayProductLessThanK(self, nums, k):
lo, prod = 0, 1
ret = 0
for hi, n in enumerate(nums):
prod *= n
while lo <= hi and prod >= k:
prod //= nums[lo]
lo += 1
ret += (hi-lo+... | eroicaleo/LearningPython | interview/leet/713_Subarray_Product_Less_Than_K.py | Python | mit | 434 |
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HCommunityPerson_if_ConnectedLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HCommunityPerson_if_ConnectedLHS.
"""... | levilucio/SyVOLT | ATLTrans/props/HCommunityPerson_if_ConnectedLHS.py | Python | mit | 2,695 |
import pprint
from itertools import permutations
places = set()
route_table = dict()
filename = '09.txt'
def add_to_route_table(start, dest, distance):
places.add(start)
places.add(dest)
if not start in route_table:
route_table[start] = dict()
if not dest in route_table[start]:
route_... | peschkaj/adventofcode | python/09.py | Python | mit | 1,075 |
#!/usr/bin/env python
# coding=utf-8
""" An example showcasing the logging system of Sacred."""
import logging
from sacred import Experiment
ex = Experiment("log_example")
# set up a custom logger
logger = logging.getLogger("mylogger")
logger.handlers = []
ch = logging.StreamHandler()
formatter = logging.Formatter('... | IDSIA/sacred | examples/log_example.py | Python | mit | 999 |
class SkipList:
def __init__(self):
self.head = None
| robin1885/algorithms-exercises-using-python | source-code-from-author-book/Listings-for-Second-Edition/listing_8_14.py | Python | mit | 65 |
"""
Django settings for becours project.
Generated by 'django-admin startproject' using Django 1.10.5.
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... | eedf/becours | becours/settings.py | Python | mit | 3,562 |
from ancestration import family
super_family = family.tests.family_a()
ClassA = family_class('ClassA', (object,), {
'a': lambda self: 'family_b: A',
'd': lambda self: 'family_b: A',
})
adopt(module='tests.adopt_into_b') | IvIePhisto/Ancestration | tests/family_b.py | Python | mit | 231 |
# -*- coding: utf-8 -*-
from collections import deque
import logging
import locale
locale.setlocale(locale.LC_ALL, "")
logger = logging.getLogger(__name__)
class Window_Stack_Constants(object):
''' Modes of Operation '''
DEPENDENCY_ERROR = -2
NO_PLAYER_ERROR_MODE = -1
NORMAL_MODE = 0
PLAYLIST_MODE... | coderholic/pyradio | pyradio/window_stack.py | Python | mit | 16,747 |
#Packetloss measurement with the FPGA + OSA crosstalk reading on new switch
from structureFiling import *
import LivePCAPReader as PCAPReader
from sys import argv
script, filename = argv;
def main():
#now time to read in some of the initial configurations
#might not need this since we can save the configurati... | elopezga/ErrorRate | ErrorRate/crosstalkpacketloss.py | Python | mit | 2,801 |
from draw import *
from effects import *
from chart import *
| J216/gimp_be | gimp_be/draw/__init__.py | Python | mit | 61 |
# -*- coding: utf-8 -*-
'''
This example demonstrates the skosprovider API with a simple
DictionaryProvider containing just three items.
'''
from pyld import jsonld
import json
from skosprovider.providers import DictionaryProvider
from skosprovider.uri import UriPatternGenerator
from skosprovider.skos import ConceptS... | koenedaele/skosprovider | examples/dump_jsonld.py | Python | mit | 3,074 |
"""
Abstract base class for stream filters
"""
import six
from collections import namedtuple
from warnings import warn
from ..misc import ensure_str, MetaGettable
base = namedtuple('StreamFilter', ('filter_name','decoder', 'EOD', 'encoder'))
base.__new__.__defaults__ = (None, None)
class StreamFilterBase(base)... | ajmarks/gymnast | gymnast/filters/stream_filter.py | Python | mit | 2,087 |
### NOTE NEED TO MANUALLY DELETE COMMA AFTER LAST POINT
LEDS_PER_METER = 30.0
# Dimensions from http://www.ikea.com/us/en/catalog/products/S99932597/
COUCH_WIDTH = 2.18
COUCH_DEPTH = 0.88
def layout_leds(width, depth, leds_per_meter):
led_coordinates = []
direction = ""
next_direction = "east"
x = -width/2
... | gregmarra/pxlart | layouts/couch_layout_gen.py | Python | mit | 1,417 |
from __future__ import absolute_import, print_function, unicode_literals
import dbus
import time
import sys
SERVICE_NAME = "org.bluez"
ADAPTER_INTERFACE = SERVICE_NAME + ".Adapter1"
DEVICE_INTERFACE = SERVICE_NAME + ".Device1"
PROFILE_MANAGER = SERVICE_NAME + ".ProfileManager1"
def get_managed_objects():
bus = db... | Octane70/BluePad | bluepad/utils.py | Python | mit | 4,859 |
#!/usr/bin/env python
from setuptools import setup
setup(
name="blackjack",
setup_requires=["vcversioner"],
vcversioner={},
py_modules=["blackjack"],
author="Corbin Simpson",
author_email="cds@corbinsimpson.com",
description="Red-black trees",
long_description=open("README.rst").read()... | MostAwesomeDude/blackjack | setup.py | Python | mit | 402 |
#!/usr/bin/env python
"""
This application demonstrates writing a series of values at a regular interval.
$ python RecurringWriteProperty.py 1.2.3.4 analogValue:1 \
presentValue 1.2 3.4 5.6
"""
import sys
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import... | JoelBender/bacpypes | samples/RecurringWriteProperty.py | Python | mit | 4,423 |
#!/usr/bin/env python3
import requests
giphy_api_key = "YOUR API KEY"
# Can be fetched from https://developers.giphy.com/dashboard/
def get_gifs(query: str, api_key: str = giphy_api_key) -> list:
"""
Get a list of URLs of GIFs based on a given query..
"""
formatted_query = "+".join(query.split())
... | TheAlgorithms/Python | web_programming/giphy.py | Python | mit | 562 |
from . import expression, units
parse = expression.Maker()
parse_with_units = units.inject(parse)
| timedata-org/expressy | expressy/__init__.py | Python | mit | 99 |
# maker.py
#
# A class representing vcdMaker specific test.
#
# Copyright (c) 2019 vcdMaker team
#
# 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 limit... | WojciechRynczuk/vcdMaker | test/functional/maker.py | Python | mit | 2,819 |
from models.pusher import push
print repr(push("Bazinga..."))
| uniite/pyirc | test_msg.py | Python | mit | 63 |
#!/usr/bin/env python3
from sys import stdin
import sys
import re
integer = "(0|-?[1-9]\d*)"
MAX = 10**15
cases = 0
while True:
line = stdin.readline()
if len(line) == 0:
break
assert re.match(integer + " " + integer + "\n", line), "'%s' is not a pair of integers" % line
(n, m) = map(int, li... | Kattis/problemtools | examples/different/input_format_validators/validate.py | Python | mit | 574 |
from flask.ext.wtf import Form
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import DataRequired, Length
class EntryForm(Form):
title = StringField('Title', validators=[
DataRequired(),
Length(1, 64)
])
text = TextAreaField('Text', validators=[DataRequ... | mxamin/exflaskr-irpycon-2015 | app/main/forms.py | Python | mit | 361 |
from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import *
from pyramid.security import authenticated_userid
from pyramid.security import forget
from pyramid.security import remember
from sqlalchemy.exc import DBAPIError
from sq... | digitalprime/pastebunker | pastebunker/views.py | Python | mit | 6,040 |
import json
import threading
import os
import codecs
import logging
from config import config
logger = logging.getLogger(config['logging']['name'])
# 1.acquire file write lock
# 2.write to file.new
# 4.rename file to file.old
# 5.rename file.new to file
# 6.remove file.old
# 7.release write lock
# *. lock should be... | usc-isi-i2/mydig-webservice | ws/data_persistence.py | Python | mit | 1,945 |
False
True
None # 作为默认参数的初始值
NotImplemented
Ellipsis
# 以下不是用于项目的
'''
quit(code=None)
exit(code=None)
copyright
license
credits
'''
| Chyroc/study-code | Language/Python/BuildInConstants.py | Python | mit | 170 |
from django.conf import settings
from django.db import models
# Create your models here.
from products.models import Product
class Transaction(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
product = models.ForeignKey(Product)
price = models.DecimalField(max_digits=100, decimal_places=2, defaul... | codingforentrepreneurs/digital-marketplace | src/billing/models.py | Python | mit | 589 |
from setuptools import find_packages, setup
setup(
name='subjunctive',
version='0.1',
install_requires=[
'PySDL2 ==0.8.0',
],
packages=find_packages(),
scripts=[
'games/think-green/think-green.py',
'games/floorpaint/floorpaint.py',
],
)
| kalgynirae/subjunctive | setup.py | Python | mit | 290 |
import pytest
import cryptopals.common as common
def test_base64_from_hex():
assert 'SGVsbG8sIHdvcmxkIQ==' == common.base64_from_hex('48656c6c6f2c20776f726c6421')
@pytest.mark.parametrize('first_bytes, second_bytes, expected_output', [
(b'Hello,', b'World!', 17),
(b'foo', b'bar', 8),
(b'baz', b'qux... | edwardsdl/cryptopals | cryptopals/tests/test_common.py | Python | mit | 1,109 |
from enum import Enum
from collections import namedtuple
import settings
import os
import dbaccess
import urllib.request
import ast
import shutil
def move_file(filename, src, dest):
src = os.path.join(src, filename)
dest = os.path.join(dest, filename)
shutil.move(src, dest)
def create_file(filename, path... | thyagostall/apollo | src/problem.py | Python | mit | 6,320 |
import math
from src.timetable_exceptions import InvalidTimeException
## Right now I'm not using datetime because the time of day for the class
# should be timestamp-independent
## 1440 is the amount of minutes in a single day, starting from 0
def getHoursAndMins(timeNum):
amtOfHours = math.floor(timeNum / 60)
... | Coteh/timetable | src/time_converter.py | Python | mit | 1,745 |
from twisted.trial.unittest import TestCase
from txaws.server.call import Call
class CallTestCase(TestCase):
def test_default_version(self):
"""
If no version is explicitly requested, C{version} is set to
2009-11-30, which is the earliest version we support.
"""
call = Ca... | lud4ik/txAWS | txaws/server/tests/test_call.py | Python | mit | 378 |
sum_of_even = 0
prev = 0
current = 1
next = current
while (prev+current) <= 4000000:
next = prev + current
prev = current
current = next
if next % 2 == 0:
sum_of_even += next
print "The sum of all even is %s" % sum_of_even
| MartinSeeler/euler-python | problem-2.py | Python | mit | 252 |
# Simple 1D GP classification example
import time
import numpy as np
import matplotlib.pyplot as plt
import GPpref
import plot_tools as ptt
from active_learners import ActiveLearner, UCBLatent, PeakComparitor, LikelihoodImprovement, ABSThresh, UCBAbsRel
import test_data
import pickle
class Learner(object):
def __i... | nrjl/GPN | active_statruns.py | Python | mit | 7,118 |
# Copyright (c) 2016 Uber Technologies, Inc.
#
# 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, merge, publ... | uber/tchannel-python | tchannel/rw.py | Python | mit | 19,427 |
# 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 ... | AutorestCI/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_11_01/models/topology_parameters.py | Python | mit | 1,697 |
"""
CONVENTIONS:
- A timesheet object is a Pandas DataFrame object with at least the columns
* ``'date'``: date worked was done; datetime object
* ``'project'``: project the work is part of
* ``'duration'``: time spent on work; hours
- A biller is a univariate function that maps duration to cost (in some... | araichev/invoicing | invoicing/main.py | Python | mit | 10,632 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(verbo... | Ourinternet/website | commission/migrations/0001_initial.py | Python | mit | 10,354 |
# Copyright (C) 2016 Intel Corporation
# Released under the MIT license (see COPYING.MIT)
from functools import wraps
class OETestDecorator(object):
case = None # Reference of OETestCase decorated
attrs = None # Attributes to be loaded by decorator implementation
def __init__(self, *args, **kwargs):
... | alimon/oeqa2 | oeqa2/test/decorator/__init__.py | Python | mit | 1,356 |
import os
from flask import current_app as app
from flask_restplus import Namespace, Resource
from requests import get
from backend.util.response.store.product_results import ProductResultsResponse
from backend.util.response.error import ErrorResponse
from backend.controller import ErrorHandler
productNS = Namespace... | willrp/willbuyer | backend/controller/api/store/product/product.py | Python | mit | 1,589 |
"""
@author: Sze "Ron" Chau
@e-mail: chaus3@wit.edu
@source: https://github.com/wodiesan/sweet-skoomabot
@desc Night sensor-->RPi for Senior Design 1
"""
import logging
import os
import RPi.GPIO as GPIO
import serial
import subprocess
import sys
import time
import traceback
# GPIO pins. Uses the BC... | wodiesan/senior_design_spring | night_sensor/night_feature.py | Python | mit | 1,274 |
# Initialization for package.
__author__ = "Ben Storer <bastorer@uwaterloo.ca>"
__date__ = "29th of April, 2015"
# Read in the defined functions. Not strictly necessary,
# but makes usage nicer. i.e. now we can use
# matpy.cheb(5) instead of matpy.cheb.cheb(5).
from .cheb import cheb
from .darkjet import darkjet
#fr... | bastorer/SPINSpy | matpy/__init__.py | Python | mit | 506 |
import sys
import json
import datetime
from django.utils import timezone
from django.core.serializers.json import DjangoJSONEncoder
from .event import Event
is_python3 = sys.version_info >= (3,)
# minutes before purging an event from the database
EVENT_TIMEOUT = 60 * 24
# attempt to trim this many events per pass
EV... | fanout/django-eventstream | django_eventstream/storage.py | Python | mit | 2,978 |
# The MIT License (MIT)
#
# Copyright (c) 2015 Christian Zielinski
#
# 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, cop... | czielinski/portfolioopt | portfolioopt/portfolioopt.py | Python | mit | 9,550 |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2014 deanishe@deanishe.net
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on 2014-04-06
#
"""
Run background tasks
"""
from __future__ import print_function, unicode_literals
import sys
import os
import subprocess
import pickle
from workfl... | dalimatt/Instastalk | dependencies/workflow/background.py | Python | mit | 7,361 |
# eval.py
# Python Lisp EVALuation function
import importlib
from .common import Symbol, List
from .env import global_env
def get_var(x, env):
" Look up a variable in the env. If it's not there, look it up globally. "
try:
val = env[x]
except KeyError:
try:
val = globals()[x]... | SilverWingedSeraph/pyparens | parens/eval.py | Python | mit | 4,263 |
from ..utils.api import api_handler
from ..utils.decorators import detect_batch_decorator
@detect_batch_decorator
def sentiment(text, cloud=None, batch=False, api_key=None, version=None, **kwargs):
"""
Given input text, returns a scalar estimate of the sentiment of that text.
Values are roughly in the ran... | IndicoDataSolutions/IndicoIo-python | indicoio/text/sentiment.py | Python | mit | 1,009 |
def grab_email(files = []):
# if passed a list of text files, will return a list of
# email addresses found in the files, matched according to
# basic address conventions. Note: supports most possible
# names, but not all valid ones.
found = []
if files != None:
mailsrch = re.compil... | ActiveState/code | recipes/Python/138889_extract_email_addresses/recipe-138889.py | Python | mit | 743 |
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Model, NOT_PROVIDED, DateTimeField
from django.utils import timezone
from django.utils.encoding import smart_text
def track_field(field):
"""
Returns whether the given field should be tracked by... | kbussell/django-auditlog | src/auditlog/diff.py | Python | mit | 5,123 |
#!/usr/bin/env python
"""
This file computes the raw defect energies (for vacancy and antisite defects)
by parsing the vasprun.xml files in the VASP DFT calculations
for binary intermetallics, where the meta data is in the folder name
"""
#from __future__ import unicode_literals
from __future__ import division
__au... | mbkumar/pydii | examples/NiAl_mp-1487/gen_def_energy.py | Python | mit | 9,115 |
# -*- coding: utf-8 -*-
import datetime
import math
from flask import current_app
from models import (
Achievement,
Coupon,
GlobalStatistics,
Level,
LevelInstanceUser,
LevelStatistics,
Organization,
OrganizationAchievement,
OrganizationCoupon,
OrganizationLevel,
Organizati... | pathwar/api.pathwar.net | pathwar_api/jobs.py | Python | mit | 7,149 |
#!/usr/bin/env python2
# encoding: utf-8
"""
A system tray icon indicates whether Firefox is running or not.
I use Firefox and I have lots of tabs opened in it (I'm lazy to delete
the old ones). As a result, when I close Firefox before shutting down
my machine, Firefox needs several seconds to fully close (on one of
... | jabbalaci/FirefoxChecker | systray.py | Python | mit | 4,260 |
import json
import os
import urllib
data = {} # Initialising an empty Dictionary
print("Chose the language of your preference :")
print("1 NodeJs")
print("2 php")
print("3 Python")
print("Enter the number to proceed"),
# Storing a {'language':'value'} pair in the Dictionary
readInt = int(input())
if(readInt == 1) :
... | IIITA-Framework/Py-interpreter | main.py | Python | mit | 3,754 |
# pylint: disable=C0111,R0903
"""Toggle twmn notifications.
Requires the following executable:
* systemctl
contributed by `Pseudonick47 <https://github.com/Pseudonick47>`_ - many thanks!
"""
import core.module
import core.widget
import core.input
import core.decorators
import util.cli
class Module(core.modul... | tobi-wan-kenobi/bumblebee-status | bumblebee_status/modules/contrib/twmn.py | Python | mit | 1,236 |
import _plotly_utils.basevalidators
class ShowticklabelsValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="showticklabels", parent_name="layout.yaxis", **kwargs
):
super(ShowticklabelsValidator, self).__init__(
plotly_name=plotly_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/layout/yaxis/_showticklabels.py | Python | mit | 484 |
# -*- coding: utf-8 -*-
from flask import Flask, request
from fbmq import Page, QuickReply, Attachment, Template
import requests, records, re, json
from flask_restful import Resource, Api
token = '<auth token here>'
metricsData = {}
macid = 111111111111
pg = Page(token)
import time
db = records.Database('mysql://<user>... | Knapsacks/power-pi-v2 | facebook-messenger-bot/app.py | Python | mit | 5,321 |
from miniworld import log
from miniworld.Scenario import scenario_config
from miniworld.model.network.linkqualitymodels import LinkQualityModel, LinkQualityConstants
__author__ = 'Nils Schmidt'
class LinkQualityModelRange(LinkQualityModel.LinkQualityModel):
#####################################################
... | miniworld-project/miniworld_core | miniworld/model/network/linkqualitymodels/LinkQualityModelRange.py | Python | mit | 6,220 |
"""
A fake data generator
"""
import random
import numpy as np
from deepchem.data import NumpyDataset
from deepchem.feat import GraphData
class FakeGraphGenerator:
"""Generates a random graphs which can be used for testing or other purposes.
The generated graph supports both node-level and graph-level labels.
... | deepchem/deepchem | deepchem/utils/fake_data_generator.py | Python | mit | 5,524 |
import _plotly_utils.basevalidators
class ColorscaleValidator(_plotly_utils.basevalidators.ColorscaleValidator):
def __init__(self, plotly_name="colorscale", parent_name="heatmap", **kwargs):
super(ColorscaleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... | plotly/plotly.py | packages/python/plotly/plotly/validators/heatmap/_colorscale.py | Python | mit | 491 |
def getSublists(L, n):
sublists = []
for i in range(len(L)):
next_sublist = L[i:i+n]
if len(next_sublist) == n:
sublists.append(next_sublist)
return sublists
# Test Cases
L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2]
print getSublists(L, 4) == [[10, 4, 6, 8], [4, 6, 8, 3], [6, 8, 3, 4]... | NicholasAsimov/courses | 6.00.1x/final/p4-1.py | Python | mit | 459 |
#
import string
import glob
import time
import xml.etree.ElementTree as ET
from itertools import chain
# Import reader
import xlrd
import csv
import requests
# Import data handlers
import collections
# Import Network Analysis Tools
import networkx as nx
import igraph as ig
# Import language processing tools
from g... | chreman/isis-praktikum | sustainabilitylsa.py | Python | mit | 20,232 |
# Copyright (c) 2007, 2008, 2009, 2010, 2011 Andrey Golovizin
#
# 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, ... | rybesh/pybtex | pybtex/bibtex/names.py | Python | mit | 6,400 |
from rest_framework import generics
from rest_framework import permissions
from django.contrib.auth.models import User
from train_traffic_app.models import TrainTrafficRequest
from train_traffic_app.serializers import TrainTrafficRequestSerializer
from train_traffic_app.serializers import UserSerializer
from train_tr... | guibargar/stt-api | train_traffic_app/views.py | Python | mit | 1,323 |
from matchers import (
linear_match as html_match,
prune_unmatched_elements
)
from spec import (
a,
accordion,
acc_body,
acc_group,
acc_heading,
div,
elem,
heading,
html,
img,
input,
option,
option_xhtml,
select,
text,
)
from formatters import (
... | thomasdunton/python-html-assert | pha/__init__.py | Python | mit | 351 |
"""Tests for RamlWrap"""
import inspect
import json
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../")))
from django.test import TestCase, Client
def _get_parent_class(method):
"""Return the class for the given method."""
members = inspect.getmember... | jmons/ramlwrap | tests/RamlWrapTest/tests/test_raml_v1.py | Python | mit | 1,448 |
import threading
import time
from collections import Counter
from httpLogSettings import WAIT_PERIOD_S
class AnalyticsThread(threading.Thread):
'''Background thread to record and aggregate statistics about requests'''
def __init__(self, updatePeriod, q, lock):
threading.Thread.__init__(self)
... | luchasei/http-log-app | httpLogAnalytics.py | Python | mit | 1,523 |
# Lior Hirschfeld
# JargonBot
# -- Imports --
import re
import pickle
import random
import praw
from custombot import RedditBot
from time import sleep
from define import getDefinition
from collections import Counter
from nltk.stem import *
from sklearn import linear_model
# -- Setup Variables --
jargonBot = RedditBo... | lhirschfeld/JargonBot | jargonbot.py | Python | mit | 5,805 |
import numpy as np
import subprocess
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def draw_scene(scene_string, filename='out.png', my_ax=None, dpi=500,
save_file=False, chop=True):
asy_string = """
import three;
import graph3;
setti... | talonchandler/dipsim | notes/2017-10-10-voxel-reconstruction/figures/my_draw_scene.py | Python | mit | 5,943 |
__author__ = 'lew'
import unittest
import random
from binary_dec_converter import to_binary, to_decimal
class TestBinaryDecConverted(unittest.TestCase):
def setUp(self):
self.random_numbers = []
for i in range(100):
self.random_numbers.append(random.randint(1,1000000000000))
def t... | LGordon2/Projects | Python/binary_dec_converter/test_binary_dec_converter.py | Python | mit | 681 |
"""
Copyright (c) 2014 Marshall Farrier
license http://opensource.org/licenses/MIT
@author: Marshall Farrier
@contact: marshalldfarrier@gmail.com
@since: 2014-11-10
@summary: Neural network
Resources:
Great performance ideas:
http://stackoverflow.com/questions/21106134/numpy-pure-functions-for-performance-caching
"""
... | aisthesis/machinelearning | experiments/neural.py | Python | mit | 5,497 |
#!/usr/bin/env python
"""
Copyright 2014 Jirafe, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable la... | concerned3rdparty/jirafe-python | jirafe/CategoryApi.py | Python | mit | 2,134 |
<<<<<<< HEAD
<<<<<<< HEAD
"""Test that the semantics relating to the 'fromlist' argument are correct."""
from .. import util
from . import util as import_util
import unittest
class ReturnValue:
"""The use of fromlist influences what import returns.
If direct ``import ...`` statement is used, the root module... | ArcherSys/ArcherSys | Lib/test/test_importlib/import_/test_fromlist.py | Python | mit | 16,364 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operati... | ninapavlich/scout-and-rove | scoutandrove/apps/sr/migrations/0001_initial.py | Python | mit | 6,950 |
#! /usr/bin/python
# this module is for jenkins attacks
from core.webModule import webModule
from requests import session
import requests
import re
from argparse import ArgumentParser
from lxml import html
import random
class jenkinsBrute(webModule):
def __init__(self, config, display, lock):
super(jenkin... | MooseDojo/myBFF | modules/jenkinsBrute.py | Python | mit | 1,691 |
# -*- coding: utf-8 -*-
"""Shared model fields and defaults."""
import binascii
import os
def default_token():
"""Generate default value for token field."""
return binascii.hexlify(os.urandom(20)).decode()
| rtfd/readthedocs.org | readthedocs/core/fields.py | Python | mit | 218 |