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 |
|---|---|---|---|---|---|---|---|---|
anak10thn/graphics-dojo-qt5 | snapscroll/snapscroll.py | Python | gpl-2.0 | 3,660 | 0.007104 | #############################################################################
##
## Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
## Contact: Qt Software Information ([email protected])
##
## This file is part of the Graphics Dojo project on Qt Labs.
##
## This file may be used under the terms of th... | #####################################################
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
if QT_VERSION < 0x0040500:
sys.stderr.write("You need Qt 4.5 or newer to run this example.\n")
sys.exit(1)
SNAP_THRESHOLD = 10
class SnapView(QWebView):
de... | in frame's view coordinate
def hitBoundingRects(self, line):
hitRects = []
points = 8
delta = QPoint(line.dx() / points, line.dy() / points)
point = line.p1()
i = 0
while i < points - 1:
point += delta
hit = self.page().mainFrame().hitTe... |
wdv4758h/ZipPy | lib-python/3/pickletools.py | Python | bsd-3-clause | 79,093 | 0.000582 | '''"Executable documentation" for the pickle module.
Extensive comments about the pickle protocols and pickle-machine opcodes
can be found here. Some functions meant for external use:
genops(pickle)
Generate all the opcodes in a pickle, as (opcode, arg, position) triples.
dis(pickle, out=None, memo=None, indentl... | y for
# well-formedness. dis() does a lot of this already.
#
# - A protocol identifier: examine a pickle and return its protocol number
# (== the highest .proto attr value among all the opcodes in the pickle).
# dis() already prints this info at the end.
#
# - A pickle optimizer: for example, tuple-building co... | is recursive. Or lots of times a PUT is generated that's never accessed
# by a later GET.
"""
"A pickle" is a program for a virtual pickle machine (PM, but more accurately
called an unpickling machine). It's a sequence of opcodes, interpreted by the
PM, building an arbitrarily complex Python object.
For the most... |
easytaxibr/redash | tests/handlers/test_authentication.py | Python | bsd-2-clause | 2,187 | 0.003201 | from tests import BaseTestCase
import mock
import time
from redash.models import User
from redash.authentication.account import invite_token
from tests.handlers import get_request, post_request
class TestInvite(BaseTestCase):
def test_expired_invite_token(self):
with mock.patch('time.time') as patched_ti... | e_token(self.factory.user)
response = get_request('/invite/{}'.format(token), org=self.factory.org)
self.assertEqual(response.status_code, 400)
def test_invalid_invite_token(self):
response = get_request('/invite/badtoken', org=self.factory.org)
self.assertEqual(response.stat | us_code, 400)
def test_valid_token(self):
token = invite_token(self.factory.user)
response = get_request('/invite/{}'.format(token), org=self.factory.org)
self.assertEqual(response.status_code, 200)
def test_already_active_user(self):
pass
class TestInvitePost(BaseTestCase):
... |
bmwiedemann/linuxcnc-mirror | lib/python/pyngcgui.py | Python | lgpl-2.1 | 128,675 | 0.015924 | #!/usr/bin/env python
# Notes:
# 1) ini file items:
# NGCGUI_PREAMBLE
# NGCGUI_SUBFILE
# NGCGUI_POSTAMBLE
# NGCGUI_OPTIONS
# nonew disallow new tabs
# noremove disallow removal of tabs
# noauto don't automatically send result file
# ... | #print(sys.exc_info())
print( traceback.format_exc())
def save_a_copy(fname,archive_dir='/tmp/old_ngc'):
if fname is None:
return
try:
if not os.path.exists(archive_dir):
os.mkdir(archive_dir)
shutil.copyfile(fname
,os.path.join(archive_dir,dt() +... | s') % archive_dir)
print(msg)
except Exception, detail:
exception_show(Exception,detail,src='save_a_copy')
print(traceback.format_exc())
sys.exit(1)
def get_linuxcnc_ini_file():
ps = subprocess.Popen('ps -C linuxcncsvr --no-header -o args'.split(),
... |
dymkowsk/mantid | Framework/PythonInterface/test/python/mantid/kernel/PythonPluginsTest.py | Python | gpl-3.0 | 1,990 | 0.002513 | from __future__ import (absolute_import, division, print_function)
import unittest
import os
import shutil
import sys
import mantid.kernel.plugins as plugins
from mantid.api import AlgorithmFactory, AlgorithmManager
__TESTALG__ = \
"""from mantid.api import PythonAlgorithm, AlgorithmFactory
class TestPyAlg(PythonAl... | e()
def tearDown(self):
try:
shutil.rmtree(self._testdir)
except shutil.Error:
pass
def test_loading_python_algorithm_increases_registered_algs_by_one(self):
loaded = plugins.load(self._testdir)
self.assertTrue(len(loaded) > | 0)
expected_name = 'TestPyAlg'
# Has the name appear in the module dictionary
self.assertTrue(expected_name in sys.modules)
# Do we have the registered algorithm
algs = AlgorithmFactory.getRegisteredAlgorithms(True)
self.assertTrue(expected_name in algs)
# Can it... |
staslev/incubator-beam | sdks/python/apache_beam/metrics/metric_test.py | Python | apache-2.0 | 5,205 | 0.003842 | #
# Licensed to the Apache Software Foundation (ASF) 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 us... | name = 'a_name'
counter = Metrics.counter(counter_ns, name)
distro = Metrics.distribution(distro_ns, name)
counter.inc(10)
counter.dec(3)
distro.update(10)
distro.update(2)
self.assertTrue(isinstance(counter, Metrics.DelegatingCounter))
self.assertTrue(isinstance(distro, Metrics.Deleg... | Equal(
container.counters[MetricName(counter_ns, name)].get_cumulative(),
7)
self.assertEqual(
container.distributions[MetricName(distro_ns, name)].get_cumulative(),
DistributionData(12, 2, 2, 10))
if __name__ == '__main__':
unittest.main()
|
hforge/ikaaro | scripts/icms-stop.py | Python | gpl-3.0 | 1,970 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (C) 2005-2007 Juan David Ibáñez Palomar <[email protected]>
# Copyright (C) 2007 Sylvain Taverne <[email protected]>
# Copyright (C) 2008 David Versmisse <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it ... | tions, args = parser.parse_args()
if len(args) == 0:
parser.error('incorrect number of arguments')
# Action!
for target in args:
try:
stop_server(target)
except LookupError:
print('Error: {} instance do n | ot exists'.format(target))
exit(1)
# Ok
exit(0)
|
python27/AlgorithmSolution | ProjectEuler/51_100/Problem#74.py | Python | agpl-3.0 | 411 | 0.007299 | import math
def digitFactorialSum(n):
return sum([math.factorial(i | nt(x)) for x in str(n)])
def repeatedLength(n):
repeatedList = []
while n not in repeatedList:
repeatedList.append(n)
n = digitFactorialSum(n)
return len(repeatedList)
if __name__ == "__main__":
cnt = 0
for i in range(1, 1000000):
if repeatedLength(i) | == 60:
cnt += 1
print cnt
|
Bargetor/chestnut | bargetor/notifiction/__init.py | Python | gpl-2.0 | 163 | 0.006135 | class NotifyCenter(object):
"""docstring for NotifyCenter"""
def __init__(self, arg):
sup | er(NotifyCent | er, self).__init__()
self.arg = arg
|
asimshankar/tensorflow | tensorflow/contrib/distribute/python/parameter_server_strategy.py | Python | apache-2.0 | 21,809 | 0.006098 | # Copyright 2018 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... | eed to do all-reduce in this strategy.
self._cross_device_ops = (
cross_device_ops_lib.ReductionToOneDeviceCrossDeviceOps(
reduce_to_device=_LOCAL_CPU))
def _initialize_multi_ | worker(self, num_gpus_per_worker, cluster_spec,
task_type, task_id):
"""Initialize devices for multiple workers.
It creates variable devices and compute devices. Variables and operations
will be assigned to them respectively. We have one compute device per
replica. The va... |
josanly/python-module-project | resources/setup.template.py | Python | gpl-3.0 | 419 | 0.002387 | from setuptools import setup
from sample import __version__, __author__
setup(name='sample',
version=__version__,
description='an example of p | ython module',
url='http://github.com/josanly/python-module-project',
author=__author__,
author_email='[email protected]',
license='GP | L v3.0',
packages=['sample'],
python_requires='>=PYTHON_VERSION',
zip_safe=False)
|
rgerkin/neuroConstruct | pythonNeuroML/nCUtils/ncutils.py | Python | gpl-2.0 | 66,510 | 0.014705 | # -*- coding: utf-8 -*-
#
#
# File to preform some standard tasks on a neuroConstruct project
#
# Author: Padraig Gleeson
#
# This file has been developed as part of the neuroConstruct project
# This work has been funded by the Medical Research Council and the
# Wellcome Trust
#
#
import sys
im... | ve been generated from the source of the model in the neuroConstruct directory.\n"+ \
"These have been added to provide examples of valid NeuroML files for testing applications & the OSB website and may be removed at any time."
readme = open(genDir.getAbsolutePath()+'/README--GENERA | TED-FILES', 'w')
readme.write(info)
readme.close()
def generateNeuroML1(projFile,
simConfigs,
neuroConstructSeed = 1234,
seed = 1234,
verbose = True):
projectManager = Pr... |
ashang/calibre | src/calibre/gui2/store/web_store_dialog.py | Python | gpl-3.0 | 1,721 | 0.001743 | # -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
__license__ = 'GPL 3'
__copyright__ = '2011, John Schember <[email protected]>'
__docformat__ = 'restructuredtext en'
from PyQt5.Qt import QDialog, QUrl
from calibre import url_slash_cleaner
from calibre.... | ass WebStoreDialog(QDialog, Ui_Dialog):
def __init__(self, gui, base_url, parent=None, detail_url=None, create_browser=None):
QDialog.__init__(self, parent=parent)
self.setupUi(self)
| self.gui = gui
self.base_url = base_url
self.view.set_gui(self.gui)
self.view.create_browser = create_browser
self.view.loadStarted.connect(self.load_started)
self.view.loadProgress.connect(self.load_progress)
self.view.loadFinished.connect(self.load_finished)
... |
jelmer/pydoctor | pydoctor/astbuilder.py | Python | isc | 17,654 | 0.002322 | """Convert ASTs into L{pydoctor.model.Documentable} instances."""
from pydoctor import model, ast_pp
from compiler import visitor, transformer, ast
import symbol, token
class str_with_orig(str):
"""Hack to allow recovery of the literal that gave rise to a docstring in an AST.
We do this to allow the users to... | elf.builder = builder
self.system = builder.system
self.module = module
def default(self, node):
for child in node.getChildNodes():
self.visit(child)
def visitModule(self, node):
assert self.module.docstring is None
self.module.docstring = node.doc
s... | baseobjects = []
for n in node.bases:
str_base = ast_pp.pp(n)
rawbases.append(str_base)
full_name = self.builder.current.expandName(str_base)
bases.append(full_name)
baseobj = self.system.objForFullName(full_name)
if not isinstance(baseo... |
schinke/solid-fortnight-ba | flask/migrations/versions/7ab3e266f711_.py | Python | mit | 5,512 | 0.007438 | """empty message
Revision ID: 7ab3e266f711
Revises: 0152d9c6e677
Create Date: 2016-08-09 20:14:58.552655
"""
# revision identifiers, used by Alembic.
revision = '7ab3e266f711'
down_revision = '0152d9c6e677'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... | op.drop_constraint(u'synonym_prod_association_product_id_fkey', 'synonym_prod_association', type_='foreignkey')
op.create_foreign_key(None, 'synonym_prod_association', 'product', ['product_id'], ['id'], ondelete='CASCADE')
op.drop_constraint(u'template_id_fkey', 'template', type_='foreignkey')
op.create_f... | t_id_fkey', 'unit_weight', type_='foreignkey')
op.create_foreign_key(None, 'unit_weight', 'scivalue', ['id'], ['id'], onupdate='CASCADE', ondelete='CASCADE')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'unit_weight'... |
mscherer/ansible-modules-extras | packaging/language/composer.py | Python | gpl-3.0 | 6,165 | 0.008597 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Dimitrios Tydeas Mengidis <[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... | ize_autoloader = dict(default="yes", type="bool", aliases=["optimize-autoloader"]),
),
supports_check_mode=True
)
options = []
# Default options
options.append('--no-ansi')
options.append('--no-progress')
options.append('--no-interaction')
options.extend(['--working-dir', ... | h.abspath(module.params['working_dir'])])
# Get composer command with fallback to default
command = module.params['command']
# Prepare options
if module.params['prefer_source']:
options.append('--prefer-source')
if module.params['prefer_dist']:
options.append('--prefer-dist')
i... |
airbnb/airflow | airflow/contrib/operators/imap_attachment_to_s3_operator.py | Python | apache-2.0 | 1,222 | 0.001637 | #
# Licensed to the Apache Software Foundation (ASF) 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 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 OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module is deprecated. Please use `airf... |
mxmzdlv/pybigquery | tests/unit/test_dialect_types.py | Python | mit | 1,632 | 0.004902 | # Copyright (c) 2017 The sqlalchemy-bigquery Authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associa | ted documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the follow... | ove copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONI... |
ikoula/cloudstack | tools/marvin/marvin/sandbox/demo/simulator/testcase/test_vm_life_cycle.py | Python | gpl-2.0 | 20,302 | 0.003546 | # -*- encoding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) 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
#... | "password": "password",
},
"small":
# Create a small virtual machine instance with disk offering
{
| "displayname": "testserver",
"username": "root", # VM creds for SSH
"password": "password",
"ssh_port": 22,
"hypervisor": 'XenServer',
"privateport": 22,
"publicport": 22,
"p... |
adsabs/ADSfulltext | adsft/entitydefs.py | Python | gpl-3.0 | 48,476 | 0.000041 | """
Contains the relevant conversions of HTML and LaTeX entities that will not be
correctly converted elsewhere. This is taken from adsabs/adsdata authored by
J. Luke.
"""
__author__ = 'J. Luke'
__maintainer__ = 'J. Elliott'
__copyright__ = 'Copyright 2015'
__version__ = '1.0'
__email__ = '[email protected]'
__statu... | udilovsky', 'A. Accomazzi', 'J. Luker']
__license__ = 'GPLv3'
import re
entitydefs = {
'nsqsupe': u'\u22e3',
'Pcy': u'\u041f',
'xharr': u'\u27f7',
'HumpDownHump': u'\u224e',
'asymp': u'\u2248',
'otimes': u'\u2297',
'Zopf': u'\u2124',
'bkarow': u'\u290d',
'lessapprox': u'\u2a85',
... | ': u'\u229f',
'ThinSpace': u'\u2009',
'equivDD': u'\u2a78',
'pertenk': u'\u2031',
'Gt': u'\u226b',
'gscr': u'\u210a',
'Backslash': u'\u2216',
'Gg': u'\u22d9',
'nparallel': u'\u2226',
'quatint': u'\u2a16',
'Igr': u'\u0399',
'iinfin': u'\u29dc',
'nsubseteqq': u'\u2ac5\u0338... |
onecoolx/picasso | tools/gyp/pylib/gyp/generator/ninja_test.py | Python | bsd-3-clause | 1,909 | 0.004191 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Unit tests for the ninja.py file. """
import sys
import unittest
import gyp.generator.ninja as ninja
class TestPrefixesAndSuffixes(u... | )
self.assertTrue(
writer.ComputeOutputFileName(spec, "static_library").endswith(".lib")
)
def te | st_BinaryNamesLinux(self):
writer = ninja.NinjaWriter(
"foo", "wee", ".", ".", "build.ninja", ".", "build.ninja", "linux"
)
spec = {"target_name": "wee"}
self.assertTrue("." not in writer.ComputeOutputFileName(spec, "executable"))
self.assertTrue(
writer.C... |
dbrattli/RxPY | rx/internal/basic.py | Python | apache-2.0 | 498 | 0 | from datetime import datetime
# Defaults
def noop(*args, **kw):
"""No operation. Returns nothing"""
pass
def identity(x):
"""Returns argument x"""
return x
def def | ault_now():
return datetime.utcnow()
def default_comparer(x, y):
return x == y
def default_sub_comparer(x, y):
return x - y
def default_key_serializer(x):
return str(x)
def default_error(err):
if isinstance(err, BaseException):
raise err
else:
raise Exc | eption(err)
|
uwcirg/true_nth_usa_portal | portal/models/group.py | Python | bsd-3-clause | 1,907 | 0 | """Group module
Groups are intented to cluster users together for logical reasons,
such as a list of users for whom patient notifications apply.
Groups should not be used to grant or restrict access - see `Role`.
"""
import re
from sqlalchemy import UniqueConstraint
from werkzeug.exceptions import BadRequest
from ... |
id = db.Column(db.Integer(), primary_key=True)
user_id = db.Column(
db.Integer(), db.ForeignKey | ('users.id', ondelete='CASCADE'),
nullable=False)
group_id = db.Column(
db.Integer(), db.ForeignKey('groups.id', ondelete='CASCADE'),
nullable=False)
__table_args__ = (UniqueConstraint(
'user_id', 'group_id', name='_user_group'),)
def __str__(self):
"""Print friendl... |
mit-dci/lit | test/itest_break.py | Python | mit | 337 | 0.005935 | import testlib
import te | st_combinators
fee = 20
initialsend = 200000
capacity = 10000 | 00
def forward(env):
lit1 = env.lits[0]
lit2 = env.lits[1]
test_combinators.run_break_test(env, lit1, lit2, lit1)
def reverse(env):
lit1 = env.lits[0]
lit2 = env.lits[1]
test_combinators.run_break_test(env, lit1, lit2, lit1)
|
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyQt4/QtCore/QTextStream.py | Python | gpl-2.0 | 7,395 | 0.010007 | # encoding: utf-8
# module PyQt4.QtCore
# from /usr/lib/python3/dist-packages/PyQt4/QtCore.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import sip as __sip
class QTextStream(): # skipped bases: <class 'sip.simplewrapper'>
"""
QTextStream()
QTextStream(QIODevice)
QTextStream... | nt """
return 0
def flush(self): # real signature unknown; restored from __doc__
""" QTextStream.flush() """
pass
def generateByteOrderMark(self): # real signature unknown; restored from __doc__
""" QTextStream.generateByteOrderMark() -> bool """
return False
def i... | def locale(self): # real signature unknown; restored from __doc__
""" QTextStream.locale() -> QLocale """
return QLocale
def numberFlags(self): # real signature unknown; restored from __doc__
""" QTextStream.numberFlags() -> QTextStream.NumberFlags """
pass
def padChar(self):... |
vahtras/amy | workshops/migrations/0119_auto_20161023_1413.py | Python | mit | 1,244 | 0.001608 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-10-23 19:13
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workshops', '0118_auto_20160922_0009'),
]
operations = [
migrations.AlterFie... | ('not-invoiced', 'Invoice not requested'), ('na-historic', 'Not applicable for historical reasons'), ('na-member', 'Not applicable because of membership'), ('na-self-org', 'Not applicable because self-organized'), ('na-waiver', 'Not applicable because waiver granted'), ('na-other', 'Not applicable because other arrang... | id', 'Paid')], default='not-invoiced', max_length=40, verbose_name='Invoice status'),
),
migrations.AlterField(
model_name='invoicerequest',
name='status',
field=models.CharField(choices=[('not-invoiced', 'Invoice not requested'), ('sent', 'Sent out'), ('paid', 'Paid'... |
mitschabaude/nanopores | nanopores/physics/default.py | Python | mit | 792 | 0.013889 | import dolfin
from nanopores.physics.params_physical import *
def lscale(geo):
# TODO: "lscale" is confusing since it is actually 1 over the length scale
try:
return geo.parameter("lscale")
except:
try:
return geo.parameter("nm")/nm
| except:
return 1e9
def grad(lscale):
def grad0(u):
return dolfin.Constant(lscale)*dolfin.nabla_grad(u)
return grad0
def div(lscale):
def div0(u):
| return dolfin.Constant(lscale)*dolfin.transpose(dolfin.nabla_div(u))
return div0
def dim(geo):
return geo.mesh.topology().dim()
cyl = False
def r2pi(cyl):
return dolfin.Expression("2*pi*x[0]", degree=1) if cyl else dolfin.Constant(1.)
def invscale(lscale):
return lambda i: dolfin.Constant(1./lscale**... |
benneely/duke-data-service-dredd | dredd/dredd_scripts/21_auth_provider.py | Python | gpl-3.0 | 1,178 | 0.006791 | import dredd_hooks as hooks
import imp
import os
import json
import uuid
#if you want to import another module for use in this workflow
utils = imp.load_source("utils",os.path.join(os.getcwd(),'utils.py'))
###############################################################################
#################################... | der affiliates > NOT_IMPL_NEW List auth provider affiliates | ")
@hooks.before("Auth Provider Affiliates > NOT_IMPL_NEW View auth provider affiliate > NOT_IMPL_NEW View auth provider affiliate")
@hooks.before("Auth Provider Affiliates > NOT_IMPL_NEW Create user account for affiliate > NOT_IMPL_NEW Create user account for affiliate")
def skippy21_1(transaction):
utils.skip_thi... |
ge0rgi/cinder | cinder/volume/drivers/dell/dell_storagecenter_common.py | Python | apache-2.0 | 83,512 | 0 | # Copyright 2016 Dell 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 agree... | ot extra specs.
:return: rinfo dict.
"""
rinfo = {'enabled': False, 'sync': False,
'live': False, 'active': | False,
'autofailover': False}
# Repl does not work with direct connect.
if not self.is_direct_connect:
if (not self.failed_over and
specs.get('replication_enabled') == '<is> True'):
rinfo['enabled'] = True
if specs.get('replication_... |
arpruss/raspberryjam-pe | p2/scripts3/pysanka.py | Python | mit | 4,144 | 0.017133 | #
# Code by Alexander Pruss and under the MIT license
#
#
# pysanka.py [filename [height [oval|N]]]
# oval: wrap an oval image onto an egg
# N: wrap a rectangular image onto an egg N times (N is an integer)
#
# Yeah, these arguments are a mess!
from mine import *
import colors
import sys
import os
... | 0 or y >= h:
return 0
if sphere:
return sqrt((h/2.)**2 - (y-h/2.)**2)
l = y / float(h-1)
# Formula from: htt | p://www.jolyon.co.uk/myresearch/image-analysis/egg-shape-modelling/
return h*a*exp((-0.5*l*l+c*l-.5*c*c)/(b*b))*sqrt(1-l)*sqrt(l)/(pi*b)
for y in range(0,h):
r = radius(y)
minimumr = min(r-2,radius(y-1),radius(y+1))
for x in range(-h,h+1):
for z in range(-h,h+1):
... |
Sound-Colour-Space/sound-colour-space | website/apps/museum/migrations/0033_collection_tags.py | Python | mit | 594 | 0.001684 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-11-04 17:41
from __future__ import unicode_literals
from django.db import migrations
import taggit.managers
class Migration(migrations.Migration):
dependenci | es = [
('museum', '0032_auto_20161104_1839'),
]
operations = [
migrations.AddField(
model_name='collection',
name='tags',
field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='mus | eum.TaggedObject', to='museum.Keyword', verbose_name='Tags'),
),
]
|
sonnyhu/scikit-learn | sklearn/tree/tree.py | Python | bsd-3-clause | 41,818 | 0.000072 | """
This module gathers tree-based methods, including decision, regression and
randomized trees. Single and multi-output problems are both handled.
"""
# Authors: Gilles Louppe <[email protected]>
# Peter Prettenhofer <[email protected]>
# Brian Holt <[email protected]>
# Noel Da... | if self.class_weight is not None:
expanded_class_weight = compute_sample_weight(
self.class_weight, y_original)
else:
self.classes_ = [None] * self.n_outputs_
self.n_classes_ = [1] * self.n_outputs_
self.n_classes_ = np.array(self.n_cl... | |
clouserw/olympia | apps/search/forms.py | Python | bsd-3-clause | 5,239 | 0.000191 | from django import forms
from django.conf import settings
from django.forms.util import ErrorDict
import happyforms
from tower import ugettext_lazy as _lazy
import amo
from amo import helpers
from search.utils import floor_version
collection_sort_by = (
('weekly', _lazy(u'Most popular this week')),
('monthly... | clean_cat(self):
return self.data.get('cat', 'all')
def placeholder(self, txt=None):
if settings.APP_PREVIEW:
return self.choices['apps']
return self.choices.get(txt or self.clean_cat(), self.choices['all'])
class SecondarySearchForm(forms.Form):
q = forms.CharField(widget... | red=False)
sort = forms.ChoiceField(label=_lazy(u'Sort By'), required=False,
choices=collection_sort_by, initial='weekly')
page = forms.IntegerField(widget=forms.HiddenInput, required=False)
def clean_pp(self):
try:
return int(self.cleaned_data.get('pp'))
... |
bigswitch/nova | nova/tests/unit/scheduler/test_scheduler.py | Python | apache-2.0 | 11,503 | 0.000435 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | est.NoDBTestCase):
"""Test case for scheduler manager."""
manager_cls = manager.SchedulerManager
driver_cls = fakes.FakeScheduler
driver_plugin_name = 'fake_scheduler'
@mock.patch.object(host_manager.HostManager, '_init_instance_info')
@mock.patch.object(host_manager.HostManager, '_init_aggreg... | elf.flags(scheduler_driver=self.driver_plugin_name)
with mock.patch.object(host_manager.HostManager, '_init_aggregates'):
self.manager = self.manager_cls()
self.context = context.RequestContext('fake_user', 'fake_project')
self.topic = 'fake_topic'
self.fake_args = (1, 2, 3)
... |
danijar/invoicepad | invoicepad/invoicepad/urls.py | Python | gpl-3.0 | 1,168 | 0.011986 | from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.views import serve
from django.views.decorators.cache import never_cache
urlpatterns = patterns('',
url(r'^admin/', include... | ps.user.views.user', name='user'),
url(r'^customer/((?P<id>[0-9]+)/)?$', 'apps.customer.views.customer', name='customer'),
url(r'^project/((?P<id>[0-9]+)/((?P<foreign>[a-z]+)/)?)?$', 'apps.project.views.project', name='project'),
url(r'^time/((?P<id>[0-9]+)/)?$', 'apps.project.views.time', name='time'),
url(r'^invo... | _URL, document_root=settings.MEDIA_ROOT)
# Skip cache for development
if settings.DEBUG:
urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', never_cache(serve)))
|
bhylak/trello_things3_sync | tasks/sync_task.py | Python | mit | 2,101 | 0.002856 | from task import Task
class SyncTask(Task):
def __init__(self, *remotes):
'''Init this task with all of the remote tasks'''
| super(SyncTask, self).__init__()
self.remote_tasks = []
for arg in remotes:
print arg
self.remote_tasks.append(arg)
for task in self.remote_tasks:
print task.name
self.update()
def update_from(self, task):
'''Use attributes: Takes all o... |
self.lastModifiedDate = task.lastModifiedDate
# todo: fill out rest of attributes
def sync_changes(self):
for remote in self.remote_tasks:
remote.set_attributes(self)
remote.push_changes()
def update(self, fetch_latest=False):
# todo: updating each tas... |
Splawik/pytigon | pytigon/appdata/plugins/standard/autocomplete/__init__.py | Python | lgpl-3.0 | 4,308 | 0.001857 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# This program 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 3, or (at your option) any later
# versio | n.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without | even the implied warranty of MERCHANTIBILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#Pytigon - wxpython and django application framework
#author: "Slawomir Cholaj ([email protected])"
#copyright: "Copyright (C) ????/2012 Slawomir Cholaj"
#license: "LGPL ... |
paulovn/artifact-manager | test/__init__.py | Python | gpl-2.0 | 50 | 0.04 |
am | = imp.load_source( 'am', 'artifact-ma | nager' )
|
hideoussquid/aureus-12-bitcore | qa/rpc-tests/getblocktemplate_proposals.py | Python | mit | 6,330 | 0.005055 | #!/usr/bin/env python2
# Copyright (c) 2014-2015 The Aureus Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import AureusTestFramework
from test_framework.util import *
from bina... | rawcoinbase = encodeUNum(tmpl['height'])
rawcoinbase += b'\x01-'
hexcoinbase = b2x(rawcoinbase)
hexoutval = b2 | x(pack('<Q', tmpl['coinbasevalue']))
tmpl['coinbasetxn'] = {'data': '01000000' + '01' + '0000000000000000000000000000000000000000000000000000000000000000ffffffff' + ('%02x' % (len(rawcoinbase),)) + hexcoinbase + 'fffffffe' + '01' + hexoutval + '00' + '00000000'}
txlist = list(bytearray(a2b_hex(a['da... |
jeanpm/pof | methods/hc.py | Python | gpl-2.0 | 234 | 0.008547 | # -*- coding: utf-8 -*-
| """
Created on Wed Jun 24 12:05:24 2015
@author: jean
"""
def hill_climbing(neighborhood, x):
y = neighborhood.randomNeighbor(x)
| if y is not None and y.isBetterThan(x):
return y
return x
|
Sorsly/subtle | google-cloud-sdk/lib/surface/spanner/databases/create.py | Python | mit | 2,377 | 0.002945 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi | le 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 OR CONDITIONS OF ANY KIND... | eate."""
from googlecloudsdk.api_lib.spanner import database_operations
from googlecloudsdk.api_lib.spanner import databases
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.spanner import flags
class Create(base.CreateCommand):
"""Cloud Spanner databases create command."""
@staticmethod... |
microcom/odoo-product-configurator | product_configurator_use_default_pricelist/models/product.py | Python | agpl-3.0 | 2,350 | 0.001277 | # -*- coding: utf-8 -*-
from odoo.exceptions import ValidationError
from odoo import models, api, _
class ProductProduct(models.Model):
_inherit = 'product.product'
_rec_name = 'config_name'
"""
Copy the function from product_configurator to show price using price list.
To Fix :
- Extra ... | val.value)
except:
raise ValidationError(
_("Could not convert custom value '%s' to '%s' on "
"product | variant: '%s'" % (val.value,
custom_type,
product.display_name))
)
else:
custom_vals[val.attribute_id.id] = val.value
#
#... |
kidaa/entropy | lib/entropy/db/__init__.py | Python | gpl-2.0 | 1,423 | 0 | # -*- coding: utf-8 -*-
"""
@author: Fabio Erculiani <[email protected]>
@contact: [email protected]
@copyright: Fabio Erculiani
@license: GPL-2
B{Entropy Framework repository datab | ase module}.
Entropy repositories (server and client) are implemented as relational
databases. Currently, EntropyRepository class is the object that wraps
sqlite3 database queries and repository logic: there are no more
abstractions between the two because there is only | one implementation
available at this time. In future, entropy.db will feature more backends
such as MySQL embedded, SparQL, remote repositories support via TCP socket,
etc. This will require a new layer between the repository interface now
offered by EntropyRepository and the underlying data retrieval l... |
mtth/kit | kit/ext/api.py | Python | mit | 15,315 | 0.008554 | #!/usr/bin/env python
"""API Extension (requires the ORM extension).
This extension provides a base class to create API views.
Setup is as follows:
.. code:: python
from kit import Flask
from kit.ext import API
app = Flask(__name__)
api = API(app)
View = api.View # the base API view
Views can then b... | iew = make_view(
self.blueprint,
view_class=View,
parser=Parser(* | *parser_options)
)
def register(self, flask_app, index_view=True):
if index_view:
@self.blueprint.route('/')
def index():
return jsonify({
'available_endpoints': sorted(
'%s (%s)' % (r.rule, ', '.join(str(meth) for meth in r.methods))
for r in flask_app.... |
aniruddha-adhikary/bookit | bookit/bookings/migrations/0002_ticket.py | Python | mit | 794 | 0.003778 | # -*- coding: utf-8 -*-
# Generated by Django 1.1 | 0.7 on 2017-08-16 17:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bookings', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Tick... | e='ID')),
('uuid', models.UUIDField()),
('qrcode', models.ImageField(blank=True, null=True, upload_to='qrcode')),
('booking', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='bookings.Booking')),
],
),
]
|
ppy/angle | scripts/export_targets.py | Python | bsd-3-clause | 10,578 | 0.003781 | #! /usr/bin/env python3
assert __name__ == '__main__'
'''
To update ANGLE in Gecko, use Windows with git-bash, and setup depot_tools, python2, and
python3. Because depot_tools expects `python` to be `python2` (shame!), python2 must come
before python3 in your path.
Upstream: https://chromium.googlesource.com/angle/an... | und = Fa | lse
for directory in os.environ['PATH'].split(os.pathsep):
vs_dir = os.path.join(directory, 'win_toolchain', 'vs_files')
if os.path.exists(vs_dir):
vs_found = True
break
if not vs_found:
GN_ENV['DEPOT_TOOLS_WIN_TOOLCHAIN'] = '0'
if len(sys.argv) < 3:
sys.exit('Usage: export_targets.py O... |
ddanier/django_price | django_price/price.py | Python | bsd-3-clause | 8,910 | 0.005387 | # coding: utf-8
import decimal
from . import settings as price_settings
from .utils import price_amount
from .currency import Currency
from .tax import NO_TAX
class Price(object):
def __init__(self, net, currency=None, tax=None, gross=None):
if currency is None:
currency = price_settings.DEFAU... | ut tax')
else:
# no tax applied
gross = net
tax = NO_TAX
self._applied_taxes[tax.unique_id] = (tax, net, gross)
self._recalcu | late_overall()
def _recalculate_overall(self):
# we pass net/gross through price_amount as late as possible, to avoid
# removing decimal_places we might need to calculate the right
# gross or tax. self._applied_taxes always stores the raw values without
# any rounding. This way ... |
persandstrom/home-assistant | homeassistant/components/weather/__init__.py | Python | apache-2.0 | 4,851 | 0 | """
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.he... | self.temperature_unit, self.precision)
forecast.append(forecast_entry)
data | [ATTR_FORECAST] = forecast
return data
@property
def state(self):
"""Return the current state."""
return self.condition
@property
def condition(self):
"""Return the current condition."""
raise NotImplementedError()
|
SuperTux/flexlay | flexlay/tools/zoom2_tool.py | Python | gpl-3.0 | 1,822 | 0 | # Flexlay - A Generic 2D Game Editor
# Copyright (C) 2014 Ingo Ruhnke <[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 3 of the License, or
# (at your option)... | l,
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program. If no | t, see <http://www.gnu.org/licenses/>.
from flexlay.gui.editor_map_component import EditorMapComponent
from flexlay.math import Point
from flexlay.tools.tool import Tool
class Zoom2Tool(Tool):
def __init__(self):
super().__init__()
self.active = False
self.click_pos = Point(0, 0)
... |
imZack/sanji | sanji/connection/mqtt.py | Python | mit | 4,240 | 0 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
from __future__ import print_function
import os
import sys
import uuid
import logging
import simplejson as json
import paho.mqtt.client as mqtt
from time import sleep
try:
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/../../')
from sanji.connect... | self.client.on_log = self.on_log
def on_log(self, mosq, obj, level, string):
pass
def connect(self):
"""
| connect
"""
_logger.debug("Start connecting to broker")
while True:
try:
self.client.connect(self.broker_host, self.broker_port,
self.broker_keepalive)
break
except Exception:
_logger.... |
RomanZWang/osf.io | website/addons/github/views.py | Python | apache-2.0 | 10,973 | 0.001185 | """Views for the node settings page."""
# -*- coding: utf-8 -*-
from dateutil.parser import parse as dateparse
import httplib as http
import logging
from flask import request, make_response
from framework.exceptions import HTTPError
from website.addons.base import generic_views
from website.addons.github.api import ... | y, value in headers.iteritems():
resp.headers[key] = value
return resp
#########
# HGrid #
#########
@must_be_contributor_or_public
@must_have_addon('github', 'node')
def github_root_folder(*args, **kwargs):
"""View function returning the root container for a Gi | tHub repo. In
contrast to other add-ons, this is exposed via the API for GitHub to
accommodate switching between branches and commits.
"""
node_settings = kwargs['node_addon']
auth = kwargs['auth']
data = request.args.to_dict()
return github_hgrid_data(node_settings, auth=auth, **data)
de... |
lablup/sorna | docs/conf.py | Python | lgpl-3.0 | 6,409 | 0.004681 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Backend.AI Library documentation build configuration file, created by
# sphinx-quickstart on Tue Mar 1 21:26:20 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present i... | [howto, manual, or own class]).
latex_documents = [
(master_doc, 'BackendAIDoc.tex', 'Backend.AI API Documentation',
author, 'manual'),
]
# -- Options for manual page out | put ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'backend.ai', 'Backend.AI API Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls... |
AlexeiBuzuma/LocalComputeNetworks | sft/client/commands/close.py | Python | mit | 1,397 | 0.002147 | import logging
from sft.common.commands.base import CommandFinished, ProgramFinished, CommandIds, ErrorIds
from sft.common.socket_manager import SocketManager
from .base import ClientCommandBase
from sft.common.utils.packets import (generate_packet, get_error_code)
from sft.common.config import Config
from sft.common.... | us.wait_for_close
def receive_data(self, data):
pass
def generate_data(self):
if self._send_request:
se | lf._finish = True
self._send_request = False
return self._request
return None
|
boegel/easybuild-easyblocks | easybuild/easyblocks/x/xalt.py | Python | gpl-2.0 | 9,134 | 0.003065 | ##
# Copyright 2020 NVIDIA
#
# This file is triple-licensed under GPLv2 (see below), MIT, and
# BSD three-clause licenses.
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Superc... | utable_tracking'])])
txt += self.module_generator.set_environment('XALT_GPU_TRACKING',
('no', 'yes')[bool(self.cfg['gpu_tracking'])])
if self.cfg['transmission'].lower() == 'curl' and self.cfg['logging_url']:
txt += self.module_generator.s... | nvironment('XALT_LOGGING_URL', self.cfg['logging_url'])
txt += self.module_generator.set_environment('XALT_SCALAR_SAMPLING',
('no', 'yes')[bool(self.cfg['scalar_sampling'])])
# In order to track containerized executables, bind mount the XALT
... |
robotblake/pdsm | src/pdsm/glue.py | Python | mit | 6,425 | 0.001712 | import copy
from typing import Any # noqa: F401
from typing import Dict # noqa: F401
from typing import Iterable # noqa: F401
from typing import List # noqa: F401
from typing import Optional # noqa: F401
from typing import Text # noqa: F401
import botocore.session
from botocore.exceptions import... | 'TableName': self.name}
partitions = [] # type: List[Partition]
while True:
result = client.get_partitions(**opts)
if 'Partitions' in result:
partitions += [Partition.from_input(pd) for pd in result['Partitions']]
if 'NextToken' in result:
... | else:
break
return partitions
def add_partitions(self, partitions):
# type: (List[Partition]) -> None
client = botocore.session.get_session().create_client('glue')
for partition_chunk in chunks(partitions, 100):
data = {'DatabaseName': self.database_name,... |
watchdogpolska/watchdog-kj-kultura | watchdog_kj_kultura/staticpages/tests.py | Python | mit | 1,351 | 0.003701 | from django.test import TestCase
from .templatetags.staticpages_tags import render_page_with_shortcode
ESCAPED_TEXT = '<div class="magnifier"><a href="x"><img src="x" class="img-responsive" />' + \
'</a></div><b>XSS</b>'
MULTILINE_TEXT = '<div class="magnifier"><a href="xxx"><img src="xxx"... | test_render_page_with_shortcode_for_valid(self):
TEST_CASE = {'[map]xxx[/map]': BASIC_TEXT, # Basic case
"[map]\nxxx\n[/map]": MULTILINE_TEXT | , # Multiline case
"[map]x[/map]<b>XSS</b>": ESCAPED_TEXT # Tests of escaped text
}
for value, expected in TEST_CASE.items():
self.assertHTMLEqual(render_page_with_shortcode({}, value, safe=False), expected)
def test_render_page_with_shortcode_for_un... |
srkama/haysolr | dataview/testapi/views.py | Python | apache-2.0 | 251 | 0.015936 | # Create y | our views here.
from django.shortcuts import render
from .froms import SampleSearchForm
def index(request):
form = SampleSearchForm(request.GET)
results = form.search()
ret | urn render(request,'index.html', {'samples':results})
|
azaghal/ansible | test/units/utils/test_unsafe_proxy.py | Python | gpl-3.0 | 3,234 | 0.000618 | # -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <[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
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy imp... | est_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(Ansib... | )), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not ... |
CptLemming/django-socket-server | socket_server/client.py | Python | bsd-3-clause | 1,594 | 0.000627 | import json
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketClientFactory
class SocketClientProtocol(WebSocketClientProtocol):
def emit(self, event_name, **kwargs):
payload = self._format_outbound_data(event_name, **kwargs)
self.sendMessage(payload)
def _format_out... | pass
def on(self, event_name, callback):
self.callbacks[event_name] = callback
def fire_callback(self, client, event_name, **kwargs):
if event_name in self.callbacks:
self.callbacks[event_name](client, **kwargs)
def handle_message(self, client, message):
payload... | lient, event, **payload)
def parse_message(self, message):
payload = json.loads(message)
if 'event' in payload:
output = payload
return output
|
ComicIronic/ByondToolsv3 | tests/ObjectTree.py | Python | mit | 2,925 | 0.004444 | '''
Created on Jan 5, 2014
@author: Rob
'''
import unittest
class ObjectTreeTests(unittest.TestCase):
def setUp(self):
from byond.objtree import ObjectTree
self.tree = ObjectTree()
def test_consumeVariable_basics(self):
test_string = 'var/obj/item/weapon/chainsaw = new'
... | rtEqual(data.special, None)
def test_consumeVariable_file_ref(self):
test_string = 'icon = \'butts.dmi\''
name, data = self.tree.consumeVariable(test_string, '', 0)
self.assertEqual(name, 'icon')
self.assertEqual(data.type, ' | /icon')
self.assertEqual(str(data.value), 'butts.dmi')
self.assertEqual(data.size, None)
self.assertEqual(data.declaration, False)
self.assertEqual(data.inherited, False)
self.assertEqual(data.special, None)
if __name__ == "__main__":
#import sys;sys.ar... |
daniboy/seantis-questionnaire | questionnaire/qprocessors/range_or_number.py | Python | bsd-3-clause | 2,702 | 0.007772 | from questionnaire import *
from django.conf import settings
from django.utils.translation import ugettext as _
from json import dumps
@question_proc('range', 'number')
def question_range_or_number(request, question):
cd = question.getcheckdict()
rmin, rmax = parse_range(cd)
rstep = parse_step(cd)
... | t' : runit,
'current' : current,
'jsinclude' : jsinclude
}
@answer_proc('range', 'number')
def process_range_or_number(question, ans | wer):
cd = question.getcheckdict()
rmin, rmax = parse_range(cd)
rstep = parse_step(cd)
convert = range_type(rmin, rmax, rstep)
required = question.getcheckdict().get('required', 0)
ans = answer['ANSWER']
if not ans:
if required:
raise AnswerException(_(u"Field cannot b... |
acigna/pywez | zsi/doc/examples/client/send_request/simple/Binding/client.py | Python | mit | 301 | 0.003322 | #!/usr/bin/env python
from ZSI import Binding
MESSAGE = "Hello from Python!"
def main():
binding = Binding(url='http://localhost:8080/server.py')
print ' Sending: %s' % MESSAGE
r | esponse | = binding.echo(MESSAGE)
print 'Response: %s' % MESSAGE
if __name__ == '__main__':
main()
|
teitei-tk/ice-pick | icePick/recorder.py | Python | mit | 4,310 | 0.000928 | import re
import datetime
from pymongo import MongoClient
from bson import ObjectId
from .exception import RecorderException, StructureException
__all__ = ['get_database', 'Recorder', 'Structure']
def g | et_database(db_name, host, port=27017):
return MongoClient(host, port)[db_name]
class Structure(dict):
__store = {}
def __init__(self, *args, **kwargs):
super(Structure, self).__init__(*args, **kwargs)
self.__dict__ = self
self._validate()
def _validate(self):
pass
... | def to_dict(self):
return self.__dict__
class Recorder:
struct = None
__store = None
class Meta:
database = None
class DataStore:
def get(self, key):
return self.__dict__.get(key)
def set(self, key, value):
self.__dict__[key] = value
... |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.4/django/conf/locale/hr/formats.py | Python | bsd-3-clause | 1,758 | 0 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. E Y.'
TIME_FORMAT = 'H:i:s'
DATETIME_FORMAT = 'j. E Y. H:i'
YEAR_MONTH... | 10-25'
'%d.%m.%Y. | %H:%M:%S', # '25.10.2006. 14:30:59'
'%d.%m.%Y. %H:%M', # '25.10.2006. 14:30'
'%d.%m.%Y.', # '25.10.2006.'
'%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59'
'%d.%m.%y. %H:%M', # '25.10.06. 14:30'
'%d.%m.%y.', # '25.10.06.'
'%d. %m. %Y. %H:%M:%S', # '2... |
ChameleonCloud/openstack-nagios-plugins | setup.py | Python | gpl-3.0 | 4,527 | 0.001546 | from setuptools import setup, find_packages # Always prefer setuptools over distutils
from codecs import open # To use a consistent encoding
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8... | 'python-ironicclient',
],
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# pip to create the appropriate form of executable for the target platform.
entry_points={
'console_scripts': [
| 'check_nova-images=openstacknagios.nova.Images:main',
'check_nova-services=openstacknagios.nova.Services:main',
'check_nova-hypervisors=openstacknagios.nova.Hypervisors:main',
'check_cinder-services=openstacknagios.cinder.Services:main',
'check_neutron-agents=ope... |
Professor-RED/Erik | TestPrograms/Chat_Client.py | Python | mit | 1,527 | 0.018337 | # chat_client.py
import sys
import socket
import select
def chat_client():
if(len(sys.argv) < 3) :
print('Usage : python chat_client.py hostname port')
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2... | .flush()
else :
# user entered a message
msg = sys.stdin.readlin | e()
s.send(msg)
sys.stdout.write('[Me] '); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
|
sadad111/leetcodebox | Binary Tree Level Order Traversal.py | Python | gpl-3.0 | 603 | 0.016584 | class Solution(object):
def __init__(self):
self.l=[]
def helper(self,root,level):
i | f not root:
return None
else:
if level<len(self.l):
self.l[level].append(ro | ot.val)
else:
self.l.append([root.val])
self.helper(root.left,level+1)
self.helper(root.right,level+1)
return self.l
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
... |
apache/incubator-airflow | airflow/providers/cncf/kubernetes/sensors/spark_kubernetes.py | Python | apache-2.0 | 5,015 | 0.001994 | #
# Licensed to the Apache Software Foundation (ASF) 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... | bernetes connection<howto/connection:kubernetes>`
to Kubernetes cluster.
:type kubernetes_conn_id: str
:param attach_log: determines whether logs for d | river pod should be appended to the sensor log
:type attach_log: bool
:param api_group: kubernetes api group of sparkApplication
:type api_group: str
:param api_version: kubernetes api version of sparkApplication
:type api_version: str
"""
template_fields = ("application_name", "namespace")... |
asiviero/shopify_python_api | shopify/resources/location.py | Python | mit | 79 | 0 | from ..base import ShopifyResource
class Location(Shop | ifyReso | urce):
pass
|
maclogan/VirtualPenPal | tests/test_adapter_validation.py | Python | bsd-3-clause | 4,912 | 0.000814 | from chatterbot import ChatBot
from chatterbot.adapters import Adapter
from .base_case import ChatBotTestCase
class AdapterValidationTests(ChatBotTestCase):
def test_invalid_storage_adapter(self):
kwargs = self.get_kwargs()
kwargs['storage_adapter'] = 'chatterbot.input.TerminalAdapter'
wi... | elf.assertEqual(
type(self.chatbot.logic.adapters[1]).__name__,
'MathematicalEvaluation'
)
def test_remove_logic_adapter(self):
self.chatbot.logic.add_adapter('chatterbot.logic.TimeLogicAdapter')
self.chatbot.logic.add_adapter('chatterbot.logic.MathematicalEvaluation... | f.assertTrue(removed)
self.assertIsLength(self.chatbot.logic.adapters, adapter_count - 1)
def test_remove_logic_adapter_not_found(self):
self.chatbot.logic.add_adapter('chatterbot.logic.TimeLogicAdapter')
adapter_count = len(self.chatbot.logic.adapters)
removed = self.chatbot.logi... |
rprabhat/elastalert | elastalert/alerts.py | Python | apache-2.0 | 60,947 | 0.00274 | # -*- coding: utf-8 -*-
import copy
import datetime
import json
import logging
import subprocess
import sys
import warnings
from email.mime.text import MIMEText
from email.utils import formatdate
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPAuthenticationError
from smtplib import SMTPEx... | retty_print_as_json(match_items)
preformatted_text = u'{{code:json}}{0}{{code}}'.format(json_blob)
self.text += preformatted_text
class Alerter(object):
""" Base class for types of alerts.
:param rule: The rule configuration.
"""
required_options = frozenset([])
def __init__(self... | self.pipeline = None
self.resolve_rule_references(self.rule)
def resolve_rule_references(self, root):
# Support referencing other top-level rule properties to avoid redundant copy/paste
if type(root) == list:
# Make a copy since we may be modifying the contents of the structur... |
gi11es/thumbor | tests/test_server.py | Python | mit | 9,543 | 0.000838 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
from unittest import TestCase
import mock
from preggy import expect... | ock(fd=None, port=1234, ip="0.0.0.0", processes=5)
server_instance_mock = mock.Mock()
server_mock.return_value = server_instance_mock
run_server(application, context)
server_instance_mock.start.assert_called_with(5)
@mock.patch.object(thumbor.server, "HTTPServer")
@mock.patch... | ock()
context = mock.Mock()
context.server = mock.Mock(fd=11, port=1234, ip="0.0.0.0", processes=1)
server_instance_mock = mock.Mock()
server_mock.return_value = server_instance_mock
socket_from_fd_mock.return_value = "socket mock"
run_server(application, context)
... |
r0x0r/pywebview | examples/localization.py | Python | bsd-3-clause | 1,251 | 0 | # -*- coding: utf-8 -*-
import webview
"""
This example demonstrates how to localize GUI strings used by pywebview.
"""
if __name__ == '__main__':
localization = {
'global.saveFile': u'Сохранить файл',
'cocoa.menu.about': u'О программе',
'cocoa.menu.services': u'Cлужбы',
'cocoa.me... | ': u'Открыть файлы',
'linux.ope | nFolder': u'Открыть папку',
}
window_localization_override = {
'global.saveFile': u'Save file',
}
webview.create_window(
'Localization Example',
'https://pywebview.flowrl.com/hello',
localization=window_localization_override,
)
webview.start(localization=localiz... |
jopohl/urh | src/urh/controller/dialogs/FilterDialog.py | Python | gpl-3.0 | 4,227 | 0.001183 | from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt
from PyQt5.QtWidgets import QDialog
from urh.signalprocessing.Filter import Filter, FilterType
from urh.ui.ui_filter_dialog import Ui_FilterDialog
class FilterDialog(QDialog):
filter_accepted = pyqtSignal(Filter)
def __init__(self, dsp_filter: Filter, parent... | f.ui.spinBoxNumTaps.setEnabled(False)
else:
self.ui.radioButtonCustomTaps.setChecked(True)
| self.ui.spinBoxNumTaps.setEnabled(True)
self.ui.lineEditCustomTaps.setEnabled(True)
def create_connects(self):
self.ui.radioButtonMovingAverage.clicked.connect(self.on_radio_button_moving_average_clicked)
self.ui.radioButtonCustomTaps.clicked.connect(self.on_radio_button_cus... |
PhantomAppDevelopment/python-getting-started | step-1/myscript.py | Python | mit | 308 | 0 | """
This file should only work on Py | thon 3.6 and newer.
Its purpose is to test a correct installation of Python 3.
"""
from random import randint
print("Generating one thousand random numbers...")
for i in range(1000):
random_number = randint(0, 100000)
print(f"Number {i} was: {rando | m_number}")
|
psychopy/versions | psychopy/visual/polygon.py | Python | gpl-3.0 | 3,361 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''Creates a regular polygon (triangles, pentagrams, ...)
as a special case of a :class:`~psychopy.visual.ShapeStim`'''
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.
# Distributed under the terms of the GNU ... | self.setVertices(self.vertices, log=False)
def setEdges(self, edges, operation='', log=None):
"""Usually you can use 'stim.attribute = value' syntax instead,
but use this method if you need to suppress the log message"""
setAttribute(self, 'edges', edges, log, operation)
@attributeSet... | lygon (distance from the center to the corners).
May be a -2tuple or list to stretch the polygon asymmetrically.
:ref:`Operations <attrib-operations>` supported.
Usually there's a setAttribute(value, log=False) method for each
attribute. Use this if you want to disable logging.
... |
jiaphuan/models | research/adversarial_text/graphs.py | Python | apache-2.0 | 24,710 | 0.004816 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | = self.language_model_graph()
train_op = optimize(loss, self.global_step)
return train_op, loss, self.global_step
def classifier_graph(self):
"""Constructs classifier graph from inputs to classifier loss.
* Caches the VatxtInput object in `self.cl_inputs`
* Caches tensors: `cl_embedded`, `cl_lo... | _inputs = inputs
embedded = self.layers['embedding'](inputs.tokens)
self.tensors['cl_embedded'] = embedded
_, next_state, logits, loss = self.cl_loss_from_embedding(
embedded, return_intermediates=True)
tf.summary.scalar('classification_loss', loss)
self.tensors['cl_logits'] = logits
se... |
gpndata/cattle | tests/integration/cattletest/core/test_projects.py | Python | apache-2.0 | 17,330 | 0 | from common_fixtures import * # NOQA
from gdapi import ApiError
_USER_LIST = [
"Owner",
"Member",
"Stranger",
"OutThereUser"
]
PROJECTS = set([])
@pytest.fixture(autouse=True, scope="module")
def clean_up_projects(super_client, request):
# This randomly times out, don't know why, disabling it... | ttribute')
_set_ | members(admin_user_client, user_clients['Member'], project.id, [],
'Attribute')
_set_members(admin_user_client, user_clients['Member'], project.id,
members, 'Attribute')
with pytest.raises(ApiError) as e:
_set_members(admin_user_client, user_clients['Stranger'],
... |
alfredodeza/ceph-deploy | ceph_deploy/hosts/fedora/install.py | Python | mit | 3,044 | 0.0023 | from ceph_deploy.lib import remoto |
from ceph_deploy.hosts.centos.install import repo_install, mirror_install # noqa
from ceph_deploy.hosts.util import install_yum_priorities
def install(distro, version_kind, version, adjust_repos, **kw):
# note: when split packages for ceph land for Fedora,
# `kw['compo | nents']` will have those. Unused for now.
logger = distro.conn.logger
release = distro.release
machine = distro.machine_type
if version_kind in ['stable', 'testing']:
key = 'release'
else:
key = 'autobuild'
if adjust_repos:
install_yum_priorities(distro)
distro.... |
bin3/bobo | bobo/fileutil.py | Python | apache-2.0 | 2,554 | 0.006265 | # -*- coding: utf-8 -*-
#
# Copyright(C) 2013 Binson Zhang.
#
# 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 o | f 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 OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific la... | ssions and limitations
# under the License.
#
__author__ = 'Binson Zhang <[email protected]>'
__date__ = '2013-8-25'
import os
import console
BUILD_ROOT_FILE = 'BUILD_ROOT'
BUILD_FILE = 'BUILD'
PATH_SEPARATOR = '/'
ROOT_PREFIX = '/'
WORKSPACE_PREFIX = '//'
EXTERNAL_PREFIX = '#'
def find_root_dir(working_dir):
... |
Rastii/pydev_docker | pydev_docker/options.py | Python | mit | 4,867 | 0.006575 | from typing import Optional, Iterable, Iterator, List
import itertools
import os.path
from pydev_docker import models
from pydev_docker import utils
class ContainerOptions:
"""
Options for running a docker container
"""
DEFAULT_PYPATH_DIR = "/pypath"
DEFAULT_SRC_DIR = "/src"
def __init__(sel... | els.Volume]:
return iter(self._ext_volumes)
def iter_en | vironment_variables(self) -> Iterator[models.Environment]:
return iter(self._environment_variables)
def get_ports(self) -> List[models.Port]:
return list(self._ports)
def get_volume_collection(self) -> List[models.Volume]:
"""
Returns a list of `models.Volume` objects that cont... |
evemorgen/GdzieJestTenCholernyTramwajProject | backend/schedule_worker/handlers/real_data_handler.py | Python | mit | 1,218 | 0.001642 | import json
import logging
from tornado.web import RequestHandler
from tornado.gen import coroutine
from db import RealDb
class RealDataHandler(RequestHandler):
def initialize(self):
self.db = RealDb()
self.db.get_all()
def set_default_headers(self):
self.set_header("Access-Control... | rams['ts'])
self.write("OK")
@coroutine
def get(self):
mes_id = self.get_argument('id')
lat = self.get_argument('lat')
lon = self.get_argument('lon')
line = self.get_argument('line')
timestamp = self.get_argument('ts')
logging.info('putting new point (%s,... | sert_point(mes_id, lat, lon, line, timestamp)
self.write("OK")
|
dpazel/music_rep | transformation/functions/tonalfunctions/tonal_permutation.py | Python | mit | 3,907 | 0.003583 | """
File: tonal_permutation.py
Purpose: Class defining a function whose cycles are composed of tone strings (no None).
"""
from function.permutation import Permutation
from tonalmodel.diatonic_tone_cache import DiatonicToneCache
from tonalmodel.diatonic_tone import DiatonicTone
class TonalPermutation(Permutation):... | ' must be a list.'.format(cycle))
new_cycle = list()
f | or tone_rep in cycle:
if isinstance(tone_rep, str):
tone = DiatonicToneCache.get_tone(tone_rep)
if tone is None:
raise Exception('Tone domain item \'{0}\' illegal syntax.'.format(tone_rep))
elif isinstance(tone_rep, Diatonic... |
vIiRuS/Lagerregal | devices/models.py | Python | bsd-3-clause | 10,243 | 0.002831 | import datetime
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.urls import reverse
import reversion
from users.models import Lageruser
from devicetypes.models import Type
from devicegroups.models import Devicegroup
from locations.models... | _(self): |
return str(self.infotype) + ": " + self.information
class Meta:
verbose_name = _('Information')
verbose_name_plural = _('Information')
@reversion.register(ignore_duplicates=True)
class Lending(models.Model):
owner = models.ForeignKey(Lageruser, verbose_name=_("Lent to"), on_delete=mo... |
NikolaYolov/invenio_backup | modules/webstat/lib/webstatadmin.py | Python | gpl-2.0 | 10,293 | 0.004372 | ## $id: webstatadmin.py,v 1.28 2007/04/01 23:46:46 tibor exp $
##
## This file is part of Invenio.
## Copyright (C) 2007, 2008, 2010, 2011 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 Foundation; ... | \n"
" -a, --args=[NAME] set column headers for additional custom event arguments\n"
" (e.g. -a country,person,car) | \n",
version=__revision__,
specific_params=("n:r:Sl:a:c:de", ["new-event=", "remove-event=", "show-events",
"event-label=", "args=", "cache-events=", "dump-config",
"load-config"]),
... |
catapult-project/catapult | third_party/gsutil/third_party/pyasn1-modules/tests/test_rfc2511.py | Python | bsd-3-clause | 1,591 | 0.000629 | #
# This file is part of pyasn1-modules software.
#
# Copyright (c) 2005-2017, Ilya Etingof <[email protected]>
# License: http://pyasn1.sf.net/license.html
#
import sys
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1_modules import pem
from pyasn1_m... | )
assert der_encoder.encode(asn1Object) == substrate
suite = unittest.TestLoader( | ).loadTestsFromModule(sys.modules[__name__])
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite)
|
cprov/snapcraft | snapcraft/internal/project_loader/_env.py | Python | gpl-3.0 | 4,619 | 0.000649 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2017 Canonical Ltd
#
# 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 h... | )
)
return env
|
def build_env(root: str, snap_name: str, arch_triplet: str) -> List[str]:
"""Set the environment variables required for building.
This is required for the current parts installdir due to stage-packages
and also to setup the stagedir.
"""
env = []
paths = common.get_include_paths(root, arch_t... |
mazaclub/electrum-nmc | lib/commands.py | Python | gpl-3.0 | 19,964 | 0.010068 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# 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... | [<recipient> <amount> ...]'
payto_syntax = "payto <recipient> <amount> [label]\n<recipient> can be a bitcoin address or a label"
paytomany_syntax = "paytomany <recipient> <amount> [<recipient> <amount> ...]\n<recipient> can be a bitcoin address or a label"
signmessage_syntax = 'signmessage <address> <message>\nIf you w... | es, or want double spaces inside the message make sure you quote the string. I.e. " Hello This is a weird String "'
verifymessage_syntax = 'verifymessage <address> <signature> <message>\nIf you want to lead or end a message with spaces, or want double spaces inside the message make sure you quote the string. I.e. " He... |
samueldmq/infosystem | infosystem/subsystem/user/manager.py | Python | apache-2.0 | 6,277 | 0 | import os
import hashlib
import flask
from sparkpost import SparkPost
from infosystem.common import exception
from infosystem.common.subsystem import manager
from infosystem.common.subsystem import operation
_HTML_EMAIL_TEMPLATE = """
<div style="width: 100%; text-align: center">
<h1>{app_name}</h1>
... | senha.</p>
<div style="width: 100%; text-align: center">
<a href="{reset_url}">Clique aqui para CONFIRMAR o
email e CRIAR uma senha.</a>
</div>
"""
def send_email(token_id, user, domain):
try:
sparkpost = SparkPost()
default_app_name = "INFOSYSTEM"
default_ema... | = 'INFOSYSTEM - CONFIRMAR email e CRIAR senha'
infosystem_app_name = os.environ.get(
'INFOSYSTEM_APP_NAME', default_app_name)
infosystem_reset_url = os.environ.get(
'INFOSYSTEM_RESET_URL', default_reset_url)
infosystem_noreply_email = os.environ.get(
'INFOSYS... |
aioc/aminiaio | aminiaio/db/contest.py | Python | mit | 1,280 | 0.035156 | from . import conn
class Contest(object):
def __init__(self, contestId, name, length, description, problems):
self._contestId = contestId
self._name = name
self._length = length
self._description = description
self._problems = problems
@classmethod |
def load(cls, contestId):
with conn.cursor() as cur:
cur.execute('SELECT name, length, description, problems FROM contests WHERE contest_id=%s;', (contestId,))
result = cur.fetchone()
if result is None:
return None
name, length, description, problems = result
return cls(contestId, name, length, d... | problems):
with conn.cursor() as cur:
cur.execute('''
INSERT INTO contests (name, length, description, problems)
VALUES (%(name)s, %(length)s, %(description)s, %(problems)s)
RETURNING contest_id;
''', {
'name': name,
'length': length,
'description': description,
'problems': problems... |
peterheim1/robbie_ros | robbie_ai/nodes/aiml/know.py | Python | bsd-3-clause | 147 | 0.027211 | #! | /usr/bin/env python
def Test():
text ='hi from'
k = text + "call "
print k
return k
def euro():
print "high"
| |
cbigler/jackrabbit | jackrabbit/request.py | Python | mit | 977 | 0.002047 | from .exceptions import MalformedRequestException
class Request(object):
def __init__(self, version, metadata, arguments):
self._version = version
self._metadata = metadata
self._arguments = arguments
@property
def version(self):
return self._version
@property
def... | lf._arguments
@property
def metadata(self):
| return self._metadata
@staticmethod
def loads(s, serializer):
try:
l = serializer.loads(s)
except(ValueError, TypeError):
raise MalformedRequestException(serializer.__name__, s)
try:
version, metadata, args = l[0:3]
except ValueError:
... |
SrNetoChan/QGIS | python/plugins/processing/algs/gdal/GridNearestNeighbor.py | Python | gpl-2.0 | 8,683 | 0.003685 | # -*- coding: utf-8 -*-
"""
***************************************************************************
GridNearestNeighbor.py
---------------------
Date : October 2013
Copyright : (C) 2013 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*****... | QgsProcessingParameterRasterDestination)
from processing.algs.gdal.GdalAlgorithm import GdalAlgorithm
from processing.algs.gdal.GdalUtils impor | t GdalUtils
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
class GridNearestNeighbor(GdalAlgorithm):
INPUT = 'INPUT'
Z_FIELD = 'Z_FIELD'
RADIUS_1 = 'RADIUS_1'
RADIUS_2 = 'RADIUS_2'
ANGLE = 'ANGLE'
NODATA = 'NODATA'
OPTIONS = 'OPTIONS'
EXTRA = 'EXTRA'
DA... |
rgayon/plaso | plaso/parsers/mac_wifi.py | Python | apache-2.0 | 10,515 | 0.006182 | # -*- coding: utf-8 -*-
"""Parses for MacOS Wifi log (wifi.log) files."""
from __future__ import unicode_literals
import re
import pyparsing
from dfdatetime import time_elements as dfdatetime_time_elements
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors
fro... | parsing.printables) +
pyparsing.Word(pyparsing.printables) +
pyparsing.Literal('logfile turned over') +
pyparsing.LineEnd(),
joinString=' ', adjacent=False).setResultsName('text'))
# Define the available log line structures.
LINE_STRUCTURES = [
('header', _MAC_WIFI_HEA... | = frozenset([key for key, _ in LINE_STRUCTURES])
def __init__(self):
"""Initializes a parser."""
super(MacWifiLogParser, self).__init__()
self._last_month = 0
self._year_use = 0
def _GetAction(self, action, text):
"""Parse the well known actions for easy reading.
Args:
action (str):... |
makinacorpus/formhub | odk_logger/migrations/0012_add_permission_view_xform.py | Python | bsd-2-clause | 7,685 | 0.007547 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
class Migration(DataMigration):
depends_on = (
("guardian", "0005_auto... | ing': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models | .fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
... |
manassolanki/frappe | frappe/core/doctype/user_permission/user_permission.py | Python | mit | 1,295 | 0.026255 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, json
from frappe.model.document import Document
from frappe.permissions import (get_valid_perms, update_permission_property)
from f... | r=None):
'''Get all users permissions for the user as a dict of doctype'''
if not user:
user = frappe.session.user
out = frappe.cache().hget("user_permissions", user)
if out is None:
out = {}
try:
for perm in frappe.get_all('User Permission',
fields=['allow', 'for_value'], filters=dict(user=user)):
... | .allow in out:
out[perm.allow] = []
out[perm.allow].append(perm.for_value)
if meta.is_nested_set():
out[perm.allow].extend(frappe.db.get_descendants(perm.allow, perm.for_value))
frappe.cache().hset("user_permissions", user, out)
except frappe.SQLError as e:
if e.args[0]==1146:
# called f... |
Cherry-project/primitiveWS | startup.py | Python | gpl-3.0 | 76 | 0.026316 | from c | herry impo | rt *
robot=Cherry.setup()
Cherry.serve()
Cherry.connect()
|
lhupfeldt/jenkinsflow | test/job_load_test.py | Python | bsd-3-clause | 3,177 | 0.002833 | # Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
import os, random
from jenkinsflow import jobload
from .framework import api_select
here = os.path.abspath(os.path.dirname(__file__))
_context = dict(
exec_time=1,
params... | d_new_pre_delete(api_type):
api = api_select.api(__file__, api_type, login=True)
full_name, short_name = _random_job_name(api)
api.job(short_name, 1, 1, 1, exec_time=1, non_existing=True)
jobload.update_job_from_template(api, full_name, api.job_xml_template, pre_delete=True, context=_context)
_asser... | _load_existing_pre_delete(api_type):
api = api_select.api(__file__, api_type, login=True)
full_name, short_name = _random_job_name(api)
api.job(short_name, 1, 1, 1, exec_time=1)
jobload.update_job_from_template(api, full_name, api.job_xml_template, pre_delete=True, context=_context)
_assert_job(api,... |
nkoech/trialscompendium | trialscompendium/trials/api/treatment/filters.py | Python | mit | 934 | 0 | from rest_framework.filters import (
FilterSet
)
from trialscompendium.trials.models import Treatment
class TreatmentListFilter(FilterSet):
"""
Filter query list from treatment database table
"""
class Meta:
model = Treatment
fields = {'id': ['exact', 'in'],
'no_r... | crops_grown': ['iexact', 'in', 'icontains'],
| 'farm_yard_manure': ['iexact', 'in', 'icontains'],
'farm_residue': ['iexact', 'in', 'icontains'],
}
order_by = ['tillage_practice', 'cropping_system', 'crops_grown']
|
james-tate/gnuradio_projects | ettus_lab/lab1/top_block.py | Python | gpl-3.0 | 3,795 | 0.016074 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Tue Dec 27 19:28:14 2016
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.sta... | izer = wx.BoxSizer(wx.VERTICAL)
| self._freq_text_box = forms.text_box(
parent=self.GetWin(),
sizer=_freq_sizer,
value=self.freq,
callback=self.set_freq,
label='freq',
converter=forms.float_converter(),
proportion=0,
)
self._freq_slider = forms.slider(
parent... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.