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 |
|---|---|---|---|---|---|
import numpy as np
from skimage import io
def read_image(fn, normalize=True):
"""Read a CCD/CMOS image in .da format (Redshirt). [1_]
Parameters
----------
fn : string
The input filename.
Returns
-------
images : array, shape (nrow, ncol, nframes)
The images (normalized b... | jni/python-redshirt | redshirt/read.py | Python | mit | 2,123 |
#!/usr/bin/env python
from os.path import dirname
import os
import sys
if __name__ == "__main__":
sample_dir = dirname(os.path.abspath(__file__))
root = dirname(dirname(sample_dir))
sys.path.append(root)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sampleproj.settings")
try:
from dja... | tipsi/tipsi_tools | django_tests/manage.py | Python | mit | 957 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10a1 on 2016-07-19 15:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dashboard', '0041_auto_20160707_1856'),
]
operations = [
migrations.AddFiel... | DLance96/ox-dashboard | dashboard/migrations/0042_studytableevent_notes.py | Python | mit | 467 |
import os
from distutils.core import setup
ROOT = os.path.dirname(os.path.realpath(__file__))
setup(
name='wmsigner',
version='0.1.1',
url='https://github.com/egorsmkv/wmsigner',
description='WebMoney Signer',
long_description=open(os.path.join(ROOT, 'README.rst')).read(),
author='Egor Smolyak... | egorsmkv/wmsigner | setup.py | Python | mit | 848 |
# -*- coding:utf-8 -*-
import test_core
import sys
import demjson
test_core.title("搜索用户")
f = open("testconfig.json", 'r')
lines = f.read()
f.close()
jsonfiledata = demjson.decode(lines)
if jsonfiledata["url"] == "":
test_core.terr("错误: 'testconfig.json' 配置不完全。")
exit()
uurl = jsonfiledata["url"]+"search.php"
u... | cxchope/YashiLogin | tests/test_searchuser.py | Python | mit | 448 |
"""Models for the ``feedback_form`` app."""
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.conf import settings
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translatio... | bitmazk/django-feedback-form | feedback_form/models.py | Python | mit | 2,071 |
#!/usr/bin/python
"""
This tests that all the PLE games launch, except for doom; we
explicitly check that it isn't defined.
"""
import nose
import numpy as np
import unittest
NUM_STEPS=150
class NaiveAgent():
def __init__(self, actions):
self.actions = actions
def pickAction(self, reward, obs):... | ntasfi/PyGame-Learning-Environment | tests/test_ple.py | Python | mit | 2,211 |
import socket
import random
from PIL import Image
import json
import sys, getopt
import math
import pika
# Screen VARS
offset_x = 80
offset_y = 24
screen_width = 240
screen_height = 240
# Internal options
queueAddress = ''
fileName = ''
workers = 36
Matrix = []
def main(argv):
global fileName, workers
inp... | jargij/led-pomper-sha2017 | img_to_queue.py | Python | mit | 3,094 |
import re
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.time import Time
from panoptes.mount.mount import AbstractMount
from ..utils.logger import has_logger
from ..utils.config import load_config
from ..utils import error as error
@has_logger
class Mount(AbstractMount):
... | fmin2958/POCS | panoptes/mount/ioptron.py | Python | mit | 10,044 |
"""
WSGI config for sms_relay 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`... | yeleman/sms_relay | sms_relay/wsgi.py | Python | mit | 1,468 |
import matplotlib.pyplot as plt
import numpy as np
import sys
import time
import scipy.interpolate as ip
infile = sys.argv[1]
indata = np.load(infile)
spec = indata[0]
samp_rate = indata[1]
fftsize = indata[2]
center_freq = 1419.4 # MHz
halffft = int(0.5*fftsize)
freqs = 0.5*samp_rate*np.array(range(-halffft,halffft)... | varenius/salsa | USRP/usrp_gnuradio_dev/testold.py | Python | mit | 2,198 |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... | pavlovicr/bac | bac/contrib/sites/migrations/0003_set_site_domain_and_name.py | Python | mit | 1,071 |
import os
import re
from subprocess import Popen, PIPE
from kivy.uix.popup import Popup
def run_syscall(cmd):
"""
run_syscall; handle sys calls this function used as shortcut.
::cmd: String, shell command is expected.
"""
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.commu... | RedXBeard/gitwatcher-ui | shortcuts.py | Python | mit | 4,040 |
"""
@author: Daniel Butum, Group 911
"""
from domain.number import Number, NumberException
from utils.number import convert_to_int
class Console:
def __init__(self):
pass
def run(self):
"""
Run the console gui
"""
# print initial help menu
print(self._get_hel... | leyyin/university | computational-logic/src-number-converter/ui/console.py | Python | mit | 5,104 |
"""
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters
----------
interv... | pablodecm/cartographer | cartographer/coverers.py | Python | mit | 4,786 |
from command import Command, is_command
from event import Event
class Say(Command):
shortname = 'say'
name = 'Say something to someone, or in the public chat'
@is_command
def say(self, player, *args):
if args[0] in self.world.players:
prefix = "(private) <%s> " % player.name
... | lysol/lvlss | src/commands/say.py | Python | mit | 1,205 |
from abc import ABCMeta
from up.utils.up_logger import UpLogger
class BaseModule(metaclass=ABCMeta):
LOAD_ORDER = 0
def __init__(self, silent=False):
self.__silent = silent
self.__logger = UpLogger.get_logger()
self.__up = None
def initialize(self, up):
self.__up = up
... | Rashitko/up | up/base_module.py | Python | mit | 1,652 |
import urllib2
import base64
import json
from link import *;
from GitFetcher import GitHubFetcher;
username = "debuggerman"
password = "megadeth"
orgUrl = "https://api.github.com/orgs"
orgName = "coeus-solutions"
gitFetcher = GitHubFetcher(username = username, password = password, orgUrl = orgUrl, orgName = orgName)
... | debuggerman/gitstats.py | gitstats.py | Python | mit | 344 |
#!/usr/bin/env python
def print_banner(s):
print('##------------------------------------------------------------------------------')
print(f'## {s}')
print('##------------------------------------------------------------------------------')
print_banner('First implementation')
class Base:
def foo(self... | eroicaleo/LearningPython | PythonTricks/ch04_05.py | Python | mit | 1,316 |
import functools
import operator
class Env(dict):
"""
Computational environment for some expression.
Implemented with recursive composition -
each environment has the outer environment.
Every lookup for a name N in the environment E
with outer environment O goes like this:
1) E.lookup(N)... | begor/lisp | lisp/environment.py | Python | mit | 2,626 |
import cv2
from collections import namedtuple
import logging
import re
import os
RecorderConfig = namedtuple('RecorderConfig',
['file_limit',
'time_limit',
'directory',
'file_base'],
... | erstrom/opencv-home-cam | opencv_home_cam/recorder.py | Python | mit | 3,907 |
# coding=utf-8
from ..models.checksum import Checksum
from ..models.address import Address
from ..models.shopping_cart_item import ShoppingCartItem
from ..models.shopping_cart import ShoppingCart
from .paymill_service import PaymillService
import json
__author__ = 'yalnazov'
class ChecksumService(PaymillService):
... | paymill/paymill-python | paymill/services/checksum_service.py | Python | mit | 5,102 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-07-25 15:51
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | daisychainme/daisychain | daisychain/channel_github/migrations/0001_initial.py | Python | mit | 1,029 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowi... | stryder199/RyarkAssignments | Assignment2/web2py/gluon/storage.py | Python | mit | 5,788 |
# pandas and numpy for data manipulation
import pandas as pd
import numpy as np
import sqlite3
from bokeh.plotting import Figure
from bokeh.models import (
CategoricalColorMapper,
HoverTool,
ColumnDataSource,
Panel,
FuncTickFormatter,
SingleIntervalTicker,
LinearAxis,
)
from bokeh.models im... | murrayo/yape | yapesrv/scripts/perfmon_tab.py | Python | mit | 3,197 |
import sys, subprocess, time
"""
This script is made as a wrapper for sc2 bots to set a timeout to the bots (in case they cant find the last enemy structure or the game is ending in a draw)
Usage:
cd into python-sc2/ directory
docker build -t test_image -f test/Dockerfile .
docker run test_image -c "python test/travi... | Dentosal/python-sc2 | test/travis_test_script.py | Python | mit | 2,800 |
# -*- coding: utf-8 -*-
""" S3 Query Construction
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
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
... | ScottBuchanan/eden | modules/s3/s3query.py | Python | mit | 82,174 |
# -*- coding: utf-8 -*-
"""
Main __init__.py for the vsgen package
"""
import pkg_resources
try:
pkg = pkg_resources.get_distribution("vsgen")
__version__ = pkg.version
except pkg_resources.DistributionNotFound:
__version__ = "0.0.0.0"
from vsgen.solution import VSGSolution
from vsgen.project import VSGPro... | dbarsam/python-vsgen | vsgen/__init__.py | Python | mit | 841 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2015 Steffen Deusch
# Licensed under the MIT license
# Beilage zu MonitorNjus, 14.09.2015 (Version 0.9.3)
import os
workingdir = os.path.dirname(os.path.realpath(__file__))
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import cgi
import imp
modul... | SteffenDE/monitornjus-classic | admin/index.py | Python | mit | 15,077 |
#!/usr/bin/env python
# Reports a summary of Kraken's results
# and optionally creates a newick Tree
# Copyright (c) 2016 Daniel Blankenberg
# Licensed under the Academic Free License version 3.0
# https://github.com/blankenberg/Kraken-Taxonomy-Report
from __future__ import print_function
import optparse
import os
i... | SANBI-SA/tools-iuc | tools/kraken_taxonomy_report/kraken_taxonomy_report.py | Python | mit | 12,936 |
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
# Declaration of Username and Password
username = 'admin'
password = 'Test1234$'
"""
Method to replicate
~~~~~~~~~~~~~~~~~~~
1. Bring up a new instance of NearBeach (grab from fixtures)
2. Try and log ... | robotichead/NearBeach | NearBeach/tests/tests_specific_bugs/test_new_instance.py | Python | mit | 1,174 |
# correctness: 100%, performance: 0%
def solution(a):
l = len(a)
if l < 3: return reduce(lambda x, y: x * y, a)
products = []
for i in xrange(0, l):
for j in xrange(i+1, l):
for k in xrange (j+1, l):
products.append(a[i] * a[j] * a[k])
return max(products)
if __name__ == '__main__':
a... | nomuna/codility | Lesson_06/max_prod_three.py | Python | mit | 390 |
# coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... | saelo/willie-modules | asm.py | Python | mit | 4,715 |
from setuptools import setup
setup(
name="sgf",
version="0.5",
description="Python library for reading and writing Smart Game Format",
license="MIT",
url="http://github.com/jtauber/sgf",
author="James Tauber",
author_email="jtauber@jtauber.com",
py_modules=["sgf"],
classifiers=[
... | jtauber/sgf | setup.py | Python | mit | 552 |
#!/usr/bin/env python
from math import *
def i321():
n = 0L
mn = 0L
tn = 0L
sn = 0L
n3 = 0L
n9 = 0L
n = 372889431
mn = 139046528497282623
tn = 1L + 8L * mn
print "M(%i) = %i\n" % (n, mn)
print "sqrt(%d) = %i\n" % (n, sqrt(n))
print "sqrt(%d) = %i\n" % (tn, sqrt(tn))
print "sqrt(%i) mod 1 ... | gotclout/PythonJunk | 3.py | Python | mit | 429 |
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT, included in this distribution as LICENSE
""" """
from rowgenerators.appurl.file.file import FileUrl
from rowgenerators.exceptions import AppUrlError
class ZipUrlError(AppUrlError):
pass
class ZipUrl(FileUrl):
"""Zip ... | CivicKnowledge/rowgenerators | rowgenerators/appurl/archive/zip.py | Python | mit | 6,923 |
# -*- coding: utf-8 -*-
from Scraping4blog import Scraping4blog
import sys,os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../util')
from settings import SettingManager
def main():
conf = SettingManager()
instance = Scraping4blog(conf)
instance.run()
if __name__ == "__main__":
main... | yamanakahirofumi/mokobot | Scraping4blog/run.py | Python | mit | 323 |
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
low=1<<31
profit=0
for p in prices:
if p<low:
low=p
if p-low>profit:
profit=p-low
return profit | Tanych/CodeTracking | 121-Best-Time-to-Buy-and-Sell-Stock/solution.py | Python | mit | 316 |
import collections
import functools
import dpath
import six
import pprint
import stringcase
from pyutrack.logger import get_logger
def print_friendly(value, sep=', '):
if isinstance(value, six.string_types):
return value
if isinstance(value, collections.Iterable):
return sep.join(str(k) for... | alisaifee/pyutrack | pyutrack/util.py | Python | mit | 11,714 |
# this program requires the 32 bit version of Python!!
import os
import glob
import math
import subprocess
import re
import sys
import string
from decimal import Decimal
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
from scipy.ndimage i... | mcnowinski/various-and-sundry | lightcurve/windows/firstlook.py | Python | mit | 10,661 |
import _plotly_utils.basevalidators
class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name="familysrc",
parent_name="funnelarea.hoverlabel.font",
**kwargs
):
super(FamilysrcValidator, self).__init__(
plotly_name=... | plotly/plotly.py | packages/python/plotly/plotly/validators/funnelarea/hoverlabel/font/_familysrc.py | Python | mit | 456 |
# being a bit too dynamic
# pylint: disable=E1101
import datetime
import warnings
import re
from math import ceil
from collections import namedtuple
from contextlib import contextmanager
from distutils.version import LooseVersion
import numpy as np
from pandas.util.decorators import cache_readonly, deprecate_kwarg
im... | bdh1011/wau | venv/lib/python2.7/site-packages/pandas/tools/plotting.py | Python | mit | 117,602 |
from __future__ import absolute_import
import logging
from uuid import uuid1
import dockets.queue
import dockets.error_queue
from .base import Queue
class DocketsQueue(Queue):
def __init__(self, redis_client, queue_name, wait_time, timeout):
self.queue = dockets.queue.Queue(redis_client,
... | gamechanger/deferrable | deferrable/queue/dockets.py | Python | mit | 5,390 |
import six
import warnings
from .. import errors
from ..utils.utils import (
convert_port_bindings, convert_tmpfs_mounts, convert_volume_binds,
format_environment, normalize_links, parse_bytes, parse_devices,
split_command, version_gte, version_lt,
)
from .base import DictType
from .healthcheck import Heal... | jarv/cmdchallenge-site | lambda_src/runcmd/docker/types/containers.py | Python | mit | 20,507 |
from ast import literal_eval
from json import dumps, loads
from urllib2 import Request, urlopen
from requests import post, get
from p3lzstring import LZString
def user_input(data):
i = 0
while i < len(data):
if 'xp' in data[i]['dragondata']['sidekick_name'][9:][5:]:
data[i]['d... | IPFR33LY/EverwingHax | Everwing_data.py | Python | mit | 8,827 |
# -*- coding: utf-8 -*-
__author__ = 'Steven Brien'
__email__ = 'sbrien@hlkagency.com'
__version__ = '0.1.0'
| spbrien/norman | norman/__init__.py | Python | mit | 110 |
from __future__ import division
import myhdl
from myhdl import instance, delay
ClockList = []
class Clock(myhdl.SignalType):
def __init__(self, val, frequency=1, timescale='1ns'):
self._frequency = frequency
self._period = 1/frequency
self._timescale = timescale
self._htick... | cfelton/myhdl_exercises | support/mysigs.py | Python | mit | 2,461 |
import io
from pathlib import Path
from typing import Mapping
import fontTools.designspaceLib
import fontTools.ttLib
import fontTools.ttLib.tables._n_a_m_e
import fontTools.varLib
import ufo2ft
import ufoLib2
import statmake.classes
import statmake.lib
def dump_axes(font, axes_array):
dump_list = []
for axi... | googlefonts/statmake | tests/testutil.py | Python | mit | 3,392 |
#!/usr/bin/env python
# Usage:
# $ KEY=<YOUR APIKEY> DEVICE=<YOUR DEVICE ID> python example.py
import os
import sys
import pprint
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from m2x.client import M2XClient
KEY = os.environ['KEY']
DEVICE_ID = os.environ['DEVICE']
client = M2XClient(key=KEY)
... | attm2x/m2x-python | examples/example.py | Python | mit | 382 |
"""
Setup script for the Gimbal package
"""
from setuptools import setup
from setuptools import find_packages
def readme():
"""Returns the contents of the README without the header image."""
header = '======\nGimbal\n======\n'
with open('README.rst', 'r') as f:
f.readline()
return header +... | ryjmacdonell/geomtools | setup.py | Python | mit | 1,588 |
import hashlib
import shutil
import os
from datetime import datetime
list_of_paths_and_strings = [
["assignment1.cpp", "main()"]
]
def main():
if acceptance_test():
make_txt_file()
zip_dir()
def get_md5_hash(file):
# opening file
file_to_hash = open(file)
read_file = file_to_hash.read()
... | shanestockall/EECS-Grading-Rig | src/packages/EECS-211-Grader/acceptancetest.py | Python | mit | 2,184 |
from django.db import models
from django.db.models import Count
from belt.managers import SearchQuerySetMixin
class PostQuerySet(SearchQuerySetMixin, models.QuerySet):
pass
class CategoryQuerySet(SearchQuerySetMixin, models.QuerySet):
pass
class BlogQuerySet(SearchQuerySetMixin, models.QuerySet):
def... | marcosgabarda/django-belt | tests/app/managers.py | Python | mit | 406 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from .generic import *
from criacao.forms import *
from criacao.models import *
from gerenciamento.models import *
logger = logging.getLogger(__name__)
class LinkView(GenericView):
def criar(self, request):
if request.method == 'POST':
try:
... | wendellpbarreto/mcc-django | criacao/views/link.py | Python | mit | 3,504 |
#!/usr/bin/env python3
# Filters one or more input text files, building a collection of words from
# the corpora, and filtering them
#
# Copyright 2016 Mathew Hunter
import argparse
import nltk
import os
import re
# default regex that filters out links, numbers, and single characters
default_regex = "^(?!http|\d)\w... | mdhunter/twitter-to-wordcloud | filter_corpus.py | Python | mit | 2,888 |
import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataViewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.... | dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/samples/dataview/CustomRenderer.py | Python | mit | 5,439 |
from findSentence import sentenceGrab
from phoneticWords import findPhonetics
from phoneticIndex import findPhoneticIndex
from random import randint
from math import floor
import sys
def main():
library = sys.argv[1]
subject = sys.argv[2]
dictionary = "/usr/share/dict/words"
phonetics = findPhonetics... | Jflinchum/pow-generator | powGenerator.py | Python | mit | 1,567 |
import numpy as np
import util
from datetime import datetime
from scipy.stats import norm
import better_exceptions
from scipy.stats import multivariate_normal as mvn
class NaiveBayers(object):
def __init__(self):
# Gaussian deviation
self.gaussians = dict()
# Class priors
self.pri... | adexin/Python-Machine-Learning-Samples | Naive_bayes_mnist/nb.py | Python | mit | 2,416 |
import collections
import functools
from typing import List
from test_framework import generic_test
from test_framework.test_utils import enable_executor_hook
Rect = collections.namedtuple('Rect', ('left', 'right', 'height'))
def compute_skyline(buildings: List[Rect]) -> List[Rect]:
# TODO - you fill in here.
... | shobhitmishra/CodingProblems | epi_judge_python/drawing_skyline.py | Python | mit | 812 |
import sys
import os
import traceback
from django import db
sys.path.append('/root/wisely/wisely_project/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'wisely_project.settings.production'
from django.db.models import F, Q
from django.utils import timezone
from users.tasks import get_coursera_courses, get_edx_courses, ge... | TejasM/wisely | wisely_project/get_courses_file.py | Python | mit | 1,721 |
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... | Fendoe/open-hackathon-o | open-hackathon-server/src/hackathon/util.py | Python | mit | 5,753 |
import unittest
import slowboy.gpu
import slowboy.interrupts
from tests.mock_interrupt_controller import MockInterruptController
STAT_IE_ALL_MASK = (slowboy.gpu.STAT_LYC_IE_MASK |
slowboy.gpu.STAT_OAM_IE_MASK |
slowboy.gpu.STAT_HBLANK_IE_MASK |
slowboy.gp... | zmarvel/slowboy | tests/test_gpu.py | Python | mit | 7,556 |
#!/usr/bin/python
import random
def roll(qty, sides):
return sum(random.randrange(1, sides + 1) for _ in range(qty))
def chances(qty, out_of):
"""'1 chance in 5' is chances(1, 5)"""
# Chance succeeds if roll is lower than max.
return roll(1, out_of) <= qty
| bstpierre/yendor | yendor/dice.py | Python | mit | 278 |
# -*- coding: utf-8 -*-
from datetime import datetime
from app.model import db
class FeedRecord(db.Model):
__tablename__ = 'feeds'
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=datetime.now())
quant = db.Column(db.Integer)
def __repr__(self):
return 'At %s eat %d ml' % (... | zeutrap/tiaotiao | app/model/feed.py | Python | mit | 350 |
'''
Setup.py script.
'''
__author__ = 'riko'
from Cython.Build import cythonize
import numpy
from setuptools import setup, Extension, find_packages
try:
use_cython = True
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
ext = '.pyx' if use_cython else '.c'
ext_modules = [... | erix5son/Tennis-Modelling | setup.py | Python | mit | 1,109 |
import pytest
TEST_HASHES = {
"test": "Jnh+8wNnELksNFVbxkya8RDrxJNL13dUWTXhp5DCx/quTM2/cYn7azzl2Uk3I2zc",
"test2": "sh33L5uQeLr//jJULb7mAnbVADkkWZrgcXx97DCacueGtEU5G2HtqUv73UTS0EI0",
"testing100" * 10: "5rznDSIcDPd/9rjom6P/qkJGtJSV47y/u5+KlkILROaqQ6axhEyVIQTahuBYerLG",
}
@pytest.mark.parametrize(('passwo... | ENCODE-DCC/encoded | src/encoded/tests/test_edw_hash.py | Python | mit | 479 |
from __future__ import absolute_import
import csv
from django.contrib import admin
from django.http import HttpResponse
from .models import Donor, Donation
class DonationInline(admin.TabularInline):
model = Donation
extra = 0
@admin.register(Donor)
class DonorAdmin(admin.ModelAdmin):
inlines = [
... | thrive-refugee/thrive-refugee | donors/admin.py | Python | mit | 2,727 |
import copy
def execute(moves):
players = [
{'name': 'Xena', 'score': 0},
{'name': 'Ophelia', 'score': 0},
]
idx = 0
first_player = 0
draw_count = 0
move_count = 0
init_map = [[False]*3, [False]*3, [False]*3]
map = copy.deepcopy(init_map)
for move in moves:
... | matslindh/codingchallenges | knowit2017/23.py | Python | mit | 2,089 |
import thoonk
from thoonk.feeds import SortedFeed
import unittest
from ConfigParser import ConfigParser
class TestLeaf(unittest.TestCase):
def setUp(self):
conf = ConfigParser()
conf.read('test.cfg')
if conf.sections() == ['Test']:
self.ps = thoonk.Thoonk(host=conf.get('Te... | andyet/thoonk.py | tests/test_sorted_feed.py | Python | mit | 5,064 |
from mininet.net import Mininet
from ..util import findPyroObjectOrNone
def monkeypatch(cls):
def decorator(func):
setattr(cls, func.__name__, func)
return func
return decorator
def getOneNodeByName(net, name):
if name in net.nameToNode:
return net.nameToNode[name]
else:
return findPyroObjectO... | itszero/onenet | emulab/onenet/onenet/inject/infect.py | Python | mit | 867 |
'''
Geometry Transform
'''
| luwei14/ShapeAnalyzer | shapeanalyzer/transform.py | Python | mit | 27 |
import numpy as np
import scipy.cluster.hierarchy as hr
import scipy.spatial as spa
import clustering
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering
import filter
class textMiningEac:
def __init__(self,k,N,low,high=0):
self.k = k
# Leer datos desde ... | fbr1/textmining-eac | main.py | Python | mit | 3,609 |
#!/usr/bin/env python
#Copyright (C) 2013 by Thomas Keane (tk2@sanger.ac.uk)
#
#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... | harvardinformatics/jobTree | batchSystems/lsf.py | Python | mit | 12,569 |
# -*- coding: utf-8 -*-
from django.conf.urls import re_path
from . import views
app_name = 'topic'
urlpatterns = [
re_path(r'^$', views.deleted, name='index'),
re_path(r'^deleted/$', views.deleted, name='deleted'),
re_path(r'^closed/$', views.closed, name='closed'),
re_path(r'^pinned/$', views.pinn... | nitely/Spirit | spirit/topic/admin/urls.py | Python | mit | 342 |
class NoResultScraped(Exception):
pass
class NotCompleteParse(Exception):
pass
class CouldNotAuthorize(Exception):
pass
| pddg/qkouserver | qkoubot/my_exception.py | Python | mit | 136 |
"""
WSGI config for c2asm 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.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTIN... | vladimir-nazarenko/c2asm | c2asm/wsgi.py | Python | mit | 388 |
from datetime import datetime
from xml.etree import ElementTree
import pkgutil
from json import loads as base_loads
from random import choice
import logging
import re
import urlparse
from sleekxmpp import ClientXMPP
from redis import Redis, ConnectionPool
import requests
from humanize import intcomma, naturaltime, int... | nikdoof/dropbot | dropbot/bot.py | Python | mit | 28,390 |
# coding: UTF-8
import os, sys
import mercadopago
def index(req, **kwargs):
mp = mercadopago.MP("CLIENT_ID", "CLIENT_SECRET")
topic = kwargs["topic"]
merchant_order_info = None
if topic == "payment"
payment_info = mp.get("/collections/notifications/"+kwargs["id"])
merchant_order_info ... | matikbird/matikbird.github.io | portfolio/quay/back_end/payments2/mercadopago/api-mercadopago-master/templates/code-examples-master/mp-checkout/shipping/python/ipn_merchant_order.py | Python | mit | 824 |
from pprint import pformat
from sqlalchemy import Column, ForeignKey, orm
from sqlalchemy.types import String, Integer, Boolean, Text
from sqlalchemy.schema import UniqueConstraint
from intranet3 import memcache
from intranet3.models import Base, User
from intranet3.log import WARN_LOG, INFO_LOG, DEBUG_LOG
LOG = INF... | pytlakp/intranetref | src/intranet3/models/project.py | Python | mit | 10,842 |
import math
def add_vectors(vector1, vector2):
#Note the vectors are tuple (angle, magnitude)
x = math.sin(vector1[0]) * vector1[1] + math.sin(vector2[0]) * vector2[1]
y = math.cos(vector1[0]) * vector1[1] + math.cos(vector2[0]) * vector2[1]
mag = math.hypot(x, y)
angle = (math.pi/2) - math.atan2(y, x)
return (a... | shantanu69/pygame-physics | PyParticleSystem/PyParticles/utils.py | Python | mit | 330 |
import numpy as np
from numpy import ma
from matplotlib import pyplot as plt
from mpl_toolkits.basemap import Basemap as bm
from mpl_toolkits.basemap import addcyclic
import palettable
class vector_plot:
def __init__(self, ucompos, vcompos):
self.ucompos = ucompos
self.vcompos = vcompos
se... | nicolasfauchereau/paleopy | paleopy/plotting/vector_plot.py | Python | mit | 1,697 |
from django.test import TestCase
from ...models import Office
class PublishedMixinTest(TestCase):
def test_only_published_manager_and_queryset_default_datetime(self):
data = [
dict(published=False, address='office', office='not_published'),
dict(office='published', address='some ... | mtrgroup/django-mtr-utils | tests/app/tests/models/mixins.py | Python | mit | 991 |
# Theme-specific settings
SITENAME = "Marc Sleegers"
DOMAIN = "marcsleegers.com"
BIO_TEXT = "Infrequent ramblings."
FOOTER_TEXT = '© 2022 Marc Sleegers. Licensed <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>.'
SITE_AUTHOR = "Marc Sleegers"
TWITTER_USERNAME = "@marcardioid"
GOOGLE_PLUS_URL =... | marcardioid/marcsleegers.com | pelicanconf.py | Python | mit | 3,987 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
# returns a random d dimensional vector, a direction to peturb in
def direction(d,t):
# if type == uniform
if(t == 'u'):
return np.random.uniform(-1/np.sqrt(2), 1/np.sqrt(2), d)
elif(t == 'n'):
return np.ra... | Aditya8795/Python-Scripts | peturb.py | Python | mit | 1,147 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
from snisi_reprohealth.models.PFActivities import (PFActivitiesR, AggPFActivitiesR)
# from snisi_reprohealth.models.ChildrenMortali... | yeleman/snisi | snisi_reprohealth/models/__init__.py | Python | mit | 540 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import collections
import logging
import os
import platform
import re
import subprocess
import types
import util
import json
from ebstall.versions import Version
from ebstall.util import normalize_string
logger = logging.getLogger(__n... | EnigmaBridge/ebstall.py | ebstall/osutil.py | Python | mit | 18,396 |
#!/usr/bin/env python
import boto
from boto.s3.connection import OrdinaryCallingFormat
from fabric.api import prompt
def confirm(message):
"""
Verify a users intentions.
"""
answer = prompt(message, default="Not at all")
if answer.lower() not in ('y', 'yes', 'buzz off', 'screw you'):
exit... | swastvedt/dailygraphics | fabfile/utils.py | Python | mit | 813 |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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 law or ag... | Sorsly/subtle | google-cloud-sdk/lib/googlecloudsdk/command_lib/compute/managed_instance_groups/update_instances_utils.py | Python | mit | 5,956 |
from reads.conf.development import * # NOQA
| martinbalfanz/reads-api | src/reads/settings.py | Python | mit | 45 |
eveapi = local_import('eveapi')
def is_igb():
return 'http_eve_charid' in request.env
def auto_vivify(charid):
if db(db.char.charid==charid).count():
return # character id already exists in db
api = eveapi.EVEAPIConnection()
try:
el = api.eve.CharacterName(ids=str(charid))
... | fsufitch/eve-shipspinning | models/utils.py | Python | mit | 7,220 |
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
#
# 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 witho... | cryptapus/electrum-myr | gui/qt/paytoedit.py | Python | mit | 9,506 |
#!/usr/bin/env python3
import Parser, Lexer
from DSL import _lexerParser, _lexerLexer
from DSL import _parserLexer, _parserParser
from DSL import makeParser, makeLexer
lexerLexerConfig = r"""#dsl
%keys ::= '%ignore' '%keys' '::='
comment ::= /#[^\n]*\n/
identifier ::= /[_a-zA-Z][_a-zA-Z0-9]*/
sqString... | coquelicot/PyDSL | src/test.py | Python | mit | 2,354 |
#coding: utf-8
from __future__ import absolute_import, unicode_literals, print_function
import cProfile
from datetime import datetime
import re
import os
import codecs
import timeit
import pymorphy
from pymorphy.contrib.tokenizers import extract_words
DICT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__)... | kmike/pymorphy | bench/__init__.py | Python | mit | 3,351 |
import calendar
import datetime
import platform
import time
import os
import ssl
import socket
import urllib
import urlparse
import warnings
import shippo
from shippo import error, http_client, version, util, certificate_blacklist
def _encode_datetime(dttime):
if dttime.tzinfo and dttime.tzinfo.utcoffset(dttime)... | bosswissam/shippo-python | shippo/api_requestor.py | Python | mit | 7,865 |
# 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/resources/azure-mgmt-resource/azure/mgmt/resource/locks/v2016_09_01/aio/operations/_management_locks_operations.py | Python | mit | 49,288 |
from src.settings import Colors
def league_color(league: str) -> Colors:
if league in [
]:
return Colors.GREEN
if league in [
'1 CFL (Montenegro)',
'A Lyga (Lithuania)',
'Bikar (Iceland)',
'Coupe de la Ligue (France)',
'EURO Qualifiers (Europe)',
'F... | vapkarian/soccer-analyzer | src/colors/v20/default.py | Python | mit | 1,079 |
import platform
from .clipboard import Clipboard
__version__ = '1.0.0'
def get_clipboard(handle=None):
system = platform.system().lower()
if 'windows' == system:
from . import win_clipboard
clip = win_clipboard.WinClipboard(handle)
elif 'darwin' == system:
raise NotImplementedEr... | sebastiandev/clipton | clipton/__init__.py | Python | mit | 598 |
from collections import namedtuple
from cairo import LINE_JOIN_ROUND
from zorro.di import di, dependency, has_dependencies
from tilenol.groups import GroupManager
from tilenol.commands import CommandDispatcher
from .base import Widget
from tilenol.theme import Theme
from tilenol.window import Window
GroupState = na... | tailhook/tilenol | tilenol/widgets/groupbox.py | Python | mit | 3,880 |
"""
Trabalho T2 da disciplina Teoria dos Grafos, ministrada em 2014/02
'All Hail Gabe Newell'
Alunos:
Daniel Nobusada 344443
Thales Eduardo Adair Menato 407976
Jorge Augusto Bernardo 407844
"""
import networkx as nx
import numpy as... | UFSCar-CS-011/graph-theory-2012-2 | tasks/task2/t2-random-walks.py | Python | mit | 6,342 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_ip_groups_operations.py | Python | mit | 27,449 |
# pylint: disable=missing-docstring
# pylint: disable=wildcard-import
from .test_mocks import *
from .cpython.testmock import *
from .cpython.testwith import *
| nivbend/mock-open | src/mock_open/test/__init__.py | Python | mit | 161 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.