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 |
|---|---|---|---|---|---|---|---|---|
mpvillafranca/hear-cloud | apps/audio/models.py | Python | gpl-3.0 | 464 | 0.00216 | from django.db import models
import datetime
# Create your models he | re.
class AudioFile(models.Model):
# Titulo: string. No nulo
# Link permanente: string. No nulo
# Modo de compartir (público/privado): String
# URL de la imagen: string
# Descripcion: string
# Duracion: int
# Genero: string
# Descargable: bool
# Fecha creacion: datetime. No nulo.
... | pertenece
|
Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/system-config-printer/authconn.py | Python | gpl-3.0 | 18,164 | 0.012387 | #!/usr/bin/python
## Copyright (C) 2007, 2008, 2009, 2010 Red Hat, Inc.
## Author: Tim Waugh <[email protected]>
## 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 Lice... | if self._use_pk:
create_object = cupspk.Connection
else:
create_object = cups.Connection
self._connection = create_object (host=self._server,
port=self._port,
| encryption=self._encryption)
if self._use_pk:
self._connection.set_parent(self._parent)
self._user = self._use_user
debugprint ("Connected as user %s" % self._user)
methodtype_lambda = type (self._connection.getPrinters)
methodtype_real = type (self._connect... |
ds17/reptiles_gh | lianjia/lianjia.py | Python | apache-2.0 | 37 | 0.027027 | # - | *- co | ding:utf-8 -*-
import scrapy |
Hijacker/vmbot | test/test_acl_decorators.py | Python | gpl-3.0 | 2,199 | 0.002729 | # coding: utf-8
from __future__ import absolute_import, division, unicode_literals, print_function
import unittest
import mock
from xmpp.protocol import JID, Message
from vmbot.helpers import database as db
from vmbot.models.user import User
from vmbot.helpers.decorators import requires_role, requires_dir_chat
@... | def test_requires_dir_chat(self):
self.assertTrue(dir_chat_acl(self, Message(frm=JID("[email protected]")),
self.default_args))
def test_requires_dir_chat_denied(self):
self.assertIsNone(dir_chat_acl(self, self.default_mess, self.default_ | args))
if __name__ == "__main__":
unittest.main()
|
fracpete/python-weka-wrapper-examples | src/wekaexamples/flow/for_loop.py | Python | gpl-3.0 | 1,959 | 0.001531 | # This program is free software: you can redistribute it and/or m | odify
# 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 distributed in the hope that it will be useful,
# but WIT | HOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# for_loo... |
selentd/pythontools | pytools/src/IndexEval/fetchdata.py | Python | apache-2.0 | 5,671 | 0.010933 | '''
Created on 15.02.2015
@author: diesel
'''
import datetime
from indexdata import IndexData, IndexHistory
import indexdatabase
def _selectTrue( idxData ):
return True
class FetchData():
'''
classdocs
'''
def __init__(self, indexName):
'''
Constructor
'''
self... | > 0:
monthlyHistory.append( indexHistory )
currentPeriod = _getNextMonth(currentPeriod[0], currentPeriod[1])
return monthlyHistory
def fetchSelectedHistory(self, startDate, endDate, startFunc, endFunc):
isInTransaction = False
meanHi | storyList = list()
idxHistory = IndexHistory()
for idxData in self.collection.find({'date': {'$gte': self.startDate, '$lt': self.endDate} }).sort('date'):
if isInTransaction:
if endFunc.checkEndTransaction( idxData, idxHistory.len() ):
meanHistoryList.app... |
ucd-cws/arcproject-wq-processing | arcproject/scripts/verify.py | Python | mit | 5,159 | 0.024423 | from datetime import datetime
import tempfile
import os
import arcpy
import pandas as pd
import geodatabase_tempfile
import amaptor
import scripts.exceptions
import scripts.funcs
from .. import waterquality
from ..waterquality import classes
from ..waterquality import api
from .. import scripts
from ..scripts import... | point in self.points:
point.extract_time(self.time_format_string)
def check_in_same_projection(summary_file, verification_date):
"""
Checks t | he summary file against the spatial reference of the records for a provided date - returns a reprojected version of it that matches the spatial reference of the stored features
:param summary_file:
:param verification_date:
:return:
"""
# get some records
wq = api.get_wq_for_date(verification_date)
sr_code = w... |
Oreder/PythonSelfStudy | Exe_02.py | Python | mit | 302 | 0.003311 | # A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a | piece of code:
# print "This won't run. | "
print("This will run.") |
larsks/python-ftn | fidonet/apps/makemsg.py | Python | gpl-3.0 | 3,792 | 0.003692 | #!/usr/bin/python
import sys
import time
import random
from fidonet import Address
from fidonet.formats import *
import fidonet.app
class App (fidonet.app.AppUsingAddresses, fidonet.app.AppUsingNames):
logtag = 'fidonet.makemsg'
def create_parser(self):
p = super(App, self).create_parser()
... | p.add_option('--output', '--out')
p.add_option('--disk', action='store_false',
dest='packed')
p.add_option('--packed', action='store_true',
dest='packed')
p.set_default('packed', True)
return p
def handle_args (self, args):
if self.opts.p... | ge.MessageParser.create()
else:
msg = diskmessage.MessageParser.create()
if not self.opts.origin:
try:
self.opts.origin = self.cfg.get('fidonet', 'address')
self.log.debug('got origin address = %s' % self.opts.origin)
except:
... |
Johnzero/OE7 | openerp/addons/mail/mail_mail.py | Python | agpl-3.0 | 16,471 | 0.005161 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms o... | hed by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version
#
# 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
# 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/>
#
##############################################################################
import bas... |
huxianglin/pythonstudy | week05-胡湘林/ATM/shop/shop_conf/settings.py | Python | gpl-3.0 | 665 | 0.019549 | #!/usr/bin/ | env python
# encoding:utf-8
# __author__: huxianglin
# date: 2016-09-18
# blog: http://huxianglin.cnblogs.com/ http://xianglinhu.blog.51cto.com/
import os
import logging
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
USER_DATABASE = {
"name":"users",
"path": os.path.join(os.path.join(... | "name":"goods",
"path": os.path.join(os.path.join(BASE_DIR,"shop_data"),"goods_data.json")
}
LOG_INFO = {
"shop_path":os.path.join(BASE_DIR,"shop_logs"),
"LOG_LEVEL":logging.INFO
}
BANK_CARD="666666" |
andysalerno/reversi_ai | agents/q_learning_agent.py | Python | mit | 8,477 | 0.000708 | """This Q-Lea | rning neural network agent is still a work in progress and is not complete yet."""
import random
from agents import Agent
from keras.layers import Dense
from keras.models import Sequential, model_from_json
from keras.optimizers import RMSprop, SGD
from util import info, opponent, color_name, numpify, best_move_val
MOD... | DEN_SIZE = 42
ALPHA = 1.0
BATCH_SIZE = 64
WIN_REWARD = 1
LOSE_REWARD = -1
optimizer = RMSprop()
# optimizer = SGD(lr=0.01, momentum=0.0)
class QLearningAgent(Agent):
def __init__(self, reversi, color, **kwargs):
self.color = color
self.reversi = reversi
self.learning_enabled = kwargs.get... |
jorgegil/kpo-pilot | KPOpilot/test/test_resources.py | Python | gpl-3.0 | 1,017 | 0.00295 | # coding=utf-8
"""Resources test.
.. note:: 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 option) any later version.
"""
__author__ = '... | est.TestCase):
"""Test rerources work."""
def setUp(self):
"""Runs before each test."""
pass
def tearDown(self):
"""Runs after each test."""
pass
def test_icon_png(self):
"""Test we can click OK."""
path | = ':/plugins/KPOpilot/icon.png'
icon = QIcon(path)
self.assertFalse(icon.isNull())
if __name__ == "__main__":
suite = unittest.makeSuite(KPOpilotResourcesTest)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
|
hachreak/invenio-pages | setup.py | Python | gpl-2.0 | 4,023 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015, 2016 CERN.
#
# Invenio 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 Fou | ndation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio 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 GNU
# General Public License for more details... |
desvox/bbj | server.py | Python | mit | 27,166 | 0.000699 | from src.exceptions import BBJException, BBJParameterError, BBJUserError
from src import db, schema, formatting
from functools import wraps
from uuid import uuid1
from sys import argv
import traceback
import cherrypy
import sqlite3
import json
dbname = "data.sqlite"
# any values here may be overrided in the config.js... | response = schema.response(value, cherrypy.thread_data.usermap)
| except BBJException as e:
response = e.schema
except json.JSONDecodeError as e:
response = schema.error(0, str(e))
except Exception as e:
error_id = uuid1().hex
response = schema.error(
1, "Internal server error: code {} {}".format(
... |
code-sauce/tensorflow | tensorflow/python/training/server_lib_test.py | Python | apache-2.0 | 16,137 | 0.003718 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | python.ops import math_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import server_lib
clas | s GrpcServerTest(test.TestCase):
def __init__(self, methodName="runTest"): # pylint: disable=invalid-name
super(GrpcServerTest, self).__init__(methodName)
self._cached_server = server_lib.Server.create_local_server()
def testRunStep(self):
server = self._cached_server
with session.Session(server... |
zxgaoray/calculate_play | calculator/Taowa.py | Python | mit | 1,409 | 0.006388 | user_input = raw_input()
class Taowa:
def __init__(self):
return
def setSize(self, m1, m2):
self.width = m1
self.height = m2
self.area = m1 * m2
class Sorter:
def __init__(self):
self.taowas = []
self.lastWidth = 0
self.lastHeight = 0
return... | y=lambda taowa:taowa.width)
def calculate(self):
l = len(self.taowas)
self.lastHeight = self.taowas[0].height
self.lastWidth = self.taowas[0].width
m = 1
for idx in range(1, l, 1):
taowa = self.taowas[idx]
w = taowa.width
h = taowa.heigh... | return m
sorter = Sorter()
sorter.setArray(user_input)
sorter.makeTaowa()
sorter.sortTaowa()
user_input = sorter.calculate()
print user_input |
rsalmaso/wagtail | wagtail/core/migrations/0024_alter_page_content_type_on_delete_behaviour.py | Python | bsd-3-clause | 684 | 0.001462 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-22 09:34
from django.db import migrations, models
import wagtail.core.models
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0023_alter_page_revision_on_delete_behaviour"),
]
operations = [
migrations.... | model_name="page",
name="content_type",
field=models.ForeignKey(
on_delete=models.SET(wagtail.core.models.get_default_page_content_type),
related_name="pages",
to="contentty | pes.ContentType",
verbose_name="content type",
),
),
]
|
kfieldho/SMQTK | TPL/libsvm-3.1-custom/tools/easy.py | Python | bsd-3-clause | 2,835 | 0.029277 | #!/usr/bin/env python
import sys
import os
from subprocess import *
if len(sys.argv) <= 1:
print('Usage: {0} training_file [testing_file]'.format(sys.argv[0]))
raise SystemExit
# svm, grid, and gnuplot executable files
is_win32 = (sys.platform == 'win32')
if not is_win32:
svmscale_exe = "/Users/sun/bin/svm-sc... | d_py = r".\grid.py"
assert os.path.exists(svmscale_exe),"svm-scale | executable not found"
assert os.path.exists(svmtrain_exe),"svm-train executable not found"
assert os.path.exists(svmpredict_exe),"svm-predict executable not found"
assert os.path.exists(gnuplot_exe),"gnuplot executable not found"
assert os.path.exists(grid_py),"grid.py not found"
train_pathname = sys.argv[1]
assert os... |
victor-gonzalez/AliPhysics | PWGJE/EMCALJetTasks/Tracks/analysis/Draw/DrawRawSpectrumFit.py | Python | bsd-3-clause | 2,015 | 0.011414 | #**************************************************************************
#* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
#* *
#* Author: The ALICE Off-line Project. *
#* Contributors ... | ******************************************
from PWG.PWGJE.EMCALJetTasks.Tracks.analysis.base.FileHandler import ResultDataBuilder
from PWG.PWGJE.EMCALJetTasks.Tracks.analysis.base.struct.DataContainers import SpectrumContainer
from plots.RawDataFittingPlot import RawDataFittingPlot
def MakeNormalisedRawSpectrum(data)... | SpectrumContainer.RangeException as e:
print str(e)
return data.MakeProjection(0, "ptSpectrum%s", "p_{#rm{t}} (GeV/c)", "1/N_{event} 1/(#Delta p_{#rm t}) dN/dp_{#rm{t}} ((GeV/c)^{-2}")
def DrawRawSpectrumIntegral(filename, trigger = "MinBias"):
reader = ResultDataBuilder("lego", filename)
content ... |
google/vulkan_test_applications | gapid_tests/command_buffer_tests/vkCmdBindVertexBuffers_test/vkCmdBindVertexBuffers_test.py | Python | apache-2.0 | 3,026 | 0.001322 | # Copyright 2017 Google Inc.
# 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, softwa... | ER_COPY,
get_read_offset_function(cmd_copy_buffer,
cmd_copy_buffer.hex_pRegions))
require_equal(0, c | opy.srcOffset)
require_equal(0, copy.dstOffset)
require_equal(1024, copy.size)
|
ahawker/decorstate | setup.py | Python | apache-2.0 | 1,177 | 0 | """
decorstate
~~~~~~~~~~
Simple "state machines" with | Python decorators.
:copyright: (c) 2015-2017 Andrew Hawker
:license: Apache 2.0, see LICENSE for more details.
"""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name='decorstate',
version='0.0.3',
description='Simple "state machines" wi | th Python decorators',
long_description=open('README.md').read(),
author='Andrew Hawker',
author_email='[email protected]',
url='https://github.com/ahawker/decorstate',
license='Apache 2.0',
py_modules=['decorstate'],
classifiers=(
'Development Status :: 4 - Beta',
'I... |
tbrittoborges/protein_motif_encoder | tests/test_protein_motif_encoder.py | Python | mit | 597 | 0.001675 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_protein_motif_encoder
-- | --------------------------------
Tests for `protein_motif_encoder` module.
"""
import pandas as pd
import pytest
from click.testing import CliRunner
import cli
def test_command_line_interface():
runner = CliRunner()
| result = runner.invoke(cli.main)
assert result.exit_code == 0
assert 'protein_motif_encoder.cli.main' in result.output
help_result = runner.invoke(cli.main, ['--help'])
assert help_result.exit_code == 0
assert '--help Show this message and exit.' in help_result.output
|
StarbotDiscord/Starbot | api/settings.py | Python | apache-2.0 | 3,398 | 0.002649 | # Copyright 2017 Starbot Discord Project
#
# 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... | # Table must be empty.
entry_prefix = None
if entry_prefix:
entry_prefix.edit(dict(serverid=id_server, prefix=prefix))
else:
# Create new entry
Table.insert(table_prefix, dict(serverid=id_server, prefix=prefix))
def prefix_get(id_server):
'''Get a server\'s prefix.'... | obal)
try:
entry_prefix = Table.search(table_prefix, 'serverid', '{}'.format(id_server))
except:
# TODO: Narrow this and other Exception clauses.
# Table must be empty.
entry_prefix = None
if entry_prefix:
return entry_prefix.data[1]
else:
return '!'
#... |
javiersanp/CatAtom2Osm | test/test_layer.py | Python | bsd-2-clause | 55,167 | 0.005384 | # -*- coding: utf-8 -*-
import unittest
import mock
import os
import random
from collections import Counter
import logging
logging.disable(logging.WARNING)
import gdal
from qgis.core import *
from PyQt4.QtCore import QVariant
os.environ['LANGUAGE'] = 'C'
import setup
import osm
from layer import *
from catatom2osm im... | self.assertEquals(ndxa, 12)
self.assertEquals(round(vx.x(), | 4), 99.9109)
self.assertEquals(round(vx.y(),4), 49.9234)
angle_v, angle_a, ndx, ndxa, is_acute, is_zigzag, is_spike, vx = \
Point(60, 50).get_spike_context(square, acute_thr, straight_thr, threshold)
self.assertFalse(is_zigzag)
class TestBaseLayer(unittest.TestCase):
def setUp... |
nanshihui/ipProxyDec | ProxyServe/manage.py | Python | gpl-3.0 | 253 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_ | SETTINGS_MODULE", "ProxyServe.settings")
| from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
purduesigbots/pros-cli | pros/conductor/interactive/NewProjectModal.py | Python | mpl-2.0 | 2,998 | 0.002668 | import os.path
from typing import *
from click import Context, get_current_context
from pros.common import ui
from pros.common.ui.interactive import application, components, parameters
from pros.conductor import Conductor
from .parameters import NonExistentProjectParameter
class NewProjectModal(application.Modal[No... | gets)
project_name_placeholder = os.path.basename(os.path.normpath(os.path.abspath(self.directory.value)))
yield components.Container(
components.InputBox('Project Name', self.project_name, placeholder=project_name_placeholder),
components.DropDownBox('Kernel Version', self.ker... | components.Checkbox('Install default libraries', self.install_default_libraries),
title='Advanced',
collapsed=self.advanced_collapsed
)
|
mozilla/socorro | webapp-django/crashstats/api/tests/test_jinja_helpers.py | Python | mpl-2.0 | 503 | 0 | # This Source Code Form is subj | ect to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from crashstats.api.templatetags.jinja_helpers import pluralize
class TestPluralize(object):
def test_basics(self):
assert pluralize(0) =... | "ies") == "ies"
|
FAB4D/humanitas | data_collection/social_media/twitter/merge.py | Python | bsd-3-clause | 933 | 0.013934 | #---------------------------------
#Joseph Boyd - [email protected]
#---------------------------------
import os ; import sys ; import pickle
def main():
num_partitions = 8
unique_users = {}
print "Merging..."
for filename in os.listdir("."):
if filename[filename.rfind('.')+1:] == 'pickle':
... | g..."
partition_size = len(unique_users) / num_partitions
for i in range(num_partitions):
f_unique_users = open('outputs/%s.pickle'%(i), 'wb')
pickle.dump(unique_users.values()[i*partition_s | ize:(i+1)*partition_size], f_unique_users)
f_unique_users.close()
if __name__ == '__main__':
main()
|
Sezzh/tifis_platform | tifis_platform/tifis_platform/urls.py | Python | gpl-2.0 | 975 | 0.002051 | """tifis_platform URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$ | ', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blo... | ))
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')), #perfom translations
url(r'^', include('usermodule.urls', namespace='usermodule')),
url(r'^', include('groupmodule.urls', namespace='groupmodule')),
url(r'... |
spinicist/QUIT | Python/Tests/test_utils.py | Python | mpl-2.0 | 2,502 | 0.001199 | from pathlib import Path
from os import chdir
import unittest
from math import sqrt
from nipype.interfaces.base import CommandLine
from qipype.commands import NewImage, Diff
from qipype.utils import PolyImage, PolyFit, Filter, RFProfile
vb = True
CommandLine.terminal_output = 'allatonce'
class Utils(unittest.TestCas... | 0, 1]
}
poly_sim = 'poly_sim.nii.gz'
mask_file = 'poly_mask.nii.gz'
NewImage(img_size=[sz, sz, sz], grad_dim=0, grad_vals=(0, 1), grad_steps=1,
out_file=mask_file, verbose=vb).run()
PolyImage(ref_file=mask_file, out_file=poly_sim,
order... | y in zip(poly['coeffs'], fit.outputs.poly['coeffs'])])
self.assertLessEqual(terms_diff, 1.e-6)
PolyImage(ref_file=mask_file, out_file='poly_sim2.nii.gz',
order=2, poly=fit.outputs.poly, verbose=vb).run()
img_diff = Diff(baseline=poly_sim,
... |
zeqing-guo/SPAKeyManager | MergeServer/migrations/0002_auto_20160113_0600.py | Python | gpl-3.0 | 480 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-13 06:00
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MergeServer', '0001_initial'),
]
operations = [
migrations.A... | ),
]
| |
lwerdna/chess | Sjeng.py | Python | gpl-3.0 | 3,014 | 0.006304 | #!/usr/bin/python
# Copyright 2012, 2013 Andrew Lamoureux
#
# This file is a part of FunChess
#
# FunChess 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... | maybe return earlier lines with supposed mate, but when further nodes are searched
# you'll see that the opponent can counter... so we search for the very very last line
for line in lines:
# format is: <i_depth> <score> <elapsed> <nodes> <principle variation>
m = re.match(r'^\s+(\d+)\s+(\d+) | \s+(\d+)\s+(\d+)\s+(.*)$', line)
if m:
(i_depth, score, elapsed, nodes, line) = m.group(1,2,3,4,5)
if int(score) > bestScore:
bestScore = int(score)
bestLine = line
#
m = re.match(r'^\s*(.*#)\s*$', bestLine)
if m:
mateLine = m.group... |
mora260/ie0117_III16 | grupo5/videoStreamClient.py | Python | gpl-3.0 | 4,583 | 0.04195 |
#Librerías y módulos requeridos para el desarrollo del app
from kivy.config import Config
Config.set('graphics','resizable',0)
from kivy.core.window import Window
Window.size = (600, 500)
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.grid... | ue define la reproducción o detención del stream
if self.ipAddress == None or self.port == None: #Revisión de los valores de ip y puerto para determinar si se puede inciar el stream
box = GridLayout(cols=1)#Creación de la venta con mensaje de error
box.add_widget(Label(text="Ip o Pue | rto no establecido"))
btn = Button(text="OK")
btn.bind(on_press=self.closePopup)
box.add_widget(btn)
self.popup1 = Popup(title='Error',content=box,size_hint=(.8,.3))
self.popup1.open()
else:
if self.ids.status.text == "Detener":self.stop()#llamado a la función stop
else:
self.ids.st... |
pedroeml/t1-fcg | CrowdDataAnalysis/const.py | Python | mit | 686 | 0.004373 | import configparser
def load_config_file(config_file_path):
config = configparser.ConfigParser()
config.read(config_file_path)
input_folder_path = config['DEFAULT']['InputFolderPath']
too_far_distance = int(config['DEFAULT']['TooFarDistance'])
grouping_max_distance = int(config['DEFAULT']['Groupi... | h, too_far_distance, grouping_max_distance, minimum_distance_change, fps
INPUT_FOLDER_PATH, TOO_FAR_DISTANCE, GROUPING_MAX_DISTANCE, MINIMUM_DISTA | NCE_CHANGE, FPS = load_config_file('.\constants.conf')
|
nazavode/tracboat | tests/test_model.py | Python | gpl-3.0 | 598 | 0 | # -*- coding: utf-8 -*-
import pytest
import peewee
from tracboat.gitlab import model
@pytest.mark.parametrize('version', [
'8.4',
'8.5',
'8.7',
'8.13',
'8.15',
'8.16',
'8.17',
'9.0.0'
])
def test_ | get_model_supported(version):
M = model.get_model(version)
assert M
a | ssert M.database_proxy
assert isinstance(M.database_proxy, peewee.Proxy)
@pytest.mark.parametrize('version', [
'8.4.0',
'9.0.1',
'9.0.0.0',
'8.7.0',
])
def test_get_model_unsupported(version):
with pytest.raises(ImportError):
model.get_model(version)
|
BitWriters/Zenith_project | zango/lib/python3.5/site-packages/django/utils/ipv6.py | Python | mit | 7,971 | 0.000125 | # This code was mostly based on ipaddr-py
# Copyright 2007 Google Inc. http://code.google.com/p/ipaddr-py/
# Licensed under the Apache License, Version 2.0 (the "License").
from django.core.exceptions import ValidationError
from django.utils.six.moves import range
from django.utils.translation import ugettext_lazy as _... | r):
"""
Ensure we have a valid IPv6 address.
Args:
ip_str: A string, the IPv6 address.
Returns:
A boolean, True if this is a valid IPv6 address.
"""
from django.core.validators import validate_ipv4_address
# We need to have at least one ':'.
if ':' not in ip_str:
... | # We can only have one '::' shortener.
if ip_str.count('::') > 1:
return False
# '::' should be encompassed by start, digits or end.
if ':::' in ip_str:
return False
# A single colon can neither start nor end an address.
if ((ip_str.startswith(':') and not ip_str.startswith('::'... |
e-loue/pyke | examples/web_framework/profile_server.py | Python | mit | 442 | 0.006787 | # profil | e_server.py
import cProfile
import simple_server
def run(port=8080, logging=False, trace_sql=False, db_engine='sqlite3'):
cProfile.runctx(
'simple_server.run(port=%d, logging=%s, trace_sql=%s, db_engine=%r)'
% (port, logging, trace_sql, db_engine),
globals(), locals(), 'profile.out')
|
def stats():
import pstats
p = pstats.Stats('profile.out')
p.sort_stats('time')
p.print_stats(20)
|
saltstack/salt | salt/modules/btrfs.py | Python | apache-2.0 | 34,445 | 0.001045 | #
# Copyright 2014 SUSE LLC
#
# 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, softw... | eration by defa | ult.
* **uuid**: Pass UUID or pass True to generate one.
Options:
* **dto**: (raid0|raid1|raid5|raid6|raid10|single|dup)
Specify how the data must be spanned across the devices specified.
* **mto**: (raid0|raid1|ra |
onajafi/Cookie_Sharing_Bot | readDatas.py | Python | gpl-3.0 | 2,844 | 0.009845 | import sqlite3 as lite
import sys
from datetime import datetime
#con = lite.connect('zthb.sqlite')
# with con:
# cur = con.cursor()
#
# cur.execute("UPDATE user_comment SET u_comment=? WHERE u_comment=?", ("__DOLLFACE__","OMG"))
# con.commit()
#
# print "Number of rows updated: %d" % cur.rowcount
# w... | astName = 'COMPUTE | R'
userMessage = 'THE MSG'
cn = lite.connect("zthb.sqlite")
cur = cn.cursor()
cur.execute("SELECT * FROM cookie_giver WHERE u_id={0}".format(userId))
cn.execute("PRAGMA ENCODING = 'utf8';")
#cur.row_factory = lite.Row
cn.text_factory = str
row = cur.fetchone()
if row != None:
... |
Fresnoy/kart | common/migrations/0001_initial.py | Python | agpl-3.0 | 1,169 | 0.002566 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='BTBeacon',
fields=[
('id', models.AutoField(ver... | uto_created=True, primary_key=True)),
('label', models.CharField(max_length=255)),
('uuid', models.UUIDField(unique=True, max_length=32)),
('rssi_in', models.IntegerField()),
('rssi_out', models.IntegerField()),
],
),
migrations... | e, auto_created=True, primary_key=True)),
('title_fr', models.CharField(max_length=255)),
('title_en', models.CharField(max_length=255)),
('language', models.CharField(max_length=2, choices=[(b'FR', b'French'), (b'EN', b'English')])),
('url', models.URLFie... |
pferreir/indico-backup | indico/MaKaC/webinterface/common/slotDataWrapper.py | Python | gpl-3.0 | 9,205 | 0.023031 | # -*- coding: utf-8 -*-
##
##
## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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; eith... | conv_family_name":data["conv_family_name"][i],
"conv_affiliation":data["conv_affiliation"][i],
"conv_email":data["conv_email"][i] }
id=len(self._conveners)
self._conveners.append(Convener(id,val))
def mapSlot(self, slot):
self._id=slot.getId()... | self._title=slot.getTitle()
self._locationName=""
self._locationAddress=""
location = slot.getOwnLocation()
if location is not None:
self._locationName=location.getName()
self._locationAddress=location.getAddress()
self._roomName=""
room = sl... |
hasgeek/hasjob | migrations/versions/470c8feb73cc_jobapplication_repli.py | Python | agpl-3.0 | 469 | 0.006397 | """JobApplication.replied_by
Revision ID: 470c8feb73cc
Revises: 449914911f93
Create Date: 2013-12-14 22 | :32:49.982184
"""
# revision identifiers, used by Alembic.
revision = '470c8feb73cc'
down_revision = '449914911f93'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
'job_application', sa.Column('replied_by_ | id', sa.Integer(), nullable=True)
)
def downgrade():
op.drop_column('job_application', 'replied_by_id')
|
houqp/iris-api | src/iris/applications/dummy_app.py | Python | bsd-2-clause | 143 | 0 | class dummy_app(object): |
name = 'dummy app'
def __i | nit__(self, vendor):
vendor.time_taken = 2
self.send = vendor.send
|
test-organization-tmp/test-repo | examples/pipelines/multiple_subjects.py | Python | bsd-3-clause | 4,182 | 0 | """
===============================
Multiple subjects pipeline demo
===============================
A basic multiple subjects pipeline. CBF maps are normalized to
the reference MNI template.
"""
import matplotlib.pylab as plt
import nipype.interfaces.spm as | spm
from nipype.caching import Memory
from nilearn import plotting
from procasl import preprocessing, quantification, datasets, _utils
# Load the dataset
heroes = datasets.load_heroes_dataset(
subjects_parent_directory='/tmp/procasl_data/heroes',
dataset_pattern={'anat': 't1mri/acquisition1/anat*.nii',
... | /acquisition1/basal_rawASL*.nii'})
# Create a memory context
mem = Memory('/tmp')
# Loop over subjects
for (func_file, anat_file) in zip(
heroes['basal ASL'], heroes['anat']):
# Get Tag/Control sequence
get_tag_ctl = mem.cache(preprocessing.GetTagControl)
out_get_tag_ctl = get_tag_ctl(in_file=func... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/contrib/auth/hashers.py | Python | bsd-3-clause | 14,277 | 0.00007 | import hashlib
from django.conf import settings
from django.utils import importlib
from django.utils.datastructures import SortedDict
from django.utils.encoding import smart_str
from django.core.exceptions import ImproperlyConfigured
from django.utils.crypto import (
pbkdf2, constant_time_compare, get_random_strin... | """
raise NotImplementedError()
class PBKDF2PasswordHasher(BasePasswordHasher):
"""
Secure password hashing using the PBKDF2 algorithm (recommended)
Configured to use PBKDF2 + HMAC + SHA256 with 10000 iterations.
The result is a 64 byte binary string. Iterations may be changed
safel... | terations = 10000
digest = hashlib.sha256
def encode(self, password, salt, iterations=None):
assert password
assert salt and '$' not in salt
if not iterations:
iterations = self.iterations
hash = pbkdf2(password, salt, iterations, digest=self.digest)
hash = h... |
mldbai/mldb | testing/MLDB-963-when-in-WHEN.py | Python | apache-2.0 | 4,955 | 0.001615 | #
# MLDB-963-when-in-WHEN.py
# mldb.ai inc, 2015
# This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved.
#
import unittest
import datetime
from mldb import mldb
now = datetime.datetime.now() - datetime.timedelta(seconds=1)
class WhenInWhen(unittest.TestCase):
@classmethod
def setUpClas... | " % now))
if __name__ == '__main__':
mldb.run_t | ests()
|
dahool/vertaal | appfeeds/feeds.py | Python | gpl-3.0 | 6,268 | 0.00702 | from django.contrib.syndication.feeds import Feed
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import U... | n POFileLog.objects.last_actions(user=self.user, release=rele | ase, limit=self.total_feeds, language=self.language)
def item_pubdate(self, item):
return item.created
def item_link(self, item):
link = '%s?%s#%s' % (reverse('list_files', kwargs={ 'release': item.pofile.release.slug,
'language': item.pofile.langua... |
tanderegg/ansible-modules-core | network/cumulus/cl_bridge.py | Python | gpl-3.0 | 13,081 | 0.000382 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, Cumulus Networks <[email protected]>
#
# This file is part of Ansible
# Ansible 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... | nables spanning tree. As of Cumulus Linux 2.5 the default
bridging mode, only per vlan RSTP or 802.1d is supported. For the
| vlan aware mode, only common instance STP is supported
default: 'yes'
ports:
description:
- list of bridge members
required: True
vlan_aware:
description:
- enables vlan aware mode.
mstpctl_treeprio:
description:
- set spannin... |
jeditekunum/Cosa | build/miniterm.py | Python | lgpl-2.1 | 23,810 | 0.012264 | #!/usr/bin/env python
# Very simple serial terminal
# (C)2002-2009 Chris Liechti <[email protected]>
# Input characters are sent directly (only LF -> CR/LF/CRLF translation is
# done), received characters are displayed as is (or escaped trough pythons
# repr, useful for debug purposes).
import sys, os, serial, thread... | \n" % (
self.serial.portstr,
self.serial.baudrate,
self.serial.bytesize,
self.serial.parity,
self.serial.stopbits,
))
sys.stderr.write('--- RTS %s\n' % (self.rts_state and 'active' or 'inactive'))
sys.stderr.write('--- DTR %s\n' % (self... | '))
sys.stderr.write('--- software flow control %s\n' % (self.serial.xonxoff and 'active' or 'inactive'))
sys.stderr.write('--- hardware flow control %s\n' % (self.serial.rtscts and 'active' or 'inactive'))
sys.stderr.write('--- data escaping: %s\n' % (REPR_MODES[self.repr_mode],))
sys.s... |
Julian/txjsonrpc-tcp | txjsonrpc/tests/test_jsonrpc.py | Python | mit | 8,101 | 0.009258 | from __future__ import absolute_import
import json
from twisted.internet import defer, error
from twisted.python import failure
from twisted.test import proto_helpers
from twisted.trial import unittest
from txjsonrpc import jsonrpc, jsonrpclib
class TestJSONRPC(unittest.TestCase):
def setUp(self):
self.... | id" : None, "error | " : err.toResponse()})
errors = self.flushLoggedErrors(jsonrpclib.InvalidRequest)
self.assertEqual(len(errors), 1)
def test_unsolicited_result(self):
"""
An incoming result for an id that does not exist raises an error.
"""
receive = {"jsonrpc" : "2.0", "id" : "1... |
AzamYahya/shogun | examples/undocumented/python_modular/features_dense_longint_modular.py | Python | gpl-3.0 | 606 | 0.062706 | #!/usr/bin/env p | ython
from modshogun import LongIntFeatures
from numpy import array, int64, all
# create dense matrix A
matrix=array([[1,2,3] | ,[4,0,0],[0,0,0],[0,5,0],[0,0,6],[9,9,9]], dtype=int64)
parameter_list = [[matrix]]
# ... of type LongInt
def features_dense_longint_modular (A=matrix):
a=LongIntFeatures(A)
# get first feature vector and set it
a.set_feature_vector(array([1,4,0,0,0,9], dtype=int64), 0)
# get matrix
a_out = a.get_feature_matri... |
cypsun/FreeCAD | src/Mod/Fem/ccxInpWriter.py | Python | lgpl-2.1 | 18,324 | 0.00382 | import FemGui
import FreeCAD
import os
import time
import sys
class inp_writer:
def __init__(self, analysis_obj, mesh_obj, mat_obj, fixed_obj, force_obj, pressure_obj, dir_name=None):
self.dir_name = dir_name
s | elf.mesh_object = mesh_obj
self.material_objects = mat_obj
self.fixed_objects = fixed_obj
self.force_objects = force_obj
self.pressure_objects = pressure_obj
if not dir_name:
self.dir_name = FreeCAD.ActiveDocument.TransientDir.replace('\\', '/') + '/FemAnl_' + analysi... | se_name = self.dir_name + '/' + self.mesh_object.Name
self.file_name = self.base_name + '.inp'
def write_calculix_input_file(self):
self.mesh_object.FemMesh.writeABAQUS(self.file_name)
# reopen file with "append" and add the analysis definition
inpfile = open(self.file_name, 'a')
... |
evazyin/Capstoneproject | stemcorpus.py | Python | agpl-3.0 | 1,104 | 0.021739 | #version1 4/14/2014 for data lemma
import codecs
import sys
sys.path.append("D:/uw course/capstone/nltk-3.0a3/")#necessary??
from nltk.stem.lancaster import LancasterStemmer
st=LancasterStemmer()
from nltk import word_tokenize
#file = codecs.open('D:/uw course/capstone/mypersonality/status_b.csv',errors='ignore')
file... | Downloads/fb_status_a.csv',errors='ignore')
file1 = open('D:/uw course/capstone/mypersonality/status_a_stem.txt','w')
while 1:
line = file.readline()
if not line:
break
lineStr = str( line, encoding='latin-1' )
lineStr = lineStr.lower()
#for my personality data only
linelist = l... | is also split
#print(lineStr1)
tokens = word_tokenize(lineStr1)
lineStr2 = ' '.join(st.stem(w) for w in tokens) #similar for stem usage
#print(lineStr2)
#print(lineStr.find('is very'))
file1.write(str(lineStr2.encode('latin-1')))
file1.write('\n')
del line
del lineStr
del lineSt... |
cnu/sorkandu | sorkandu/manage.py | Python | apache-2.0 | 251 | 0 | #!/usr/bin/env p | ython
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sorkandu.settings")
from django.core.management import | execute_from_command_line
execute_from_command_line(sys.argv)
|
TieWei/nova | nova/tests/virt/hyperv/test_vhdutils.py | Python | apache-2.0 | 3,634 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Cloudbase Solutions Srl
#
# 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/LICE... | ed_vhd_size = 1 * 1024 ** 3 - 512
self.assertEqual(expected_vhd_size, real_size)
def test_get_internal_vhd_size_by_file_s | ize_dynamic(self):
vhdutil = vhdutils.VHDUtils()
root_vhd_size = 20 * 1024 ** 3
vhdutil.get_vhd_info = mock.MagicMock()
vhdutil.get_vhd_info.return_value = {'Type':
constants.VHD_TYPE_DYNAMIC}
vhdutil._get_vhd_dynamic_blk_size = mock.M... |
justinslee/Wai-Not-Makahiki | makahiki/apps/widgets/group_prizes/views.py | Python | mit | 632 | 0.011076 | """Prepares the views for point scoreboard widget."""
import datetime
from ap | ps.managers.score_mgr import score_mgr
from apps.managers.challenge_mgr import challenge_mgr
from apps.managers.resource_mgr import resource_mgr
from apps.widgets.resource_goal import resource_goal
from apps.managers.team_mgr.models import Team, Group
def supply(request, page_name):
"""Supply view_objects contents... | content."""
_ = request
group_winner = score_mgr.group_points_leader()
return {
'group_winner':group_winner}
#view_objects
|
hinshun/smile | please/utils.py | Python | mit | 849 | 0.011779 | from conf import paths
import scipy.io
import numpy as np
def load_train():
""" Loads all training data. | """
tr_set = scipy.io.loadmat(file_name = paths.TR_SET)
tr_identity = tr_set['tr_identity']
tr_labels = tr_set['tr_labels']
tr_images = tr_set['tr_images']
return tr_identity, tr_labels, tr_images
def load_unlabeled():
""" Loads all unlabeled data."""
unlabeled_set = scipy.io.loadmat(file_... | unlabeled_images
def load_test():
""" Loads training data. """
test_set = scipy.io.loadmat(file_name = paths.TEST_SET)
test_images = test_set['public_test_images']
# hidden_set = scipy.io.loadmat(file_name = paths.HIDDEN_SET)
# hidden_images = hidden_set['hidden_test_images']
return test_ima... |
z-uo/pixeditor | dock_timeline.py | Python | gpl-3.0 | 24,676 | 0.005025 | #!/usr/bin/env python3
#-*- coding: utf-8 -*-
from PyQt4 import QtGui
from PyQt4 import QtCore
from dialogs import RenameLayerDialog
from widget import Button, Viewer
class LayersCanvas(QtGui.QWidget):
""" Widget containing the canvas list """
def __init__(self, parent):
QtGui.QWidget.__init__(self... | echFrame = False
self.setMinimumSize(self.getMiniSize()[0], self.getMiniSize()[1])
|
def paintEvent(self, ev=''):
fW, fH = self.frameWidth, self.frameHeight
mX, mY = self.margeX, self.margeY
p = QtGui.QPainter(self)
fontLight = QtGui.QFont('SansSerif', 7, QtGui.QFont.Light)
fontBold = QtGui.QFont('SansSerif', 8, QtGui.QFont.Normal)
p.setBrush(self.wh... |
usakhelo/FreeCAD | src/Mod/Fem/PyGui/_CommandFemMaterialMechanicalNonlinear.py | Python | lgpl-2.1 | 4,731 | 0.002959 | # ***************************************************************************
# * *
# * Copyright (c) 2016 - Bernd Hahnebach <[email protected]> *
# * *
# * Th... | hasattr(o, "Proxy") and o.Proxy is not None and o.Proxy.Type == "FemMaterialMechanicalNonlinear" and o.LinearBaseMaterial == lin_mat_obj:
FreeCAD.Console.PrintError(o.Name + ' is based on the selected | material: ' + lin_mat_obj.Name + '. Only one nonlinear object for each material allowed.\n')
allow_nonlinear_material = False
break
if allow_nonlinear_material:
string_lin_mat_obj = "App.ActiveDocument.getObject('" + lin_mat_obj.Name + "')"
... |
shucommon/little-routine | python/python-crash-course/matplot/surface3d.py | Python | gpl-3.0 | 842 | 0 | # This import registers the 3D projection | , but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = | fig.gca(projection='3d')
# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
# Customize the z axis.
ax.set_zlim(... |
tzpBingo/github-trending | codespace/python/tmp/example19.py | Python | mit | 2,905 | 0.001334 | """
扩展性系统性能
- 垂直扩展 - 增加单节点处理能力
- 水平扩展 - 将单节点变成多节点(读写分离/分布式集群)
并发编程 - 加速程序执行 / 改善用户体验
耗时间的任务都尽可能独立的执行,不要阻塞代码的其他部分
- 多线程
1. 创建Thread对象指定target和args属性并通过start方法启动线程
2. 继承Thread类并重写run方法来定义线程执行的任务
3. 创建线程池对象ThreadPoolExecutor并通过submit来提交要执行的任务
第3种方式可以通过Future对象的result方法在将来获得线程的执行结果
也可以通过done方法判定线程是否执行结束
- 多进程
- 异步I/O
"""
i... | for t in threads:
# t.join()
# end = time.time()
# print(f'耗时: {end - start}秒')
def main():
pool = ThreadPoolExecutor(max_workers=30)
futures = []
start = time.ti | me()
for infile in glob.glob('images/*'):
# submit方法是非阻塞式的方法
# 即便工作线程数已经用完,submit方法也会接受提交的任务
future = pool.submit(gen_thumbnail, infile)
futures.append(future)
for future in futures:
# result方法是一个阻塞式的方法 如果线程还没有结束
# 暂时取不到线程的执行结果 代码就会在此处阻塞
future.result()
... |
kumarrus/voltdb | lib/python/voltcli/voltdb.d/rejoin.py | Python | agpl-3.0 | 1,838 | 0.002176 | # This file is part of VoltDB.
# Copyright (C) 2008-2015 VoltDB Inc.
#
# This file contains original code and/or modifications of original code.
# Any modifications made by VoltDB Inc. are licensed under the following
# terms and conditions:
#
# Permission is hereby granted, free of charge, to any person obtaining
# a... | L THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
@VOLT.Command(
bundles = VOLT.ServerBundle('rejoin',
ne... | fault_host=False,
safemode_available=False,
supports_daemon=True,
supports_multiple_daemons=True,
check_environment_config=True),
description = 'Rejoin the current node to a VoltDB cluster... |
anhstudios/swganh | data/scripts/templates/object/draft_schematic/clothing/shared_clothing_boots_casual_12.py | Python | mit | 462 | 0.047619 | #### NOTICE: THIS F | ILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Intangible()
result | .template = "object/draft_schematic/clothing/shared_clothing_boots_casual_12.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
kubernetes-client/python | kubernetes/client/models/v1beta1_flow_schema_spec.py | Python | apache-2.0 | 8,042 | 0.000124 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import si... | configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._distinguisher_method = None
self._matching_precedence = None
self._priority_level_configuration = None
self._rules = None
self.discriminator = None
if distinguisher_me... | od is not None:
self.distinguisher_method = distinguisher_method
if matching_precedence is not None:
self.matching_precedence = matching_precedence
self.priority_level_configuration = priority_level_configuration
if rules is not None:
self.rules = rules
@... |
shaggytwodope/rtv | rtv/submission_page.py | Python | mit | 11,574 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
import curses
from . import docs
from .content import SubmissionContent, SubredditContent
from .page import Page, PageController, logged_in
from .objects import Navigator, Color, Command
from .exceptions import TemporaryFileError
class Subm... | ager(self):
"Open the selected item with the system's pager"
data = self.get_selected_item()
if data['type'] == 'Submission':
text = '\n\n'.join((data['permalink'], da | ta['text']))
self.term.open_pager(text)
elif data['type'] == 'Comment':
text = '\n\n'.join((data['permalink'], data['body']))
self.term.open_pager(text)
else:
self.term.flash()
@SubmissionController.register(Command('SUBMISSION_POST'))
@logged_in
... |
formencode/formencode | src/formencode/htmlfill_schemabuilder.py | Python | mit | 3,632 | 0.000275 | """
Extension to ``htmlfill`` that can parse out schema-defining
statements.
You can either pass ``SchemaBuilder`` to ``htmlfill.render`` (the
``listen`` argument), or call ``parse_schema`` to just parse out a
``Schema`` object.
"""
from __future__ import absolute_import
from . import validators
from . import schema
... | name:
# @@: should warn if you try to validate unnamed fields
return
v = compound.All(validators.Identity())
add_to_end = None
# for checkboxes, we must set if_missing = False
if tag.lower() == "input":
type_attr = get_attr(attrs, "type").lower().stri... | elif type_attr == "checkbox":
v.validators.append(validators.Wrapper(to_python=force_list))
elif type_attr == "file":
add_to_end = validators.FieldStorageUploadConverter()
message = get_attr(attrs, 'form:message')
required = to_bool(get_attr(attrs, 'f... |
jawilson/home-assistant | homeassistant/components/ezviz/camera.py | Python | apache-2.0 | 11,868 | 0.000927 | """Support ezviz camera devices."""
from __future__ import annotations
import logging
from pyezviz.exceptions import HTTPError, InvalidHost, PyEzvizError
import voluptuous as vol
from homeassistant.components import ffmpeg
from homeassistant.components.camera import PLATFORM_SCHEMA, SUPPORT_STREAM, Camera
from homea... | importing camera account.
if CONF_CAMERAS in config:
cameras_conf = config[CONF_CAMERAS]
for serial, camera in cameras | _conf.items():
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
ATTR_SERIAL: serial,
CONF_USERNAME: camera[CONF_USERNAME],... |
mmerce/python | bigml/tests/create_script_steps.py | Python | apache-2.0 | 3,531 | 0.002266 | # -*- coding: utf-8 -*-
#
# Copyright 2015-2020 BigML
#
# 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... | import HTTP_ACCEPTED
from bigml.api import FINISHED
from bigml.api import FAULTY
from bigml.api import get_status
from bigml.util import is_url
|
from .read_script_steps import i_get_the_script
#@step(r'the script code is "(.*)" and the value of "(.*)" is "(.*)"')
def the_script_code_and_attributes(step, source_code, param, param_value):
res_param_value = world.script[param]
eq_(res_param_value, param_value,
("The script %s is %s and the expec... |
lukas-hetzenecker/home-assistant | tests/components/zwave_js/test_siren.py | Python | apache-2.0 | 6,133 | 0 | """Test the Z-Wave JS siren platform."""
from zwave_js_server.event import Event
from homeassistant.components.siren import ATTR_TONE, ATTR_VOLUME_LEVEL
from homeassistant.components.siren.const import ATTR_AVAILABLE_TONES
from homeassistant.const import STATE_OFF, STATE_ON
SIREN_ENTITY = "siren.indoor_siren_6_2"
TO... | d.call_args[0][0]
assert args["command"] == "node.set_value"
assert args["nodeId"] == node.node_id
assert args["valueId"] == TONE_ID_VALUE_ID
assert args["value | "] == 1
assert args["options"] == {"volume": 50}
client.async_send_command.reset_mock()
# Test turn on with specific tone ID and volume level
await hass.services.async_call(
"siren",
"turn_on",
{
"entity_id": SIREN_ENTITY,
ATTR_TONE: 1,
ATTR_... |
smartczm/python-learn | Old-day01-10/s13-day5/get/day5/Atm/src/admin.py | Python | gpl-2.0 | 2,982 | 0.002172 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import os
import json
from lib import commons
from config import settings
CURRENT_USER_INFO = {'is_authenticated': False, 'current_user': None}
def init():
"""
初始化管理员信息
:return:
"""
dic = {'username': 'admin', 'password': commons.md5('123')}
json.... | n(os.path.joi | n(settings.ADMIN_DIR_FOLDER, username), 'r'))
if username == user_dict['username'] and commons.md5(password) == user_dict['password']:
CURRENT_USER_INFO['is_authenticated'] = True
CURRENT_USER_INFO['current_user'] = username
return True
else:
... |
cloew/KaoJson | kao_json/conversion_context.py | Python | mit | 559 | 0.008945 | from | .providers import ProviderContext
from kao_decorators import proxy_for
@proxy_for('config', ['newConverter'])
class ConversionContext:
""" Represents the Configuration and Keyword Arguments provided to a Converter """
def __init__(self, config, **kwargs):
""" Initialize with the config and... | Return a Provider Context """
return ProviderContext(name, obj, self.kwargs) |
clusterpy/clusterpy | clusterpy/core/data/createVariable.py | Python | bsd-3-clause | 2,144 | 0.007933 | # encoding: latin1
"""createVariable
"""
__author__ = "Juan C. Duque, Alejandro Betancourt, Juan Sebastian Marín"
__credits__ = "Copyright (c) 2010-11 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "[email protected]"
__all__ = ['fieldOperation']
im... | ion defined by the user, written like a py | thon operation
:type function: string
:rtype: list (Y dictionary with the results)
"""
variables = []
positions = []
auxiliar1 = []
count = 0
results = []
newfunc = ''
for i in fieldnames[0:]:
if re.search(i,function):
if not (function[function.index(i) - 2:... |
RedHatQE/python-moncov | moncov/monkey.py | Python | gpl-3.0 | 2,050 | 0.003902 | '''monkey patch hacks'''
import conf
import os
def _iter_filename_over_mountpoints(self, filename):
'''iterate absolute filename over self.mountpoints and self.root'''
for mountpoint in self.mountpoints + [self.root]:
_drivename, _filename = os.path.splitdrive(filename)
_filename = _filename.ls... | ov.data.arc2tuple(arc))
data['lines'][filename].append(moncov.data.arc2line(arc))
# duplicate with various mountpoints
try:
for mount_filename in self.iter_filename_over_mountpoints(filename):
data['arcs'][mount_filename] = data['a | rcs'][filename]
data['lines'][mount_filename] = data['lines'][filename]
except Exception as e:
import sys
print sys.exc_info()
self._moncov_data_cache = data
return self._moncov_data_cache
CoverageData.raw_data = raw_data
|
juanfont/hls-proxy | m3u8.py | Python | gpl-2.0 | 7,177 | 0.004319 | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Copyright (C) 2009-2010 Fluendo, S.L. (www.fluendo.com).
# Copyright (C) 2009-2010 Marc-Andre Lureau <[email protected]>
# Copyright (C) 2014 Juan Font Alonso <[email protected]>
# This file may be distributed and/or modified under the terms of
# th... | print "stream info: " + str(d)
d['uri'] = self._lines.next()
self._add_playlist(d)
elif l.startswith('#EXT-X-TARGETDURATION'):
self.target_duration = int(l[22:])
elif l.startswith('#EXT-X-MEDIA-SEQUENCE'):
self.media... | UITY'):
discontinuity = True
elif l.startswith('#EXT-X-PROGRAM-DATE-TIME'):
print l
elif l.startswith('#EXT-X-ALLOW-CACHE'):
allow_cache = l[19:]
elif l.startswith('#EXT-X-KEY'):
self._encryption_method = l.split(',')[0]... |
YaoQ/zigbee-on-pcduino | zigbee.py | Python | mit | 8,403 | 0.041652 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
import urllib
import urllib2
import json
import serial
import time
import gpio
import re
import binascii
import threading
import datetime
import sys
# use your deviceID and apikey
deviceID="xxxxxxxxxx"
apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
key_pin = "gpio12"
s = ""
doo... | zone_type == "28 00":
Smoke_mac = short
f=open('smoke.txt','w')
f.write(short)
f.close()
report()
elif zone_type == "11 00":
Remote_mac = short
f=open('remote.txt','w')
f.write(short)
f.close()
report()
# Check the a... | on from zigbee sensor node
data=alarm()
if data != -1:
short_mac = data[0:5]
print"short mac:"+short_mac
status = data[5]
p |
jbadigital/django-openid-auth | django_openid_auth/models.py | Python | bsd-2-clause | 2,456 | 0 | # django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2007 Simon Willison
# Copyright (C) 2008-2013 Canonical Ltd.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions o... | models.TextField(max_length=2047)
handle = models.CharField(max_length=255)
secr | et = models.TextField(max_length=255) # Stored base64 encoded
issued = models.IntegerField()
lifetime = models.IntegerField()
assoc_type = models.TextField(max_length=64)
def __unicode__(self):
return u"Association: %s, %s" % (self.server_url, self.handle)
class UserOpenID(models.Model):
... |
alexander-95/client_python | tests/test_client.py | Python | apache-2.0 | 22,394 | 0.004599 | from __future__ import unicode_literals
import os
import threading
import time
import unittest
from prometheus_client import Gauge, Counter, Summary, Histogram, Metric
from prometheus_client import CollectorRegistry, generate_latest, ProcessCollector
from prometheus_client import push_to_gateway, pushadd_to_gateway, ... | ple_value('g'))
with self.gauge.time():
time.sleep(.001)
self.assertNotEqual(0, self.registry.get_sample_value('g'))
class TestSummary(unittest.TestCase):
def setUp(self):
self.registry = CollectorRegistry()
self.summary = Summary('s', 'help', registry=sel | f.registry)
def test_summary(self):
self.assertEqual(0, self.registry.get_sample_value('s_count'))
self.assertEqual(0, self.registry.get_sample_value('s_sum'))
self.summary.observe(10)
self.assertEqual(1, self.registry.get_sample_value('s_count'))
self.assertEqual(10, self.r... |
kamiseko/factor-test | idiVol IN.py | Python | mit | 17,571 | 0.005826 | #!/Tsan/bin/python
# -*- coding: utf-8 -*-
# Libraries To Use
from __future__ import division
from CloudQuant import MiniSimulator
import numpy as np
import pandas as pd
import pdb
import cvxopt as cv
from cvxopt import solvers
from datetime import datetime, date, time
import barraRiskModel as brm
impor... | = list(inputArray[i:m+i])
newMatrix.append(newdata)
#newMatrix = np.array(newMatrix).reshape(n,m)
return np.array(newMatrix)
def recreateArray(newMatrix,t,m):
ret = []
n = t - m + 1
for p in range(1, t+1):
if p < m:
alpha = p
elif p > t-m+1:
... | i = p - j + 1
if i > 0 and i < n+1:
sigma += newMatrix[i-1][j-1]
ret.append(sigma/alpha)
return np.array(ret)
def getSVD(inputArray,t,m):
inputmatrix = getNewMatrix(inputArray, t, m)
u, s, v = np.linalg.svd(inputmatrix)
eviNum = 1 if s[0]/s.sum() > 0.9... |
GreatLakesEnergy/sesh-dash-beta | seshdash/api/enphase.py | Python | mit | 6,147 | 0.020823 | import requests, json, logging
from lxml import html
from datetime import datetime
logger = logging.getLogger(__name__)
class EnphaseAPI:
API_BASE_URL = "https://api.enphaseenergy.com/api/v2/systems/{system_id}/{function}?key={key}&user_id={user_id}"
API_BASE_URL_INDEX = "https://api.enphaseenergy.com/api/v2/... | if self.IS_INITIALIZED:
print "system initialized"
logger.info("System Initialized with %s systems"%len(self.SYSTEMS_IDS))
else:
logger.error("unable to initialize the api")
"""
Initialization functio | n This will talk to enphase and get aall system ids
"""
def _initialize(self):
formatedURL = self.API_BASE_URL_INDEX.format(
key = self.KEY,
user_id = self.USER_ID,
)
response = requests.get(formatedURL)
#check that everything is go... |
PiJoules/translation | __init__.py | Python | apache-2.0 | 847 | 0.022432 | # Call vendor to add the dependencies to the classpath
import vendor
vend | or.add('lib')
# Import the Flask Framework
from flask import Flask, render_template, url_for, request, jsonify
app = | Flask(__name__)
import translate
# Root directory
@app.route('/')
def index_route():
phrase = request.args.get("q")
if not phrase:
return render_template("index.html", phrase="")
return render_template("index.html", phrase=phrase)
@app.route("/translate")
def translate_route():
phrase = request.args.get("te... |
jss367/assemble | congress/congress/spiders/example.py | Python | mit | 1,924 | 0.002079 | import scrapy
from congress.items import Article
class Example(scrapy.Spider):
'''Modeled after scrapy tutorial here:
https://doc.scrapy.org/en/latest/intro/tutorial.html
'''
# spider name should be name of website/source
name = 'example'
def start_requests(self):
# list of URLs or ... | have used
# @class="author" as well. This will return any small tag with class
# that contains the w | ord "author"
author = quote.xpath('.//small[contains(@class, "author")]').extract_first()
# now we create our article item for a list of available fields see items.py
article = Article(
# Required fields
language=language,
... |
Simon-Hohberg/Pi-Radio | radiocontrol/manage.py | Python | mit | 255 | 0 | #!/usr/bin/env python
import os
import sys
if | __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_ | MODULE", "radiocontrol.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
starcruiseromega/insolent-meow | import_resolver/test_import_resolver.py | Python | gpl-2.0 | 6,124 | 0.023607 | # coding=utf-8
from __future__ import print_function, unicode_literals
__author__ = "Sally Wilsak"
import codecs
import os
import sys
import textwrap
import unittest
import import_resolver
# This isn't strictly correct; it will only work properly if your terminal is set to UTF-8.
# However, Linux is ... |
"/home/badger/a.ts <- /home/badger/d.ts",
"/home/badger/b.ts <- /home/badger/a.ts",
])
self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string)
def test_triangle_deps(self):
triangle_deps = {
"/home/badger/a.ts": "import b = require('./b.ts');\nimport ... | gle_deps[x]
expected_string = "\n".join([
"/home/badger/c.ts <- /home/badger/a.ts /home/badger/b.ts",
"/home/badger/a.ts <- ",
"/home/badger/b.ts <- /home/badger/a.ts",
])
self.assertEqual(import_resolver.do_dependency_resolve(["/home/badger/a.ts"]), expected_string)
def test_inaccessible_deps(... |
photo/export-flickr | fetch.py | Python | apache-2.0 | 5,401 | 0.018885 | #!/usr/bin/env python
import datetime
# import os for file system functions
import os
# import json
import json
# import regex
import re
# for date parsing
import time
# import flickrapi
# `easy_install flickrapi` or `pip install flickrapi`
import flickrapi
# main program
def fetch(api_key, api_secret):
# create a... | = raw_input()
per_page = 100
(token, frob) = flickr.get_token_part_one('read')
flickr.get_token_part_two((token, frob))
# we'll paginate through the results
# start at `page` and get `per_page` results at a time
page=1
# store everything in a list or array or whatever python calls this
photos_out=[]... |
print "Fetching page %d..." % page,
photos_resp = flickr.people_getPhotos(user_id=user_id, per_page=per_page, page=page, extras='original_format,tags,geo,url_o,url_b,url_c,url_z,date_upload,date_taken,license,description')
print "OK"
# increment the page number before we forget so we don't endlessly l... |
tersmitten/ansible | lib/ansible/modules/remote_management/foreman/_katello.py | Python | gpl-3.0 | 20,771 | 0.002503 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Eric D Helms <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version... | required: true
entity:
description:
- The Foreman resource that the action will be performed on (e.g. organization, host).
choices:
- repository
- manifest
- repository_set
- sync_plan
- content_view
- lifecycle_e... | description:
- action associated to the entity resource to set or edit in dictionary format.
- Possible Action in relation to Entitys.
- "sync (available when entity=product or entity=repository)"
- "publish (available when entity=content_view)"
- "promote ... |
MauHernandez/cyclope | cyclope/core/series/admin.py | Python | gpl-3.0 | 2,378 | 0.003786 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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 Foundat... | neric.GenericStackedInline):
model = SeriesContent
form = SeriesContentForm
ct_field = 'self_type'
ct_fk_field = 'self_id'
extr | a = 0
return [SeriesContentInline]
class SeriesAdmin(CollectibleAdmin, BaseContentAdmin):
inlines = series_inline_factory(Series) + CollectibleAdmin.inlines + BaseContentAdmin.inlines
list_display = ('name', 'creation_date') + CollectibleAdmin.list_display
search_fields = ('name', 'description', ... |
prechelt/typecheck-decorator | typecheck/test_typecheck_basics.py | Python | bsd-2-clause | 25,312 | 0.005768 | # Most of this file is from the lower part of Dmitry Dvoinikov's
# http://www.targeted.org/python/recipes/typecheck3000.py
# reworked into py.test tests
import random
import re
import time
from traceback import extract_stack
import typecheck as tc
import typecheck.framework
from .testhelper import expected
#########... | ert exc_type is not None, \
"expected {0:s} to have been thrown".format(self._type.__name__)
msg = str(exc_value)
return (issubclass(exc_type, self._type) and
(se | lf._msg is None or
msg.startswith(self._msg) or # for instance
re.match(self._msg, msg))) # for class + regexp
############################################################################
def test_wrapped_function_keeps_its_name():
@tc.typecheck
def foo() -> type(None):
... |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.10/Lib/json/tests/test_tool.py | Python | apache-2.0 | 2,037 | 0.000982 | import os
import sys
import textwrap
import unittest
im | port subprocess
from test import test_support
from test.script_helper import assert_python_ok
class TestTool(unittest.TestCase):
data = """
[["blorpie"],[ "whoops" ] , [
],\t"d-shtaeou",\r"d-nthiouh",
"i-vhbjkhnth", {"nifty":87}, {"morefield" :\tfalse,"fie... | rpie"
],
[
"whoops"
],
[],
"d-shtaeou",
"d-nthiouh",
"i-vhbjkhnth",
{
"nifty": 87
},
{
"field": "yes",
"morefield": false
}
]
""")
def test_stdin_stdout... |
patrickshuff/artofmemory | tests/test_major.py | Python | mit | 489 | 0 | """Ensure testing of | the Major System does what we expect"""
from artofmemory.major import NaiveMajorSystem, PhonemesMajorSystem
def test_office():
# office shouldn't be "887" but rather actually "80"!
naive_value = "887"
correct_value = "80"
assert NaiveMajorSystem().word_to_major("office") == naive_value
assert Ph... | burn => 942, Nope, it is 92
|
dimagi/commcare-hq | corehq/ex-submodules/pillow_retry/migrations/0002_pillowerror_queued.py | Python | bsd-3-clause | 372 | 0 | from django.db import models, migrations
class Migration(migrations.Migration):
|
dependencies = [
('pillow_retry', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='pillowerror',
name='queued',
field=models.BooleanField(default=False),
preserve_defa | ult=True,
),
]
|
jmesteve/saas3 | openerp/addons/crm/wizard/crm_merge_opportunities.py | Python | agpl-3.0 | 4,577 | 0.00284 | ##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public L... | version 3 of the
# License, or (at your option) any later version.
#
# T | his 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
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General ... |
acabey/acabey.github.io | projects/demos/engineering.purdue.edu/scriptingwithobjects/swocode/chap7/Static4.py | Python | gpl-3.0 | 1,295 | 0.027027 | #!/usr/bin/python
### Static3.py
#------------------------- class Callable ----------------------------
class Callable: #(A)
def __init__( self, anycallable ): #(B)
self.__call__ = anycallable ... | ------
class X: #(D)
def __init__( self, nn ): #(E)
self.n = nn
def getn( self ): | #(F)
return self.n #(G)
def foo(): #(H)
print "foo called" #(I)
foo = Callable( foo ) #(J)
#--------... |
lhupfeldt/multiconf | test/utils_test.py | Python | bsd-3-clause | 753 | 0 | # Copyright (c) 2012 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from multiconf import caller_file_line
from .utils.utils import next_line_num
from .utils_test_help | ers import bb, fn_aa_exp, ln_aa_exp
ln_bb_exp = None
def test_caller_file_line():
def cc():
global ln_bb_exp
fnc, lnc = caller_file_line(2)
print("fnc, l | nc:", fnc, lnc)
ln_bb_exp = next_line_num()
fnb, lnb, fna, lna = bb()
return fnc, lnc, fnb, lnb, fna, lna
fn_exp = __file__
ln_cc_exp = next_line_num()
fnc, lnc, fnb, lnb, fna, lna = cc()
assert fn_exp == fnc
assert ln_cc_exp == lnc
assert fn_exp == fnb
assert ln... |
lexibrent/certificate-transparency | python/ct/client/log_client.py | Python | apache-2.0 | 22,405 | 0.000714 | """RFC 6962 client API."""
import base64
import json
from ct.crypto import verify
from ct.proto import client_pb2
import gflags
import logging
import requests
import urllib
import urlparse
FLAGS = gflags.FLAGS
gflags.DEFINE_integer("entry_fetch_batch_size", 1000, "Maximum number of "
"entries t... | y, e))
return sth_response
def _parse_entry(json_entry):
"""Convert a json array element to an EntryResponse."""
entry_response = client_pb2.EntryResponse()
try:
entry_response.leaf_input = base64.b64decode(
json_entry["leaf_input"])
entry_response.extra_data = base64.b64de... | _response
def _parse_entries(entries_body, expected_response_size):
"""Load serialized JSON response.
Args:
entries_body: received entries.
expected_response_size: number of entries requested. Used to validate
the response.
Returns:
a list of client_pb2.EntryResponse ... |
patrickwestphal/owlapy | owlapy/model/owlclassexpression.py | Python | gpl-3.0 | 174 | 0.005747 | from | .owlpropertyrange import OWLPropertyRange
from .swrlpredicate import SWRLPredicate
class OWLClassExpression(OWLPropertyRange, SWRLPredicate):
"""TODO: i | mplement""" |
ergo/ziggurat_foundations | ziggurat_foundations/migrations/versions/438c27ec1c9_normalize_constraint_and_key_names.py | Python | bsd-3-clause | 12,558 | 0.001593 | """normalize constraint and key names
correct keys for pre 0.5.6 naming convention
Revision ID: 438c27ec1c9
Revises: 439766f6104d
Create Date: 2015-06-13 21:16:32.358778
"""
from __future__ import unicode_literals
from alembic import op
from alembic.context import get_context
from sqlalchemy.dialects.postgresql.base... | op.execute(
"ALTER INDEX users_permissions_pkey RENAME to pk_users_permissions"
) # noqa
if (
users_resources_permissions_pkey
== insp.get_pk_constraint("users_resources_permissions")["name"]
):
op.execute(
"ALTER INDE... | s_pkey RENAME to pk_users_resources_permissions"
) # noqa
if (
"external_identities_pkey"
== insp.get_pk_constraint("external_identities")["name"]
):
op.execute(
"ALTER INDEX external_identities_pkey RENAME to pk_external_identities"
... |
dpgaspar/Flask-AppBuilder | examples/quickcharts2/build/lib/app/views.py | Python | bsd-3-clause | 5,082 | 0.004132 | import random
import logging
import datetime
import calendar
from flask_appbuilder.models.datamodel import SQLAModel
from flask_appbuilder.views import ModelView
from flask_appbuilder.charts.views import DirectChartView, DirectByChartView, GroupByChartView
from models import CountryStats, Country, PoliticalType
from ap... | roup': 'country',
'series': [(aggregate_avg, 'unemployed'),
(aggre | gate_avg, 'population'),
(aggregate_avg, 'college')
]
},
{
#'label': 'Monthly',
'group': 'month_year',
'formatter': pretty_month_year,
'series': [(aggregate_avg, 'unemployed'),
(aggregate_avg, 'popu... |
ioos/comt | python/pyugrid_test.py | Python | mit | 3,158 | 0.00665 |
# coding: utf-8
# ##Test out UGRID-0.9 compliant unstructured grid model datasets with PYUGRID
# In[1]:
name_list=['sea_surface_elevation',
'sea_surface_height_above_geoid',
'sea_surface_height','water level',
'sea_surface_height_above_sea_level',
'water_surface_height_ab... | from_ncfile(url)
cube.mesh = ug
cube.mesh_dimension = 1
return cube
def get_triang(cube):
lon = cube.mesh.nodes[:, 0]
lat = cube.mesh.nodes[:, 1]
nv = cube.mesh.faces
return tri.Triangulation(lon, lat, tri | angles=nv)
# In[5]:
tris = dict()
for model, cube in cubes.items():
url = models[model]
cube = get_mesh(cube, url)
cubes.update({model: cube})
tris.update({model: get_triang(cube)})
# In[6]:
get_ipython().magic('matplotlib inline')
import numpy as np
import cartopy.crs as ccrs
import matplotlib.... |
SvetoslavKuzmanov/altimu10v5 | altimu10v5/lsm6ds33.py | Python | mit | 6,967 | 0.000431 | # -*- coding: utf-8 -*-
"""Python library module for LSM6DS33 accelerometer and gyroscope.
This module for the Raspberry Pi compu | ter helps interface the LSM6DS33
accelerometer and gyro.The library makes it | easy to read
the raw accelerometer and gyro data through I²C interface and it also provides
methods for getting angular velocity and g forces.
The datasheet for the LSM6DS33 is available at
[https://www.pololu.com/file/download/LSM6DS33.pdf?file_id=0J1087]
"""
import math
from i2c import I2C
from time import sleep
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.