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 -*-
# Form implementation generated from reading ui file 'ui/about.ui'
#
# Created: Thu Jun 4 15:32:51 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_About(object):
def setupUi(self,... | tmtowtdi/MontyLacuna | gui/ORIGships/lib/gui/ui_about.py | Python | mit | 2,866 |
# See http://cens.ioc.ee/projects/f2py2e/
from __future__ import division, print_function
import os
import sys
for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]:
try:
i = sys.argv.index("--" + mode)
del sys.argv[i]
break
except ValueError:
pass
os.environ["NO_SC... | DailyActie/Surrogate-Model | 01-codes/numpy-master/numpy/f2py/__main__.py | Python | mit | 740 |
from flex.error_messages import MESSAGES
from flex.exceptions import ValidationError
from flex.constants import (
EMPTY,
INTEGER,
STRING,
)
from flex.utils import pluralize
from flex.validation.common import (
generate_object_validator,
)
from flex.decorators import (
pull_keys_from_obj,
suffix_... | pipermerriam/flex | flex/loading/common/max_length.py | Python | mit | 1,274 |
import json
import struct
import os
origen = open("./FK.ind", "rb")
destino = open("./extra_data","w")
origen.read(256 + 7) # saco header
cantidad_mapas = struct.unpack('<H', (origen.read(2)))[0] # l1
x = 1
while (x < cantidad_mapas +1):
# numero X = numero de mapa
lluvia = struct.unpack('<B', (origen.read(1)))... | horacioMartinez/dakara-client | tools/misc/traductor de indices y mapas/mapas/extra_data_generator/lluvia_extra_data_generator.py | Python | mit | 601 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utility functions that can be used in multiple scripts.""" | MartinThoma/pysec | pysec/utils.py | Python | mit | 108 |
from setuptools import setup
setup(
name = "hackchat",
py_modules = ["hackchat"],
version = "0.2.0",
description = "An event-driven hack.chat client library.",
author = "Gokberk Yaltirakli",
author_email = "webdosusb@gmail.com",
url = "https://github.com/gkbrk/hackchat",
keywords = ["ha... | gkbrk/hackchat | setup.py | Python | mit | 404 |
#!/Users/abhisheksamdaria/GitHub/pstHealth/venv/bin/python2.7
from __future__ import print_function
import base64
import os
import sys
if __name__ == "__main__":
# create font data chunk for embedding
font = "Tests/images/courB08"
print(" f._load_pilfont_data(")
print(" # %s" % os.path.basen... | samabhi/pstHealth | venv/bin/createfontdatachunk.py | Python | mit | 600 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('firecares_core', '0011_auto_20161208_2205... | FireCARES/firecares | firecares/firecares_core/migrations/0012_departmentinvitation_user.py | Python | mit | 557 |
from django.test import TestCase
from eventex.subscriptions.models import Subscription
from django.shortcuts import resolve_url as r
class SubscriptionDetailGet(TestCase):
def setUp(self):
self.obj = Subscription.objects.create(
name='Luca Bezerra', cpf='12345678901',
email='lucabe... | Golker/wttd | eventex/subscriptions/tests/test_view_detail.py | Python | mit | 1,288 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-15 05:57
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... | Louis31415/opugStore | Store/polls/migrations/0001_initial.py | Python | mit | 1,230 |
# Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... | rauburtin/pysftpserver | pysftpserver/tests/stub_sftp.py | Python | mit | 6,888 |
"""Implementations of commenting abstract base class searches."""
# pylint: disable=invalid-name
# Method names comply with OSID specification.
# pylint: disable=no-init
# Abstract classes do not define __init__.
# pylint: disable=too-few-public-methods
# Some interfaces are specified as 'markers' and inclu... | mitsei/dlkit | dlkit/abstract_osid/commenting/searches.py | Python | mit | 8,401 |
import datetime
import logging
from lxml import html
import simplejson
from . import details
from . import essay
from . import helpers
from . import looking_for
from . import util
from .question import QuestionFetcher
from .xpath import xpb
log = logging.getLogger(__name__)
class Profile(object):
"""Represent... | IvanMalison/okcupyd | okcupyd/profile.py | Python | mit | 14,154 |
#!/usr/bin/env python
"""
The MIT License (MIT)
Copyright (c) 2015 Maker Musings
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... | damianolombardo/fauxmo | fauxmo.py | Python | mit | 17,632 |
class PxlLookableMixin():
instances = {}
def register(instance, id, className):
pass
| desk467/pyxel | src/mixins/lookable_mixin.py | Python | mit | 102 |
from os.path import join
from tempfile import TemporaryDirectory
from django.apps import AppConfig
from 臺灣言語工具.語音辨識.聲音檔 import 聲音檔
from 臺灣言語工具.系統整合.程式腳本 import 程式腳本
class 語料庫Config(AppConfig):
name = '語料庫'
def ready(self):
with TemporaryDirectory() as 資料夾:
檔名 = join(資料夾, 'audio.wav')
... | i3thuan5/gi2_liau7_khoo3 | 語料庫/apps.py | Python | mit | 1,078 |
# -*- coding: utf-8 -*-
import contextlib
import json
import os
import yaml
from .._protos.public.client import Config_pb2 as _ConfigProtos
from . import _utils
# TODO: make this a named tuple, if it would help readability
CONFIG_YAML_FILENAME = "verta_config.yaml"
CONFIG_JSON_FILENAME = "verta_config.json"
CONFI... | mitdbg/modeldb | client/verta/verta/_internal_utils/_config_utils.py | Python | mit | 6,135 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Script to upload images to wikipedia.
Arguments:
-keep Keep the filename as is
-filename Target filename without the namespace prefix
-noverify Do not ask for verification of the upload description if one
is given
-abortonwarn: Abor... | eranroz/hewiktionary_checker | upload.py | Python | mit | 8,269 |
#!/usr/bin/env python2
import distutils.dir_util
import os
import shutil
import subprocess
import sys
import tempfile
import time
DOC_ARGS = '--no-deps'
DOC_FEATURES = "conv num rustc-serialize serde"
DOC_TARGET_BRANCH = 'gh-pages'
TEMP_CHECKOUT_PREFIX = 'gh-pages-checkout-'
TEMP_OUTPUT_PREFIX = 'gh-pages-generated-'... | DanielKeep/rust-numeric-float | update-docs.py | Python | mit | 5,819 |
#!/usr/bin/python
tab = ' '
class Tag():
def __init__(self, name, HTML):
self.name = name
self.HTML = HTML
def __enter__(self):
self.HTML.content += tab * self.HTML.indent + '<' + self.name + '>\n'
self.HTML.indent += 1
def __exit__(self, exc_type, exc_value, traceback):... | fantopop/post-production-scripts | Session info to table/modules/html.py | Python | mit | 1,144 |
# Copyright 2009 Paul J. Davis <paul.joseph.davis@gmail.com>
#
# This file is part of the python-spidermonkey package released
# under the MIT license.
import unittest
import gloom
from gloom import GloomError, TransportError, ProtocolError, ServerError
class test(object):
def __call__(self, func):
def ru... | alepharchives/gloom | clients/python/tests/t.py | Python | mit | 1,505 |
# -*- coding: utf-8 -*-
import romspy
romspy.hview('nc/ob500_grd-v5.nc',
'ob500_grd-v5.png',
vname='h',
cblabel='Depth[m]',
vmax=0, vmin=-120, interval=20, cff=-1,
obsfile='nc/ob500_obs_tsdc.nc')
| okadate/romspy | example/OB500/hview_ob500_grd.py | Python | mit | 263 |
# Statement for enabling the development environment
DEBUG = True
# Define the application directory
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
# Define the database - we are working with
# SQLite for this example
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(BASE_DIR, 'app.db')
DATABAS... | drincruz/slidedecker | config.py | Python | mit | 838 |
from flask import Blueprint, render_template
from regenesis.core import app, engine, get_catalog
from regenesis.views.util import dimension_type_text
from regenesis.database import statistic_table, dimension_table
blueprint = Blueprint('catalog', __name__)
@blueprint.route('/<catalog>/index.html')
def view(catalog)... | pudo/regenesis | regenesis/views/catalog.py | Python | mit | 819 |
# 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/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2016_02_03/aio/operations/_iot_hub_resource_operations.py | Python | mit | 67,149 |
"""231. Power of Two
https://leetcode.com/problems/power-of-two/
Given an integer n, return true if it is a power of two. Otherwise, return
false.
An integer n is a power of two, if there exists an integer x such that n ==
2^x.
Example 1:
Input: n = 1
Output: true
Explanation: 2^0 = 1
Example 2:
Input: n = 16
Out... | isudox/leetcode-solution | python-algorithm/leetcode/problem_231.py | Python | mit | 1,321 |
def greeting(msg):
print(msg)
def valediction(msg):
for char in reversed(msg):
print(char, end = "" )
print("\n")
| CDHgit/cs3240-labdemo | helper.py | Python | mit | 137 |
"""Account service tests."""
from unittest import TestCase
from . import PyiCloudServiceMock
from .const import AUTHENTICATED_USER, VALID_PASSWORD
class AccountServiceTest(TestCase):
"""Account service tests."""
service = None
def setUp(self):
"""Set up tests."""
self.service = PyiCloud... | picklepete/pyicloud | tests/test_account.py | Python | mit | 4,486 |
########################################################################
# MCU Gear(R) system Sample Code
# Auther:y.kou.
# web site: http://www.milletool.com/
# Date : 8/OCT/2016
#
########################################################################
#Revision Information
#
#########################################... | yoshinarikou/MilleFeuilleRaspberryPi | milpython/MoistureTest.py | Python | mit | 835 |
from dolfin import assemble, MixedFunctionSpace, tic,toc
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
import CheckPetsc4py as CP
import StokesPrecond
import NSprecond
import MaxwellPrecond as MP
import PETScIO as IO
import numpy as np
import P as PrecondMulti
import MHDprecond
import ... | wathen/PhD | MHD/FEniCS/MHD/Stabilised/Precond/test/Solver.py | Python | mit | 4,626 |
import sys
import os
from os import walk, chdir
import fnmatch
from invoke import run, task, Collection
from colorama import init, Fore
import yaml
import numpy
PEP8_IGNORE = 'E402,E266,F841'
init()
# These things don't pass syntax/lint checks and are external deps.
EXCLUDE_DIRS = ['nextdoor/lib/python/kingpin',
... | Nextdoor/rightscale_rightlink10_rightscripts | tasks.py | Python | mit | 6,904 |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... | Kraymer/beets | beets/dbcore/query.py | Python | mit | 27,242 |
#!/usr/bin/env python3
import sys
import os
import time
import atexit
from signal import SIGTERM
import logging
import logging.handlers
# load the config
from foostat import config
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
filehandler = logging.handlers.TimedRotatingFileHandler(config["files"]["lo... | dhardtke/foostat | Daemon.py | Python | mit | 5,006 |
"""
SDoc
Copyright 2016 Set Based IT Consultancy
Licence MIT
"""
# ----------------------------------------------------------------------------------------------------------------------
import re
from sdoc import sdoc2
from sdoc.antlr.sdoc2ParserVisitor import sdoc2ParserVisitor
from sdoc.sdoc.SDocVisitor import SDo... | OlegKlimenko/py-sdoc | sdoc/sdoc2/SDoc2Visitor.py | Python | mit | 7,232 |
# Copyright (C) 2015 by Per Unneberg
import pytest
from snakemakelib.sample.organization import sample_org
def test_sample_org():
print (sample_org)
| percyfal/snakemakelib-core | snakemakelib/sample/tests/test_sampleorganization.py | Python | mit | 154 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ZetCode PyQt5 tutorial
This program creates a toolbar.
The toolbar has one action, which
terminates the application, if triggered.
author: Jan Bodnar
website: zetcode.com
last edited: January 2015
"""
import sys
from PyQt5.QtWidgets import QMainWindow, QAction, qApp... | mskovacic/Projekti | raspberrypi/isprobavanje/pyqt5/Toolbar.py | Python | mit | 1,043 |
import re
from tornado.escape import xhtml_escape, _unicode, _URL_RE
_MENTION_RE = re.compile(r'((?:^|\W)@\w+)')
_FLOOR_RE = re.compile(r'((?:^|\W)#\d+)')
_TOPIC_RE = re.compile(r'((?:^|\W)t[a-z0-9]{24})')
_EMAIL_RE = re.compile(r'([A-Za-z0-9-+.]+@[A-Za-z0-9-.]+)(\s|$)')
def make_content(text, extra_params='rel="nof... | JmPotato/College | handlers/utils.py | Python | mit | 2,237 |
default_app_config = 'snoopy.apps.SnoopyConfig'
| Pradeek/django-snoopy | snoopy/__init__.py | Python | mit | 48 |
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
import os
from PIL import Image
#http://javiergodinez.blogspot.fi/2008/03/square-thumbnail-with-python-image.html
def _thumbnail(img, size):
width, height = img.size
if width > height:
delta =... | juslop/angular-chat | django_chat/chat/models.py | Python | mit | 2,659 |
import re
def str_contains_whitespace(str):
return bool(re.search(r"\s", str)) | Frumple/mrt-file-server | mrt_file_server/utils/string_utils.py | Python | mit | 81 |
def get_filename_from_pathname(pathnames):
# if arg is a not a list, make it so
# https://stackoverflow.com/a/922800/861745
if not isinstance(pathnames, (list, tuple)):
pathnames = [pathnames]
for pathname in pathnames:
# print( pathname )
print( pathname.replace('\\','/').... | jgstew/tools | Python/get_filename_from_pathname.py | Python | mit | 894 |
"""
Django settings for eureka project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... | SWE574-Nerds/friendly-eureka | backend/eureka/eureka/settings.py | Python | mit | 4,075 |
# -*- coding: utf-8 -*-
#
# climenu documentation build configuration file, created by
# sphinx-quickstart on Tue Apr 11 09:13:31 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# A... | mtik00/pyclimenu | docs/conf.py | Python | mit | 4,835 |
# -*- coding: utf-8 -*-
"""
This file should contain functions for the following operations:
- load data from raw txt format (in German)
- stemming
- (maybe) remove stop-words (e.g. der, die, das, in, am ...)
- create dictionary containing all desired words
"""
import os
import fnmatch
import re
from nltk.stem.snowba... | eonum/medword | preprocess.py | Python | mit | 14,369 |
import unittest
from test.test_support import (check_syntax_error, _check_py3k_warnings,
check_warnings, run_unittest)
class ScopeTests(unittest.TestCase):
def testSimpleNesting(self):
def make_adder(x):
def adder(y):
return x + y
... | babyliynfg/cross | tools/project-creator/Python2.6.6/Lib/test/test_scope.py | Python | mit | 16,217 |
#!/usr/bin/env python
import os
import sys
import csv
import argparse
from spoutP import PRED_HEADER
def doStuff(args):
# def removeRedundantCells(row):
# del row[6]
# del row[1]
uniquePeptides = set()
with open(args.filteredFile, 'wb') as out:
out.write('\t'.join(PRED_HEADER) + '\n')
reader = csv.reader... | cschu/spoutp_Galaxy | spFilter.py | Python | mit | 1,984 |
#! /usr/bin/env python
# -*- coding : utf-8 -*-
''' Container for calculation types (CG, MD, NPR)
'''
import os, copy
import options as Opts
class CalcType():
''' Generic class for all calculation types
'''
keys = {'MD.TypeOfRun' : ['s', None]}
ctd = {'CG' : 'CG',
'MD' : 'Nose',
... | ansobolev/shs | shs/calctypes.py | Python | mit | 4,614 |
import ctypes
class _DpxGenericHeaderBigEndian(ctypes.BigEndianStructure):
_fields_ = [
('Magic', ctypes.c_char * 4),
('ImageOffset', ctypes.c_uint32),
('Version', ctypes.c_char * 8),
('FileSize', ctypes.c_uint32),
('DittoKey', ctypes.c_uint32),
('GenericSize', ctyp... | plinecom/pydpx_meta | pydpx_meta/low_header_big_endian.py | Python | mit | 4,246 |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
""" Tweet rirrakuma 4kuma submit.
"""
import tweepy
TWEET_CONTENT = (
"リラックマの4クマ漫画が更新されました!\n"
"http://www.shufu.co.jp/contents/4kuma/"
)
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
def main():
auth = tweepy.OAuthHandler(... | pyohei/rirakkuma-crawller | tweet.py | Python | mit | 565 |
import unittest
class TestExample(unittest.TestCase):
def test_example(self):
self.assertEquals(0, 0)
| ryanpdwyer/newtex | newtex/tests/test_git.py | Python | mit | 116 |
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP
from django.core.exceptions import SuspiciousOperation
# Default settings that can be overwritten in secrets
DEBUG = True
SECRET_KEY = 'foobar'
DATABASE_ENGINE = 'django.db.backends.sqlite3'
DATABASE_NAME = 'julython.db'
DATABASE_PASS... | julython/julython.org | july/settings.py | Python | mit | 8,557 |
import os
import shutil
import stat
import sys
import unittest
import platform
from collections import namedtuple
from conans import tools
from conans.model.conan_file import ConanFile
from conans.model.ref import ConanFileReference
from conans.model.build_info import CppInfo, DepsCppInfo
from conans.model.settings i... | birsoyo/conan | conans/test/build_helpers/cmake_test.py | Python | mit | 41,766 |
import metrics
def rate(artToCatSim, label, membershipData, categoryTree, artNamesDict, catNamesDict):
# countBefore1 = artToCatSim.count_nonzero()
# for article in membershipData:
# id_and_categories = article.split('\t')
# articleId = int(id_and_categories[0])
# del id_and_categories... | pcejrowski/iwi | notebooks/calcs/rating.py | Python | mit | 2,328 |
import json
from flask import abort, request, views, make_response
from warmsea import db
from warmsea.models import Category
from . import forms
class CategoriesView(views.MethodView):
"""/Categories
"""
response_headers = {
"Content-Type": "application/json; charset=utf-8"
}
# @auth... | warmsea/warmsea.net | warmsea/models/rest_handlers.py | Python | mit | 1,844 |
#!/usr/bin/env python
import argparse
import logging
import os
import shutil
import sys
import glob
# Location of saved templates
SAVE_DIR = os.environ.get("RECYCLE_TEMPLATES_DIR", "~/.recycle")
try:
input = raw_input
except NameError:
pass
def should_overwrite(typeOfThing, path):
assert os.path.exists(p... | williamg/recycle | recycle/recycle.py | Python | mit | 6,538 |
#!/usr/bin/env python3
from .label import Label
from .table import Table
def ItemType(item_type):
if item_type == "Label":
return Label
elif item_type == "Table":
return Table
else:
raise TypeError("No such item type " + item_type)
| eblade/radiant | radiant/grid/item.py | Python | mit | 271 |
#!/usr/bin/env/python
from __future__ import print_function
import MDAnalysis as mda
from MDAnalysis.analysis.distances import contact_matrix
import numbers
import operator
def contact_sample(siatom, sample, vdw_radii, overlap=1.0):
"""
Checks if atom of silica is in contact with the protein+water system
... | jmborr/confinedBSA | simulation/silica/amorphous_from_md/confineBSA/poretop/carve_silica.py | Python | mit | 11,095 |
import celery
from .core import update_modules
@celery.task(ignore_result=True)
def update_bigbrother():
logger = update_bigbrother.get_logger()
logger.info('Updating BigBrother modules...')
update_modules()
logger.info('Update complete.') | anderspetersson/django-bigbrother | bigbrother/tasks.py | Python | mit | 257 |
from parsley.decorators import update_widget_attrs
#
# Hack of parsleyfy decorator: remove hardcoded jquery url.
#
def parsleyfy(klass):
"A decorator to add {prefix}-* attributes to your form.fields"
old_init = klass.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
... | aaee-enscachan/aaee-front | aaee_front/lib/parsley_decorator.py | Python | mit | 1,386 |
from PdfProcessor import *
import argparse
from datetime import datetime
import ConfigParser
import ProcessLogger
import traceback
from urllib2 import HTTPError, URLError
parser = argparse.ArgumentParser(description='Processes the pdf and extracts the text')
parser.add_argument('-l','--language', help='Language of inp... | anjesh/pdf-processor | run.py | Python | mit | 2,284 |
from Queue.Queue import Queue
if __name__ == '__main__':
q = Queue()
q.en_queue("first")
print(q.queue_front())
print(q.queue_rear())
q.en_queue("second")
print(q.queue_front())
print(q.queue_rear())
q.en_queue("third")
print(q.queue_front())
print(q.queue_rear()) | martindavid/code-sandbox | algorithm/COMP90038/queue_test.py | Python | mit | 305 |
# -*- coding: UTF-8 -*-
"""
This modules helps computing interesting stats about the scores stored on the
Web server.
"""
import re
from collections import defaultdict
def stats(scores):
"""
Compute stats on a ``ScoresStore``, and return a dict that can then be used
in a template. Each value is a string... | bfontaine/rogue_scores | rogue_scores/web/stats.py | Python | mit | 1,355 |
import time
import wx
import xapian
from threading import Thread
from stop_words import stop_words
class NoteEntryFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, None, title="Note Entry", size=(300, 300))
self.db_path = "db"
self.InitUI()
def InitUI(self):
panel = wx.Panel(se... | narrowmark/engelbart | note_entry.py | Python | mit | 4,157 |
# Solution to exercise MaxCounters
# http://www.codility.com/train/
def solution(N, A):
counters = [0 for _ in range(N)]
last_max_counter = 0
current_max_counter = 0
# Iterate through A. At each step, the value of counter i is
# last_max_counter or counters[i], whichever is greater
... | jmaidens/Codility | MaxCounters.py | Python | mit | 951 |
import asyncio
import time
import psycopg2
import psycopg2.pool
import os
import sys
class Database:
def __init__(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.init_connection())
@asyncio.coroutine
def init_connection(self):
result = 1
loop_end =... | STOP2/stop2.0-backend | src/db.py | Python | mit | 4,799 |
#!/usr/bin/env python3
from monosat import *
import argparse
from itertools import tee
import random
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
parser = argparse.ArgumentParser(description='BGAMapper')
parser.add_argument("--seed"... | sambayless/monosat | examples/python/shortestpath_benchmark.py | Python | mit | 5,539 |
"""
Created on Dec 20, 2011
@author: StarlitGhost
"""
from twisted.plugin import IPlugin
from zope.interface import implementer
from desertbot.message import IRCMessage
from desertbot.moduleinterface import IModule
from desertbot.modules.commandinterface import BotCommand
from desertbot.response import IRCResponse, R... | DesertBot/DesertBot | desertbot/modules/commands/Join.py | Python | mit | 1,084 |
"""Defines all search scopes used in this project."""
from os import path
ROOT_PATH = path.abspath('/')
class TreeSearchScope:
"""Encapsulation of a search scope to search up the tree."""
def __init__(self,
from_folder=ROOT_PATH,
to_folder=ROOT_PATH):
"""Initialize ... | niosus/EasyClangComplete | plugin/utils/search_scope.py | Python | mit | 2,889 |
#!/usr/bin/env python
###################################################################################
#
# Copyright (c) 2010-2016 Motsai
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Softwa... | Motsai/neblina-python | test/neblinaTest.py | Python | mit | 4,448 |
import unicodecsv as csv
import sys
csvoutfile = open(sys.argv[3], 'wb')
citywriter = csv.writer(csvoutfile, delimiter=',')
with open(sys.argv[1], 'rb') as csvfile:
cityreader = csv.reader(csvfile, delimiter=',')
#Skip headings
headings = next(cityreader, None)
#Write headings
citywriter.writerow(... | okfde/odm-datenerfassung | utils/extractFileName.py | Python | mit | 660 |
"""
This script was created by Sergey Tomin for Workshop: Designing future X-ray FELs. Source and license info is on GitHub.
August 2016.
"""
# this python library provides generic shallow (copy) and deep copy (deepcopy) operations
from copy import deepcopy
# import from Ocelot main modules and functions
from ... | sergey-tomin/workshop | 2_tracking.py | Python | mit | 2,857 |
# Copyright (c) 2020, Manfred Moitzi
# License: MIT License
import pytest
from ezdxf.lldxf.attributes import DXFAttr, RETURN_DEFAULT
def test_return_default():
attr = DXFAttr(
code=62,
default=12,
validator=lambda x: False,
fixer=RETURN_DEFAULT,
)
assert attr.fixer(7) == 1... | mozman/ezdxf | tests/test_00_dxf_low_level_structs/test_054_dxfattr.py | Python | mit | 541 |
"""
Functions for calculating statistics and handling uncertainties.
(c) Oscar Branson : https://github.com/oscarbranson
"""
import numpy as np
import uncertainties.unumpy as un
import scipy.interpolate as interp
from scipy.stats import pearsonr
def nan_pearsonr(x, y):
xy = np.vstack([x, y])
xy = xy[:, ~np.a... | oscarbranson/latools | latools/helpers/stat_fns.py | Python | mit | 7,150 |
# 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/keyvault/azure-keyvault-keys/azure/keyvault/keys/_generated/v7_2/aio/_configuration.py | Python | mit | 2,282 |
import logging
import os.path
import shutil
import tempfile
import urllib2
import zipfile
from django.contrib.gis.gdal import DataSource, OGRGeometry, OGRGeomType
from django.db import transaction
from django.db.utils import IntegrityError
logger = logging.getLogger('neighborhoods.importer')
class NeighborhoodShapef... | coddingtonbear/django-neighborhoods | neighborhoods/importer.py | Python | mit | 3,743 |
import re
class UnknowItem(Exception):
pass
KEYWORDS = ("and", "as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "not", "or", "pass", "print", "raise", "return", "try", "while", "with", "yield")
... | cbonoz/codehealth | dependencies/baron/tokenizer.py | Python | mit | 3,585 |
import os
import datetime
def export_dataframe(df, filename='exported.pkl'):
filepath = os.path.join('data', filename)
print('Saving to pickle file %s...' % filepath)
df.to_pickle(filepath)
def timestamp_to_ordinal(value):
return datetime.datetime.fromtimestamp(float(value)).toordinal()
| MasterScrat/ChatShape | parsers/utils.py | Python | mit | 308 |
import types
import unittest
from SuperGLU.Util.TestGenerator import UnitTestTemplateGenerator, breakStringIntoLines, \
getBestSeparatorIndex, getLeadingSpaces
class TestGenerator_FunctionsTest(unittest.TestCase):
def testBreakStringIntoLines_tooSmallToBreak(self):
maxColumnWidth = 80
tabSize ... | GeneralizedLearningUtilities/SuperGLU | python_module/SuperGLU/Util/Tests/TestGenerator_UnitTests.py | Python | mit | 9,642 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'D:\Sebastian\Mis documentos\Programacion\Proyectos\IA2013TPIRL\gui\qt\IA2013TPIRLGUI\gwgenrndestadosdialog.ui'
#
# Created: Tue Jul 09 15:27:46 2013
# by: PyQt4 UI code generator 4.10.2
#
# WARNING! All changes made in this file will be... | ssebastianj/ia2013-tpi-rl | src/gui/qtgen/gwgenrndestadosdialog.py | Python | mit | 1,334 |
# -*- coding: utf-8 -*-
""" Sahana Eden Menu Structure and Layout
@copyright: 2011-2012 (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 So... | mrGeen/eden | modules/eden/menus.py | Python | mit | 70,805 |
# The code in this files is borrowed from Gedit Synctex plugin.
#
# Copyright (C) 2010 Jose Aliste
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free Software
# Foundation; either version 2 of the Licence, or (at your... | xdega/.dotfiles | .vim/.vim/R/synctex_evince_forward.py | Python | mit | 5,473 |
import _plotly_utils.basevalidators
class ShapesValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(self, plotly_name="shapes", parent_name="layout", **kwargs):
super(ShapesValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | plotly/python-api | packages/python/plotly/plotly/validators/layout/_shapes.py | Python | mit | 8,858 |
"""data structure module
"""
import csv
# setup csv format
csv.register_dialect('result', delimiter='\t', lineterminator='\n')
class Track(object):
"""Tracked point data struct.
Public properties:
point -- [Point] Tracked/clicked point position
label -- [int] Index number
time -- [float] Click... | ptsg/AtamaTracker | atamatracker/data.py | Python | mit | 2,081 |
import logging
import time
import numpy as np
from pycqed.measurement import mc_parameter_wrapper
import qcodes
class Sweep_function(object):
'''
sweep_functions class for MeasurementControl(Instrument)
'''
def __init__(self, **kw):
self.set_kw()
def set_kw(self, **kw):
'''
... | QudevETH/PycQED_py3 | pycqed/measurement/sweep_functions.py | Python | mit | 14,291 |
import os
import csv
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
from pdfminer.layout import LAParams... | zzyxzz/T2-list-parser | t2-parser.py | Python | mit | 4,480 |
#!/usr/bin/env python3
###############################################################################
#
# VFR importer based on GDAL library
#
# Author: Martin Landa <landa.martin gmail.com>
#
# Licence: MIT/X
#
###############################################################################
"""
Imports VFR data to P... | ctu-osgeorel/gdal-vfr | vfr2pg.py | Python | mit | 5,000 |
#! /usr/bin/env python3
from prettytable import PrettyTable
class Tickets(object):
header = ["车次", "出发\到达站", "出发\到达时间", "历时", "一等座", "二等座", "软卧", "硬卧", "软座", "硬座", "无座"]
def __init__(self, rows):
self.rows = rows
# 获取车次运行时间
@classmethod
def _get_duration(cls, row):
duration = row... | MedusaLeee/py3-12306-command-line | Tickets.py | Python | mit | 2,248 |
from django.contrib import admin
from .models import User
class UserAdmin(admin.ModelAdmin):
list_display = ('first_name', 'last_name', 'date_joined', 'email', 'is_active',)
admin.site.register(User, UserAdmin)
| notfier/touristique | registration/admin.py | Python | mit | 220 |
# coding: utf-8
from .graphviz_wrapper import board, add_digraph, add_digraph_node, add_digraph_edge
from .jupyter_helper import jupyter_pan_and_zoom, jupyter_show_as_svg
__author__ = "akimach"
__version__ = "0.0.7"
__license__ = "MIT"
| akimach/tfgraphviz | tfgraphviz/__init__.py | Python | mit | 239 |
import pdb
import numpy as np
import math as m
import sys
import matplotlib.pyplot as plt
#Calculate average and its error for a given data set
def Average(values, error= None):
#No error in the values
if (error is None):
#Calculate the average
mu = np.sum(values)/values.shape[0]
... | Yogesh3/Data-Reduction | Exoplanet/lightcurve.py | Python | mit | 4,335 |
# coding: utf8
from __future__ import unicode_literals
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from clldutils.path import Path
from dplace_app.models import *
from dplace_app.load import load
from dplace_app.loader import s... | NESCent/dplace | dplace_app/tests/test_api.py | Python | mit | 14,228 |
'''
Camera
======
Core class for acquiring the camera and converting its input into a
:class:`~kivy.graphics.texture.Texture`.
.. versionchanged:: 1.10.0
The pygst and videocapture providers have been removed.
.. versionchanged:: 1.8.0
There is now 2 distinct Gstreamer implementation: one using Gi/Gst
wo... | LogicalDash/kivy | kivy/core/camera/__init__.py | Python | mit | 4,415 |
from setuptools import setup
from setuptools import find_packages
setup(name='Keras-layers',
version='0.0.1',
description='Collection of useful non-standard layers for keras',
author='Atanas Mirchev',
author_email='taimir93@gmail.com',
url='https://github.com/taimir/keras-layers',
... | taimir/keras-layers | setup.py | Python | mit | 367 |
from dbconnect import connection
from flask import Flask, render_template
@app.route('/index/')
def display_data():
try:
c, conn = connection()
query = "SELECT * from sensors"
c.execute(query)
data = c.fetchall()
conn.connection()
#return data
return render_template("in... | wikkii/raspluonto | old/python_flask/old/main.py | Python | mit | 388 |
"""Test that PuttyMachine initializes its SshMachine correctly"""
import pytest
from plumbum import PuttyMachine, SshMachine
@pytest.fixture(params=["default", "322"])
def ssh_port(request):
return request.param
class TestPuttyMachine:
def test_putty_command(self, mocker, ssh_port):
local = mocker... | tomerfiliba/plumbum | tests/test_putty.py | Python | mit | 1,938 |
import Tkinter
import calendar
import time
import tkFont
import ttk
def sequence(*functions): # to run 2 or more functions on button click
for function in functions:
function()
def update(y, m, tx, curdate): # generate calendar with right colors
calstr = calendar.month(y, m)
tx.configure(state=T... | Rohit4198/Calendargui | main.py | Python | mit | 4,749 |
import os,sys
import utils as cu
import MemoryUsage
import numpy as np
import scipy.io
import cPickle as pickle
import random
from utils import tic, toc
class RelationsDB():
def __init__(self, dbDir, randomize):
self.images = [img for img in os.listdir(dbDir) if img.endswith('.mat')]
self.dir = dbDir
se... | jccaicedo/localization-agent | detection/relations/RelationsDB.py | Python | mit | 4,781 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author: Gillett Hernandez
# @Date: 2016-06-24 18:59:07
# @Last Modified by: Gillett Hernandez
# @Last Modified time: 2017-08-10 12:37:57
from euler_funcs import timed
numberDict={}
numberDict[1]='one'
numberDict[2]='two'
numberDict[3]='three'
numberDict[4]='four'... | gillett-hernandez/project-euler | Python/problem_17.py | Python | mit | 2,193 |
# -*- coding: utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
from django_js_reverse.core import generate_js
try:
from django.urls import get_resolver
except ImportError:
from django.core.urlresolvers import get_resolver
register = template.Library()
urlconf = template.V... | ierror/django-js-reverse | django_js_reverse/templatetags/js_reverse.py | Python | mit | 838 |
#!/usr/bin/env python3
# Copyright (C) 2013-2014 Jai Luthra <me@jailuthra.in>
# See LICENSE file for more details
'''Encrypt or Decrypt data using One-Time Pad'''
import binascii, argparse, itertools
def main():
parser = argparse.ArgumentParser(
description='Encrypt or Decrypt data using One-Time Pa... | jailuthra/onetimepad | onetimepad.py | Python | mit | 2,562 |