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 |
|---|---|---|---|---|---|
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(direction, None)
def add_paths(self, paths):
self.paths.update(paths)
central_corridor = Ro... | zedshaw/learn-python3-thw-code | ex52/gothonweb/gothonweb/planisphere.py | Python | mit | 4,537 |
from caffe import io as c
import numpy as np
import os,sys
if len(sys.argv) < 3:
print 'Use: convertProtobinToNumpy protobinFile numpyOutput'
sys.exit()
protoData = c.caffe_pb2.BlobProto()
f = open(sys.argv[1],'rb')
protoData.ParseFromString(f.read())
f.close()
array = c.blobproto_to_array(protoData)
np.save(sys.... | jccaicedo/localization-agent | learn/cnn/convertProtobinToNumpy.py | Python | mit | 447 |
import pytest
from formulaic.parser.types import Factor, Term
class TestTerm:
@pytest.fixture
def term1(self):
return Term([Factor("c"), Factor("b")])
@pytest.fixture
def term2(self):
return Term([Factor("c"), Factor("d")])
@pytest.fixture
def term3(self):
return Ter... | matthewwardrop/formulaic | tests/parser/types/test_term.py | Python | mit | 1,044 |
# Shorten the import for this because it will be used in configs
from libqtile.backend.wayland.inputs import InputConfig # noqa: F401
| qtile/qtile | libqtile/backend/wayland/__init__.py | Python | mit | 135 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20150914_2147'),
]
operations = [
migrations.AlterField(
model_name='movie',
name=... | rtancman/filmes | movies/core/migrations/0003_auto_20150914_2157.py | Python | mit | 408 |
from django.conf.urls import patterns,include,url
from . import views
app_name='sensorValue'
urlpatterns = [
url(r'^([0-9]+)/$',views.SensorValueView,name='sensorValue'),
] | Ferdous-Al-Imran/Aqualizer | website/website/sensorValue/urls.py | Python | mit | 181 |
import numpy as np
import cv2
#from common import anorm
from functools import partial
help_message = '''SURF image match
USAGE: findobj.py [ <image1> <image2> ]
'''
FLANN_INDEX_KDTREE = 1 # bug: flann enums are missing
flann_params = dict(algorithm = FLANN_INDEX_KDTREE,
trees = 4)
def anorm2... | Dzess/ALFIRT | alfirt.opencv/src/samples/find_obj.py | Python | mit | 3,725 |
# https://www.hackerrank.com/challenges/diagonal-difference
n = int(input().strip())
primary = 0
secondary = 0
for a_i in range(n):
a_temp = list(map(int, input().strip().split(' ')))
primary += a_temp[a_i]
secondary += a_temp[- a_i - 1]
print(abs(primary - secondary))
| denisrmp/hacker-rank | hacker-rank/warmup/diagonal_difference.py | Python | mit | 280 |
from django.core.urlresolvers import reverse
from django.db import models
from gamesoup.games.models import *
class Match(models.Model):
game = models.ForeignKey(Game)
state = models.TextField(blank=True)
def __unicode__(self):
return self.game.name
class Meta:
verbose_name_plural = ... | ktonon/GameSoup | gamesoup/matches/models.py | Python | mit | 520 |
#!/usr/bin/python3
import heatmap
import btrfs
height = 25
width = 100
for color in heatmap.metadata_extent_colors:
pngfile = "doc/%s.png" % btrfs.ctree._key_objectid_str_map[color]
print(pngfile)
bcolor = heatmap.struct_color.pack(*heatmap.metadata_extent_colors[color])
rows = ((bcolor for _ in range... | knorrie/btrfs-heatmap | doc/extent/update_color_map.py | Python | mit | 418 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import pytest
from sqlalchemy import create_engine
from pyramid import testing
from cryptacular.bcrypt import BCRYPTPasswordManager
import journal
DB_USR = os.environ.get("USER", )
TEST_DATABASE_URL = os.environ.get(
'DATABASE_URL',
... | tlake/learning-journal | tests/conftest.py | Python | mit | 4,853 |
import libtcodpy as libtcod
import math
import shelve
import textwrap
#############################################
# Constants and Big Vars
#############################################
# Testing State
TESTING = True
# Size of the window
SCREEN_WIDTH = 100
SCREEN_HEIGHT = 70
# Size of the Map
MAP_WIDTH = SCREEN_WI... | emersonp/roguelike | rl.py | Python | mit | 45,673 |
import os.path
from zope import component
from zope import interface
from zope.component.factory import Factory
from sparc.configuration import container
import mellon
from mellon.factories.filesystem.file import MellonByteFileFromFilePathAndConfig
from mellon.factories.filesystem.file import \
... | CrowdStrike/mellon | mellon/factories/git/file.py | Python | mit | 4,601 |
import logging
import os
from ftplib import FTP as FTPClient
from paramiko import SFTPClient, Transport as SFTPTransport
ALLOWED_BACKEND_TYPES = ['ftp', 'sftp']
DEFAULT_BACKEND_TYPE = 'ftp'
from wok_hooks.misc import Configuration as _Configuration
class Configuration(_Configuration):
def __init__(self, path, ... | abbgrade/wok_hooks | wok_hooks/hook_distribute.py | Python | mit | 9,715 |
"""
REST server API resource definitions.
.. moduleauthor:: Martijn Vermaat <martijn@vermaat.name>
.. Licensed under the MIT license, see the LICENSE file.
"""
from .annotations import AnnotationsResource
from .coverages import CoveragesResource
from .data_sources import DataSourcesResource
from .groups import Grou... | varda/varda | varda/api/resources/__init__.py | Python | mit | 518 |
##----------------------------------------------------------------##
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtCore import Qt, pyqtSignal
##----------------------------------------------------------------##
class CategoryContainer( QtGui.QWidget ):
foldChanged = pyqtSignal( bool )
def __init__(... | tommo/gii | lib/gii/qt/controls/CategoryList.py | Python | mit | 2,776 |
from math import pow
# use weights for slope and intercept
def predict(x, slope, intercept):
return (slope * x) + intercept
def calculate_y_hats(inputs, slope, intercept):
return [predict(x, slope, intercept) for x in inputs]
def calculate_total_mean_squared_error(inputs, outputs, slope, intercept, n):
... | DanielDeychakiwsky/python-machine-learning | src/linear_regression/gradient_descent/calculations.py | Python | mit | 633 |
from game.board import Board
from game.settings import *
__author__ = 'bengt'
import unittest
class TestBoard(unittest.TestCase):
def setUp(self):
pass
def test_init(self):
b = Board(False)
self.assertEqual(len(b.get_move_pieces(WHITE)), 0)
self.assertEqual(len(b.get_move_pi... | Zolomon/reversi-ai | tests/board.py | Python | mit | 7,995 |
#!/usr/bin/env python
# coding: utf-8
from itertools import starmap
from operator import mul
PROBS = [1.0, 1.0, 1.0, .75, .5, 0]
def iev(xs):
return 2 * sum(starmap(mul, zip(PROBS, xs)))
if __name__ == "__main__":
with open("data/rosalind_iev.txt") as f:
xs = map(int, f.read().split())
pr... | genos/online_problems | rosalind/iev.py | Python | mit | 333 |
import requests
import demjson
import datetime
import string
from dateutil import parser
from bs4 import BeautifulSoup
class CmcBackend(object):
#self.menus format:
# {'day':
# {'meal': ['fooditems']
# }
# }
menus = {
'mon': {},
'tue': {},
'wed': {},
... | aspc/mainsite | aspc/menu/backends/cmc.py | Python | mit | 2,496 |
#!/usr/bin/env python
"""Setup file for HT-BAC Tools.
"""
__author__ = "Ole Weidner"
__email__ = "ole.weidner@rutgers.edu"
__copyright__ = "Copyright 2014, The RADICAL Project at Rutgers"
__license__ = "MIT"
""" Setup script. Used by easy_install and pip. """
import os
import sys
import subprocess
from s... | radical-cybertools/radical.ensemblemd.mdkernels | setup.py | Python | mit | 5,031 |
import json
from django.test import TestCase, Client
from heltour.tournament.models import *
def createCommonAPIData():
team_count = 4
round_count = 3
board_count = 2
league = League.objects.create(name='Team League', tag='team', competitor_type='team')
season = Season.objects.create(league=leag... | cyanfish/heltour | heltour/tournament/tests/test_api.py | Python | mit | 1,289 |
# This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import base64
import mimetypes
import re
from contextlib import contextmanager
from urllib.parse import ur... | ThiefMaster/indico | indico/modules/events/static/util.py | Python | mit | 6,995 |
from .logger import Logger
class ConsoleLogHandler(object):
'''
A log handler that writes (prints) to the console.
Messages at Warning level or greater are prefixed with the log level.
'''
def __init__(self, minimum_log_level=Logger.WARNING):
self.minimum_log_level = minimum_log_level
... | richard-shepherd/monopyly | monopyly/utility/console_log_handler.py | Python | mit | 1,051 |
import unittest
from pyml.nearest_neighbours import KNNClassifier, KNNRegressor
from pyml.datasets import gaussian, regression
from pyml.preprocessing import train_test_split
class TestKNNClassifier(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.datapoints, cls.labels = gaussian(n=100, d=2... | gf712/PyML | tests/nearest_neighbours_tests.py | Python | mit | 2,186 |
class GraphNode(object):
def __init__(self, name=None):
self.reset()
self.name = name
self.data = None
def __str__(self):
if self._strcache is None:
self._strcache = "<GraphNode %s>" % str(self.name)
return self._strcache
def __repr__(self):
retu... | dna2github/dna2oldmemory | dna2poem/tiny/matchbox/graph.py | Python | mit | 8,836 |
from nose.tools import assert_equal
import urllib
from base import *
from bibserver import web, ingest
import os
class TestWeb(object):
@classmethod
def setup_class(cls):
web.app.config['TESTING'] = True
cls.app = web.app.test_client()
# fixture data
recdict = fixtures['records... | okfn/bibserver | test/test_web.py | Python | mit | 3,627 |
mustBeAdmin = ['You must be the webadmin to access this page.','danger']
mustBeStudentCoord = ['You must be a student coordinator to access this page.','danger']
from sockdefs import *
print("forming routes...")
monkey.patch_all()
# MAIN EVENTS PAGE #
@app.route('/', methods=['GET', 'POST'])
def index():
if requ... | theapricot/oppapp2 | app.py | Python | mit | 13,357 |
"""Reverse generated from CSS back to PY via pyg_css_convert.py."""
from pygments.style import Style
from pygments.token import Keyword, Name, Comment, String, Error, Text, Number # noqa
from pygments.token import Operator, Generic, Whitespace, Punctuation, Other, Literal # noqa
class ReadthedocsStyle(Style):
... | facelessuser/pymdown-styles | pymdown_styles/readthedocs.py | Python | mit | 3,732 |
# -*- coding: utf-8 -*-
"""
Presence analyzer unit tests.
"""
# pylint: disable=maybe-no-member, too-many-public-methods, invalid-name
from datetime import datetime, date, timedelta
import os.path
import unittest
from unittest.mock import patch
from .main import app, db, mail
from . import main, utils
from .fixtures ... | pdyba/lunch-app | src/lunch_app/tests.py | Python | mit | 35,088 |
#!/usr/bin/python
# coding=utf-8
import threading, time, math, sys, os, random
from flask import Flask, render_template, jsonify
from functools import partial
from pluginbase import PluginBase
here = os.path.abspath(os.path.dirname(__file__))
get_path = partial(os.path.join, here)
PWMAvailable = False
try:
sys.... | Q42/partyled | partyled.py | Python | mit | 6,344 |
# -*- coding: utf-8 -*-
import sys
from typing import List
import OCC.TopoDS
import aocutils.display.topology
from XcMath import utils
from point3d import point3d
from point2d import point2d
# http://opencascade.blogspot.com/2009/02/topology-and-geometry-in-open-cascade_12.html
r"""This module ... | Iwan-Zotow/Fiducial | CADhelpers.py | Python | mit | 9,989 |
from unittest import TestCase
from unittest.mock import patch
from remote_host.public import RemoteHost
from source.public import Source
from target.public import Target
from test_assets.public import TestAsset
from ..hook_handling import HookEventHandler
class TestHookHandling(TestCase, metaclass=TestAsset.Patc... | jdepoix/goto_cloud | goto_cloud/hook_handling/tests/test_hook_handling.py | Python | mit | 5,986 |
import subprocess
from . import ExternalItem
class CommandItem(ExternalItem):
"""
A menu item to execute a console command
"""
def __init__(self, text, command, arguments=None,
menu=None, should_exit=False):
"""
:ivar str command: The console command to be executed
... | trottmpq/test_manager | test_manager/menu/items/command_item.py | Python | mit | 1,385 |
# Copyright (c) 2015 Kurt Yoder
# See the file LICENSE for copying permission.
import os
import logging
import ZODB
import BTrees.OOBTree
import transaction
class DB(object):
'''Encapsulate access to the inferences database.'''
def __init__(self, path):
self.path = os.path.join(path, 'inferences.zodb... | Doveps/savant | savant/db.py | Python | mit | 906 |
# MenuTitle: Copy to Background, Decompose, Remove Overlaps, Correct Path Direction
for layer in Glyphs.font.selectedLayers:
g = layer.parent
for l in g.layers:
l.background = l.copy()
l.decomposeComponents()
l.removeOverlap()
l.correctPathDirection()
| jenskutilek/Glyphs-Scripts | Glyphs/DecRO.py | Python | mit | 292 |
# -*- coding: utf-8 -*-
#
# This file is part of REANA.
# Copyright (C) 2017, 2018, 2020, 2021 CERN.
#
# REANA is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""REANA client tests."""
from __future__ import absolute_import, print_fun... | reanahub/reana-client | tests/test_version.py | Python | mit | 444 |
# Generated by Django 2.2.13 on 2021-03-06 00:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('suncreative', '0007_postrecord_state'),
]
operations = [
migrations.CreateModel(
name='MediaFo... | ZhangDubhe/Tropical-Cyclone-Information-System | TyphoonApi/suncreative/migrations/0008_auto_20210306_0049.py | Python | mit | 891 |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains t... | ademilly/waterflow | waterflow/_version.py | Python | mit | 16,749 |
# -*- coding:utf-8 -*-
from ..client import Client
from .resource import Resource
from ...util import Util
import saklient
# module saklient.cloud.resources.routerplan
class RouterPlan(Resource):
## ルータ帯域プラン情報の1レコードに対応するクラス。
# (instance field) m_id
# (instance field) m_name
# (instance... | hnakamur/saklient.python | saklient/cloud/resources/routerplan.py | Python | mit | 4,491 |
from sqlalchemy import Column
from sqlalchemy import exc
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import testing
from sqlalchemy.orm import clsregistry
from sqlalchemy.orm import registry
from sqlalchemy.orm import relationship
from sqlalchemy.testing import assert_raises_message
f... | sqlalchemy/sqlalchemy | test/orm/declarative/test_clsregistry.py | Python | mit | 12,127 |
__author__ = 'heroico'
#trimmed from PredictDBAnalysis/gencode_input
import csv
import gzip
import pandas
K_NOT_GENES = ["transcript","exon","CDS","UTR","start_codon","stop_codon","Selenocysteine"];
# look at gencode http://www.gencodegenes.org/data_format.html
class GFTF:
"""gencode file table format"""
CHR... | hakyimlab/MetaXcan-Postprocess | source/Gencode.py | Python | mit | 2,470 |
"""GLX context creation and management.
Depends on the binary glxcontext module.
@todo: Include glxcontext in distribution as an optional module.
@author: Stephan Wenger
@date: 2012-08-28
"""
try:
from glxcontext import GLXContext as _GLXContext
from glitter.contexts.context import Context
from glitter... | swenger/glitter | glitter/contexts/glx.py | Python | mit | 1,256 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-17 08:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('cms', '0008_blogindexpage_blogpost_blogposttag'),
]
oper... | kingsdigitallab/kdl-django | cms/migrations/0009_blogpost_date.py | Python | mit | 565 |
def findBestShift(wordList, text):
text = "".join((char if char.isalpha() else " ") for char in text).split()
max_valid = 0
best_shift = 0
for shift in range(26):
num_valid = 0
for word in text:
plaintext = applyShift(word, shift)
if isWord(wordList, plaintext):... | iharsh234/MIT6.00x | pset6-P2-FindBestShift.py | Python | mit | 475 |
import sublime
import sublime_plugin
import re
from Statement import statement
from Expression import expression
try:
from SublimeLinter.lint import persist
except ImportError as error:
print("Dependency import failed; please read readme for " +
"Semicolon plugin for installation instructions; to disable this ... | shagabutdinov/sublime-semicolon | semicolon.py | Python | mit | 3,677 |
"""Character count
This program counts how often each character appears in a string.
"""
def main():
message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
"""str: Message to count characters."""
count = {}
"""dict: Characters as keys and counts as values."""
... | JoseALermaIII/python-tutorials | pythontutorials/books/AutomateTheBoringStuff/Ch05/P2_characterCount.py | Python | mit | 496 |
def _reset_sys_path():
# Clear generic sys.path[0]
import sys, os
resources = os.environ['RESOURCEPATH']
while sys.path[0] == resources:
del sys.path[0]
_reset_sys_path()
def _chdir_resource():
import os
os.chdir(os.environ['RESOURCEPATH'])
_chdir_resource()
def _disable_linecache():... | JRock007/boxxy | dist/Boxxy server.app/Contents/Resources/__boot__.py | Python | mit | 1,863 |
import os
import io
from unittest import TestCase
from py_linq import Enumerable
from tests import _empty, _simple, _complex
from py_linq import exceptions
import itertools
class IssueTests(TestCase):
def setUp(self):
self.empty = Enumerable(_empty)
self.simple = Enumerable(_simple)
self.c... | viralogic/py-enumerable | tests/test_issues.py | Python | mit | 10,030 |
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst.
from __future__ import unicode_literals
# from django.db import models
# from django.utils.translation import ugettext_lazy as _
# Create your models here.
| ddsc/ddsc-api | ddsc_api/models.py | Python | mit | 216 |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='django-quickadmin',
version='0.1.2',
description='Django appli... | zniper/django-quickadmin | setup.py | Python | mit | 1,119 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals, print_function
import abc
import re
import os
import glob
import shutil
import warnings
from itertools import chain
from copy import deepcopy
import six
impo... | tallakahath/pymatgen | pymatgen/io/vasp/sets.py | Python | mit | 58,824 |
import rdflib
import SPARQLWrapper
import enum
from sparqllib.querycomponent import QueryComponent, Triple
from sparqllib.formatter import BasicFormatter
from sparqllib.utils import serialize_rdf_term
class Query(QueryComponent):
''' Representation of a SPARQL Query.
Attributes:
method (QueryMethod): ... | ALSchwalm/sparqllib | sparqllib/query.py | Python | mit | 3,677 |
# -*- coding: utf-8 -*-
import unittest
import qiidly.feedly
class TestFeedly(unittest.TestCase):
"""Test for qiidly.feedly
Getting Started with Sandbox
https://developer.feedly.com/v3/sandbox/
OAuth clientId: sandbox
OAuth clientSecret: CNKEATM7ICEGVOZ3P5A1 (expires on October 1st 2016)
AP... | uraxy/qiidly | tests/test_feedly.py | Python | mit | 1,969 |
import numpy as np
na = np.newaxis
import scipy
import scipy.sparse as sps
kron3 = lambda x,y,z: sps.kron(x,sps.kron(y,z))
class CubicTopology(object):
def __init__(self, N, E, periodic=False):
self.N, self.E = N, E
self.periodic = periodic
# Unpack E
if hasattr(E, "__len__"):
... | shigh/sempy | sempy/topology.py | Python | mit | 3,862 |
cmd = r"C:\Users\wittr\sdr\kalibrate-win-release\kal.exe"
import os, re
from subprocess import Popen, PIPE
pattern_band = r'\s*band to scan\s*\((.+)\)'
pattern_chan = r'(chan).+?(\d+).+?([\d.]+)(\w+).+?([\d.]+)(\w+).+?(\w+).+?([\d.]+)'
process = Popen(cmd + ' -h', shell=True, stdout=PIPE) # To use a pipe with the... | wittrup/crap | python/kal.py | Python | mit | 1,302 |
#! /usr/bin/env python3
import sys
in_class = False
for l in sys.stdin:
if l.startswith("class"):
in_class = True
if in_class:
if l.startswith("};"):
in_class = False
continue
else:
print(l, end='')
| ctongfei/nexus | torch/remove_classes.py | Python | mit | 259 |
"""Usage: dbutils.py [-dfh]
Options:
-d --dropall Deletes all collections in the database. Use this very wisely.
-f --force Forces all questions to 'yes'
-h --help show this
"""
import sys
from docopt import docopt
from laserpony import app
from laserpony.util import db
##UTILITY FUNCTIONS
... | JackRamey/LaserPony | dbutils.py | Python | mit | 1,980 |
import os
import json
import argparse
from math import ceil, floor
from geojson import Polygon, Feature, FeatureCollection, dump
from shapely.geometry import shape, Point
"""
Code adapted from answer to question here:
http://gis.stackexchange.com/questions/54119/creating-square-grid-polygon-shapefile-with-python
"""
... | joh12041/route-externalities | preprocessing/grid_creation.py | Python | mit | 3,570 |
#Brought to you by Jeremy Rubin, 2013
#Put all imports here:
#Config
from config import config
#System
import sys
sys.dont_write_bytecode = True # prevent .pyc
import os.path
import os
#Tornado
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import torn... | JeremyRubin/tornado-trails | Imports.py | Python | mit | 644 |
from . import config_params
from . import util
import http.server
import threading
import json
import logging
logger = logging.getLogger(__name__)
_not_set = object()
class StatusServer(config_params.Configurable):
_params = [
("port", _not_set, "Port where to serve the status page. Default is to not ru... | bluecube/pysystemfan | pysystemfan/status_server.py | Python | mit | 2,693 |
import logging
import struct
from copy import deepcopy
from pymoku._oscilloscope import _CoreOscilloscope
from pymoku._instrument import to_reg_signed
from pymoku._instrument import from_reg_signed
from pymoku._instrument import to_reg_unsigned
from pymoku._instrument import from_reg_unsigned
from pymoku._instrument i... | liquidinstruments/pymoku | pymoku/_iirfilterbox.py | Python | mit | 32,876 |
from flask import Flask
from flask import request
from flask import jsonify
from flask import abort
import time
app = Flask(__name__)
@app.route('/api/1', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/api/1/<path:path>', methods=['GET', 'POST'])
def api1(path):
time.sleep(20)
return jsonify({
... | jie/microgate | test_server.py | Python | mit | 1,151 |
#pylint: disable=C0103,R0903
from ansi.colour.base import Graphic
from ansi.colour.fx import bold
# ECMA-048 standard names
black = Graphic('40')
red = Graphic('41')
green = Graphic('42')
yellow = Graphic('43')
blue = Graphic('44')
magenta = Graphic('45')
cy... | tehmaze/ansi | ansi/colour/bg.py | Python | mit | 1,639 |
# Repeated String
# Developer: Murillo Grubler
# https://www.hackerrank.com/challenges/repeated-string/problem
# Time Complexity = O(n)
import math
def repeated_string(text, total):
if len(text) == 1 and text == 'a':
return total
if text.find('a')!=-1:
add_value = len([text[i] for i in range... | Murillo/Hackerrank-Algorithms | Algorithms/Implementation/repeated-string.py | Python | mit | 597 |
# -*- coding: utf-8 -*-
__all__ = ['Actions']
import dbus
import dbus.service
import os
from subprocess import Popen
import dal
import bill
from lib import common, scheduler
from lib.utils import force_string
from lib.utils import Message
from db.billstable import BillsTable
class Actions(object):
def __init__... | google-code/billreminder | src/lib/dbus_actions.py | Python | mit | 5,266 |
import sys
def load_num():
return int(sys.stdin.readline().rstrip())
def load_case():
_ = sys.stdin.readline() # Empty line
npeople = load_num()
return [load_num() for _ in range(npeople)]
def find_split(weights, total_weight):
reachable = [0 for _ in range(total_weight+1)]
reachable[0] = 1
... | secnot/uva-onlinejudge-solutions | 10032 - Tug of War/main.py | Python | mit | 1,768 |
__author__ = 'k-sthan(II)'
def greeting(msg):
print(msg) | kvs6rj/cs3240-labdemo | helper.py | Python | mit | 61 |
"""
Unit tests for the portion of this project which collects text from social
media sources
"""
import unittest
from unittest.mock import MagicMock
from unittest.mock import patch
import tweepy
# Magically manipulate sys.path
from testassets import pathmagic
from SocialNPHS.sources.twitter import discover
from Soc... | SocialNPHS/SocialNPHS | tests/sources.py | Python | mit | 5,885 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Pruebas unitarias de libkarel."""
import unittest
import libkarel
class TestLibKarelInput(unittest.TestCase):
"""Prueba libkarel.KarelInput."""
# pylint: disable=R0904
def test_basic(self):
"""Prueba básica."""
karel_in = libkarel.KarelInput... | pacharrin/karel.js | libkarel/libkarel_test.py | Python | mit | 3,511 |
"""Some primitive movement definitions"""
import Robot
def go_straight(speed=50, distance=0):
"""
Travel forwards or backwards in a straight line.
:param speed: Speed to travel, as % of maximum
:param distance: Distance to travel, in millimetres. +ve for forwards, -ve for backwards
:return: 0 for ... | Steven-Eardley/pibot_motor | Moves.py | Python | mit | 2,279 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2017 TickSmith Corp.
#
# Licensed under the MIT License
#
# 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, ... | TickSmith/tickvault-python-api | tickvaultpythonapi/parsing/predicate.py | Python | mit | 3,342 |
# This script created a queue
#
# Author - Paul Doyle + Damian Szczepny
#
#
import boto.sqs
import boto.sqs.queue
from boto.sqs.message import Message
from boto.sqs.connection import SQSConnection
from boto.exception import SQSError
import sys
import urllib2
# Get the keys from a specific url and then use them to conn... | dasheq/lab11 | list-aws-queues.py | Python | mit | 901 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
from .. import activations, initializations
from ..utils.theano_utils import shared_scalar, shared_zeros, alloc_zeros_matrix
from ..layers.core import Layer, MaskedLayer
from six.moves import range... | stephenbalaban/keras | keras/layers/recurrent.py | Python | mit | 29,818 |
#!/bin/python3
import sys
n = int(input().strip())
s = input().strip()
k = int(input().strip())
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+k) % 26 + c)
print(''.join([d.get(c, c) for c in s]))
| avtomato/HackerRank | Algorithms/_03_Strings/_04_Caesar_Cipher/solution.py | Python | mit | 233 |
# -*- coding: utf-8 -*-
import os,tcxparser
cd = os.path.dirname(os.path.abspath(__file__)) #use to browse tcx files at the correct location
file_list=os.listdir(os.getcwd())
f=open("result.txt","a")
f.write("date (ISO UTC Format)"+'\t'+"Distance [m]"+'\t'+"Duration [s]"+'\n')
for a in file_list:
if a == "result... | tdargent/TCXfilestodata | readTCXFiles.py | Python | mit | 784 |
# -*- coding: utf-8 -*-
"""
@file
@brief Helpers for :epkg:`Flask`.
"""
import traceback
import threading
from flask import Response
def Text2Response(text):
"""
convert a text into plain text
@param text text to convert
@return textReponse
"""
return Response(text... | sdpython/ensae_teaching_cs | src/ensae_teaching_cs/td_1a/flask_helper.py | Python | mit | 1,966 |
# -*- coding: utf-8 -*-
"""This module contains the parser/generators (or coders/encoders if you
prefer) for the classes/datatypes that are used in iCalendar:
###########################################################################
# This module defines these property value data types and property parameters
4.2 D... | ForTheYin/ical2fullcalendar | icalendar/prop.py | Python | mit | 30,705 |
from __future__ import absolute_import
from fulltext.backends import __html
from fulltext.util import run, assert_cmd_exists
from fulltext.util import BaseBackend
def cmd(path, **kwargs):
cmd = ['hwp5proc', 'xml']
cmd.extend([path])
return cmd
def to_text_with_backend(html):
return __html.handle_fo... | btimby/fulltext | fulltext/backends/__hwp.py | Python | mit | 544 |
# coding: utf-8
import os, sys
reload(sys)
sys.setdefaultencoding("utf-8")
from flask import Flask, render_template, request, url_for
from datetime import datetime
_wd = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, static_url_path='/static')
@app.route('/')
def home():
return render_template('h... | mabdrabo/FlaskHero | app/proj.py | Python | mit | 380 |
"""
WSGI config for SYSite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SYSite.settings")
from django.core.wsg... | KevinJiao/SnapYak | SYSite/SYSite/wsgi.py | Python | mit | 387 |
import math
import string
from Conundrum.utils import sanitize
letter_to_value = dict(zip('z' + string.ascii_lowercase, range(0, 27)))
value_to_letter = dict(zip(range(0, 27), 'z' + string.ascii_lowercase))
def encrypt(msg: str, key: str) -> str:
msg = sanitize(msg)
key = sanitize(key)
repeat = int(math... | physicalattraction/kerstpuzzel | src/Conundrum/key_cipher.py | Python | mit | 1,290 |
#!/usr/bin/python
# coding: UTF-8
# Driver for testing pydPiper display
# Uses the curses system to emulate a display
# Written by: Ron Ritchey
import time, curses
import lcd_display_driver
class lcd_curses(lcd_display_driver.lcd_display_driver):
def __init__(self, rows=2, cols=16 ):
self.FONTS_SUPPORTED = Fa... | dhrone/pydKeg | displays/lcd_curses.py | Python | mit | 1,770 |
from keras.layers import Conv2D
from keras.layers import Input
from keras.layers import MaxPooling2D
from keras.layers import ZeroPadding2D
from keras.models import Model
def modified_VGG16(input_shape=(300, 300, 3), num_classes=21,
weights_path=None, frozen_layers=None, randomize_top=False):
... | oarriaga/single_shot_multibox_detector | src/utils/tests/modified_VGG.py | Python | mit | 4,151 |
from flask import render_template, request, redirect, url_for, abort, flash,\
make_response
from flask_login import login_required, current_user
from bson.objectid import ObjectId
from . import main
from .forms import EditProfileForm, EditProfileAdminForm, PostForm
from .. import db
from ..paginations import Pag... | nonemaw/Flask_nonemaw | app/main/views.py | Python | mit | 13,717 |
#!/usr/bin/env python3
import argparse, os, subprocess, json, requests, re, string
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("source_host", type=str)
parser.add_argument("target_path", type=str)
args = parser.parse_args()
print("Now, what do we have here?")
... | michcioperz/shirley | shirley.py | Python | mit | 1,574 |
#!/usr/bin/env python3
# NOTE: this example requires PyAudio because it uses the Microphone class
import logging
import speech_recognition as sr
from threading import Thread, Event
logger = logging.getLogger(__name__)
class SpeechRecogniser(object):
def __init__(self, config):
# Read in config
... | m0re4u/SmartLight | client/modules/speech_recognizer.py | Python | mit | 6,500 |
#
# SVC (SVM Multi classifier)
#
# @ author becxer
# @ e-mail becxer87@gmail.com
#
import numpy as np
from pytrain.SVM import SVM
from pytrain.lib import convert
from pytrain.lib import ptmath
class SVC:
def __init__(self, mat_data, label_data):
self.x = np.mat(convert.list2npfloat(mat_data))
sel... | becxer/pytrain | pytrain/SVM/SVC.py | Python | mit | 1,018 |
"""user permissions management
Revision ID: bd67c88713b8
Revises: 10023013f155
Create Date: 2021-03-31 21:31:47.278834
"""
# revision identifiers, used by Alembic.
import datetime
from sqlalchemy import orm, text
from sqlalchemy.engine.reflection import Inspector
revision = "bd67c88713b8"
down_revision = "1002301... | hasadna/anyway | alembic/versions/bd67c88713b8_user_permissions_management.py | Python | mit | 3,369 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""Pytests for demo/app_template/__init__.py
"""
# Import standard packages.
import os
import sys
# Import installed packages.
# Import local packages.
sys.path.insert(0, os.path.curdir)
import demo
def test__all__(
ref_all=[
'main',
'template']
... | stharrold/demo | tests/test_app_template/test_app_template__init__.py | Python | mit | 591 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from bottle import template, redirect
import utils
def GET(**params):
return template('materiales_index.html')
| andres-hurtado-lopez/naranjaverdeprod | app/produccion/__init__.py | Python | mit | 163 |
#!/usr/bin/env python
# #To familiarize yourself with pyinotify, run a first example like this:
#
# # $ cd pyinotify-x-x-x && python setup.py build
# # $ python src/pyinotify/pyinotify.py -v my-dir-to-watch
#
# # Let's start a more detailed example. Say, we want to monitor the temp directory '/tmp' and all its subdire... | relic7/prodimages | python/DirWatchManager.py | Python | mit | 15,047 |
import pytest
from wtforms.validators import ValidationError
from mdt_app.main.forms import *
from mdt_app.models import *
@pytest.mark.usefixtures('db_session', 'populate_db')
class TestQuerySelectFunctions:
def test_get_meetings(self):
"""returns future meetings that are not cancelled in order"""
... | stefpiatek/mdt-flask-app | tests/unit/test_main_forms.py | Python | mit | 10,190 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('managers', '0009_managerprofile_description'),
]
operations = [
migrations.AlterField(
model_name='managerprofil... | ritashugisha/ASUEvents | ASUEvents/managers/migrations/0010_auto_20150422_2018.py | Python | mit | 581 |
"""Models for the builds app."""
from __future__ import absolute_import
import logging
import os.path
import re
from shutil import rmtree
from builtins import object
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_u... | pombredanne/readthedocs.org | readthedocs/builds/models.py | Python | mit | 17,368 |
import traceback
from sqlalchemy import Column, Boolean, Integer, String, ForeignKey, create_engine
from sqlalchemy.orm import relationship, sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('sqlite:///bag_of_holding.db')
Base.metadata... | gradiuscypher/internet_illithid | bag_of_holding/libs/user_manager.py | Python | mit | 2,633 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
flask.logging
~~~~~~~~~~~~~
Implements the logging support for Flask.
:copyright: (c) 2011 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
import web
from logging import getLogger
from logging import getLo... | comick/barduino | app/weblib/logging.py | Python | mit | 1,603 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-15 23:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... | tassolom/twq-app | api/users/migrations/0001_initial.py | Python | mit | 1,356 |
from django.apps import AppConfig
class QsiteConfig(AppConfig):
name = 'qsite'
verbose_name = '站点管理'
| gzqichang/wa | qsite/qsite/apps.py | Python | mit | 119 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# This file is part of my-weather-indicator
#
# Copyright (c) 2012 Lorenzo Carbonell Cerezo <a.k.a. atareao>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... | atareao/my-weather-indicator | src/comun.py | Python | mit | 7,329 |