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 |
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
import os
import django
from .fixtures import * # noqa
# import pytest
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
def pytest_configure(config):
django.setup()
| pythonindia/junction | tests/conftest.py | Python | mit | 212 |
from artifacts.life import Life
from artifacts.points import Point
from artifacts.super_bomb_artifact import SuperBombArtifact
from bomb import Bomb
from brick import Brick
from context import Context
from game_over_error import GameOverError
from monster import Monster
def draw_scene(context, graphic_buffer):
co... | angelinawawrzyniak/bomberman | game.py | Python | mit | 2,898 |
# -*- coding: utf-8 -*-
"""
This module implements community detection.
"""
from __future__ import print_function
import random
from networkx import nx
import time
__author__ = """Thomas Aynaud (thomas.aynaud@lip6.fr)"""
# Copyright (C) 2009 by
# Thomas Aynaud <thomas.aynaud@lip6.fr>
# All rights reserved.
# ... | ceddie/gavis | controller/louvain.py | Python | mit | 11,429 |
#!/usr/bin/env python
n = int(input())
count = 0
i = 1
while count <= n:
i += 1
count += i * (i - 1) / 2
print(i - 2)
| pybae/etc | CodeForces/492A.py | Python | mit | 129 |
class Items:
def __init__(self, connection, cache_values=True):
self.conn = connection
self.cache_values = True
| EducatedMachine/pysprintly | api/items.py | Python | mit | 133 |
# encoding: utf-8
import mimetypes
import re
from django.core.urlresolvers import reverse
def order_name(name):
"""order_name -- Limit a text to 20 chars length, if necessary strips the
middle of the text and substitute it for an ellipsis.
name -- text to be limited.
"""
name = re.sub(r'^.*/', '... | extremoburo/django-jquery-file-upload | fileupload/serialize.py | Python | mit | 1,030 |
#!/usr/bin/env python
# coding=utf-8
import struct
from twisted.internet import defer
from txportal.packet import cmcc, huawei
from txportal.simulator.handlers import base_handler
import functools
class AuthHandler(base_handler.BasicHandler):
def proc_cmccv1(self, req, rundata):
resp = cmcc.Portal.newMess... | talkincode/txportal | txportal/simulator/handlers/auth_handler.py | Python | mit | 1,737 |
import torch
import numpy as np
from models import SSD300
# weights_path = '../trained_models/vgg16_reducedfc.pth'
weights_path = '../trained_models/ssd_300_VOC0712.pth'
vgg_weights = torch.load(weights_path)
biases = []
weights = []
for name, torch_weights in vgg_weights.items():
print(name)
if 'bias' in na... | oarriaga/single_shot_multibox_detector | src/pytorch2keras.py | Python | mit | 1,252 |
# Running Finesse
import subprocess
# Editing kat file
import fileinput
# Copying files
import shutil
# Adding Gaussian noise
from skimage import io, util
# Navigating directories
import os
# Cropping raw images
from PIL import Image
# Nice loading bars for loops
# Keras preprocessing package for augmentat... | adrianhindes/cavity-sml | createOnlyNoise.py | Python | mit | 2,479 |
from dungeon.dungeon import Dungeon
def main():
testdungeon = Dungeon('level1.txt')
print(testdungeon)
if main.__name__ == '__main__':
main() | int3l/dungeons-and-pythons | main.py | Python | mit | 155 |
import config
def debug(*args):
if config.DEBUG:
print(*args) | BobWhitelock/termtris | termtris/debug.py | Python | mit | 74 |
"""
Parser that converts (C style) binary structs named tuples.
The struct can be read from a file or a byte string.
"""
import struct
def _make_struct_class(name, names):
class Struct(object):
_names = names
def __init__(self, **kwargs):
vars(self).update(kwargs)
def __rep... | olemb/dbfread | dbfread/struct_parser.py | Python | mit | 1,188 |
import os
import sys
import time
from datetime import datetime
import requests
ICONS = {
"01d": "๎", # clear sky
"02d": "๎", # few clouds
"03d": "๎ฝ", # scattered clouds
"04d": "๎", # broken clouds
"09d": "๎", # shower rain
"10d": "๎", # rain
"11d": "๎", # thunderstorm
"13d": "๎"... | tiborsimon/dotfiles | configs/lemon-modules/config/config/modules/weather/weather.py | Python | mit | 2,018 |
# Rackspace Cloud Files configuration settings
env.cloudfiles_username = 'my_rackspace_username'
env.cloudfiles_api_key = 'my_rackspace_api_key'
env.cloudfiles_container = 'my_cloudfiles_container'
# Github Pages configuration
env.github_pages_branch = "gh-pages"
# Port for `serve`
PORT = 8000
def clean():
"""Re... | IsakFalk/blogg | content/static/code/test_example.py | Python | mit | 637 |
#!/usr/bin/env python3
import pytest
def circ_pairs(sequence, distance=1):
"""Zip elements some distance apart in sequence and wrap around
For example:
[4, 5, 1] -> [(4, 5), (5, 1), (1, 4)]
"""
return zip(sequence, sequence[distance:] + sequence[:distance])
def int_to_sequence(integer):
"... | robjwells/adventofcode-solutions | 2017/python/2017-01.py | Python | mit | 3,488 |
# -*- coding: utf-8 -*-
# Project: TORNADO
# ---------------------------------------------------------
# Purpose: Crawling Turkish Language Society's web page
# (tdk.gov.tr) to get Turkish words and their meanings to
# provide a better service to people who want to contribute
# improvement of Turkish language studie... | buraktekin/tornado | tornado.py | Python | mit | 1,301 |
from os.path import join, abspath, dirname, normpath
DEBUG = False
TEMPLATE_DEBUG = DEBUG
PROJECT_ROOT = abspath(join(dirname(__file__), '..', '..', '..'))
ADMINS = (
('Uber Mailman', 'mailman@uberlearner.com'),
)
MANAGERS = ADMINS
# Local time zone for this installation. Choices can be found here:
# http://en... | Uberlearner/uberlearner | uberlearner/uberlearner/settings/base/__init__.py | Python | mit | 5,935 |
ATTACK_PATTERN = {
'response': {
"id": "attack-pattern--01a5a209-b94c-450b-b7f9-946497d91055",
"name": "ATTACK_PATTERN 1",
"type": "attack-pattern",
"modified": "2020-05-13T22:50:51.258Z",
"created": "2017-05-31T21:30:44.329Z",
"description": "Adversaries may abuse Wi... | VirusTotal/content | Packs/FeedMitreAttackv2/Integrations/FeedMitreAttackv2/test_data/mitre_test_data.py | Python | mit | 33,575 |
"""
WSGI config for gocms project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` s... | taojy123/GoCMS | gocms/wsgi.py | Python | mit | 1,300 |
```
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5,... | UmassJin/Leetcode | Array/Search_in_2D_matrix.py | Python | mit | 999 |
#!/usr/bin/env python
#
# test_doctests.py - test runner for COT doctests
#
# July 2016, Glenn F. Matthews
# Copyright (c) 2016-2017 the COT project developers.
# See the COPYRIGHT.txt file at the top-level directory of this distribution
# and at https://github.com/glennmatthews/cot/blob/master/COPYRIGHT.txt.
#
# This ... | glennmatthews/cot | COT/tests/test_doctests.py | Python | mit | 1,224 |
__version__ = '2.0.3'
try:
from .convert import Dictionary
except ImportError:
# To make setup.py work
pass
| dchaplinsky/LT2OpenCorpora | lt2opencorpora/__init__.py | Python | mit | 121 |
'''This module contains differnet implementations of distributed average consensus'''
| ZacBlanco/adac | adac/consensus/__init__.py | Python | mit | 86 |
# -*- coding: utf-8 -*-
import scrapy
import json
import re
from locations.items import GeojsonPointItem
class LjsilversSpider(scrapy.Spider):
name = "ljsilvers"
allowed_domains = ["ljsilvers.com"]
start_urls = (
'http://www.ljsilvers.com/locator?postalcode=76010',
)
def parse(self, resp... | iandees/all-the-places | locations/spiders/ljsilvers.py | Python | mit | 1,524 |
#standard library
from _functools import reduce
import imghdr
### IMPORT THE APPLICABLE SETTINGS SET IN manage.py ###
from manage import USED_SETTINGS
import importlib
used_settings = importlib.import_module(USED_SETTINGS)
settings_media_root = used_settings.MEDIA_ROOT
settings_media_url = used_settings.MED... | fagusMcFagel/ticketsystem | ticketsystem/tickets/views.py | Python | mit | 49,979 |
import os
from nose.tools import assert_equal
from nose import SkipTest
from unittest import TestCase
from tests import TEST_APP_KEY, TEST_APP_SECRET
from bigdoorkit.client import Client
from bigdoorkit.resources.level import NamedLevelCollection, NamedLevel
from bigdoorkit.resources.award import NamedAwardCollection... | splee/bigdoorkit | tests/test_resource.py | Python | mit | 3,184 |
# -*- coding: utf-8 -*-
#The MIT License (MIT)
#
#Copyright (c) 2015,2018 Sami Salkosuo
#
#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 r... | samisalkosuo/clipasswordmgr | clipwdmgr/commands/AddAccountCommand.py | Python | mit | 3,179 |
'''
UITranslator v1.0
based on Univeral Tool Template based v006.1
update: 2016.07.22
by ying
usage in maya:
import UITranslator
UITranslator.main()
usage in commandline:
python UITranslator.py
'''
deskMode = 0
qtMode = 0 # 0: PySide; 1 : PyQt
try:
import maya.OpenMayaUI as mui
except ImportError:
deskMode... | shiningdesign/universal_tool_template.py | _ARCHIVE/UITranslator_v1.0.py | Python | mit | 34,443 |
import pyaudio
import wave
import sys
import time
import cv2
import numpy as np
import os
from Tkinter import *
from pydubtest import play, make_chunks
from pydub import AudioSegment
from threading import Thread
from vidAnalysis import vid2SoundFile
from eventBasedAnimationClass import EventBasedAnimationClass
import i... | anisridhar/AudioShop | analysisClass.py | Python | mit | 5,377 |
import logging
from .Column import Column
logger = logging.getLogger('Table').print_pos
class Table(object):
def __init__(self, name: str) -> None:
self.name = name
self.columns = {}
self.pk_column = None
self.indexes = []
self.blooms = []
def add_column(self, column... | bmstu-iu9/mill-db | pymilldb/context/Table.py | Python | mit | 921 |
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from numpy import array
import numpy as np
import struct
import serial, time
import twitter
#ser = serial.Serial('/dev/ttyACM0', 1000000)
ser = serial.Serial('/dev/cu.usbmodem1421', 1000000)
time.sleep(2)
def convertImageToPins(img, xoffset):
... | bytestudios/balitmorenode-lightboard | master control - python/control.sendpercolumn.py | Python | mit | 7,835 |
'''
View the coding live on Twitch @ https://www.twitch.tv/gmangavin and look at the github @ https://github.com/gmangavin/PyWeb
chromedriver for gui view, phantomjs for ghost view.
'''
import selenium.webdriver #Imports module
import time #Imports time
import threading #Imports threading, used to have multiple things... | gmangavin/PyMegle | Other Py/PyMegleTwo.py | Python | mit | 5,053 |
def _magic_get_file_type(f, _):
file_type = magic.from_buffer(f.read(1024), mime=True)
f.seek(0)
return file_type.decode('utf-8')
def _guess_file_type(_, filename):
return mimetypes.guess_type(filename)[0]
try:
import magic
except ImportError:
import mimetypes
get_file_type = _guess_file... | xbot/alfred-pushbullet | lib/pushbullet/filetype.py | Python | mit | 373 |
import re
import socket
pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})"
ipv4pattern = re.compile(pattern)
class DNSQuery:
def __init__(self, data):
self.data = data
self.domain = ''
t = (ord(data[2]) >> 3) & 15 # O... | pombredanne/kunai-1 | kunai/dnsquery.py | Python | mit | 3,161 |
from setuptools import setup, find_packages
setup(name='core_overshoot_clusters',
version='0.1',
description='Repo for reproducing Rosenfield et. al ApJ 2017, xxx, xxx',
url='http://github.com/philrosenfield/core_overshoot_clusters',
author='Philip Rosenfield',
author_email='philip.rosenf... | philrosenfield/core_overshoot_clusters | setup.py | Python | mit | 901 |
# -*- coding: utf-8 -*-
#
# Response Builder documentation build configuration file, created by
# sphinx-quickstart on Wed Jan 29 11:43:14 2014.
#
# 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 fi... | wotek/response-builder | docs/conf.py | Python | mit | 8,236 |
#!/usr/bin/python
file = open('prog.txt','r')
s = ""
for b in file.read():
s+="%d," % ord(b)
print(s[:-1])
| rarmknecht/SimpleQuine | mkarray.py | Python | mit | 111 |
import numpy as np
from functools import reduce
def flatten_list(l): return reduce(lambda x, y: x+y, l)
def compute_beta_matrix(num_qubits):
"""
Computes the matrix necesary to invert the beta coefficients.
"""
num_states = 2**num_qubits
matrix_B = np.zeros((num_states, num_states))
for i in r... | DiCarloLab-Delft/PycQED_py3 | pycqed/analysis_v2/tomo_functions.py | Python | mit | 6,955 |
"""
Write a program that will help you play poker by telling you what kind of hand you have.
Input:
The first line of input contains the number of test cases (no more than 20). Each test case consists of one line - five
space separated cards. Each card is represented by a two-letter (or digit) word. The first characte... | DayGitH/Python-Challenges | DailyProgrammer/20120330B.py | Python | mit | 3,384 |
from werkzeug.contrib.securecookie import SecureCookie
from werkzeug.utils import cached_property
from werkzeug.wrappers import BaseRequest
from partial import scanner
class Request(BaseRequest):
@cached_property
def session(self):
return SecureCookie.load_cookie(self, secret_key=scanner.CONFIG['SECR... | RentennaDev/partial | partial/request.py | Python | mit | 325 |
import sys
import time
import datetime
import telepot
import pprint
import json
class GMT5(datetime.tzinfo):
def utcoffset(self,dt):
return datetime.timedelta(hours=5,minutes=30)
def tzname(self,dt):
return "GMT +5:30 (IST)"
def dst(self,dt):
return datetime.timedelta(0)
gmt5 = GMT... | diveshuttam/MessMenuBot | bot.py | Python | mit | 4,965 |
import numpy as np
import matplotlib.pyplot as plt
def generate_random(a, M, c, seed):
for i in range(1000 * seed // 10):
seed = (a * seed + c) % M
return seed / M
y = [generate_random(45, 989993, 12, i) for i in range(1000)]
plt.plot(np.arange(1000), y)
plt.show()
| LorenzoBi/courses | UQ/rand_gen.py | Python | mit | 286 |
# -*- test-case-name: twisted.test.test_fdesc -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Utility functions for dealing with POSIX file descriptors.
"""
import os
import errno
try:
import fcntl
except ImportError:
fcntl = None
# twisted imports
from twisted.internet.main ... | perkinslr/pypyjs | addedLibraries/twisted/internet/fdesc.py | Python | mit | 3,297 |
"""Base views and view utilities."""
from django.views.generic import View
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
class LoginRequiredMixin(object):
"""Ensures that user must be authenticated in order to access view."""
@classmethod
def as_view(cls, ... | joshsamara/game-website | core/views/base.py | Python | mit | 691 |
#!/usr/bin/python
from flask import Flask, request
from flask_debugtoolbar import DebugToolbarExtension
from linode import api as l
from cloudflare import CloudFlare as CF
import os
import yaml
config = yaml.load(open('config.yml'))
app = Flask(__name__)
app.debug = config['DYN_DEBUG'] == '1'
if app.debug:
app.confi... | ashneo76/dynip | app.py | Python | mit | 3,009 |
import hmac
class Helper_cookie:
secret = 'This is a secret'
@classmethod
def make_secure_val(self, val):
return '%s|%s' % (val, hmac.new(self.secret, val).hexdigest())
@classmethod
def check_secure_val(self, secure_val):
val = secure_val.split('|')[0]
if secure_val == se... | YuhanLin1105/Multi-User-Blog | utils/helper_cookie.py | Python | mit | 368 |
# encoding: utf-8
from __future__ import unicode_literals, division, print_function, absolute_import
try: # This to handle Python 2.6 which is missing a lot.
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
from marrow.wsgi.objects.adapters.content import ContentType, Content... | marrow/wsgi.objects | tests/test_adapters/test_content_adapters.py | Python | mit | 2,463 |
import distutils.dir_util
import os
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
### Rest API setup
import rest_framework.routers
import rest_framework.viewsets
import rest_framework.filters
import... | andyneff/voxel-globe | voxel_globe/ingest/views.py | Python | mit | 4,787 |
from collections import defaultdict
def before_scenario(context, _):
context.results = defaultdict(list)
| twonds/healthmonger | integration/features/environment.py | Python | mit | 110 |
#!/usr/bin/env python3
"""
A simple script for sending raw serial commands to Gemini.
"""
import time
import serial
import readline
def main():
ser = serial.Serial('/dev/ttyACM0', baudrate=9600)
while True:
cmd = input('> ')
if len(cmd) == 0:
continue
# losmandy native... | bgottula/point | point/gemini_cmd.py | Python | mit | 1,195 |
#!/usr/bin/env python
import sys
from distutils.core import setup
from filechunkio import __version__
PY3 = sys.version_info[0] == 3
_unicode = str if PY3 else unicode
setup(
name="filechunkio",
version=_unicode(__version__),
description="FileChunkIO represents a chunk of an OS-level file "\
"co... | pcn/filechunkio | setup.py | Python | mit | 582 |
import copy
import logging
import numpy
import theano
from theano import tensor
from theano.gradient import disconnected_grad
from blocks.bricks import (
Bias, Identity, Initializable, MLP, Tanh, Softmax, Random)
from blocks.bricks.attention import SequenceContentAttention
from blocks.bricks.base import applicati... | rizar/actor-critic-public | lvsr/bricks/recognizer.py | Python | mit | 38,728 |
from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:9666")
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
| Cancercoin/Cancercoin | contrib/wallettools/walletchangepass.py | Python | mit | 220 |
import unittest
import os
from flow.benchmarks.baselines.bottleneck0 import bottleneck0_baseline
from flow.benchmarks.baselines.bottleneck1 import bottleneck1_baseline
from flow.benchmarks.baselines.bottleneck2 import bottleneck2_baseline
from flow.benchmarks.baselines.figureeight012 import figure_eight_baseline
from ... | cathywu/flow | tests/slow_tests/test_baselines.py | Python | mit | 2,809 |
# -*- coding: utf-8 -*-
"""Tests for the Timestamp class."""
#
# (C) Pywikibot team, 2014
#
# Distributed under the terms of the MIT license.
#
from __future__ import unicode_literals
__version__ = '$Id: 1b449d4b47c5f646b8b4b59feb5505e2f6639af4 $'
import calendar
import datetime
from pywikibot import Timestamp as T... | hperala/kontuwikibot | tests/timestamp_tests.py | Python | mit | 3,175 |
import types
from sikwidgets.widgets.widget import Widget
from sikwidgets.widgets.widget import WidgetError
from sikwidgets.util import to_snakecase
def gen_widget_method(widget_class):
def widget_method(self, *args, **kwargs):
return self.create_widget(widget_class, *args, **kwargs)
return widget_meth... | griffy/sikwidgets | sikwidgets/widgets/page.py | Python | mit | 2,250 |
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import sys
import os
import pytest
from contextlib import contextmanager
import genpac
from genpac._compat import string_types, iterkeys, iteritems
parametrize = pytest.mark.parametrize... | JinnLynn/genpac | tests/util.py | Python | mit | 1,389 |
import os,os.path,shutil
import numpy as np
import pickle
import dmdd
import dmdd_efficiencies as eff
def check_min_mass(element='fluorine', Qmin=1., v_esc=544., v_lag=220., mx_guess=1.):
experiment = dmdd.Experiment('test',element,Qmin, 40.,100., eff.efficiency_unit)
res = experiment.find_min_mass(v_esc=v_e... | veragluscevic/dmdd | dmdd/tests/test.py | Python | mit | 8,718 |
#!/usr/bin/env python
import bottle
from bottle import (
get,
run,
abort,
static_file,
template
)
import thisplace
example_locs = [("sydney", (-33.867480754852295, 151.20700120925903)),
("battery", (40.70329427719116, -74.0170168876648)),
("san_fran", (37.79011487... | amueller/ThisPlace | app.py | Python | mit | 1,992 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... | rwl/PyCIM | CIM15/IEC61968/Common/Agreement.py | Python | mit | 2,456 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SiteSettings.language_code'
db.add_column(u'begood_sites_sitesettings', 'language_code',
... | AGoodId/begood-sites | begood_sites/migrations/0005_auto__add_field_sitesettings_language_code.py | Python | mit | 7,865 |
from django.contrib import admin
from .models import Channel, Post, Subreddit
@admin.register(Subreddit)
class SubredditAdmin(admin.ModelAdmin):
list_display = ('__str__', 'low_score_limit', 'score_limit', 'pass_nsfw',
'show_title', 'active', 'on_moderation')
@admin.register(Post)
class Pos... | vaniakosmos/memes-reposter | apps/reddit/admin.py | Python | mit | 951 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'demo.views.index', name='index'),
url(r'^all_events/', 'demo.views.all_events', name='all_events'),
url(r'^admin/', include(admin.site.urls)),
)
| rodrigoamaral/django-fullcalendar | demo/demo/urls.py | Python | mit | 320 |
from mpf.tests.MpfTestCase import MpfTestCase
class TestSettings(MpfTestCase):
def get_config_file(self):
return 'config.yaml'
def get_machine_path(self):
return 'tests/machine_files/settings/'
def get_platform(self):
return 'smart_virtual'
def _tilted(self, **kwargs):
... | missionpinball/mpf | mpf/tests/test_Settings.py | Python | mit | 844 |
import json, glob
from PIL import Image, ImageTk
import Tkinter as tk
import Utils
canvas = None
lblImage = None
lblVertex = None
FileName = None
CurrentFrame = None # current frame number
CurrentVertex = None
FrameName = None
Images = None # the image names
ImageGlob = None
Vertices = None
Lines = None
Frames = None ... | hmoraldo/AnimationEditor | src/AnimationEditor.py | Python | mit | 4,150 |
"""Migrate the usage data from the old bundled Transit Relay database.
The magic-wormhole package used to include both servers (Rendezvous and
Transit). "wormhole server" started both of these, and used the
"relay.sqlite" database to store both immediate server state and long-term
usage data.
These were split out to ... | warner/magic-wormhole-transit-relay | misc/migrate_usage_db.py | Python | mit | 1,883 |
import warnings
import sys
import argparse
from etk.extractors.cryptographic_hash_extractor import CryptographicHashExtractor
cryptographic_hash_extractor = CryptographicHashExtractor()
def add_arguments(parser):
"""
Parse arguments
Args:
parser (argparse.ArgumentParser)
"""
parser.descr... | usc-isi-i2/etk | etk/cli/cryptographic_hash_extractor.py | Python | mit | 947 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-07 16:56
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
... | cliffton/localsecrets | offers/migrations/0001_initial.py | Python | mit | 3,179 |
import tensorflow as tf
from .sections import GraphSection, section_from_name
from tensorflow.python.client.session import _FetchMapper
from .utils import VerboseTimer
from contextlib import ExitStack
def _flatten_list(nested_list):
"""
Given a nested list, returns flat list of all its elements
:param ne... | jakob-bauer/partialflow | partialflow/manager.py | Python | mit | 26,395 |
from .groups import GROUPS
from .segments import SEGMENTS
MESSAGES = {
'ACK': ('sequence',
(('MSH', SEGMENTS['MSH'], (1, 1), 'SEG'),
('MSA', SEGMENTS['MSA'], (1, 1), 'SEG'),
('ERR', SEGMENTS['ERR'], (0, 1), 'SEG'),)),
'ADR_A19': ('sequence',
(('MSH', SEGMEN... | crs4/hl7apy | hl7apy/v2_3_1/messages.py | Python | mit | 47,596 |
from selenium import webdriver
from time import sleep
driver=webdriver.Firefox()
#ๆๅผๆ่ฆ่ชๅญฆ็ฝ้กต้ขๅนถๆชๅพ
driver.get("http://www.51zxw.net/")
driver.get_screenshot_as_file(r'E:\0python_script\four\Webdriver\zxw.jpg')
sleep(2)
#ๆๅผ็พๅบฆ้กต้ขๅนถๆชๅพ
driver.get("http://www.baidu.com")
driver.get_screenshot_as_file(r'E:\0python_script\four\Web... | 1065865483/0python_script | four/Webdriver/screenshot.py | Python | mit | 405 |
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2014 Hรฅvard Gulldahl
# 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
#... | havardgulldahl/perpetual-yearcal | models.py | Python | mit | 1,783 |
from unittest.mock import patch
def mocked_execute(remote_executor, command, *args, **kwargs):
from .test_assets import TestAsset
return TestAsset.REMOTE_HOST_MOCKS[remote_executor.hostname].execute(
command
)
class PatchRemoteHostMeta(type):
"""
can be used as a metaclass for a TestCase ... | jdepoix/goto_cloud | goto_cloud/test_assets/remote_host_patch_metaclass.py | Python | mit | 1,494 |
#!/usr/bin/env python3
# Copyright (c) 2014-2020 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 descendant package tracking code."""
from decimal import Decimal
from test_framework.blocktools ... | domob1812/bitcoin | test/functional/mempool_packages.py | Python | mit | 16,008 |
"""Qsignature: detection of sample mixups.
https://sourceforge.net/p/adamajava/wiki/qSignature/
"""
import os
import shutil
import subprocess
import lxml
import pysam
import toolz as tz
from bcbio import bam, utils
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio.pro... | brainstorm/bcbio-nextgen | bcbio/qc/qsignature.py | Python | mit | 8,491 |
# -*-coding:Utf-8 -*
# ====================================================================
# ====================================================================
# Packages
# ====================================================================
import sys
import numpy as np
from muLAn.models.multipole import hexamag... | muLAn-project/muLAn | muLAn/models/fhexaBL.py | Python | mit | 2,911 |
#A client for testing the bluetooth server running on the pi
import socket
serverMACAddress = 'b8:27:eb:f1:bb:a6'
port = 3
s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
s.connect((serverMACAddress,port))
s.send("Hello")
while 1:
#client, address == s.accept()
#data = s.recv(... | contactgsuraj/ICHack2017 | RBP/test_client.py | Python | mit | 390 |
from rpython.jit.metainterp.optimizeopt.intutils import IntBound, IntUpperBound, \
IntLowerBound, IntUnbounded
from rpython.jit.metainterp.optimizeopt.intbounds import next_pow2_m1
from copy import copy
import sys
from rpython.rlib.rarithmetic import LONG_BIT
def bound(a,b):
if a is None and b is None:
... | oblique-labs/pyVM | rpython/jit/metainterp/optimizeopt/test/test_intbound.py | Python | mit | 8,982 |
"""Compute statistics over midi files.
Usage
-----
# Run with default parameters
$ python midi_tools.py "data/*.mid" stats.json
# Run with full verbosity
$ python midi_tools.py "data/*.mid" stats.json --verbose 50
# Run with only one CPU
$ python midi_tools.py "data/*.mid" stats.json --n_jobs 1
# Run with two CPUs ... | ejhumphrey/osr-intro | midi_tools.py | Python | mit | 2,374 |
"""
http://community.topcoder.com/stat?c=problem_statement&pm=1692
Single Round Match 146 Round 1 - Division II, Level One
Single Round Match 212 Round 1 - Division II, Level One
"""
class Yahtzee:
def maxPoints(self, toss):
sums = [0] * 7
for value in toss:
sums[value] += value
... | warmsea/tc-srm | srm146/Yahtzee.py | Python | mit | 340 |
import StringIO
import sys
import unittest
from mock import patch
from mnp.command import *
# For tests needing subprocess
class SubprocessTest(unittest.TestCase):
def setUp(self):
patcher1 = patch("subprocess.check_call")
self.addCleanup(patcher1.stop)
self.mockSubprocess_check_call = pa... | heryandi/mnp | mnp/test/test_command.py | Python | mit | 6,569 |
from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from procyon.starcatalog.models import Star
class StarCatalog(TestCase):
def setUp(self):
star1 = Star.objects.create(**{"HR": None, "spectrum": "G5", "Y": -28.6581, "VY": 5.7579e-05, "HD": None, "HIP": 70767, "RV"... | jaycrossler/procyon | procyon/starcatalog/tests.py | Python | mit | 1,921 |
import tomodachi
from tomodachi.discovery.dummy_registry import DummyRegistry
from tomodachi.envelope.protobuf_base import ProtobufBase
@tomodachi.service
class DummyService(tomodachi.Service):
name = "test_dummy_protobuf"
discovery = [DummyRegistry]
message_envelope = ProtobufBase
options = {
... | kalaspuff/tomodachi | tests/services/dummy_protobuf_service.py | Python | mit | 838 |
"""
.. module:: __init__.py
__init__.py
*************
:Description: __init__.py
:Authors: bejar
:Version:
:Created on: 21/01/2015 9:00
"""
__author__ = 'bejar'
from .samples_generator import make_blobs
__all__ = ['make_blobs']
| bejar/kemlglearn | kemlglearn/datasets/__init__.py | Python | mit | 249 |
#!/home/hjnan/OMOOC2py/_src/om2py6w/xieriji/bin/python
# -*- coding: utf-8 -*-
"""
Bottle is a fast and simple micro-framework for small web applications. It
offers request dispatching (Routes) with url parameter support, templates,
a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and
template ... | huijuannan/OMOOC2py | _src/om2py6w/xieriji/bin/bottle.py | Python | mit | 149,613 |
from math import sqrt, log10
class WelfordRunningVariance(object):
"""
Python implentation of Welford's running variance algorithm
http://www.johndcook.com/standard_deviation.html
"""
def __init__(self):
self._count = 0
self._mean = None
self._last_mean = None
self._... | monkut/deso | deso/deso/functions.py | Python | mit | 3,384 |
__author__ = 'victor'
import unittest
from data.adaptors import *
import csv
import os
mydir = os.path.dirname(os.path.abspath(__file__))
class TestAdaptor(object):
def test_words(self):
ex = self.adaptor.to_example(self.raw)
self.assertEqual(ex.words, [w.lower() for w in self.words])
def t... | vzhong/sent2rel | tests/test_adaptors.py | Python | mit | 10,128 |
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab
from sendit.settings import (
INSTALLED_APPS,
BROKER_URL
)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendit.settings')
app = Celery('sendit',broker=BROKER_URL)... | pydicom/sendit | sendit/celery.py | Python | mit | 512 |
#!/usr/bin/env python3
"""Select starting configs for each US window"""
import argparse
import pdb
import sys
import random
import copy
from origamipy.op_process import read_ops_from_file
from origamipy.op_process import sort_by_ops
from origamipy.origami_io import *
from origamipy.us_process import create_win_filen... | acumb/LatticeDNAOrigami | scripts/simutils/select_starting_configs.py | Python | mit | 1,850 |
๏ปฟ#!/usr/bin/python3
"""datahelpers.py: Provides functions for handling data."""
__author__ = 'Andrei Muntean'
__license__ = 'MIT License'
import numpy as np
def shuffle_data(x, y):
random_indexes = np.random.permutation(x.shape[0])
shuffled_x = np.empty_like(x)
shuffled_y = np.empty_like(y)
for in... | andreimuntean/LinearRegression | LinearRegression/datahelpers.py | Python | mit | 1,252 |
#/###################/#
# Import modules
#
#ImportModules
import ShareYourSystem as SYS
#/###################/#
# Build the model
#
#Simulation time
BrianingDebugVariable=25.
#A - transition matrix
JacobianTimeFloat = 30. #(ms)
A = (-1./float(JacobianTimeFloat)
)*SYS.numpy.array([[1.]])
#Define
MyPredicter=SYS.P... | Ledoux/ShareYourSystem | Pythonlogy/ShareYourSystem/Specials/Predicters/Predicter/tests/01_tests_dynamic_rate/01_test_dynamic_rate_oneagent_onesensor_ExampleCell.py | Python | mit | 852 |
from __future__ import print_function
import argparse
import yaml
from .bocca import make_project, ProjectExistsError
def main():
parser = argparse.ArgumentParser()
parser.add_argument('file', type=argparse.FileType('r'),
help='Project description file')
parser.add_argument('--cl... | csdms/wmt-exe | wmtexe/cmi/make.py | Python | mit | 673 |
from datetime import timedelta
from flask import Flask, json, helpers, request
from flask.views import MethodView
from wordpress_xmlrpc import Client
from wordpress_xmlrpc import methods as wp_methods
from wordpress_xmlrpc.methods import taxonomies as wp_taxonomies
app = Flask(__name__)
wp = Client('http://localhos... | maxcutler/wp-xmlrpc-rest-wrapper | wp-rest.py | Python | mit | 13,839 |
from src.types.game import Game
from src.types.player import Player
class GamesAndPlayers(object):
def __init__(self, player_db):
self.player_db = player_db
def parse(self, data):
pdb = self.player_db
# Single values
self.points = data.get('CurrentTotalPoints')
# Arr... | gak/giant-multiplayer-robot-helper | src/types/games_and_players.py | Python | mit | 846 |
import functools
from flask import Flask, jsonify, request
from . import api
from .log import logger
app = Flask(__name__)
global_store = {}
def error_handle(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
# pylint: disable=broad-ex... | msincenselee/vnpy | vnpy/api/easytrader/server.py | Python | mit | 2,858 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2015_06_15/aio/operations/_virtual_machine_extension_images_operations.py | Python | mit | 9,333 |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import io
import six
import time
import unicodecsv
import tableschema
from apiclient.http import MediaIoBaseUpload
from .mapper import Mapper
# ... | okfn/jsontableschema-bigquery-py | tableschema_bigquery/storage.py | Python | mit | 9,230 |
from distutils.core import setup
import py2exe, sys
sys.argv.append('py2exe')
MANIFEST = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
<dependentAssembly>
<assemblyIdentity
type=... | schiz21c/CDListPy | setup_py2exe.py | Python | mit | 1,169 |
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
### Show an update instance ###
@register.inclusion_tag("feeds/update.html", takes_context=True)
def show_update(context, update):
feed_object = update.feed.feed_object
... | caseywstark/colab | colab/apps/object_feeds/templatetags/object_feeds_tags.py | Python | mit | 2,666 |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from .models import Profile
class ProfileInline(admin.StackedInline):
model = Profile
verbose_name = '็จๆท'
verbose_name_plural = '็จๆทๆฉๅฑ'
c... | mittya/duoclub | duoclub/accounts/admin.py | Python | mit | 528 |