repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
tnotstar/pycalcstats | src/stats/utils.py | Python | mit | 3,781 | 0.00238 | #!/usr/bin/env python3
## Copyright (c) 2011 Steven D'Aprano.
## See the file __init__.py for the licence terms for this software.
"""
General utilities used by the stats package.
"""
__all__ = ['add_partial', 'coroutine','minmax']
import collections
import functools
import itertools
import math
# === Excepti... | # Two pass algorithm.
xydata = as_sequence(xydata)
ny, sumy = _generalised_sum((t[1] for t in xydata), None)
if ny == 0:
raise StatsError('no data items')
my = sumy/ny
return _generalised_sum(xydata, lambda t: (t[0]-mx)*(t[1]-my))
def _validate_int(n):
# This ... | Error (for infinities) or
# ValueError (for NANs or non-integer numbers).
if n != int(n):
raise ValueError('requires integer value')
# === Generic utilities ===
from stats import minmax, add_partial
|
Shashank95/Intellifarm | logdata.py | Python | mit | 1,310 | 0.010687 | import RPi.GPIO as GPIO
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
import serial
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter = ... | oisture) VALUES (%s,%s,%s,%s)""",(datetimeWrite,temp,humidity,moisture))
try:
print "Writing to database..."
# Execute the SQL command
cur.execute(*sql) |
# Commit your changes in the database
db.commit()
print "Write Complete"
except:
# Rollback in case there is any error
db.rollback()
print "Failed writing to database"
time.sleep(0.5)
|
binghongcha08/pyQMD | setup.py | Python | gpl-3.0 | 324 | 0 | from setuptools | import setup
setup(name='scitools',
version='0.1',
description='The funniest joke in the world',
url='http://github.com/storborg/funniest',
author='Flying Circus',
author_email='[email protected]',
license='MIT',
packages= | ['scitools'],
zip_safe=False)
|
debugger06/MiroX | osx/build/bdist.macosx-10.5-fat/lib.macosx-10.5-fat-2.7/miro/importmedia.py | Python | gpl-2.0 | 4,213 | 0.000949 | # Miro - an RSS based video player application
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011
# Participatory Culture Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; eithe... | ecified in the
iTunes settings or None if it cannot find the xml file, or does not
contain the path for some reason."""
music_path = None
try:
parser = xml.sax.make_parser()
| handler = iTunesMusicLibraryContentHandler()
parser.setContentHandler(handler)
# Tell xml.sax that we don't want to parse external entities, as it
# will stall when no network is installed.
parser.setFeature(xml.sax.handler.feature_external_ges, False)
parser.setFeature(xml.s... |
znoland3/zachdemo | venvdir/lib/python3.4/site-packages/mako/ext/autohandler.py | Python | mit | 1,829 | 0 | # ext/autohandler.py
# Copyright (C) 2006-2015 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""adds autohandler functionality to Mako templates.
requires t | hat the TemplateLookup class is used with templates.
usage:
<%!
from mako.ext.autohandler import autohandler
%>
<%inherit file="${autohandler(template, context)}"/>
or with custom autohandler filename:
<%!
from mako.ext.autohandler import autohandler
%>
<%inherit file="${autohan | dler(template, context, name='somefilename')}"/>
"""
import posixpath
import os
import re
def autohandler(template, context, name='autohandler'):
lookup = context.lookup
_template_uri = template.module._template_uri
if not lookup.filesystem_checks:
try:
return lookup._uri_cache[(auto... |
GBlomqvist/blender-Wirebomb | src/ops.py | Python | gpl-3.0 | 4,735 | 0.001901 | # Copyright (C) 2020 Gustaf Blomqvist
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distr... | ne, list_prop, collection_index):
"""
Removes a collection from one of the lists in the UI.
:param scene: The Blender scene.
:param list_prop: Name of the property for the UI list, e.g. 'collections_affected'.
:param | collection_index: Index of the collection to remove from the list.
"""
ui_list = getattr(scene.wirebomb, list_prop)
ui_list.remove(collection_index)
# decrement active index if last was removed
attr_active_index = list_prop + '_active'
active_index = getattr(scene.wirebomb, attr_active_index)
... |
gabobert/climin | climin/__init__.py | Python | bsd-3-clause | 899 | 0 | from __future__ imp | ort absolute_import
# What follows is part of a hack to make control breaking work on windows even
# if scipy.stats ims imported. See:
# http://stackoverflow.com/questions/15457786/ctrl-c-crashes-python-after-importing-scipy-stats
import sys
import os
import imp
import ctypes
if sys.platform == 'win32':
basepath ... | coremd.dll'))
from .adadelta import Adadelta
from .adam import Adam
from .asgd import Asgd
from .bfgs import Bfgs, Lbfgs, Sbfgs
from .cg import ConjugateGradient, NonlinearConjugateGradient
from .gd import GradientDescent
from .nes import Xnes
from .rmsprop import RmsProp
from .rprop import Rprop
from .smd import Smd
... |
ashaarunkumar/spark-tk | python/sparktk/dicom/ops/drop_rows_by_keywords.py | Python | apache-2.0 | 4,404 | 0.003005 | # vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... | DicomAttribute>
<DicomAttribute keyword="MediaStorageSOPInstanceUID" tag="00020003" vr="UI"><Value number="1">1.3.6.1.4.1.14519.5.2.1.7308.2101.234736319276602547946349519685</Value></DicomAttribute>
...
>>> keywords_values_dict = {"SOPInstanceUID":"1.3.6.1.4.1.14519.5.2.1.7308.... | >>> dicom.drop_rows_by_keywords(keywords_values_dict)
>>> dicom.metadata.count()
2
<skip>
#After drop_rows
>>> dicom.metadata.inspect(truncate=30)
[#] id metadata
=======================================
[0] 1 <?xml version="1.0" encodin...
... |
redbo/swift | releasenotes/source/conf.py | Python | apache-2.0 | 10,523 | 0.000095 | # -*- coding: utf-8 -*-
# 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 agreed to in writing, software... | ut the
# built documents.
#
# The short X.Y version.
version = __version__.rsplit(' | .', 1)[0]
# The full version, including alpha/beta/rc tags.
release = __version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line ... |
tryton/calendar_classification | calendar_.py | Python | gpl-3.0 | 5,284 | 0.001893 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import vobject
from trytond.tools import reduce_ids, grouped_slice
from trytond.transaction import Transaction
from trytond.pool import Pool, PoolMeta
__all__ = ['Event']
__... | )
if fields_names is None:
fields_names = []
fields_names = fields_names[:]
to_remove = set()
for field in ('classification', 'calendar', 'transp'):
if field not in fields_names:
f | ields_names.append(field)
to_remove.add(field)
res = super(Event, cls).read(ids, fields_names=fields_names)
for record in res:
if record['classification'] == 'confidential' \
and record['id'] not in writable_ids:
cls._clean_confidential(rec... |
jasonwee/asus-rt-n14uhp-mrtg | src/lesson_text/textwrap_fill.py | Python | apache-2.0 | 102 | 0 | import textwrap |
from textwrap_example import sample_te | xt
print(textwrap.fill(sample_text, width=50))
|
cdcq/jzyzj | test/test_controller.py | Python | mit | 932 | 0.001073 | import unittest
import syzoj
import hashlib
from random import randint
class TestRegister(unittest.TestCase):
def md5_pass(self, password):
md5 | = hashlib.md5()
md5.update(password)
return md5.hexdigest()
def test_register(self):
user = "tester_%d" % randint(1, int(1e9))
pw = self.md5_pass("123_%d" % randint(1, 100))
email = "84%[email protected]" % randint(1, 10000)
print user, pw, email
self.assertEqual(syz... | ontroller.register(user, pw, email), 1)
self.assertNotEqual(syzoj.controller.register(user, pw, email), 1)
def test_multiple_register(self):
rid = randint(1, 10000)
for i in range(1, 2):
pw = self.md5_pass("123_%d_%d" % (rid, i))
print i, pw
self.assertE... |
telegraphic/fits2hdf | fits2hdf/unit_conversion.py | Python | mit | 2,314 | 0.000432 | # -*- coding: utf-8 -*-
"""
unit_conversion.py
==================
Functions for checking and sanitizing units that do not follow the FITS specification.
This uses functions from ``astropy.unit`` to parse and handle units.
"""
import warnings
from astropy.units import Unit, UnrecognizedUnit
from astropy.io.fits.verify... | : ' | s',
'days': 'd',
'day': 'd',
'steradians': 'sr',
'steradian': 'sr',
'radians': 'rad',
'radian': 'rad',
'jy': 'Jy',
'au': 'AU',
}
try:
new_units = ""
if unit_str is None:
unit_str = ''
unit_str = unit_str.lower(... |
actframework/FrameworkBenchmarks | frameworks/Python/api_hour/yocto_http/etc/hello/api_hour/gunicorn_conf.py | Python | bsd-3-clause | 309 | 0.003236 | import multiprocessing
import os
_is_travis = os.environ.get('TRAVIS') == 'true'
workers = multiprocessing.cpu_count()
if _is_travis:
workers = 2
bind = ['0.0.0.0:8080', '0.0.0.0:8081', '0.0.0.0:8082']
keepalive = 120
errorlog = '-'
pidfile = '/t | mp/api_hour. | pid'
pythonpath = 'hello'
backlog = 10240000 |
rafallo/p2c | gui/desktop/main.py | Python | mit | 428 | 0.004673 | # -*- coding: utf-8 -*-
import sys
import logging
from PyQt5.QtWidgets import QApplication
from p | 2c.app import P2CDaemon
from gui.desktop.mainwindow import MainWindow
logging.basicConfig(level=logging.DEBUG | )
def main():
app = QApplication(sys.argv)
ui = MainWindow()
ui.setupUi(ui)
logic = P2CDaemon()
ui.connect_app(logic)
# ui.play()
sys.exit(app.exec_())
if __name__ == '__main__':
main() |
roboime/pyroboime | roboime/clients/iris.py | Python | agpl-3.0 | 1,711 | 0.001169 | #
# Copyright (C) 2013-2015 RoboIME
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distrib... | , (same name, call and
# documentation, and inserting that into the closure.
def _closure_hack():
cmd_func = func.im_func
global_func = lambda *args: cmd_func(self, *args)
global_func.orig_func = cmd_func
| global_func.func_name = cmd_func.func_name
global_func.func_doc = cmd_func.func_doc
globals()[cmd] = global_func
_closure_hack()
def cli_loop(self):
print 'Welcome to IRIS (Interactive RoboIME Intelligence Shell)'
#IPython.start_ipython()
... |
ustroetz/python-osrm | osrm/extra.py | Python | mit | 9,281 | 0.000215 | # -*- coding: utf-8 -*-
"""
@author: mthh
"""
import matplotlib
import numpy as np
from geopandas import GeoDataFrame, pd
from shapely.geometry import MultiPolygon, Polygon, Point
from . import RequestConfig, Point as _Point
from .core import table
if not matplotlib.ge | t_backend():
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
def contour_poly(gdf, field_name, n_class):
"""
Interpolate the time values (stored in the column ` | field_name`)
from the points contained in `gdf` and compute the contour polygons
in `n_class`.
Parameters
----------
gdf : :py:obj:`geopandas.GeoDataFrame`
The GeoDataFrame containing points and associated values.
field_name : str
The name of the column of *gdf* containing the v... |
poiesisconsulting/openerp-restaurant | portal_project/tests/test_access_rights.py | Python | agpl-3.0 | 14,973 | 0.004809 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2013-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | ect tasks visible
task_ids = self.project_task.search(cr, self.user_public_id, [('project_id', '=', pigs_id)])
self.assertEqual(set(task_ids), test_task_ids,
'access rights: public user cannot see all tasks of a public project')
# Test: all project tasks readable
... | ask.write, cr, self.user_public_id, task_ids, {'description': 'TestDescription'})
# ----------------------------------------
# CASE2: portal project
# ----------------------------------------
self.project_project.write(cr, uid, [pigs_id], {'privacy_visibility': 'portal'})
# Do:... |
mlavin/django | tests/ordering/tests.py | Python | bsd-3-clause | 12,431 | 0.001368 | from datetime import datetime
from operator import attrgetter
from django.db.models import F
from django.db.models.functions import Upper
from django.test import TestCase
from .models import Article, Author, Reference
class OrderingTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Arti... | 6))
cls.a2 = Article.objects.create(headline="Article 2", pub_date=datetime(2005, 7, 27))
cls.a3 = Article.objects.create(headline="Article 3", pub_date=datetime(2005, 7, 27))
cls.a4 = Article.objects.create(headline="Article 4", pub_date=datetime(2005, 7, 28))
cls.author_1 = | Author.objects.create(name="Name 1")
cls.author_2 = Author.objects.create(name="Name 2")
for i in range(2):
Author.objects.create()
def test_default_ordering(self):
"""
By default, Article.objects.all() orders by pub_date descending, then
headline ascending.
... |
chrisjluc/ProjectEuler | Power.py | Python | mit | 409 | 0.01467 | class Power:
def __init__(self, base, exponent):
self.base = base
self.exponent = exponent
def addexponent(self):
self.exponent += 1
def getTotal(self):
return self.base**self.exponent
def getBase | (self):
return self.base
def getexponent(self):
return self. | exponent
def printSelf(self):
print self.base
print self.exponent |
paulnurkkala/comm-slackbot | plugins/get_source/get_source.py | Python | gpl-2.0 | 297 | 0.030303 | bot_user = 'U041TJU13'
irc_channel = 'C040NNZHT'
outputs = []
def process_message(data):
message_text = data.get('text')
if message_t | ext:
if (bot_user in message_text) and ('source' in message_text):
outputs.append([irc_channel, '`htt | ps://github.com/paulnurkkala/comm-slackbot`'])
|
OmniLayer/omnicore | test/functional/wallet_groups.py | Python | mit | 3,669 | 0.001363 | #!/usr/bin/env python3
# Copyright (c) 2018-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet group functionality."""
from test_framework.test_framework import BitcoinTestFramework
fro... | v.sort()
assert_approx(v[0], 0.2)
assert_approx(v[1], 1.3, 0.0001)
# Empty out node2's wallet
self.nodes[2].sendtoaddress(address=self.nodes[0].getnewaddress(), amount=self.nodes[2].getbalance(), subtractfeefromamount=True)
self.sync_all()
self.nodes[0].generate(1)
... | i in range(5):
raw_tx = self.nodes[0].createrawtransaction([{"txid":"0"*64, "vout":0}], [{addr2[0]: 0.05}])
tx = FromHex(CTransaction(), raw_tx)
tx.vin = []
tx.vout = [tx.vout[0]] * 2000
funded_tx = self.nodes[0].fundrawtransaction(ToHex(tx))
signe... |
amlyj/pythonStudy | 2.7/standard_library/study_filter.py | Python | mit | 516 | 0.005587 | #!/usr/bin/env python
# -*- coding: ut | f-8 -*-
# @Time : 17-7-22 上午1:18
# @Author : tom.lee
# @Site :
# @File : study_filter.py
# @Software: PyCharm
"""
按照某种规则过滤掉一些元素
接收一个 boolean返回值的函数,可用时lambda,可以是自定义的函数,
迭代传入的可迭代对象的每个元素进行过滤
"""
lst = [1, 2, 3, 4, 5, 6]
# 所有奇数都会返回True, 偶数会返回False被过滤掉
print filter(lambda x: x % 2 != 0, lst)
# 输出结果 [1, 3, 5 | ]
|
Jgarcia-IAS/SITE | addons/website_forum/models/forum.py | Python | agpl-3.0 | 36,003 | 0.004444 | # -*- coding: utf-8 -*-
from datetime import datetime
import uuid
from werkzeug.exceptions import Forbidden
import logging
import openerp
from openerp import api, tools
from openerp import SUPERUSER_ID
from openerp.addons.website.models.website import slug
from openerp.exceptions import Warning
from openerp.osv impo... | get_post_from_hierarchy(self, cr, uid, ids, context=None):
post_ids = set(ids)
for post in self.browse(cr, SUPERUSER_ID, ids, context=context):
if post.parent_id:
post_ids.add(post.parent_id.id)
return list(post_ids)
def _get_child_count(self, cr, uid, ids, field... | (cr, uid, ids, context=context):
if post.parent_id:
res[post.parent_id.id] = len(post.parent_id.child_ids)
else:
res[post.id] = len(post.child_ids)
return res
def _get_uid_answered(self, cr, uid, ids, field_name, arg, context=None):
res = dict... |
uvchik/pvlib-python | pvlib/test/test_spa.py | Python | bsd-3-clause | 16,534 | 0.002722 | import os
import datetime as dt
try:
from importlib import reload
except ImportError:
try:
from imp import reload
except ImportError:
pass
import numpy as np
from numpy.testing import assert_almost_equal
import pandas as pd
import unittest
import pytest
from pvlib.location import Locatio... | 54.413442486
dt_actual_array = np.array([1.7184831e+04, 5.7088051e+03, 1.5730419e+03,
1.9801820e+02, 1.3596506e+01, -2.1171894e+00,
2.9289261e+01, 4.0824887e+01, 5.4724581e+01,
5.7426651e+01, 6.4108015e+01, 6.5038015e+01])
mix_year_array = n... | 10), month)
mix_year_actual = np.full((10), dt_actual)
mix_month_actual = mix_year_actual
class SpaBase(object):
"""Test functions common to numpy and numba spa"""
def test_julian_day_dt(self):
dt = times.tz_convert('UTC')[0]
year = dt.year
month = dt.month
day = dt.day
... |
450586509/DLNLP | src/dataUtils.py | Python | apache-2.0 | 5,682 | 0.012172 | #-*- coding: utf-8 -*-
#2016年 03月 03日 星期四 11:01:05 CST by Demobin
#code from:http://www.jianshu.com/p/7e233ef57cb6
import json
import h5py
import codecs
corpus_tags = ['S', 'B', 'M', 'E']
def saveCwsInfo(path, cwsInfo):
'''保存分词训练数据字典和概率'''
print('save cws info to %s'%path)
fd = open(path, 'w')
(initP... | for char in vocab:
fd.write(char.encode('utf-8') + '\t' + str(vocab[char]) + '\n')
fd.close()
def loadCwsInfo(path):
'''载入分词训练数据字典和概率'''
print('load cws info from %s'%path)
fd = open(path, 'r')
line = fd.readline()
j = json.loads(line.strip())
initProb, tranProb = j[0], j[1]
... | lines:
rst = line.strip().split('\t')
if len(rst) < 2: continue
char, index = rst[0].decode('utf-8'), int(rst[1])
vocab[char] = index
indexVocab[index] = char
return (initProb, tranProb), (vocab, indexVocab)
def saveCwsData(path, cwsData):
'''保存分词训练输入样本'''
print('sa... |
abhikeshav/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ncs1k_mxp_lldp_oper.py | Python | apache-2.0 | 5,511 | 0.022138 | """ Cisco_IOS_XR_ncs1k_mxp_lldp_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR ncs1k\-mxp\-lldp package operational data.
This module contains definitions
for the following management objects\:
lldp\-snoop\-data\: Information related to LLDP Snoop
Copyright (c) 2013\-2015 by Cisco Sy... | xp-lldp-oper'
_revision = '2015-11-09'
def __init__ | (self):
self.ethernet_controller_names = LldpSnoopData.EthernetControllerNames()
self.ethernet_controller_names.parent = self
class EthernetControllerNames(object):
"""
Ethernet controller snoop data
.. attribute:: ethernet_controller_name
port Na... |
gobstones/PyGobstones | pygobstones/gui/editor.py | Python | gpl-3.0 | 5,582 | 0.002866 | from views.viewEditor import *
from views.boardPrint.board import *
from views.boardPrint.boardEditor import *
import views.resources
import boardOption
from helpOption import *
from pygobstones.commons.i18n import *
from pygobstones.commons.qt_utils import saveFileName
class Editor(QtGui.QWidget):
def __init__(s... | dFromDisk(self):
self.board = boardToString(self.ui.boardEditor.getEditedBoard())
filename = saveFileName(self, '*.gbb')
if not filename == QtCore.QString(''):
(filep, filen) = os.path.split(str(filename))
| if not filename[-4:] == '.gbb':
filename = filename + '.gbb'
myFile = open(filename, 'w')
myFile.write(self.board)
myFile.close()
self.reset_combo_persist()
def saveBoardToImage(self):
filename = saveFileName(self, '*.png')
if not... |
abonaca/gary | gary/coordinates/__init__.py | Python | mit | 124 | 0 | fr | om .core import *
from .sgr import *
from .orphan import *
from .propermotion import *
from .velocity_transforms import | *
|
shubhamdipt/django-autocomplete-light | test_project/select2_taggit/migrations/0001_initial.py | Python | mit | 1,006 | 0.002982 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-30 15:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_au... | auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
| ('for_inline', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inline_test_models', to='select2_taggit.TModel')),
('test', taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='tag... |
Bitka0/serenade | homepage/usermanag/views.py | Python | mit | 1,656 | 0.027174 | # coding: utf-8
# Copyright (c) 2011 Lukas Martini, Phillip Thelen.
# This file may be used and distributed under the terms found in the
# file COPYING, which you should have received along with this
# program. If you haven't, please refer to [email protected].
from django.utils.translation import ugettext_lazy ... | t_object_or_404, get_list_or_404, redirect
import util
from django.contrib.auth import authenticate, login, logout
def userlogin(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
l... | gin(request, user)
title = _("Login was successful")
message = _("Welcome {0}".format(username))
else:
title = _("Login failed")
message = _("The account is disabled")
else:
title = _("Login failed")
message = _("Username and/or password wrong")
context = util.generateContext(request, contextType = ... |
hughperkins/kgsgo-dataset-preprocessor | thirdparty/future/tests/test_future/test_pasteurize.py | Python | mpl-2.0 | 7,644 | 0.001177 | # -*- coding: utf-8 -*-
"""
This module contains snippets of Python 3 code (invalid Python 2) and
tests for whether they can be passed to ``pasteurize`` and
immediately run under both Python 2 and Python 3.
"""
from __future__ import print_function, absolute_import
import pprint
from subprocess import Popen, PIPE
imp... | .request
URL = 'http://pypi.python.org/pypi/{}/json'
package = 'future'
r = urllib.request.urlopen(URL.format(package))
pprint.pprin | t(r.read())
"""
after = """
import pprint
import future.standard_library.urllib.request as urllib_request
URL = 'http://pypi.python.org/pypi/{}/json'
package = 'future'
r = urllib_request.urlopen(URL.format(package))
p... |
henglinyang/Pace | TrainWeeks.py | Python | bsd-2-clause | 1,931 | 0.001554 | from datetime import date, timedelta
from sys import argv
class TrainWeeks(object):
def __init__(self, month, day, year, nr_weeks=16, nr_days=0):
self._race = date(year, month, day)
self._duration = timedelta(weeks=nr_weeks, days=nr_days)
self._start = self._race - self._duration + timedelt... | self._race.day,
y=self._race.year,
u=self._duration.days)
if __name__ == '__main__':
def usage_and_exit():
print('Today is {t}.\nUsage: {c} <mm/dd/yy> <number of weeks>'.format(
t=dat | e.today(), c=argv[0].split('/')[-1]))
exit()
argc = len(argv)
if argc == 1:
usage_and_exit()
date_minutes = argv[1].split('/')
if len(date_minutes) < 2:
usage_and_exit()
if len(date_minutes) < 3:
date_minutes.append(str(date.today().year))
if argc < 3:
tw ... |
AKFourSeven/antoinekougblenou | old/wiki/includes/zhtable/Makefile.py | Python | mit | 13,221 | 0.037138 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# @author Philip
import tarfile as tf
import zipfile as zf
import os, re, shutil, sys, platform
pyversion = platform.python_version()
islinux = platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
o... | ret
def dictToSortedList( src_table, pos ):
return sorted( src_table.it | ems(), key = lambda m: m[pos] )
def translate( text, conv_table ):
i = 0
while i < len( text ):
for j in range( len( text ) - i, 0, -1 ):
f = text[i:][:j]
t = conv_table.get( f )
if t:
text = text[:i] + t + text[i:][j:]
i += len(t) - 1... |
jnidzwetzki/bboxdb | bin/experiments/experiment_sampling_calculate_std.py | Python | apache-2.0 | 2,322 | 0.030146 | #!/usr/bin/python
#
# Calculate the standard deviation of the
# sampling size experiment
#
############################################
import sys
import re
import math
# Check args
if len(sys.argv) < 2:
print "Usage:", sys.argv[0], "<filename>"
sys.exit(0)
# Regex
samplingSizePattern = re.compile("^Simula... | ([\d\.]+)");
experimentPattern = re.compile("^(\d+)\s(\d+)\s(\d+)\s\d+\s\d+")
class Experiment(object):
samplingSize = -1
leftRegion = []
totalElements = -1
def __init__(self, samplingSize):
self.samplingSize = sa | mplingSize
self.leftRegion = []
self. totalElements = -1
def get_std_str(self):
'''Error in STD'''
totalDiff = 0;
for result in self.leftRegion:
diff = abs(self.totalElements/2 - result)
totalDiff = totalDiff + math.pow(diff, 2)
std = math.sqrt(totalDiff / len(self.leftRegion))
stdPer = float(std... |
sejust/pykit | zkutil/__init__.py | Python | mit | 1,117 | 0 | from .exceptions imp | ort (
ZKWaitTimeout,
)
from .zkacid import (
cas_loop,
)
from .zkconf import (
KazooClientExt,
ZKConf,
kazoo_client_ext,
)
from .zkutil import (
PermTypeError,
close_zk,
init_hierarchy,
export_hierarchy,
is_backward_locking,
lock_id,
make_acl_entry,
make_digest,
... | _acl,
parse_kazoo_acl,
parse_lock_id,
perm_to_long,
perm_to_short,
wait_absent,
get_next,
)
from .zklock import (
LockTimeout,
ZKLock,
make_identifier,
)
from .cached_reader import (
CachedReader,
)
__all__ = [
"PermTypeError",
"ZKWaitTimeout",
"cas_loop",
... |
tracykteal/replicate-filter | scripts/repeats_html_template.py | Python | gpl-3.0 | 2,972 | 0.004711 | HTML_TEMPLATE = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/
DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
Copyright: Darren Hester 2006, http://www.designsbydarren.com
L... | if you contact the authors and will be made available here soon.
<p class="block"><s | trong>Comments/Questions:</strong>
<br>If you have any comments or questions about these programs, please contact the \
<a href=mailto:[email protected]>authors</a>.
</div>
</div>
<div id="page_footer">
<p><font size=-2> <br />
<!--
<a href="http://validator.w3.org/check?uri=referer" target="_blank">Valid XHT... |
krafczyk/spack | var/spack/repos/builtin/packages/perl-soap-lite/package.py | Python | lgpl-2.1 | 1,976 | 0.001012 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for m... | s program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PerlSoapLite(PerlPackage):
"""Perl's Web Services Toolkit"""
homepage = "http://sear... |
birdchan/project_euler | problems/014/run.py | Python | mit | 979 | 0.034729 |
import math
import string
lookup_map = {}
def memcache_read(n):
global lookup_map
if lookup_map.has_key(n):
return lookup_map[n]
else:
return None
def memcache_write(n, value):
global lookup_map
lookup_map[n] = value
def get_chain_length(n):
| # check cache
cache = memcache_read(n)
if cache != None:
return cache
# no cache, so caculate
if n <= 1:
memcache_write(1, 1)
return 1
if n % 2 == 0:
n = n / 2
else:
n = 3*n + 1
return get_chain_length(n) + 1
def find_longest_chain_under_N(n):
max_chai | n_num = -1
max_chain_length = 0
for i in xrange(1, n, 1):
chain_length = get_chain_length(i)
memcache_write(i, chain_length)
if chain_length > max_chain_length:
max_chain_length = chain_length
max_chain_num = i
#print max_chain_num
#print max_chain_length
return max_chain_num
if __nam... |
getpatchwork/patchwork | patchwork/api/__init__.py | Python | gpl-2.0 | 1,807 | 0 | # Patchwork - automated patch tracking system
# Copyright (C) 2020, Stephen Finucane <[email protected]>
#
# SPDX-License-Identifier: GPL-2.0-or-later
from rest_framework.fields import empty
from rest_framework.fields import get_attribute
from rest_framework.fields import SkipField
from rest_framework.relations import... | key patch django-rest-framework to work around issue #7550 [1] until #7574
# [2] or some other variant lands
#
# [1] https://github | .com/encode/django-rest-framework/issues/7550
# [2] https://github.com/encode/django-rest-framework/pull/7574
def _get_attribute(self, instance):
# Can't have any relationships if not created
if hasattr(instance, 'pk') and instance.pk is None:
return []
try:
relationship = get_attribute(in... |
kylewmoser/HistoryEmergent | run.py | Python | mit | 187 | 0.005348 | from histo | ryemergent import app
# Comment out the line below if you are using something other than the built-in
# Flask development server
app.run(host='127.0.0.1', port=5000, debug=Tru | e) |
seims/SEIMS | preprocess/post_process_taudem.py | Python | gpl-2.0 | 8,376 | 0.000955 | #! /usr/bin/env python
# coding=utf-8
# Post process of TauDEM
# 1. convert subbasin raster to polygon shapefile
# 2. add width and default depth to reach.shp
# @Author: Junzhi Liu, 2012-4-12
# @Revised: Liang-Jun Zhu, 2016-7-7
#
import platform
from osgeo import ogr
from chwidth import chwidth
from config import ... | taValueStream
else:
outputStream[i][j] = outputSubbasin[i][j]
WriteGTiffFile(outputSubbasinFile, nRows, nCols, outputSubbasin,
subbasin.geotrans, subbasin.srs, noDataValue, gdal.GDT_Int32)
WriteGTiffFile(outputStreamLinkFile, nRows, nCols, outputStream,
... | Raster.srs, noDataValue, gdal.GDT_Int32)
def ChangeFlowDir(flowDirFileTau, flowDirFileEsri):
# flowDirFileTau is float
dirMap = {1.: 1.,
2.: 128.,
3.: 64.,
4.: 32.,
5.: 16.,
6.: 8.,
7.: 4.,
8.: 2.}
replaceByD... |
half2me/libant | libAnt/node.py | Python | mit | 4,209 | 0.001663 | import threading
from queue import Queue, Empty
from time import sleep
from libAnt.drivers.driver import Driver
from libAnt.message import *
class Network:
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
self.key = key
self.name = name
self.number = 0
def __str__(self... | elf._waiters.clear()
sleep(1)
class Node:
def __init__(self, driver: Driver, name: str = None):
self._driver = driver
self._name = name
self._out = Queue()
self._init = []
self._pump = None
self._configMessages = Queue()
| def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
def start(self, onSuccess, onFailure):
if not self.isRunning():
self._pump = Pump(self._driver, self._init, self._out, onSuccess, onFailure)
self._pump.start()
de... |
thushear/MLInAction | kaggle/blending.py | Python | apache-2.0 | 3,727 | 0.00161 | """Kaggle competition: Predicting a Biological Response.
Blending {RandomForests, ExtraTrees, GradientBoosting} + stretching to
[0,1]. The blending scheme is related to the idea Jose H. Solorzano
presented here:
http://www.kaggle.com/c/bioresponse/forums/t/1889/question-about-the-process-of-ensemble-learning/10950#pos... | print "Fold", i
X_train = X[train]
y_train = y[train]
X_test = X[test]
y_test = y[test]
clf.fit(X | _train, y_train)
y_submission = clf.predict_proba(X_test)[:, 1]
dataset_blend_train[test, j] = y_submission
dataset_blend_test_j[:, i] = clf.predict_proba(X_submission)[:, 1]
dataset_blend_test[:, j] = dataset_blend_test_j.mean(1)
print
print "Blending."
clf = Lo... |
dymkowsk/mantid | scripts/Reflectometry/isis_reflectometry/saveModule.py | Python | gpl-3.0 | 3,083 | 0.025949 | #pylint: disable=invalid-name
from __future__ import (abso | lute_import, division, print_function)
from PyQt4 import QtCore
from mantid.simpleapi import *
import numpy as n
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False):
fname+='.dat'
... | for i in range(0,len(x1)-1):
X1[i]=(x1[i]+x1[i+1])/2.0
y1=a1.readY(0)
e1=a1.readE(0)
f=open(fname,'w')
if title:
f.write(titl)
samp = a1.getRun()
for log in logs:
prop = samp.getLogData(str(log.text()))
headerLine='#'+log.text() + ': ' + str(prop.value) + '\n'
... |
samabhi/pstHealth | venv/lib/python2.7/site-packages/gunicorn/workers/geventlet.py | Python | mit | 1,452 | 0.003444 | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from __future__ import with_statement
import os
try:
import eventlet
except ImportError:
raise RuntimeError("You need eventlet installed to use this worker.")
from eventlet import hu... | hub()
super(EventletWorker, self).init_process()
def timeout_ctx(self):
return eventlet.Timeout(self.cfg.keepalive, False)
def run(self):
self.socket = GreenSocket(family_or_realsock=self.socket.sock)
self.socket.setblocking(1)
self.acceptor = eventlet.spawn(event | let.serve, self.socket,
self.handle, self.worker_connections)
while self.alive:
self.notify()
if self.ppid != os.getppid():
self.log.info("Parent changed, shutting down: %s", self)
break
eventlet.sleep(1.0)
self.notif... |
OpenCanada/website | articles/migrations/0030_auto_20150806_2136.py | Python | mit | 928 | 0.002155 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import wagtail.core.blocks
import wagtail.core.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0029_auto_20150811_1924'),
]
operations = [
migrations.Add... | e',
name='end_notes',
field=wagtail.core.fields.StreamField([('end_note', wagtail.core.blocks.StructBlock([(b'identifier', wagtail.core.blocks.CharBlock()), (b'text', wagtail.core.blocks.TextBlock())]))], null=True, blank=True),
),
migrations.AddField(
model_name='cha... | extBlock())]))], null=True, blank=True),
),
]
|
111pontes/ydk-py | core/ydk/providers/_importer.py | Python | apache-2.0 | 1,938 | 0.001032 | # ----------------------------------------------------------- | -----
# Copyright 2016 Cisco Systems
#
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES ... |
emacsway/ascetic | ascetic/contrib/polymorphic.py | Python | mit | 7,432 | 0.00148 | # -*- coding: utf-8 -*-
from collections import OrderedDict
from ascetic import exceptions
from ascetic.mappers import Load, Mapper, OneToOne, Result
from ascetic.utils import to_tuple
from ascetic.utils import cached_property
from ascetic.contrib.gfk import GenericForeignKey
# TODO: Support for native support inherit... | cMapper, self).save(obj)
class PolymorphicResult(Result):
_polymorphic = True
def polymorphic(self, val=True):
self._polymorphic = val
return self._query
def fill_cache(self):
if self._cache is not None or | not self._polymorphic:
return super(PolymorphicResult, self).fill_cache()
if self._cache is None:
polymorphic, self._polymorphic = self._polymorphic, False
self._cache = list(self.iterator())
self._cache = PopulatePolymorphic(self._cache, self.mapper.get_mapper).... |
CantemoInternal/pyxb | tests/trac/trac-0196/check.py | Python | apache-2.0 | 2,993 | 0.015703 | # -*- coding: utf-8 -*-
from __future__ import print_function
import logging
if __name__ == '__main__':
logging.basicConfig()
_log = logging.getLogger(__name__)
import unittest
import qq0196 as qq
import qu0196 as qu
import uq0196 as uq
import uu0196 as uu
import mix
from pyxb.utils.domutils import BindingDOMSuppo... | q_i, uu_i)
try:
print(i.toDOM().toprettyxml())
except pyxb.ValidationError as e:
print(e.details())
raise
i = mix.uue(a='a')
print(i.toxml('utf-8'))
class TestTrac0196 (unittest.Tes | tCase):
module_map = { qq : ( qq.Namespace, qq.Namespace ),
qu : ( qu.Namespace, None ),
uq : ( None, uq.Namespace ),
uu : ( None, None ) }
global_a = ( 'a', 'aq', 'au' )
global_e = ('e', 'eq', 'eu' )
local_a = ( 'ta', 'taq', 'tau' )
local_e ... |
Ninja-1/Circle2 | circlelib/proxy.py | Python | gpl-2.0 | 7,644 | 0.008503 | # UDP Proxy
# The Circle - Decentralized resource discovery software
# Copyright (C) 2001 Paul Francis Harrison
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version ... |
try:
message, address = sock.recvfrom(65536,MSG_DONTWAIT)
cPickle.dump((0,address,message),sys.stdout,1)
sys.stdout.flush()
except:
do_error()
elif sock in result[2]:
do_error()
"""
# queue = [ ]
# while select.select([sys.stdin],[ ],[ ]... | request:
# sys.exit(0)
# try:
# sock.sendto(request[1],request[0])
# except:
# pass
#proxy_program = string.replace(proxy_program,"\n","\\n")
def _make_connection_win32(host, password):
split = string.split(host,'@')
command = 'plink '+split[-1]
if len(split) == 2:
c... |
roadmapper/ansible | lib/ansible/modules/network/cloudengine/ce_lldp.py | Python | gpl-3.0 | 32,532 | 0.002859 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
from __future__ import (abso | lute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ce_lldp
version_added: "2.10"
short_description: Manages LLDP configuration on HUAWEI... | es LLDP configuration on HUAWEI CloudEngine switches.
author:
- xuxiaowei0512 (@CloudEngine-Ansible)
notes:
- This module requires the netconf system service be enabled on the remote device being managed.
- Recommended connection is C(netconf).
- This module also works with C(local) connections for lega... |
mpharrigan/msmbuilder | tools/ci/push-docs-to-s3.py | Python | gpl-2.0 | 802 | 0.001247 | import os
import boto
from boto.s3.key import Key
# The secret key is available as a secure environment variable
# on travis-ci to push the build documentation to Amazon S3.
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = os.environ | ['AWS_SECRET_ACCESS_KEY']
BUCKET_NAME = 'msmbuilder.org'
bucket_name = AWS_ACCESS_KEY_ID.lower() + '-' + BUCKET_NAME
conn = boto.connect_s3(AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(BUCKET_NAME)
root = 'docs/sphinx/_build/html'
for dirpath, dirnames, filenames in os.walk(root):... | ey = os.path.relpath(fn, root)
k.set_contents_from_filename(fn)
|
cloudtools/troposphere | troposphere/inspector.py | Python | bsd-2-clause | 1,446 | 0.002075 | # Copyright (c) 2012-2022, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
from . import AWSObject, PropsDictType, Tags
from .validators import integer
class AssessmentTarget(AWSObject):
"""
`AssessmentTarget <htt... | amazon.com/AWSCloudFormation/latest/UserGuide/aws-reso | urce-inspector-assessmenttarget.html>`__
"""
resource_type = "AWS::Inspector::AssessmentTarget"
props: PropsDictType = {
"AssessmentTargetName": (str, False),
"ResourceGroupArn": (str, False),
}
class AssessmentTemplate(AWSObject):
"""
`AssessmentTemplate <http://docs.aws.ama... |
rafael2reis/iqextractor | qextractor/preprocessing/baseline.py | Python | gpl-3.0 | 8,010 | 0.006991 | # module baseline.py
#
# Copyright (c) 2015 Rafael Reis
#
"""
baseline module - Functions to produce the Baseline System's features.
"""
__version__="1.0"
__author__ = "Rafael Reis <[email protected]>"
import re
#import globoquotes
def boundedChunk(s):
"""Indetifies the Bounded Chunk.
Assigns a 1 to the... | start(0), m.end(0))
#print(m.group(0))
i = dicIndex[m.start(0)]
end = dicIndex[m.end(0)-1]
while i < end:
bc[i] = 1
i += 1
for m in re.finditer(p2, text):
| #print(m.start(0), m.end(0))
#print(m.group(0))
i = dicIndex[m.start(0)]
end = dicIndex[m.end(0)-1]
while i < end:
bc[i] = 1
i += 1
for m in re.finditer(p3, text):
#print(m.start(0), m.end(0))
#print(m.group(0))
i = dicIndex[m.sta... |
labsland/labmanager | alembic/versions/3ee46f95bcce_make_laboratory_name_longer.py | Python | bsd-2-clause | 600 | 0.016667 | """Make Laboratory name longer
Revision ID: 3ee46f95bcce
Revises: 4bc4c1ae0f38
Create Date: 2014-04-29 21:29:43.714010
"""
# revision identifiers, used by Alembic.
revision = '3ee46f95bcce'
d | own_revision = '4bc4c1ae0f38'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.alter_column("laboratories", "laboratory_id", type_ = sa.Unicode(350))
op.alter_column("laboratories", "name", type_ = sa.Unicode(350))
def downgrade():
op.alter_column("laboratories", "laboratory_id", type_ ... | sa.Unicode(50))
|
tobinmori/neo4j-python-clients-review | models.py | Python | gpl-2.0 | 544 | 0.003676 |
class Series(object):
def __init__(self, name=None):
| self.name = name
def __str__(self):
return self.name
class Episode(object):
def __init__(self, name=None):
self.name = name
def __str__(self):
return self.name
class Organization(object) | :
def __init__(self, name=None):
self.name = name
def __str__(self):
return self.name
class Actor(object):
def __init__(self, name=None):
self.name = name
def __str__(self):
return self.name
|
SYSTRAN/geographic-api-python-client | systran_geographic_api/models/full_inspiration.py | Python | apache-2.0 | 2,585 | 0.005803 | #!/usr/bin/env python
# coding: utf-8
"""
Copyright 2015 SYSTRAN Software, 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/licen... | Inspira | tion type
self.type = None # str
# Title
self.title = None # str
# Introduction
self.introduction = None # str
# Content
self.content = None # str
# Array of Photos
self.photos = None # list[Photo]
... |
taw/python_koans | python3/koans/about_class_attributes.py | Python | mit | 4,920 | 0.002236 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutClassMethods in the Ruby Koans
#
from runner.koan import *
class AboutClassAttributes(Koan):
class Dog:
pass
def test_objects_are_objects(self):
fido = self.Dog()
self.assertEqual(True, isinstance(fido, object))
def... | self.assertRegexpMatches(self.Dog2.growl(), "classmethod growl, arg: cls=Dog2")
def test_classmethods_are_not_independent_of_instance_methods(self):
fido = self.Dog2()
self.assertRegexpMatches(fido.growl(), "classmeth | od growl, arg: cls=Dog2")
self.assertRegexpMatches(self.Dog2.growl(), "classmethod growl, arg: cls=Dog2")
def test_staticmethods_are_unbound_functions_housed_in_a_class(self):
self.assertRegexpMatches(self.Dog2.bark(), "staticmethod bark, arg: None")
def test_staticmethods_also_overshadow_inst... |
pygeo/pycmbs | pycmbs/tests/test_icon.py | Python | mit | 1,061 | 0.006598 | # -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
import unittest
from pycmbs.icon import Icon
class TestPycmbsIcon(unittest.TestCase):
def setUp(self):
# requires local installation of ICON sample files... | hing.nc', 'novar')
with self.assertRaises(ValueError):
x.read()
def test_IconInitMissingGridFile(self):
x = Icon(self.datafile, 'nothing.nc', 'novar')
with self.assertRaises(ValueError):
| x.read()
#~ def test_IconReadOK(self):
#~ x = Icon(self.datafile, self.datafile, 'rsns')
#~ x.read()
if __name__ == "__main__":
unittest.main()
|
SrNetoChan/QGIS | cmake/FindSIP.py | Python | gpl-2.0 | 3,000 | 0.002 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2007, Simon Edwards <[email protected]>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain... | TY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL Simon Edwards <[email protected]> BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, O... | CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# FindSIP.py
# Copyright (c) 2007, Simon Edwards <[email protected]>
# Redi... |
echristophe/lic | src/LicBinaryWriter.py | Python | gpl-3.0 | 13,727 | 0.003424 | """
Lic - Instruction Book Creation software
Copyright (C) 2010 Remi Gagne
This file (LicBinaryWriter.py) is part of Lic.
Lic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, eithe... | tream.writeInt32(len(submodelList))
for model in submodelList:
__writeSubmodel(stream, model)
def __writeAbstractPart(stream, part):
stream << QString(part.filename) << QString(part.name)
stream. | writeBool(part.isPrimitive)
stream.writeInt32(part.width)
stream.writeInt32(part.height)
stream.writeInt32(part.leftInset)
stream.writeInt32(part.bottomInset)
stream << part.center
stream.writeFloat(part.pliScale)
stream.writeFloat(part.pliRotation[0])
stream.writeFloat(part.pl... |
paulcwatts/1hph | gonzo/utils/__init__.py | Python | bsd-3-clause | 2,240 | 0.009821 | import re
import unicodedata
from htmlentitydefs import name2codepoint
from StringIO import StringIO
try:
from django.utils.encoding import smart_unicode
except ImportError:
def smart_unicode(s):
return s
from django import forms
from django.core.files.uploadedfile import SimpleUploadedFile
# From ht... | ot frm.is_valid():
| return False
setattr(instance, field_name, frm.cleaned_data['image'])
return True
|
themoken/canto-curses | canto_curses/reader.py | Python | gpl-2.0 | 9,002 | 0.005332 | # -*- coding: utf-8 -*-
#Canto-curses - ncurses RSS reader
# Copyright (C) 2016 Jack Miller <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
from canto_ne... | et then grab that from the server now and setup
# a hook to get notified when sel's attributes are changed.
l = [ | "description", "content", "links", "media_content",
"enclosures"]
for attr in l:
if attr not in sel.content:
tag_updater.request_attributes(sel.id, l)
s += "%BWaiting for content...%b\n"
on_hook("curses_attribut... |
20tab/django-taggit-live | setup.py | Python | bsd-3-clause | 1,287 | 0.003885 | import os
from setuptools import setup, find_packages
from setuptools.dist import Distribution
import pkg_resources
import taggit_live
setup(name='django-taggit-live',
version=taggit_live.__version__,
description="It's an autocomplete widget for django-taggit TagField",
author='20tab srl: Raffaele Co... | icense='Mit License',
platforms=['OS Independent'],
classifiers=[
#'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
#'License :: OSI Approved :: BSD License',
... | Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks',
],
install_requires=[
'Django >=1.6',
'django-taggit'
],
packages=find_packages(),
include_package_data... |
cyrobin/patrolling | timer.py | Python | bsd-3-clause | 580 | 0.003448 | """ Timer
inspired by
http://stackoverflow.com/q | uestions/5849800/tic-toc-functions-analog-in-python
Usage :
with Timer('foo_stuff'):
# do some foo
# do some stuff
"""
import time
from constant import *
class Timer(object):
def __init__(self, name=None):
self.name = name
def __enter__(self):
self.tstart = time.time()
... | print '[%s]' % self.name,
print 'Elapsed: %s s' % (time.time() - self.tstart)
|
movitto/snap | snap/config.py | Python | gpl-3.0 | 10,759 | 0.005763 | # Snap! Configuration Manager
#
# (C) Copyright 2011 Mo Morsi ([email protected])
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, Version 3,
# as published by the Free Software Foundation
#
# This program is distributed in the hope that it will... | argets to lists of backends to use when backing up / restoring them
self.target_backends = {}
# mapping of targets to lists of entities to include when backing up
self.target_includes = {}
# mapping of targets to lists of entities to exclude when backing up
self.target_excludes... | # output format to backup / restore
self.outputformat = 'snapfile'
# location of the snapfile to backup to / restore from
self.snapfile = None
# Encryption/decryption password to use, if left as None, encryption will be disabled
self.encryption_password = None
... |
AASHE/django-aashestrap | aashestrap/management/commands/get_menu.py | Python | mit | 1,101 | 0 | #!/usr/bin/env python
"""
Retrieves menu from Drupal site
"""
from aashestrap.models import Menu
from django.core.management.base import BaseCommand
import urllib2
from django.http import HttpResponse
from BeautifulSoup import BeautifulSoup
from django.core.exceptions import ObjectDoesNotExist
class Command(BaseC... | rch | and extract the footer
results = soup.findAll(id="block-menu_block-3")
footer = results[0].__str__('utf8')
# Search and extract the navigation bar
results = soup.findAll(id="navigation")
header = results[0].__str__('utf8')
menu.footer = footer
menu.header = header
menu.save()
|
resync/resync | tests/test_client_utils.py | Python | apache-2.0 | 6,834 | 0.000878 | from .testlib import TestCase
import argparse
import logging
import os.path
import re
import unittest
from resync.client_utils import init_logging, count_true_args, parse_links, parse_link, parse_capabilities, parse_capability_lists, add_shared_misc_options, process_shared_misc_options
from resync.client import Client... | = argparse.ArgumentParser()
add_shared_misc_options(parser, default_logfile='/tmp/abc.log', include_remote=True)
args = parser.parse_args(['--noauth',
'--access-token', 'VerySecretToken',
'--delay', '1.23',
... | th)
self.assertEqual(args.access_token, 'VerySecretToken')
self.assertEqual(args.delay, 1.23)
self.assertEqual(args.user_agent, 'rc/2.1.1')
# Remote options note selected
parser = argparse.ArgumentParser()
add_shared_misc_options(parser, default_logfile='/tmp/abc.log', in... |
elelianghh/gunicorn | tests/support.py | Python | mit | 1,597 | 0.000626 | import functools
import sys
import unittest
import platform
HOST = "127.0.0.1"
def requires_mac_ver(*min_version):
"""Decorator raising SkipTest if the OS is Mac OS X and the OS X
version if less than min_version.
For example, @requires_mac_ver(10, 5) raises SkipTest if the OS X version
is lesser th... | mpleNamespace
except ImportError:
class SimpleNamespace(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
return "{}({})".... | return self.__dict__ == other.__dict__
|
DrewMeyersCUboulder/UPOD_Bridge | Server/Mongodb.py | Python | mit | 147 | 0.006803 | """
Mongo database connection class
use mongodb to store/retriv | e data
"""
from AbstractDb import Abstr | actDb
class Mongodb(AbstractDb):
pass
|
visionegg/visionegg | demo/mouse_gabor_perspective.py | Python | lgpl-2.1 | 11,119 | 0.015559 | #!/usr/bin/env python
"""Perspective-distorted sinusoidal grating in gaussian window"""
from VisionEgg import *
start_default_logging(); watch_exceptions()
from VisionEgg.Core import *
from VisionEgg.Gratings import *
from VisionEgg.SphereMap import *
from VisionEgg.Text import *
from VisionEgg.Textures import *
impo... | r_text = Text( text = "temporary text",
position=(xpos,ypos),**text_params)
set_filter_and_text()
text_stimuli.append( filter_text )
ypos += text_stimuli[-1].parameters.size[1] + yspace
sf_cutoff_text = Text(text = "'c/C' changes cutoff SF (now %.2f cycles per texel)"%(grating_stimulus.parameters.l... | es_per_texel),
position=(xpos,ypos),**text_params)
text_stimuli.append( sf_cutoff_text )
ypos += text_stimuli[-1].parameters.size[1] + yspace
zoom_text = Text(text = "'z/Z' changes zoom (X field of view %.2f degrees)"%(fov_x),
position=(xpos,ypos),**text_params)
text_stimuli.append( zoo... |
coandco/pywinauto | pywinauto/unittests/test_common_controls.py | Python | lgpl-2.1 | 34,027 | 0.005466 | # GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library 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 (at you... |
app.start_(os.path.join(controlspy_folder, "List View.exe"))
self.texts = [
("Mercury", '57,910,000', '4,880', '3.30e23'),
("Venus", '108,200,000', '12 | ,103.6', '4.869e24'),
("Earth", '149,600,000', '12,756.3', '5.9736e24'),
("Mars", '227,940,000', '6,794', '6.4219e23'),
("Jupiter", '778,330,000', '142,984', '1.900e27'),
("Saturn", '1,429,400,000', '120,536', '5.68e26'),
("Uranus", '2,870,990,000'... |
mikel-egana-aranguren/SADI-Galaxy-Docker | galaxy-dist/lib/galaxy/tools/deps/containers.py | Python | gpl-3.0 | 10,514 | 0.002378 | from abc import (
ABCMeta,
abstractmethod
)
import os
import string
from galaxy.util import asbool
from ..deps import docker_util
import logging
log = logging.getLogger(__name__)
DEFAULT_CONTAINER_TYPE = "docker"
class ContainerFinder(object):
def __init__(self, app_info):
self.app_info = app_... | (destination_name, default)
env_directives = []
for pass_through_var in self.tool_info.env_pass_through:
env_directives.append('"%s=$%s"' % (pass_through_var, pass_through_var))
# Allow destinations to explicitly set environment variables just for
# docker contain | er. Better approach is to set for destination and then
# pass through only what tool needs however. (See todo in ToolInfo.)
for key, value in self.destination_info.iteritems():
if key.startswith("docker_env_"):
env = key[len("docker_env_"):]
env_directives.app... |
svisser/ipuz | ipuz/puzzlekinds/wordsearch.py | Python | mit | 1,438 | 0 | from ipuz.exceptions import IPUZException
from ipuz.structures import (
validate_crosswordvalues,
validate_dimensions,
validate_groupspec_dict,
)
from ipuz.validators import (
validate_bool,
validate_dict_of_strings,
validate_elements,
validate_list_of_strings,
validate_non_negative_int,... | "points": (validate_elements, ["linear", "log", None]),
"zigzag": validate_bool,
"retrace": validate | _bool,
"useall": validate_bool,
"misses": validate_dict_of_strings,
}
|
pku9104038/edx-platform | common/lib/capa/capa/capa_problem.py | Python | agpl-3.0 | 28,574 | 0.002625 | #
# File: capa/capa_problem.py
#
# Nomenclature:
#
# A capa Problem is a collection of text and capa Response questions.
# Each Response may have one or more Input entry fields.
# The capa problem may include a solution.
#
"""
Main module which shows problems (of "capa" type).
This is used by capa_module.
"""
from ... | Recreate the problem
| 2) Populate any student answers.
"""
return {'seed': self.seed,
'student_answers': self.student_answers,
'correct_map': self.correct_map.get_dict(),
'input_state': self.input_state,
'done': self.done}
def get_max_score(self):
... |
yast/yast-python-bindings | examples/Tree-Checkbox4.py | Python | gpl-2.0 | 2,467 | 0.011755 | # encoding: utf-8
# Tree with recursive multi selection
from yast import import_module
import_module('UI')
from yast import *
import copy
class TreeCheckbox4Client:
def main(self):
UI.OpenDialog(
VBox(
Heading("YaST2 Mini Control Center"),
Tree(
Id("mod"),
... | ged Event")
if event["EventReason"] == "ValueChanged":
ycpbuiltins.y2error("Value Changed Event")
if event["EventType"] == "TimeoutEvent":
ycpbuiltins.y2error("Timeout Event")
if event != None:
ycpbuiltins.y2error(self.formatEvent(event))
id = event["ID"... |
break
UI.CloseDialog()
def formatEvent(self, event):
event = copy.deepcopy(event)
html = "Event:"
for key, value in ycpbuiltins.foreach(event).items():
html = html + " " + key + ": " + ycpbuiltins.tostring(value) + ""
return html
TreeCheckbox4Client().main()
|
simpeg/simpeg | tutorials/05-dcr/plot_inv_2_dcr2d_irls.py | Python | mit | 15,085 | 0.001061 | """
2.5D DC Resistivity Inversion with Sparse Norms
===============================================
Here we invert a line of DC resistivity data to recover an electrical
conductivity model. We formulate the inverse problem as a least-squares
optimization problem. For this tutorial, we focus on the following:
- De... | rsion with SimPEG requires that we define the uncertainties on our data.
# This represents our estimate of the standard deviation of the
# noise in our data. For DC dat | a, the uncertainties are 10% of the absolute value.
#
#
dc_data.standard_deviation = 0.05 * np.abs(dc_data.dobs)
########################################################
# Create Tree Mesh
# ------------------
#
# Here, we create the Tree mesh that will be used invert the DC data
#
dh = 4 # base cell width
dom_widt... |
ales-erjavec/scipy | scipy/ndimage/utils/generate_label_testvectors.py | Python | bsd-3-clause | 1,672 | 0.001196 | import numpy as np
from scipy.ndimage import label
def generate_test_vecs(infile, strelfile, resultfile):
"test label with different structuring element neighborhoods"
def bitimage(l):
return np.array([[c for c in s] for s in l]) == '1'
data = [np.ones((7, 7)),
bitimage(["1110111",
... | stype(int).tostring() for t in strels)]
inputs = np.vstack(data)
results = np.vstack([label(d, s)[0] for d in data for s in strels])
strels = np.vstack(strels)
np.savetxt(infile, inputs, fmt="%d")
np.savetxt(strelfile, strels, fmt="%d")
np.sa | vetxt(resultfile, results, fmt="%d")
generate_test_vecs("label_inputs.txt", "label_strels.txt", "label_results.txt")
|
living180/git-cola | cola/widgets/spellcheck.py | Python | gpl-2.0 | 4,103 | 0.000487 | from __future__ import absolute_import, division, print_function, unicode_literals
import re
from qtpy.QtCore import Qt
from qtpy.QtCore import QEvent
from qtpy.QtCore import Signal
from qtpy.QtGui import QMouseEvent
from qtpy.QtGui import QSyntaxHighlighter
from qtpy.QtGui import QTextCharFormat
from qtpy.QtGui impor... | pellcheck.check(word_object.group()):
self.setFormat(
word_object.start(), word_object.end() - word_object.start(), fmt
| )
class SpellAction(QAction):
"""QAction that returns the text in a signal."""
result = Signal(object)
def __init__(self, *args):
QAction.__init__(self, *args)
# pylint: disable=no-member
self.triggered.connect(self.correct)
def correct(self):
self.re... |
django-danceschool/django-danceschool | danceschool/discounts/cms_toolbars.py | Python | bsd-3-clause | 1,622 | 0.000617 | from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from cms.toolbar_pool import toolbar_pool
from cms.toolbar_base import CMSToolbar
from cms.toolbar.items import Break
@toolbar_pool.register
class DiscountLinksToolbar(CMSToolbar):
''' Add discounts to the financial menu '''
... | position = financial_menu.find_first(
Break,
identifier='financial_related_items_break'
) + 1
related_menu = financial_menu.get_or_create_menu(
'financial-related', _('Related Items'), position=position
)
if self.request.user.has_... | scounts.change_discountcombo'):
related_menu.add_link_item(
_('Discounts'), url=reverse('admin:discounts_discountcombo_changelist')
)
if self.request.user.has_perm('discounts.change_discountcategory'):
related_menu.add_link_item(
_('Discount Ca... |
puruckertom/poptox | poptox/generic/generic_parameters.py | Python | unlicense | 406 | 0.022167 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 17 14:50:59 2012
@author: JHarston
"""
import os |
os.environ['DJANGO_SETTINGS_MODULE']='settings'
from django import forms
from django.db import models
class genericInp(forms.Form):
chemical_name = forms.CharField(widget=forms.Textarea (attrs={'col | s': 20, 'rows': 2}))
body_weight_of_bird = forms.FloatField(required=True,label='NEED TO GET INPUTS.') |
dennybaa/st2 | st2common/st2common/persistence/base.py | Python | apache-2.0 | 12,025 | 0.002328 | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | _object.id) if conflict_object else None
message = str(e)
raise StackStormDBObjectConflictError(message=message, conflict_id=confli | ct_id,
model_object=model_object)
is_update = str(pre_persist_id) == str(model_object.id)
# Publish internal event on the message bus
if publish:
try:
if is_update:
cls.publish_update(model_object... |
robotics-at-maryland/qubo | src/vl_qubo/src/arduino_node.py | Python | mit | 7,826 | 0.009839 | #!/usr/bin/env python
#sgillen - this program serves as a node that offers the arduino up to the rest of the ros system.
# the packets send to the arduino should be in the following format: p<data>!
# p tells the arduino which command to execute, the data that follows will depend on which command this is
# in genera... | (msg.data)
def sway_callback(msg):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", msg.data)
sway_cmd = thruster_map(msg.data)
def thruster_callback(msg):
rospy.loginfo(rospy.get_caller_id() + "I heard %s", msg.data)
for i in range(0,num_thrusters):
thruster_cmds[i] = thruster_map(msg.data... | ------
# main
if __name__ == '__main__':
# map for messages
msg = {'t': '', 'd': '', 's': ''}
#!!! this also restarts the arduino! (apparently)
# Keep trying to open serial
while True:
try:
ser = serial.Serial(device,115200, timeout=0,parity=serial.PARITY_NONE,stopbits=serial.... |
xuru/pyvisdk | tests/test_facade.py | Python | mit | 1,752 | 0.005137 | import unittest,types
from pyvisdk import Vim
from pyvisdk.base.managed_object_types import ManagedObjectTypes
from pyvisdk.mo.host_system import HostSystem
from pyvisdk.mo.folder import Folder
from pyvisdk.mo.datastore import Datastore
from pyvisdk.mo.cluster_compute_resource import ClusterComputeResource
from pyvisdk... | property_collector import CachedPropertyCollector, HostSystemCachedPropertyCollector
from tests.common import get_options
from time import sleep
from re import match
class Test_Facades(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.options = get_options()
cls.vim = Vim(cls.options.se... | f tearDownClass(cls):
cls.vim.logout()
def test_HostPropertyCollectorFacade(self):
facade = HostSystemCachedPropertyCollector(self.vim, ["config.storageDevice"])
properties = facade.getProperties()
self.assertGreater(len(properties.keys()), 0)
self.assertEqual(len(properties... |
stackforge/watcher | watcher/decision_engine/solution/solution_comparator.py | Python | apache-2.0 | 832 | 0 | # -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# Authors: Jean-Emile DARTOIS <[email protected]>
#
# 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/... | stributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions | and
# limitations under the License.
#
import abc
class BaseSolutionComparator(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def compare(self, sol1, sol2):
raise NotImplementedError()
|
Decalogue/chat | chat/word2pinyin.py | Python | mit | 4,070 | 0.004119 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PEP 8 check with Pylint
"""Word to pinyin.
"""
from numpy import mat, zeros, where
from pypinyin import pinyin, lazy_pinyin
# from .mytools import time_me
def sum_cosine(matrix, threshold):
"""Calculate the parameters of the semantic Jaccard model based on... | return dict(total=total, num_not_match=num, total_dif=max_score)
def match_pinyin(pinyin1, pinyin2):
"""Similarity score betwe | en two pinyin.
计算两个拼音的相似度得分。
"""
assert pinyin1 != "", "pinyin1 can not be empty"
assert pinyin2 != "", "pinyin2 can not be empty"
pv_match = 0
if len(pinyin1) < len(pinyin2):
len_short = len(pinyin1)
len_long = len(pinyin2)
pv_long = pinyin2
pv_short = ... |
rschnapka/partner-contact | partner_relations_in_tab/model/__init__.py | Python | agpl-3.0 | 1,051 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | anty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################... | pe
from . import res_partner
|
chrislit/abydos | tests/compression/test_compression_rle.py | Python | gpl-3.0 | 3,657 | 0 | # Copyright 2014-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | self.assertEqual(
self.bwt.decode(
self.rle.decode(self.rle.encode(self.bwt.encode('banana')))
),
'banana',
)
self.assertEqual(self.rle.decode(self.rle.encode(self.bws)), self.bws)
self.assertEqual(
self.bwt.decode(
... | (self.rle.encode('Schifffahrt')), 'Schifffahrt'
)
self.assertEqual(
self.bwt.decode(
self.rle.decode(
self.rle.encode(self.bwt.encode('Schifffahrt'))
)
),
'Schifffahrt',
)
if __name__ == '__main__':
uni... |
tommyogden/moldy-argon | plot/plot_moldy_argon.py | Python | mit | 1,728 | 0.00463 | #!/usr/bin/env python
import sys
import numpy as np
import json
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def main():
json_data = open('moldy_argon.json')
data = json.load(json_data)
json_data.close()
num_t_steps = len(data)
num_atoms = data[0]['atoms']['num... | frames=len(t_range),
# interval=200)#, blit=True)
anim = animation.FuncAnimation(fig, animate, init_func=init, interval=1)
plt.show()
if __name__ == '__main__':
status = main( | )
sys.exit(status) |
iskandr/prototype-pan-allele-class2 | mhc_names.py | Python | apache-2.0 | 3,134 | 0.000638 | from collections import defaultdict
# source: wikipedia article on HLA-DQ
dq_allele_freq_table = """
05:01 02:01 13.16
02:01 02:02 11.08
03:02 02:02 0.08
03:01 04:02 0.03
03:02 04:02 0.11
04:01 04:02 2.26
01:01 05:01 10.85
01:02 05:01 0.03
01:03 05:01 0.03
01:04 05:01 0.71
01:02... | 6:09 0.71
02:01 03:01 0.05
03:01 03:01 0.16
03:03 03:01 6.45
03:01 03:04 0.09
03:02 03:04 0.09
04:01 03:01 0.03
05:05 03:01 11.06
06:01 03:01 0.11
03:01 03:02 9.62
03:02 03:02 0.93
02:01 03:03 3.66
03:02 03:03 0.79
"""
# map each beta to a list of (alpha, freq) pairs
d... | )
if not line:
continue
a, b, freq = line.split()
a = a.replace(":", "")
b = b.replace(":", "")
freq = float(freq)
dq_beta_to_alphas[b].append((a, freq))
dq_alpha_to_betas[a].append((b, freq))
dq_beta_to_alpha = {
b: max(pairs, key=lambda x: x[1])[0]
for (b, pairs) in dq_bet... |
xiaoda99/keras | keras/initializations.py | Python | mit | 2,556 | 0.002739 | from __future__ import absolute_import
import theano
import theano.tensor as T
import numpy as np
from .utils.theano_utils import sharedX, shared_zeros, shared_ones
def get_fans(shape):
fan_in = shape[0] if len(shape) == 2 else np.prod(shape[1:])
fan_out = shape[1] if len(shape) == 2 else shape[0]
return... | return uniform(shape, s)
def he_normal(shape):
''' Reference: He et al., http://arxiv.org/abs/1502.01852
'''
fan_in, fan_out = get_fans(shape)
s = np.sqrt(2. / fan_in)
ret | urn normal(shape, s)
def he_uniform(shape):
fan_in, fan_out = get_fans(shape)
s = np.sqrt(6. / fan_in)
return uniform(shape, s)
def orthogonal(shape, scale=1.1):
''' From Lasagne. Reference: Saxe et al., http://arxiv.org/abs/1312.6120
'''
flat_shape = (shape[0], np.prod(shape[1:]))
a = n... |
w495/python-video-shot-detector | shot_detector/filters/compound/sigma_cascade.py | Python | bsd-3-clause | 1,654 | 0.008475 | # -*- coding: utf8 -*-
"""
The main idea of this module, that you can combine
any number of any filters without any knowledge about their
implementation. You have only one requirement — user functions
should return a filter (or something that can be cast to a filter).
"""
from __future__ import absolu... | min_size_filter_generator(start, stop, step, pivot, **kwargs)
res = sum(res) / (stop - start) / step
return res
def min_size_filter_generator(start, stop, step=None, sigma=None,
**kwargs):
"""
:param start:
:param stop:
:param step:
:param sigma:
... | ean = mean(s=c_size, **kwargs)
c_std = std(s=c_size, **kwargs)
# noinspection PyTypeChecker
bill = (original > (c_mean + sigma * c_std)) | int
yield bill
|
Tyler-Ward/GolemClock | display/mq.py | Python | mit | 1,102 | 0.016334 | import pika
import pickle
from display import LCDLinearScroll
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='clock_output', type='fanout')
result = channel.queue_declare(exclusive=True)
queue_name = result.m... | el.basic_publish(exchange='clock_output', routing_key='', body='ALARM_STOP')
channel.basic_publish(exchange='clock_output', routing_key='', body='ALARM_CANCEL')
def callback(ch, method, properties, body):
print("message received: | {0}".format(body))
if body == "ALARM_START":
items = ("It's sunny today", "Meeting at 2pm")
lcd_scroller = LCDLinearScroll(items, select_callback=select_callback)
lcd_scroller.display_message("Scroll through\nmessages")
#lcd_scroller.setup_scroll_events()
channel.basic_consume(callback, queue=queue_name, no... |
jmcnamara/XlsxWriter | xlsxwriter/test/comparison/test_simple09.py | Python | bsd-2-clause | 1,048 | 0 | ########################################################################## | #####
#
# Tests for XlsxWriter.
#
# SPDX-License-Identifier: BSD-2-Clause
# Copyright (c), 2013-2022, John McNamara, [email protected]
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWrit... | ile created by Excel.
"""
def setUp(self):
self.set_filename('simple09.xlsx')
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Test data out of range. ... |
ktan2020/legacy-automation | win/Lib/site-packages/wx-3.0-msw/wx/lib/agw/rulerctrl.py | Python | mit | 57,819 | 0.005967 | # --------------------------------------------------------------------------------- #
# RULERCTRL wxPython IMPLEMENTATION
#
# Andrea Gavana, @ 03 Nov 2006
# Latest Revision: 17 Aug 2011, 15.00 GMT
#
#
# TODO List
#
# 1. Any idea?
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
... | erskoil.com
# [email protected]
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #
"""
:class:`Rul | erCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget.
Description
===========
:class:`RulerCtrl` implements a ruler window that can be placed on top, bottom, left or right
to any wxPython widget. It is somewhat similar to the rulers you can find in text
e... |
Rahi374/PittAPI | PittAPI/textbook.py | Python | gpl-2.0 | 5,449 | 0.03964 | '''
The Pitt API, to access workable data of the University of Pittsburgh
Copyright (C) 2015 Ritwik Gupta
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your ... | """
request_objs = []
course_names = [] # need to save these
instructors = [] # need to save these
for i in range(len(courses_info)):
book_info = courses_info[i]
print(book_info)
| course_names.append(book_info['course_name'])
instructors.append(book_info['instructor'])
request_objs.append(grequests.get(get_department_url(book_info['department_code'], book_info['term']), timeout=10))
responses = grequests.map(request_objs) # parallel requests
course_ids = []
j = 0 #... |
ForTheYin/ical2fullcalendar | ics-convert.py | Python | mit | 1,883 | 0.020181 | #!/usr/bin/env python
"""Converts the .ics/.ical file into a FullCalendar compatiable JSON file
FullCalendar uses a specific JSON format similar to iCalendar format. This
script creates a JSON file containing renamed event components. Only the
title, description, start/end time, and url data are used. Does not support... | e: python ' + sys.argv[0] + ' file [output]'
exit(1)
# default output filename (just adds .json extension on the given file)
out_fi | le = sys.argv[1] + '.json'
if (len(sys.argv) == 3):
# changes output filename to the 2nd arugment
out_file = sys.argv[2]
# opens the input .ics file and parses it as iCalendar Calendar object
ics_file = open(sys.argv[1],'rb')
ics_cal = Calendar.from_ical(ics_file.read())
# array of event information
result = []
fo... |
alviproject/alvi | alvi/client/scenes/traverse_tree_depth_first.py | Python | mit | 588 | 0 | from alvi.client.scenes.create_tree import CreateTree
class TraverseTreeDepthFirst(CreateTree):
def traverse(self, marker, tree, node):
marker.append(node)
tree.stats.traversed_nodes += 1
tree.sync()
for child in node.children:
self.traverse(marker, tree, child)
de... | sync():
super().run(**kwargs)
marker = tree.create_multi_marker("Traversed")
tree.stats.traversed_nodes = 0
self.traverse(marker, tree, tree.ro | ot)
|
ekosareva/vmware-dvs | networking_vsphere/tests/unit/drivers/test_ovs_firewall.py | Python | apache-2.0 | 28,260 | 0 | # Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
# 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/LICEN... | _res_port = {'security_group_source_groups': 'abc',
'mac_address': '00:11:22:33:44:55',
'network_id': "netid",
'id': "123",
'security_groups' | : "abc",
'lvid': "100",
'device': "123"}
cookie = ("0x%x" % (hash("123") & 0xffffffffffffffff))
class TestOVSFirewallDriver(base.TestCase):
@mock.patch('networking_vsphere.drivers.ovs_firewall.OVSFirewallDriver.'
'check_ovs_firewall_restart')
@mock.patch('ne... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.