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 |
|---|---|---|---|---|---|---|---|---|
Vauxoo/stock-logistics-warehouse | stock_inventory_verification_request/models/stock_slot_verification_request.py | Python | agpl-3.0 | 5,256 | 0 | # Copyright 2017 Eficent Business and IT Consulting Services S.L.
# (http://www.eficent.com)
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class SlotVerificationRequest(models.Model):
_name = 'stock.slot.verification.request'
_inherit = 'mail.thr... | ion = self.env.ref('stock.stock_move_action')
result = action.read()[0]
result['contex | t'] = {}
moves_ids = self.mapped('involved_move_ids').ids
if len(moves_ids) > 1:
result['domain'] = [('id', 'in', moves_ids)]
elif len(moves_ids) == 1:
res = self.env.ref('stock.view_move_form', False)
result['views'] = [(res and res.id or False, 'form')]
... |
ASMlover/study | zeroMQ/python/push-pull/worker.py | Python | bsd-2-clause | 1,961 | 0.008159 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# ... | E) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
import time
if __name__ == '__main__':
ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://local... | y:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close()
|
renatopp/behavior3py | tests/test_runner.py | Python | mit | 358 | 0.00838 | import b3
import unittest
from common import *
class TestRunner(unittest.TestCase):
def test_category(self):
self.assertEqual(b3.Runner.category, b3.ACTION)
def test_tick(self):
node = b3.Runner()
status = n | ode._execute(TickStub())
s | elf.assertEqual(status, b3.RUNNING)
if __name__ == '__main__':
unittest.main() |
scolby33/OCSPdash | src/ocspdash/web/wsgi.py | Python | mit | 330 | 0.00303 | # -*- coding: utf-8 -*-
"""This file should be used to run the flask app with something like Gunicorn.
For example: gunicorn -b 0.0.0.0:8000 ocspdash.web.wsgi:app
This file should NOT be imported anywhere, though, since it would in | stantiate the app.
"""
from ocspdash.web import create_application
app | = create_application()
|
Skaper/RMCStudio | images/emotion/eyes/type1/ico/__init__.py | Python | apache-2.0 | 21 | 0 | from modu | le import * | |
wbrefvem/openshift-ansible | setup.py | Python | apache-2.0 | 16,830 | 0.000951 | """A setuptools based setup module.
"""
from __future__ import print_function
import os
import fnmatch
import re
import sys
import subprocess
import yaml
# Always prefer setuptools over distutils
from setuptools import setup, Command
from setuptools_lint.setuptools_command import PylintCommand
from six import string... | , exclude_dirs, include_dirs, file_regex):
''' find files matching file_regex '''
found = []
exclude_regex = ''
include_regex = ''
if exclude_dirs is not None:
exclude_regex = r'|'.join([fnmatch.translate(x) for x in exclude_dirs]) or r'$.'
# Don't use include_dirs, it is broken
if... | ne:
include_regex = r'|'.join([fnmatch.translate(x) for x in include_dirs]) or r'$.'
for root, dirs, files in os.walk(base_dir):
if exclude_dirs is not None:
# filter out excludes for dirs
dirs[:] = [d for d in dirs if not re.match(exclude_regex, d)]
if include_dirs... |
tiborsimon/dotfiles | configs/lemon-modules/config/config/modules/weather/weather.py | Python | mit | 2,018 | 0 | import os
import sys
import time
from datetime import datetime
import requests
ICONS = {
"01d": "", # clear sky
"02d": "", # few clouds
"03d": "", # scattered clouds
"04d": "", # broken clouds
"09d": "", # shower rain
"10d": "", # rain
"11d": "", # thunderstorm
"13d": ""... | f"%{{T5}}{ICON_SUNRISE} %{{T1}}{sunri | se}"
else:
sunset = sunset.strftime("%H:%M")
sun = f"%{{T5}}{ICON_SUNSET} %{{T1}}{sunset}"
print(f"%{{T1}}%{{A:weather:}}{temp} {sun}%{{A}}")
if __name__ == "__main__":
main()
|
davidbgk/udata | udata/core/reuse/api_fields.py | Python | agpl-3.0 | 4,422 | 0.001809 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from udata.api import api, fields, base_reference
from udata.core.badges.api import badge_fields
from udata.core.dataset.api_fields import dataset_ref_fields
from udata.core.organization.api_fields import org_ref_fields
from udata.core.user.api_fields im... | elds.ImageField(description='The reuse thumbnail thumbnail (cropped) URL'),
'image_thumbnail': fields.ImageField(attribute='image', size=BIGGEST_IMAGE_SIZE,
description='The reuse thumbnail thumbnail URL. This is the square '
'({0}x{0}) and cropped version.'.format(BIGGEST_IMAGE_SIZE)),
'uri': f... | da o: {'reuse': o},
description='The reuse API URI', readonly=True),
'page': fields.UrlFor(
'reuses.show', lambda o: {'reuse': o},
description='The reuse page URL', readonly=True),
})
reuse_type_fields = api.model('ReuseType', {
'id': fields.String(description='The reuse type identifier... |
glesica/django-site-news | site_news/context_processors.py | Python | bsd-3-clause | 379 | 0.007916 | from django.conf import settings
from site_news.models import SiteNewsItem
def site_news(request):
"""
Inserts the currently active news items into the template context.
This ignores MAX_SITE_NEWS_ITEMS.
"""
| # Grab all active items in proper date/time range.
items = SiteNewsItem.current_and_active.all()
|
return {'site_news_items': items}
|
sxjscience/tvm | tests/python/unittest/test_auto_scheduler_loop_state.py | Python | apache-2.0 | 18,652 | 0.000804 | # 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 u... | auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE["threadIdx.y"]
res = s1.parallel(C, j1)
assert res == s1[C].iters[3]
assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE["parallel"]
res = s1.unroll(C, j2)
assert res == s1[C].iters[4]
assert res.annotation == a... | TABLE["unroll"]
res = s1.vectorize(C, j3)
assert res == s1[C].iters[5]
assert res.annotation == auto_scheduler.loop_state.State.ANNOTATION_TRANS_TABLE["vectorize"]
def test_compute_at_root_inline():
dag = auto_scheduler.ComputeDAG(
conv2d_nchw_bn_relu_auto_scheduler_test(
N=1, H=2... |
ericflo/hurricane | setup.py | Python | bsd-3-clause | 766 | 0.001305 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name="hurricane",
version="0.1",
description="Hurricane is a project for easily creating Comet web applications",
classifiers=[
"Progr | amming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Software Development :: Libraries :: Application Frameworks",
"Environment :: Web Environment",
],
keywords="comet,asynchronous,messages,messaging,framework",
author="The Hurricane D... |
url="http://github.com/ericflo/hurricane",
)
|
govarguz/espressopp | src/interaction/VSphereSelf.py | Python | gpl-3.0 | 4,028 | 0.013406 | # Copyright (C) 2012,2013, 2017
# Max Planck Institute for Polymer Research
# Copyright (C) 2008,2009,2010,2011
# Max-Planck-Institute for Polymer Research & Fraunhofer SCAI
#
# This file is part of ESPResSo++.
#
# ESPResSo++ is free software: you can redistribute it and/or modify
# it under the term... | lf, interaction_SelfVSphere
class VSphereSelfLocal(PotentialLocal, interaction_VSphereSelf):
def __init__(self, e1=0.0, a1=1.0, a2=0.0, Nb=1,
cutoff=infinity, shift=0.0):
"""Initialize the local VSphere object."""
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.... | else:
cxxinit(self, interaction_VSphereSelf, e1, a1, a2, Nb, cutoff, shift)
class SelfVSphereLocal(InteractionLocal, interaction_SelfVSphere):
def __init__(self, system, potential):
if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup()... |
loli/medpy | medpy/core/__init__.py | Python | gpl-3.0 | 1,978 | 0.005561 | """
=====================================================================
Core functionalities and shared exception objects (:mod:`medpy.core`)
=====================================================================
.. currentmodule:: medpy.core
This package collect the packages core functionalities, such as an
event Lo... | on 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 General Public License for more details.
#
# You shou... |
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# import all functions/methods/classes into the module
from .logger import Logger
from .exceptions import ArgumentError, FunctionError, SubprocessError, ImageLoadingError, \
DependencyError, ImageSavingError, ImageTypeErro... |
yongshengwang/hue | build/env/lib/python2.7/site-packages/Werkzeug-0.6-py2.7.egg/werkzeug/wrappers.py | Python | apache-2.0 | 63,444 | 0.000347 | # -*- coding: utf-8 -*-
"""
werkzeug.wrappers
~~~~~~~~~~~~~~~~~
The wrappers are simple request and response objects which you can
subclass to do whatever you want them to do. The request object contains
the information transmitted by the client (webbrowser) and the response
object contains al... | rgs)
def _warn_if_string(iterable):
"""Helper for the response objects to check if the iterable returned
to the WSGI server is not a string.
"""
if isinstance(iterable, basestring):
from warnings import Warning
warn(Warning('response iterable was set to a string. This appears '
| 'to work but means that the server will send the '
'data to the client char, by char. This is almost '
'never intended behavior, use response.data to assign '
'strings to the response object.'), stacklevel=2)
class BaseRequest(object):
... |
chop-dbhi/biorepo-portal | accounts/views.py | Python | bsd-2-clause | 4,178 | 0.002393 | from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.views import logout_then_login, LoginView
from django.contrib.auth import authenticate, login
from django.contrib.flatpages.models import FlatPage
from django.views.decora... | tionError:
form = {
'non_field_errors': ['Redis not connected. Unable to create session.']
}
return render(request, template_name, {
'form': form,
'is_IE': is_IE,
| })
except:
raise
login_allowed = throttle_login(request)
if login_allowed:
try:
username = request.POST['email']
password = request.POST['password']
except:
error_message = "Please enter both usernam... |
davidsanchez/CTAtools | Example/ExReadFermiCatalog.py | Python | gpl-3.0 | 2,277 | 0.038208 | # author David Sanchez david.sanchez@lapp.in2p3.fr
# ------ Imports --------------- #
import numpy
from Plot.PlotLibrary import *
from Catalog.ReadFermiCatalog import *
from environ import FERMI_CATALOG_DIR
# ------------------------------ #
#look for this 2FGL source
#source = "2FGL J1015.1+4925"
#source = "1FHL J215... | ead DATA Point 3FHL
em3FHL,ep3FHL,flux3FHL,dflux3FHL = Cat.GetDataPoints('3FHL') #energy in TeV since the user ask for that in the call of Cat
ener3FHL = numpy.sqrt(em3FHL*ep3FHL)
dem3FHL = ener3FHL-e | m3FHL
dep3FHL = ep3FHL-ener3FHL
c3FHL=Cat.ReadPL('3FHL')[2]
dnde3FHL = (-c3FHL+1)*flux3FHL*numpy.power(ener3FHL*1e6,-c3FHL+2)/(numpy.power((ep3FHL*1e6),-c3FHL+1)-numpy.power((em3FHL*1e6),-c3FHL+1))*1.6e-6
ddnde3FHL = dnde3FHL*dflux3FHL/flux3FHL
#plot
import matplotlib.pyplot as plt
plt.loglog()
plt.plot(enerbut, but, ... |
holtwick/pyxer | example/public/directory/__init__.py | Python | mit | 1,078 | 0.003711 | # -*- coding: UTF-8 -*-
from pyxer.base import *
import os
import os.path
@controller
def index():
c.dir = req.params.get("dir", os.path.dirname(__file__))
if os.path.isdir(c.dir):
c.parent = os.path.split(c.dir)[0]
c.files = [(name, os.path.join(c.dir, name), os.path.isdir(os.path.join(c.dir... | , cssclass="source")
c.pretty = highlight(c.code, lexer | , formatter)
c.css = HtmlFormatter().get_style_defs('.highlight')
except:
log.exception("Pygments failed?")
c.pretty = None
c.css = ""
log.debug("Code: %r", c.css)
|
mvondracek/wifimitm | wifimitm/wep.py | Python | mit | 24,467 | 0.003638 | #!/usr/bin/env python3
"""
WEP cracking
Automation of MitM Attack on WiFi Networks
Bachelor's Thesis UIFS FIT VUT
Martin Vondracek
2016
#Implementation notes
- Airodump-ng writes its Text User Interface to stderr, stdout is empty.
- Airodump-ng has difficulties saving PRGA XOR based on some station vendors
`"that's... | utbr.cz'
logger = logging.getLogger(__name__)
class FakeAuthentication(UpdatableProcess):
"""
"The fake authentication attack allows you to perform the two types of WEP authentication (Open System and
Shared Key) plus associate with the access point (AP). This is only useful when you need an associ | ated MAC
address in various aireplay-ng attacks and there is currently no associated client.
It should be noted that the fake authentication attack does NOT generate any ARP packets.
Fake authentication cannot be used to authenticate/associate with WPA/WPA2 Access Points."
`fake_authentication[Aircrack... |
mosarg/gestione_scuola | backend/helpers.py | Python | gpl-3.0 | 972 | 0.005144 | import inspect
class Enum(object):
class __metaclass__(type):
def __init__(self, *args, **kwargs):
self._data = []
for name, value in inspect.getmembers(self):
if not name.startswith('_') and not inspect.ismethod(value):
if isinstance(value, tupl... | self._data.append(data)
setattr(self, name, data[0])
self._hash = dict(self._data)
def __iter__(self):
for value, data in self._da | ta:
yield (value, data)
@classmethod
def get_value(self, key):
return self._hash[key]
class DefinedBackends(Enum):
SAMBA4='samba4'
DJANGO='django'
MOODLE='moodle'
GAPPS='gapps'
|
HappyFaceMonitoring/HappyFace | hf/database.py | Python | apache-2.0 | 1,009 | 0.000993 | # -*- coding: utf-8 -*-
#
# Copyright 2012 Institut für Experimentelle Kernphysik - Karlsruher Institut für Technologie
#
# 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://... | F ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from sqlalchemy import *
import hf
metadata = MetaData()
engine = None
def connect(implicit_execution=False):
config = dict(hf.config.items("database"))
hf.databa... | isconnect():
pass
|
safwanrahman/kitsune | kitsune/questions/tests/test_notifications.py | Python | bsd-3-clause | 15,416 | 0.000259 | import re
from django.contrib.sites.models import Site
from django.core import mail
from django.test.utils import override_settings
import mock
from nose.tools import eq_
from kitsune.questions.events import QuestionReplyEvent, QuestionSolvedEvent, email_utils
from kitsune.questions.models import Question
from kitsu... | ail&utm_source=notification\
#answer-{answer_id}
If this comment is helpful, vote on it:
https://testserver/{locale}questions/{question_id}/vote/{answer_id}\
?utm_campaign=questions-reply&utm_medium=email&helpful=&utm_source=notification
Help other Firefox users by browsing for unsolved questions on testserver:
https... | uestions?filter=unsolved
You might just make someone's day!
--
Unsubscribe from these emails:
https://testserver/{locale}unsubscribe"""
ANSWER_EMAIL = u'Hi {to_user},\n\n' + ANSWER_EMAIL_TO_ANONYMOUS
ANSWER_EMAIL_TO_ASKER = u"""Hi {asker},
{replier} has posted an answer to your question on testserver:
{title}
{re... |
plotly/plotly.py | packages/python/plotly/plotly/validators/heatmap/_colorscale.py | Python | mit | 491 | 0.004073 | import _plotly_utils.basevalidators
class ColorscaleValidator(_plotly_utils.basevalidators.ColorscaleValidator):
def __init__(self, plotly_na | me="colorscale", parent_name="heatmap", **kwargs):
super(ColorscaleValidator, self).__init__(
plotly_name=plotly_name | ,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
implied_edits=kwargs.pop("implied_edits", {"autocolorscale": False}),
**kwargs
)
|
eLBati/website | website_event_register_free_with_sale/models/website.py | Python | agpl-3.0 | 1,450 | 0 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2015 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com)
# Pedro M. Baeza <pedro.baeza@serviciosbaeza.com>
#
# This program is free software: you can redistribute it a... | . 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/>.
#
########### | ###################################################################
from openerp import models, api
class Website(models.Model):
_inherit = 'website'
@api.multi
def sale_get_order(self, force_create=False, code=None,
update_pricelist=None):
res = super(Website, self).sale_g... |
ray-project/ray | dashboard/optional_deps.py | Python | apache-2.0 | 426 | 0 | # Th | ese checks have to come first because aiohttp looks
# for opencensus, too, and raises a different error ot | herwise.
import opencensus # noqa: F401
import prometheus_client # noqa: F401
import aiohttp # noqa: F401
import aiohttp.web # noqa: F401
import aiohttp_cors # noqa: F401
from aiohttp import hdrs # noqa: F401
from aiohttp.typedefs import PathLike # noqa: F401
from aiohttp.web import RouteDef # noqa: F401
|
fairbird/OpenPLI-BlackHole | lib/python/Plugins/SystemPlugins/SoftwareManager/plugin.py | Python | gpl-2.0 | 116,942 | 0.011262 | import os
import time
import cPickle
from Plugins.Plugin import PluginDescriptor
from Screens.Console import Console
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.Ipkg import Ipkg
from Screens.... | 2), size = | (330, 24), flags = RT_HALIGN_LEFT, text = 1), # index 0 is the MenuText,
],
"fonts": [gFont("Regular", 22)],
"itemHeight": 25
}
... |
rowhit/h2o-2 | py/testdir_single_jvm/test_parse_specific_case4.py | Python | apache-2.0 | 3,961 | 0.015148 | import unittest, random, sys, time, os
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i
import codecs, unicodedata
print "create some specific small datasets with exp row/col combinations"
print "This injects the full set of single byte UTF8 in a col, except for some special h2o chars"
... | expected col count
tryList = []
for unicodeNum in toDoList:
unicodeSymbol = unichr(unicodeNum)
tryList.append(
((
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b... | unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
'a,b,c,d' + unicodeSymbol + 's,n\n'
), 10, 5, [0,0,0,0,0], ['Enum', 'Enum', 'Enum', 'Enum', 'Enum'], unicodeNum)
)
def write_syn_dataset(csvPat... |
petrutlucian94/nova | nova/objects/migration.py | Python | apache-2.0 | 4,655 | 0 | # Copyright 2013 IBM Corp.
#
# 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... | elds.StringField(nullable=True),
'dest_host': fields.StringField(nullable=True),
'old_instance_type_id': fields.IntegerField(nullable=True),
'new_instance_type_id': fields.IntegerField(nullable=True),
'instance_uuid': fields.StringField(nullable=True),
'status': fields.StringFiel... | elds:
migration[key] = db_migration[key]
migration._context = context
migration.obj_reset_changes()
return migration
@base.remotable_classmethod
def get_by_id(cls, context, migration_id):
db_migration = db.migration_get(context, migration_id)
return cls._from... |
pllim/ginga | ginga/rv/plugins/Header.py | Python | bsd-3-clause | 8,904 | 0 | # This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
"""
The ``Header`` plugin provides a listing of the metadata associated with the
image.
**Plugin Type: Global**
``Header`` is a global plugin. Only one instance can be opened.
**Usage**
The ``Header`` plugin... | :
keys.sort()
for key in keys:
card = header.get_card(key)
tree_dict[key] = card
table.set_tree(tree_dict)
# Resize column widths
n_rows = len(tree_dict)
if n_rows < self.settings.get('max_rows_for_col_resize', 5000):
| table.set_optimal_column_widths()
self.logger.debug("Resized columns for {0} row(s)".format(n_rows))
self.logger.debug("setting header done ({0})".format(is_sorted))
self._image = image
def add_channel(self, viewer, channel):
if not self.gui_up:
return
... |
alirizakeles/zato | code/zato-server/src/zato/server/connection/http_soap/url_data.py | Python | gpl-3.0 | 63,529 | 0.002944 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2012 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import logging
from datetime import datetime
from hashlib import sha256
... | \
OAuthSignatureMethod_PLAINTEXT, OAuthToken
# regex
from regex import compile as re_compile
# sec-wall
from secwall.server import on_basic_auth, on_wsse_pwd
from secwall.wsse import WSSE
# SortedContainers
from sortedcontainers import SortedListWithKey
# Zato
from zato.bunch import Bunch
from zato.common impo... | , VAULT as VAULT_BROKER_MSG
from zato.common.dispatch import dispatcher
from zato.common.util import parse_tls_channel_security_definition
from zato.server.connection.http_soap import Forbidden, Unauthorized
from zato.server.jwt import JWT
logger = logging.getLogger(__name__)
_internal_url_path_indicator = '{}/zato/'... |
PetePriority/home-assistant | homeassistant/components/mqtt/cover.py | Python | apache-2.0 | 20,402 | 0 | """
Support for MQTT cover devices.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/cover.mqtt/
"""
import logging
import voluptuous as vol
from homeassistant.components import cover, mqtt
from homeassistant.components.cover import (
ATTR_POSITION, ... | (config, config_entry, discovery_hash)])
class MqttCover(MqttAttributes, MqttAvailability, MqttDiscoveryUpdate, |
MqttEntityDeviceInfo, CoverDevice):
"""Representation of a cover that can be controlled using MQTT."""
def __init__(self, config, config_entry, discovery_hash):
"""Initialize the cover."""
self._unique_id = config.get(CONF_UNIQUE_ID)
self._position = None
self._... |
ms-azure-cloudbroker/cloudbridge | cloudbridge/cloud/providers/azure/integration_test/helpers.py | Python | mit | 7,555 | 0.000132 | import functools
import os
import sys
import unittest
from contextlib import contextmanager
from cloudbridge.cloud.factory import CloudProviderFactory
from cloudbridge.cloud.interfaces import InstanceState
from cloudbridge.cloud.interfaces import TestMockHelperMixin
from six import reraise
def parse_bool(val):
... | get(key)
elif "OpenStackCloudProvider" in provider. | name:
return TEST_DATA_CONFIG.get("OpenStackCloudProvider").get(key)
elif "AzureCloudProvider" in provider.name:
return TEST_DATA_CONFIG.get("AzureCloudProvider").get(key)
return None
def create_test_network(provider, name):
"""
Create a network with one subnet, returning the network a... |
nop33/indico | indico/modules/rb/models/locations.py | Python | gpl-3.0 | 5,228 | 0.000765 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 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; either version 3 of the
# License, or (a... | oin=(id == Aspect.location_id),
lazy='dynamic',
)
default_aspect = db.relationship(
'Aspect',
primaryjoin=default_aspect_id == Aspect.id,
post_update=True,
)
rooms = db.relationship(
'Room',
backref='location',
cascade='all, delete-orphan',
... | tionship(
'RoomAttribute',
backref='location',
cascade='all, delete-orphan',
lazy='dynamic'
)
equipment_types = db.relationship(
'EquipmentType',
backref='location',
lazy='dynamic',
cascade='all, delete-orphan'
)
holidays = db.relationshi... |
asedunov/intellij-community | python/testData/inspections/PyInitNewSignatureInspection/test.py | Python | apache-2.0 | 780 | 0.05 | class B(object):
def __init__<warning descr="Signature is not compatible to __new__">(self)</warning>: # error
pass
def __new__<warning descr="Signature is not compatible to __init__">(cls, x, y)</warning>: # error
pass |
class A1(B):
pass
class A2(A1):
def __new__<warning descr="Signature is not compatible to __init__">(cls, a)</warning>: # error
pass
class A3(A2):
def __new__(cls, *a): # ok
pass
class C(object):
def __new__(cls, *args, **kwargs):
pass
class C1(C):
def __init__(s... |
class SeoA(SeoB):
pass
import enum
# PY-24749
class Planet(enum.Enum):
EARTH = (5.976e+24, 6.37814e6)
def __init__(self, mass, radius): # OK
pass |
muzixing/python_challenge | l3_match.py | Python | apache-2.0 | 515 | 0.003883 | import re
import string_example
"""
O | ne small letter,
surrounded by EXACTLY three big bodyguards on each of its sides.
"""
class StingMatch(object):
"""String match " | ""
def __init__(self):
self.msg = string_example.string
def match(self):
Pattern = '[^A-Z][A-Z]{3}[a-z][A-Z]{3}[^A-Z]'
result = re.findall(Pattern, self.msg)
print (''.join(x[4:5] for x in result))
def main():
test = StingMatch()
test.match()
if __name__ == '__main__... |
Tithen-Firion/youtube-dl | youtube_dl/extractor/xtube.py | Python | unlicense | 5,972 | 0.00067 | from __future__ import unicode_literals
import itertools
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
js_to_json,
orderedSet,
parse_duration,
sanitized_Request,
str_to_int,
)
class XTubeIE(InfoExtractor):
_VALID_URL = r'''(?x)
(?:... | video_id,
'display_id': display_id,
'title': title,
'description': description,
'uploader': uploader,
'duration': duration,
'view_count': view_count,
| 'comment_count': comment_count,
'age_limit': 18,
'formats': formats,
}
class XTubeUserIE(InfoExtractor):
IE_DESC = 'XTube user profile'
_VALID_URL = r'https?://(?:www\.)?xtube\.com/profile/(?P<id>[^/]+-\d+)'
_TEST = {
'url': 'http://www.xtube.com/profile/greensho... |
GAMPTeam/vampyre | vampyre/estim/gaussian.py | Python | mit | 6,954 | 0.012367 | """
gaussian.py: Classes for Gaussian estimation
"""
from __future__ import division
from __future__ import print_function
import numpy as np
from vampyre.common.utils import get_var_shape, repeat_axes, repeat_sum
from vampyre.common.utils import VpException
from vampyre.estim.base import BaseEst
class GaussEst(Base... | axes on which the variance is averaged.
(default=`all` indicating all axes are averaged, meaning that
the variance is a scalar)
:param zmean_axes: axis on which the prior mean is
repeated. (default=`all` indicating prior mean is repeated
on all axes, meaning that the prior mean... | on. This is used for the cost computation.
:param Boolean tune_zvar: indicates if :code:`zvar` is to be
estimated via EM
:param Boolean tune_rvar: indicates if the proximal variance
:code:`rvar` is estimated.
"""
def __init__(self, zmean, zvar, shape,name=None,\
va... |
chriskuehl/pgctl | tests/conftest.py | Python | mit | 653 | 0 | # -*- coding: utf-8 -*-
# p | ylint:disable=redefined-outer-name,unused-argument
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import shutil
from pytest | import yield_fixture as fixture
TOP = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@fixture
def in_example_dir(tmpdir, service_name):
template_dir = os.path.join(TOP, 'tests/examples', service_name)
tmpdir = tmpdir.join(service_name)
shutil.copytree(template_dir, tmpdir.strpath)
with ... |
jbloom/mapmuts | src/stats.py | Python | gpl-3.0 | 1,472 | 0.004755 | """Performs statistics operations for ``mapmuts`` package.
Written by Jesse Bloom.
List of functions
----------------------
`Median` : returns the median of a list of numbers.
`Mean` : returns the mean of a list of numbers.
Documentation for individual functions
----------------------------------------
Documentat... | e two middle entries
med = xlist[n / 2] + xlist[n / 2 - | 1]
med = float(med) / 2.0
return med
else: # odd length list, get middle entry
return xlist[n / 2]
def Mean(numlist):
"""Returns the mean of a list of numbers.
`numlist` : a list of numbers.
Example:
>>> print "%.3f" % Mean([1.0, 1.5, 3])
1.833
"""
... |
anscii/django-modelnotice | modelnotice/default_settings.py | Python | bsd-2-clause | 60 | 0.033333 | #from django.conf import settings
NOTICE_FROM_AN | ONYMOUS = | 1 |
sh01/gonium | src/dns_resolving/stub.py | Python | gpl-2.0 | 23,265 | 0.024973 | #!/usr/bin/env python
#Copyright 2007,2008,2012 Sebastian Hagen
# This file is part of gonium.
#
# gonium 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) ... | .type_validate(rtype)
self.name = name
self.type = rtype
self.rclass = rclass |
self.ttl = ttl
self.rdata = rdata
@classmethod
def build_from_binstream(cls, binstream):
name = DomainName.build_from_binstream(binstream)
tctl_str = binstream.read(10)
if (len(tctl_str) < 10):
raise ValueError('Insufficient data in binstream')
(rtype, rcla... |
rimbalinux/MSISDNArea | djangoappengine/db/creation.py | Python | bsd-3-clause | 1,719 | 0.002909 | from .db_settings import get_model_indexes
from djangotoolbox.db.creation import NonrelDatabaseCreation
class StringType(object):
def __init__(self, internal_type):
self.internal_type = internal_type
def __mod__(self, field):
indexes = get_model_indexes(field['model'])
if fiel... | ue
self.connection.flush()
def destroy_test_db(self, *args, **kw):
"""Destroys the test datastore files."""
from .base import destro | y_datastore, get_test_datastore_paths
destroy_datastore(*get_test_datastore_paths())
|
lichuan261/wuand | XX-Net/goagent/3.1.49/local/openssl_wrap.py | Python | gpl-2.0 | 4,813 | 0.002701 |
# OpenSSL is more stable then ssl
# but OpenSSL is different then ssl, so need a wrapper
import sys
import os
import OpenSSL
SSLError = OpenSSL.SSL.WantReadError
import select
import time
import socket
import logging
ssl_version = ''
class SSLConnection(object):
"""OpenSSL Connection Wrapper"""
def __ini... | ssl_version = "SSLv23"
if sys.platform == "darwin":
ssl_version = "TLSv1"
logging.info("SSL use version:%s", ssl_version)
protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version)
ssl_context = OpenSSL.SSL.Context(protocol_version)
if ... | t.load_verify_locations(os.path.abspath(ca_certs))
ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok)
else:
ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok)
ssl_context.set_cipher_list(':'.join(cipher_suites))
return ssl_c... |
blueboxgroup/keystone | keystone/tests/test_revoke.py | Python | apache-2.0 | 24,633 | 0.000041 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | w.return_value = now
# Build a token and validate it. This will seed the cache for the
# future 'synchronize' call.
token_values = _sample_token_values()
user_id = _new_id()
self.revoke_api.revoke_by_user(user_id)
token_values['user_id'] = user_id
self.assertRai... | exception.TokenNotFound,
self.revoke_api.check_token,
token_values)
# Move our clock forward by 2h, build a new token and validate it.
# 'synchronize' should now be exercised and remove old expired events
mock_utcnow.return_value = now_plus_2h... |
roadhead/satchmo | satchmo/shipping/tests.py | Python | bsd-3-clause | 2,174 | 0.00414 | from django.db import models
from django.test import TestCase
from satchmo import caching
from satchmo.configuration import config_value
from satchmo.product.models import *
from satchmo.shipping.modules.flat.shipper import Shipper as flat
from satchmo.shipping.modules.per.shipper import Shipper as per
from satchmo.sho... | btype1, 'is_shippable', True))
self.assert_(self.cartitem1.is_shippable)
self.assert_(self.product1.is_shippable)
self.assert_(self.cart1.is_shippable)
self.assertEqual(flat | (self.cart1, None).cost(), Decimal("4.00"))
self.assertEqual(per(self.cart1, None).cost(), Decimal("12.00"))
|
MagicStack/httptools | httptools/parser/errors.py | Python | mit | 566 | 0 | __all__ = ('HttpParserError',
'HttpParserCallbackErr | or',
'HttpParserInvalidStatusError',
'HttpParserInvalidMethodError',
'HttpParserInvalidURLError',
'HttpParserUpgrade')
class HttpParserError(Exception):
pass
class HttpPa | rserCallbackError(HttpParserError):
pass
class HttpParserInvalidStatusError(HttpParserError):
pass
class HttpParserInvalidMethodError(HttpParserError):
pass
class HttpParserInvalidURLError(HttpParserError):
pass
class HttpParserUpgrade(Exception):
pass
|
rubik/poly | setup.py | Python | mit | 867 | 0.001153 | from setuptools import setup
setup(name='poly',
| version='0.1',
description='A Python Polynomial Library',
author='Michele Lacchia',
author | _email='michelelacchia@gmail.com',
license='MIT',
url='http://poly.readthedocs.org/',
download_url='http://github.com/rubik/poly/downloads/',
packages=['poly'],
platforms='any',
classifiers=['Topic :: Scientific/Engineering :: Mathematics',
'Intended Audience :: Sc... |
sid88in/incubator-airflow | airflow/migrations/versions/947454bf1dff_add_ti_job_id_index.py | Python | apache-2.0 | 1,261 | 0 | # -*- coding: 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
# "License"); you may not use this file exce... | e.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 limit... |
jtushman/state_machine | docs/conf.py | Python | mit | 8,221 | 0.006204 | # -*- coding: utf-8 -*-
#
# state_machine documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 3 08:46:47 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | esses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manua | l page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'state_machine', u'state_machine Documentation',
[u'Jonathan Tushman'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------... |
cnHackintosh/theHarvester | discovery/dnssearch-threads.py | Python | gpl-2.0 | 3,642 | 0.002197 | import IPy
import DNS
import string
import socket
import sys
class dns_reverse():
def __init__(self, range, verbose=True):
self.range = range
self.iplist = ''
self.results = []
sel | f.verbose = verbose
try:
DNS.ParseResolvConf("/etc/resolv.conf")
nameserver = DNS.defaults['server'][0]
except:
print "Error in DNS resolvers"
sys.exit()
def run(self, host):
a = string.split(host, '.')
a.reverse()
b = string.j... | bose:
ESC = chr(27)
sys.stdout.write(ESC + '[2K' + ESC + '[G')
sys.stdout.write("\r" + host)
sys.stdout.flush()
try:
name = DNS.Base.DnsRequest(b, qtype='ptr').req().answers[0]['data']
return host + ":" + name
except:
pa... |
strikedebt/debtcollective-web | be/proj/collectives/migrations/0003_auto__add_field_collective_slug__add_field_action_slug.py | Python | gpl-2.0 | 5,792 | 0.007424 | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Collective.slug'
db.add_column(u'collectives_collective',... | 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {... | del', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),... |
AustereCuriosity/astropy | astropy/io/fits/util.py | Python | bsd-3-clause | 27,553 | 0.000254 | # Licensed under a 3-clause BSD style license - see PYFITS.rst
from __future__ import division
import gzip
import itertools
import io
import mmap
import operator
import os
import platform
import signal
import string
import sys
import tempfile
import textwrap
import threading
import warnings
import weakref
from contex... | D
E
C
>>> # get ALL (new-style) classes currently defined
>>> [cls.__name__ for cls in itersubclasses(object)]
[...'tuple', ...'type', ...]
From http://code.activestate.com/recipes/576949/
"""
if not isinstance(cls, type):
raise TypeError('itersubclasses must be called with '
... | 'new-style classes, not {:.100r}'.format(cls))
if _seen is None:
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError: # fails only when cls is type
subs = cls.__subclasses__(cls)
for sub in sorted(subs, key=operator.attrgetter('__name__')):
... |
KanoComputing/kano-feedback | kano_feedback/RadioInput.py | Python | gpl-2.0 | 1,658 | 0 | #!/usr/bin/env python
# RadioInput.py
#
# Copyright (C) 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPL v2
#
from gi.repository import Gtk, GObject
class RadioInput(Gtk.Box):
__gsignals__ = {
'radio-changed': (GObject.SIGNAL_RUN_FIRST, None, ())
}
def __init_... | es.pop(0)
for v in values:
radio = Gtk.RadioButton.new_with_l | abel_from_widget(
self._first_radio, v
)
self.pack_start(radio, False, False, 10)
buttons.append(radio)
def _emit_value_changed(self, widget, value):
self.emit('radio-changed')
def get_selected_text(self):
group = self._first_radio.get_group(... |
ciudadanointeligente/write-it | nuntium/middleware.py | Python | gpl-3.0 | 1,275 | 0.000784 | from collections import OrderedDict
from django.middleware.locale import LocaleMiddleware
from django.utils import translation
from django.conf import settings
from instance.mode | ls import WriteItInstanceConfig
def get_language_from_request(request, check_path=False):
if check_path:
lang_code = translation.get_language_from_path(request.path_info)
if lang_code is not None:
return lang_code
try:
lang_code = Writ | eItInstanceConfig.objects.get(writeitinstance__slug=request.subdomain).default_language
except WriteItInstanceConfig.DoesNotExist:
lang_code = None
if lang_code is not None and translation.check_for_language(lang_code):
return lang_code
# Call with check_path False as we've already done th... |
totokaka/Powerfulperms-web | backend/setup.py | Python | gpl-3.0 | 347 | 0 | from setuptools import setup, find_packag | es
setup(
name="backend",
packages=find_packages(),
include_package_data=True,
install_requires=[
'flask',
'flask-restful',
'flask-cors',
'mysqlclient',
'flask-sqlalchemy',
'passlib',
'flask-httpauth',
| 'itsdangerous'
]
)
|
simonmonk/make_action | python/experiments/microstepping.py | Python | mit | 1,397 | 0.010021 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
step_pin = 24
dir_pin = 25
ms1_pin = 23
ms2_pin = 18
GPIO.setup(step_pin, GPIO.OUT)
GPIO.setup(dir_pin, GPIO.OUT)
GPIO.setup(ms1_pin, GPIO.OUT)
GPIO.setup(ms2_pin, GPIO.OUT)
period = 0.02
def step(steps, direction, period): # (1)
GPIO.output(dir_pin, di... | to end
parameter = int(parameter_str)
if command[0] == 'p':
period = parameter / 1000.0
elif command[0] == 'm':
step_mode(pa | rameter)
elif command[0] == 'f':
step(parameter, True, period)
elif command[0] == 'r':
step(parameter, False, period)
finally:
print('Cleaning up')
GPIO.cleanup() |
pozdnyakov/chromium-crosswalk | native_client_sdk/src/build_tools/buildbot_run.py | Python | bsd-3-clause | 2,125 | 0.010353 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Main entry point for the NaCl SDK buildbot.
The entry point used to be build_sdk.py itself, but we want
to be able to simplify ... | ffic through the proxy to
# localhost (we get 504 gateway errors), so we clear it here.
env = dict(os.environ)
if 'http_proxy' in env:
del env['http_proxy']
Run([sys.executable, 'test_all.py'], env=env, cwd=SDK_SRC_DIR)
def StepBuildSDK(args):
is_win = getos.GetPlatform() == 'win'
# Windows has a pa... | characters, after joining cwd with a
# relative path. Use subst before building to keep the path lengths short.
if is_win:
subst_drive = 'S:'
root_dir = os.path.dirname(SRC_DIR)
new_root_dir = subst_drive + '\\'
subprocess.check_call(['subst', subst_drive, root_dir])
new_script_dir = os.path.jo... |
pombredanne/drf-nested-serializer | nested_serializers/validators.py | Python | bsd-2-clause | 288 | 0.003472 | from rest | _framework.serializers import ValidationError
from six import string_types
def has_id_field(value):
if value is None:
raise ValidationError('Nested object must contain an `id` attribute.')
if isinstance(value | , string_types):
raise ValidationError(value)
|
doraemonext/wechat-platform | wechat_platform/system/rule_match/models.py | Python | bsd-2-clause | 2,385 | 0.000932 | # -*- coding: utf-8 -*-
import logging
from django.db import models
from system.official_account.models import OfficialAccount
from system.rule.models import Rule
logger_rule_match = logging.getLogger(__name__)
class RuleMatchManager(models.Manager):
"""
微信规则回复表 Manager
"""
def add(self, rule, plu... | 启用', default=True)
objects = models.Manager()
manager = RuleMatchManager()
class Meta:
verbose_name = u'微信规则匹配表'
verbose_name | _plural = u'微信规则匹配表'
db_table = 'wechat_rule_match'
def __unicode__(self):
return self.plugin_iden
|
Ifsttar/I-Simpa | src/python_bindings/samples/spps_conversion_resultats.py | Python | gpl-3.0 | 2,657 | 0.006398 | #----------------------------------------------------------------------
# I-SIMPA (http://i-simpa.ifsttar.fr). This file is part of I-SIMPA.
#
# I-SIMPA is a GUI for 3D numerical sound propagation modelling dedicated
# to scientific acoustic simulations.
# Copyright (C) 2007-2014 - IFSTTAR - Judicael Picaut, Nicol... |
# I-SIMPA is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# I-SIMPA is distributed in the hope that it will be useful,
# but ... | mplied 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor... |
stosdev/nawia2014 | ldapdb/__init__.py | Python | gpl-3.0 | 2,247 | 0.000445 | # -*- coding: utf-8 -*-
#
# django-ldapdb
# Copyright (c) 2009-2011, Bolloré telecom
# Copyright (c) 2013, Jeremy Lainé
# All rights reserved.
#
# See AUTHORS file for a full list of contributors.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the foll... | ed with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CO... | BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF... |
bahadley/mgc | scripts/ex-3/heartBeat.py | Python | mit | 2,789 | 0.003586 | #!/usr/bin/python
from time import sleep
from signal import SIGINT
from mininet.net import Mininet
from mininet.node import Controller, OVSKernelAP
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import setLogLevel
def topology():
"Create a network."
net = Mininet(controller=Cont... | po2.send_signal( SIGINT )
po3.send_signal( SIGINT )
print "*** Ending test..."
print "*** Running CLI | "
CLI(net)
print "*** Stopping network"
net.stop()
if __name__ == '__main__':
setLogLevel('info')
topology()
|
davidsminor/gaffer | python/GafferSceneUI/__init__.py | Python | bsd-3-clause | 3,021 | 0.002317 | ##########################################################################
#
# Copyright (c) 2012, John Haddon. All rights reserved.
# Copyright (c) 2012-2014, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provi... | prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COP | YRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WH... |
lahwaacz/qutebrowser | qutebrowser/misc/sessions.py | Python | gpl-3.0 | 19,672 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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 S... | s currently active.
"""
data = {'history': []}
if active:
data['active'] = True
for idx, item in enumerate(tab.history):
qtutils.ensure_valid(item)
item_data = self._save_tab_item(tab, idx, item)
data['history'].append(item_data)
| return data
def _save_all(self, *, only_window=None, with_private=False):
"""Get a dict with data for all windows/tabs."""
data = {'windows': []}
if only_window is not None:
winlist = [only_window]
else:
winlist = objreg.window_registry
for win_id in... |
randayh/umaro | contrib/misc/linearize.py | Python | mit | 3,196 | 0.035044 | #!/usr/bin/python
#
# linearize.py: Construct a linear, no-fork, best version of the blockchain.
#
#
# Copyright (c) 2013 The Umaro developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import json
import struct
import... | 1000) == 0:
sys.stdout.write("Wrote block " + str(height) + "\n")
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: linearize.py CONFIG-FILE"
sys.exit(1)
f = open(sys.argv[1])
for line in f:
# skip comment lines
m = re.search('^\s*#', line)
if m:
continue |
# parse key=value lines
m = re.search('^(\w+)\s*=\s*(\S.*)$', line)
if m is None:
continue
settings[m.group(1)] = m.group(2)
f.close()
if 'netmagic' not in settings:
settings['netmagic'] = 'f9beb4d9'
if 'output' not in settings:
settings['output'] = 'bootstrap.dat'
if 'host' not in settings:
set... |
oisinmulvihill/nozama-cloudsearch | nozama/cloudsearch/service/environ_settings.py | Python | bsd-3-clause | 599 | 0 | import os
def get(var, default, type_=None):
"""Return a function to recover latest env variable contents."""
def _env_getter():
"""Recover the latest setting from | the environment."""
val = os.environ.get(var, default)
if type_:
val = type_(val)
return val
return _env_getter
MONGO_DBNAME = get('MONGO_DBNAME', 'nozama-cloudsearch')
MONGO_HOST = get(' | MONGO_HOST', 'localhost')
MONGO_PORT = get('MONGO_PORT', 27017, int)
ELASTICSEARCH_HOST = get('ELASTICSEARCH_HOST', 'localhost')
ELASTICSEARCH_PORT = get('ELASTICSEARCH_PORT', 9200, int)
|
lsp84ch83/PyText | PyDj/guest/sign/urls.py | Python | gpl-3.0 | 1,121 | 0.022302 | from django.urls import path
from sign import | views_if,views_if_sec
app_name = 'sign'
urlpatterns = [
path('add_event/', views_if.add_event, name='add_event'),
path('add_guest/', views_if.add_guest, name='add_guest'),
path('get_event_list/', views_if.get_event_list, name = 'get_event_list'),
path('get_guest_list/', views_if.get_guest_lis | t, name = 'get_guest_list'),
path('user_sign/', views_if.user_sign, name = 'user_sign'),
path('sec_get_event_list/', views_if_sec.get_event_list, name='get_event_list'),
path('sec_add_event/', views_if_sec.add_event, name='add_event'),
path('sec_get_guest_list/', views_if_sec.get_guest_list, name='get_guest_... |
zarelit/django-localflavor | localflavor/sk/forms.py | Python | bsd-3-clause | 1,546 | 0.000647 | """
Slovak-specific form helpers
"""
from __future__ import absolute_import, unicode_literals
from django.forms.fields import Select, RegexField
from django.utils.translation import ugettext_lazy as _
from .sk_districts import DISTRICT_CHOICES
from .sk_regions import REGION_CHOICES
class SKRegio | nSelect(Select):
"""
A select widget widget with list of Slovak regions as choices.
"""
def __init__(self, attrs=None):
super(SKRegionSelect, self).__init__(attrs, choices=REGION_CHOICES)
class SKDistrictSelect(Select):
"""
A select widget with list of Slovak districts as choices.
... | _CHOICES)
class SKPostalCodeField(RegexField):
"""
A form field that validates its input as Slovak postal code.
Valid form is XXXXX or XXX XX, where X represents integer.
"""
default_error_messages = {
'invalid': _('Enter a postal code in the format XXXXX or XXX XX.'),
}
def __ini... |
GNOME/nanny | client/common/src/Categories.py | Python | gpl-2.0 | 12,609 | 0.002141 | #!/usr/bin/env python
# Copyright (C) 2009,2010 Junta de Andalucia
#
# Authors:
# Roberto Majadas <roberto.majadas at openshine.com>
# Cesar Garcia Tapia <cesar.garcia.tapia at openshine.com>
# Luis de Bethencourt <luibg at openshine.com>
# Pablo Vieytes <pvieytes at openshine.com>
#
# This program is free so... | ng")),
# To translators : This string is a category name or a category | description
"frencheducation": (_("frencheducation"), _("Sites to do with french education")),
# To translators : This string is a category name or a category description
"gambling": (_("gambling"), _("Gambling sites including stocks and shares")),
# To translators : This string is a category name or a... |
fvigo/minemeld-okta | mmokta/node.py | Python | apache-2.0 | 4,293 | 0.003727 | import logging
import json
import yaml
import os
from mmokta import okta as okta
from minemeld.ft.actorbase import ActorBaseFT
import minemeld.ft.base as base
LOG = logging.getLogger(__name__)
# Okta Output Node for MineMeld
class OktaOutput(ActorBaseFT):
def configure(self):
super(OktaOutp... | clusively with user-id indicators
if(value['type'] != 'user-id') | :
LOG.debug('{} - Received Indicator of type {}, expecting user-id, skipping'.format(self.name, value['type']))
return
# Lookup user
user = okta.lookup_user(self.oktatarget, indicator)
# Remove user from Group
if self.quarantine_group is not None:
... |
stefan0722/gitflowv2 | script/python/r02_finish-release-branch.py | Python | apache-2.0 | 1,179 | 0.005089 | #!/usr/bin/python
import webbrowser
from helper import gitflow
git_flow_func = gitflow.GitFunctions()
print("\nAv | ailable local release branches: \n")
git_flow_func.show_branch_state("release")
release_version = input("Please enter name of release branch: release-")
release_branch = "release-" + release_version
git_flow_func.get_clean_branch_state(release_branch)
print("\n-- Step A: Change local repository to master branch -... | rrent version of master from GitHub --")
git_flow_func.pull_branch("master")
print("\n-- Step C: Change local repository to " + release_branch + " branch --")
git_flow_func.checkout_branch(release_branch)
print("\n-- Step D: Merge changes from master to " + release_branch +" branch --")
git_flow_func.merge_br... |
deepmind/dm_control | dm_control/_render/executor/render_executor.py | Python | apache-2.0 | 6,153 | 0.011377 | # Copyright 2017-2018 The dm_control Authors.
#
# 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... | endering calls on the same thread. This is provided to minimize
thread-switching overhead.
In a multithreaded setting, `Offloading | RenderExecutor` maintains a separate
dedicated thread on which the OpenGL context is created and made current. All
subsequent rendering calls are then offloaded onto this dedicated thread.
"""
import abc
import collections
from concurrent import futures
import contextlib
import threading
_NOT_IN_CONTEXT = 'Cannot be... |
zhangmingkai4315/Flask-Web-App | app/models.py | Python | mit | 628 | 0.030255 |
from flask.ext.sqlalchemy import SQLAlchemy
from . import db
class Role(db.Model):
__tablename__='roles'
id=db.Column(db.Integer,primary_key=True)
name=db.Column(db.String(64),unique=True)
users=db.relationship('User',backref='role')
def __repr__(self):
return '<Role>{}</Role>'.format(self.... | les.id'))
username=db.Column(db.String(64),unique=True,index=True)
def __repr__( | self):
return '<Username>{}</Username>'.format(self.username)
|
lightcode/OVM | tests/test_resource_loader.py | Python | mit | 1,714 | 0 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
import os
from ovm.exceptions import OVMError
from ovm.resources.resources import Resources
ROOT = os.path.dirname(os.path.realpath(__file__))
CONFIG = | os.path.join(ROOT, 'files', 'resources.yml')
class TestResourceLoader(unittest.TestCase):
def test_to_ | load_storage(self):
"""get_storage_pools should return 2 pools"""
Resources(CONFIG)
self.assertEqual(len(Resources.get_storage_pools()), 2)
def test_to_load_storage_several_times(self):
"""get_storage_pools should return 2 pools"""
Resources(CONFIG)
Resources.get_sto... |
sgoudelis/mybitbank | mybitbank/apps/login/forms.py | Python | mit | 2,092 | 0.00239 | """
The MIT License (MIT)
Copyright (c) 2016 Stratos Goudelis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, me... | ata.get('pas | sword', "")
# remember = cleaned_data.get('remember', False)
# next_url = cleaned_data.get('next_url', "")
return cleaned_data
|
GitHubRGI/geopackage-python | Tools/generate_wms_aligned_relative.py | Python | gpl-3.0 | 1,363 | 0.003668 | #!/usr/bin/python
# Author: Steven D. Lander, RGi
# March 18, 2016
# This script assumes world-referenced tile coordinates
def gen_bbox(bbox, tiles):
if tiles == 1:
return ["&BBOX={},{},{},{}".format(bbox[0],
bbox[1], bbox[2], bbox[3])]
else:
sub_count = tiles / 4
min_x, m... | + \
gen_bbox(bbox_lr, sub_count)
base_url = "http://localhost/GPEP/Hybrid-Performance-Test/service?"
base_url += "VERSION=1.3.0&REQUEST=GetMap&CRS=CRS:84&WIDTH=256&HEIGHT=256"
base_url += "&LAYERS=2&STYLES=,,,,&EXCEPTIONS=xml&FORMAT=image/png"
base_url += "&BGCOLOR=0xFEFFFF&TRANSPARENT=TRUE"
z_min = 0
... | = []
for task in tasks:
for entry in gen_bbox(bbox, task):
print(base_url + entry)
|
tempbottle/ironpython3 | Tests/interop/net/property/__init__.py | Python | apache-2.0 | 1,852 | 0.0054 | #####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of th... | - Incorrect argument number, type
- (python) Overloaded index properties in general: foo['xyz'], foo['xyz', 'def'], (foo[] ?)
* repeating from the derived class or its instance
* (python) __set__/__get__...
* Negative scenario: property as By-ref argument
* Ab | le to call the actual underlying methods
* Other operations against them
- Call, dot,
''' |
hryamzik/ansible | lib/ansible/modules/cloud/ovirt/ovirt_affinity_label_facts.py | Python | gpl-3.0 | 5,875 | 0.002383 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# 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 of the License, or
#... | s not found." % module.params['vm'])
| labels.extend([
label
for label in all_labels
for vm in connection.follow_link(label.vms)
if fnmatch.fnmatch(vms_service.service(vm.id).get().name, module.params['vm'])
])
if not (module.params['vm'] or module.params['host'] ... |
ArtezGDA/text-IO | Esmee/Collections/Array/array1esmee.py | Python | mit | 1,099 | 0.036397 | >>> couses = ['Photography', 'Design Philosophy', 'Media Theory', 'Design Research', 'Digital Media', 'Computer Skills', 'Graphic Design', 'Typography']
>>> print len | (couses)
8
>>> couses.append(Media Theory lecture series)
File "<stdin>", line 1
couses.append(Media Theory lecture series)
| ^
SyntaxError: invalid syntax
>>> couses.append(9)
>>> 9=[Media Theory lecture series]
File "<stdin>", line 1
9=[Media Theory lecture series]
^
SyntaxError: invalid syntax
>>> couses.append(Media Theory lecture series)
File "<stdin>", line 1
couses.append(Media Th... |
larssima/AmiJukeBoxRemote | AmiJukeBoxRemote/gui/RaspberryPi/playjbd.py | Python | mit | 869 | 0.057537 | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
pin = 17
first = 1
gap = 1
second = 1
def play(nra):
# D Letter
firstCount = 5
secondCount = nra
pin = 17
first = 1
gap = 1
second = 1
firstSleepTimeOn = 0.02
firstSleepTimeOff = 0.04
secondSleepTimeOn = 0.02
secondSleepTimeOff = 0.04
gapSleepT... | GPIO.LOW)
time.sleep( | firstSleepTimeOn);
GPIO.output(pin, GPIO.HIGH)
time.sleep(firstSleepTimeOff);
# wait for second string
if (gap==1):
GPIO.output(pin, GPIO.LOW)
time.sleep(gapSleepTime);
if (second == 1):
for x in xrange(secondCount):
GPIO.output(pin, GPIO.LOW)
time.sleep(secondSleepTimeOn);
GPIO.output(pin, G... |
clchiou/garage | py/g1/http/http1_servers/setup.py | Python | mit | 348 | 0 | from setuptools import setup
setup(
name='g1.http.http1_servers',
packages=[
'g1.http.http1_servers',
],
install_requires=[
'g1.asyncs.bases',
'g1.bases',
],
ext | ras_require={
'parts': [
'g1.apps',
'g1.networks.servers[parts]',
],
},
| zip_safe=False,
)
|
davidastephens/pandas-accounting | pandas_accounting/core/tests/test_core.py | Python | mit | 439 | 0.002278 | """
Tests for core and utility classes
"""
import unittest
from pandas_accounting import Company, Subsidiary
class TestCompany(unittest.TestCase):
def setUp(self):
self.C = Company(shares=100)
def test_com | pany_shares(self):
self.assertEqual(self.C.shares, 100)
class TestSubsidiary(unittest.TestCase):
def setUp(self):
self.S = Subs | idiary()
def test_sub(self):
self.assertEqual(0,0)
|
kgullikson88/gullikson-scripts | kglib/fitters/histogram.py | Python | mit | 5,838 | 0.003083 | from __future__ import print_function, division, absolute_import
from george import kernels, GP
import numpy as np
from kglib import fitters
from scipy.integrate import quad
from scipy.optimize import minimize
class HistFitter(fitters.Bayesian_LS):
def __init__(self, mcmc_samples, bin_edges):
"""
... | # Find which bin each q falls in |
self.bin_idx = np.digitize(self.mcmc_samples, self.bin_edges) - 1
# Determine the censoring function for each bin (used in the integral)
self.censor_integrals = np.array([quad(func=self.censoring_fcn,
a=left, b=right)[0] for (left, right) in
... |
InfoSec-CSUSB/club-websystem | src/clubmembers/management/commands/warm_profile_photos.py | Python | mit | 886 | 0.009029 | import sys
from django.core.management.base import BaseCommand
from clubmembers.models import Member
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
class Command(BaseCommand):
help = "Creates the resized copies of member's profile photos, as described in the VERSATILEIMAGEFIELD_RENDITION_KEY_... | _queryset=Member.objects.all(),
rendition_key_set='memberphoto',
image_attr='photo',
verbose=True
).warm()
if len(failed_to_crea | te):
image_list = "\n".join("- "+str(n) for n in failed_to_create)
self.stderr.write("\nFailed to create {} images:\n".format(len(failed_to_create)) + image_list)
sys.exit(1)
|
CharLLCH/jianchi_alimobileR | ftrldata/TCReBuild/codes/mylibs/index.py | Python | gpl-2.0 | 6,098 | 0.009675 | '''
Index : get behavior
Dic_Builder : get_dic
'''
import size
import csv
class DicBuilder:
def __init__(self, path):
self.path = path
def get_dic(self, key = [], value = []):
if len(key) == 0 or len(self.path) == 0:
return {}
dic = {}
f = open(self.path... | ttribute['time']]
self.__two_level_dictionary__('category_time', item_category, time, behavior_type)
self.__two_level_dictionary__('item_time', ite | m_id, time, behavior_type)
self.__two_level_dictionary__('user_time', user_id, time, behavior_type)
def __two_level_dictionary__(self, dic_name, index1, time2, behavior_type):
index1 = int(index1)
if self.dic[dic_name][index1].has_key(time2):
self.dic[dic_name][index1][t... |
punesemu/puNES | src/extra/p7zip-17.04/Utils/file_7z_so.py | Python | gpl-2.0 | 12,112 | 0.000248 |
files_c=[
'C/7zBuf2.c',
'C/7zCrc.c',
'C/7zCrcOpt.c',
'C/7zStream.c',
'C/Aes.c',
'C/Alloc.c',
'C/Bcj2.c',
'C/Bcj2Enc.c',
'C/Blake2s.c',
'C/Bra.c',
'C/Bra86.c',
'C/BraIA64.c',
'C/BwtSort.c',
'C/CpuArch.c',
'C/Delta.c',
'C/HuffEnc.c',
'C/LzFind.c',
'C/LzFindMt.c',
'C/Lzma2Dec.c',
'C/Lzma2Enc.c',
'C/L... | c',
'C/zstdmt/lz4-mt_common.c',
'C/zstdmt/lz4-mt_compress.c',
'C/zstdmt/lz4-mt_decompress.c',
'C/zstdmt/lz5-mt_common.c',
'C/ | zstdmt/lz5-mt_compress.c',
'C/zstdmt/lz5-mt_decompress.c',
'C/zstdmt/zstd-mt_threading.c',
'C/zstdmt/brotli-mt_common.c',
'C/zstdmt/brotli-mt_compress.c',
'C/zstdmt/brotli-mt_decompress.c',
'C/brotli/br_backward_references.c',
'C/brotli/br_backward_references_hq.c',
'C/brotli/br_bit_cost.c',
'C/brotli/br_bit_r... |
wickman/compactor | compactor/testing.py | Python | apache-2.0 | 507 | 0.011834 | from contextlib import contextmanager
import logging
import unittest
from .context import Context |
log = logging.getLogger(__name__)
class | EphemeralContextTestCase(unittest.TestCase):
def setUp(self):
self.context = Context()
log.debug('XXX Starting context')
self.context.start()
def tearDown(self):
log.debug('XXX Stopping context')
self.context.stop()
@contextmanager
def ephemeral_context(**kw):
context = Context(**kw)
con... |
priseborough/ardupilot | Tools/ardupilotwaf/ardupilotwaf.py | Python | gpl-3.0 | 14,418 | 0.003676 | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
from waflib import Build, ConfigSet, Configure, Context, Errors, Logs, Options, Utils
from waflib.Configure import conf
from waflib.Scripting import run_command
from waflib.TaskGen import before_method, feature
import os.path, os
from collec... | _name=None,
**kw):
if 'target' in kw:
bld.fatal('Do not pass target for program')
if 'defines' not in kw:
kw['defines'] = []
if 'source' not in kw:
kw['source'] = bld.path. | ant_glob(SOURCE_EXTS)
if not program_name:
program_name = bld.path.name
if use_legacy_defines:
kw['defines'].extend(get_legacy_defines(bld.path.name))
kw['cxxflags'] = kw.get('cxxflags', []) + ['-include', 'ap_config.h']
kw['features'] = kw.get('features', []) + bld.env.AP_PROGRAM_FEA... |
pe2mbs/pytelnet | telnetlib/emulation/color.py | Python | gpl-3.0 | 6,546 | 0.02872 |
class TerminalForeColors:
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
GREY = 37
# end class
class TerminalBackColors:
BLACK ... | EEN ),
( self._yellow, TerminalForeColors.YELLOW ),
( self._blue, TerminalForeColors.BLUE ),
( self._magenta, TerminalForeColors.MAGENTA ),
( self._cyan, TerminalForeColors.CYAN ),
... | | self._r << 16 | self._g << 8 | self._b
for rbgColor, TermColor in colorList:
diff = abs( argb - rbgColor )
if diff < retdiff:
retdiff = diff
rettermcolor = TermColor
# end if
# next
return rettermcolor
# end def... |
dana-i2cat/felix | vt_manager/src/python/vt_manager/communication/gapi3communication.py | Python | apache-2.0 | 2,654 | 0.01055 | from django.http import *
import os, sys, logging
from vt_manager.common.rpc4django import rpcmethod
from vt_manager.common.rpc4django import *
from vt_manager.communication.geni.v3.configurators.handlerconfigurator import HandlerConfigurator
#URL_NAME
GAPI3_URL = "gapi"
# Parameter Types
CREDENTIALS_TYPE = 'array' #... | ], url_name=GAPI3_URL)
def Provision(urns, creds, options):
return handler.Provision(urns, creds, options)
@rpcmethod(signature=[SUCCESS_TYPE, URNS_TYPE, CREDENTIALS_TYPE], url_name=GAPI3_URL)
def Delete(urns, creds, options):
return handler.Delete(urns, creds, options)
@rpcmethod(signature=[SUCCESS_TYPE, URN... | er.PerformOperationalAction(urns, creds, action, options)
@rpcmethod(signature=[STATUS_TYPE, URNS_TYPE, CREDENTIALS_TYPE, OPTIONS_TYPE], url_name=GAPI3_URL)
def Status(urns, creds, options):
return handler.Status(urns, creds, options)
@rpcmethod(signature=[SUCCESS_TYPE, URNS_TYPE, CREDENTIALS_TYPE, TIME_TYPE, OPT... |
uranix/ttpy | tt/setup.py | Python | mit | 1,856 | 0.001078 | # | setup.py
# This script | will build the main subpackages
# See LICENSE for details
from distutils.util import get_platform
from numpy.distutils.misc_util import Configuration, get_info
from numpy.distutils.core import setup
from os.path import join
import sys
TTFORT_DIR = 'tt-fort'
TTFORT_SRC = [
'nan.f90',
'default.f90',
'... |
alexmic/great-again | ga/utils.py | Python | mit | 1,008 | 0 | # -*- coding: utf-8 -*-
import json
import os
from contextlib import contextmanager
from ga import settings
def _resource_directory_path(resource_directory='resources'):
dirname = os.path.dirname(__file__)
tokens = dirname.split(os.sep)
path = ['/']
for token in toke | ns:
if not token:
continue
path.append(token)
if token == settings.PROJECT_ROOT:
break
path.append(resource_directory)
return os.path.join(*path)
RESOURCE_DIRECTORY = _resource_directory_path()
def get_resource_path(filename):
return os.path.join(RESOURCE_... | e_path(filename)
with open(path) as data_file:
contents = data_file.read()
return json.loads(contents) if from_json else contents
@contextmanager
def timing(name):
import time
start = time.time()
yield
print "Timing: name=%s, took=%.2fs" % (name, time.time() - start)
|
anhstudios/swganh | data/scripts/templates/object/ship/shared_blacksun_heavy_s04.py | Python | mit | 415 | 0.050602 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Ship()
result.template = "object/ship/shared_blacksun_heavy_s04.i | ff"
result.attribute_template_id = | -1
result.stfName("","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
drogenlied/qudi | hardware/magnet/magnet_dummy.py | Python | gpl-3.0 | 26,940 | 0.00297 | # -*- coding: utf-8 -*-
"""
This file contains the dummy for a magnet interface.
Qudi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Qudi... | .')
# checking for the right configuration
for key in config.keys():
self.log.info('{0}: {1}'.format(key,config[key]))
#these label should be actually set by the config.
self._x_axis = MagnetAxisDummy('x')
self._y_axis = MagnetAxisDummy('y')
self._z_axis = M... |
def on_activate(self, e):
""" Definition and initialisation of the GUI.
@param object e: Fysom.event object from Fysom class.
An object created by the state machine module Fysom,
which is connected to a specific event (have a look in
... |
onoga/toolib | toolib/wx/controls/Choice.py | Python | gpl-2.0 | 86 | 0.034884 | import wx
class Choice(wx.Cho | ice):
def GetValue(self):
return se | lf.GetSelection()
|
petry/django-pressroom-googlecode | setup.py | Python | bsd-3-clause | 1,034 | 0.026112 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "django-pressroom",
version = "0.4.2.1",
url = 'https://github.com/petry/django-pressroom',
license = 'BSD',
description = "A pressroom applic... | .",
author = 'Justin Driscoll, Michael Thornhill, Marcos Daniel Petry',
author_email = 'marcospetry@gmail.com',
packages = find_packages('src'),
package_dir = {'': 'src'},
install_requires = ['setuptools', 'django-photologue'],
dependency_links = [
'http://github.com/petry/django | -photologue/tarball/master#egg=django-photologue',
],
classifiers = [
'Development Status :: 4.2 - Beta',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Languag... |
naparuba/shinken | shinken/db.py | Python | agpl-3.0 | 4,671 | 0.000214 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you ca... | ANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have re | ceived a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
class DB(object):
"""DB is a generic class for SQL Database"""
def __init__(self, table_prefix=''):
self.table_prefix = table_prefix
def stringify(self, val):
"""Get ... |
asottile/virtualenv-hax | virtualenv_hax.py | Python | mit | 2,216 | 0 | fro | m __future__ import absolute_import
from __future__ import print_function
import argparse
import distutils.spawn
import subprocess
import sys
import virtualenv
def main(argv=None):
parser = argparse.ArgumentParser(description=(
| 'A wrapper around virtualenv that avoids sys.path sadness. '
'Any additional arguments are passed directly to `virtualenv`.'
))
parser.add_argument('-p', '--python', default=sys.executable)
args, rest_argv = parser.parse_known_args(argv)
# The way virtualenv deals with -ppython is to exec i... |
henry-zhang/Cmdb_Puppet | cmdb/hostinfo/admin.py | Python | epl-1.0 | 836 | 0.029904 | #from models import Host, IPaddr
from models import Host, HostGroup
from django.contrib import admin
class HostAdmin(admin.ModelAdmin):
list_display = ['vendor',
'sn',
'product',
'cpu_model',
'cpu_num',
'cpu_vendor',
'memory_part_number',
'memory_manufacture... | n',
'device_size',
'osver',
'hostname',
'os_release',
'ipaddr',
'identity'
]
#class IPaddrAdmin(admin.ModelAdmin):
# list_display = ['ipaddr',
# 'host'
# ]
class HostGroupAdmin(admin.ModelAdmin):
list_display = ['name',]
|
admin.site.register(HostGroup,HostGroupAdmin)
admin.site.register(Host, HostAdmin)
#admin.site.register(IPaddr, IPaddrAdmin)
|
openatv/enigma2 | lib/python/Screens/PowerTimerEdit.py | Python | gpl-2.0 | 10,350 | 0.027536 | from functools import cmp_to_key
from time import time
from timer import TimerEntry as RealTimerEntry
from PowerTimer import PowerTimerEntry, AFTEREVENT
from Components.ActionMap import ActionMap
from Components.Button import Button
from Components.config import config
from Components.Label import Label
from Components... | ": self.addCurrentTimer,
"log": self.showLog,
"left": self.left,
"right": self.right,
"up": self.up,
"down": self.down
}, -1)
self.setTitle(_("PowerTimer Overview"))
self.session.nav | .PowerTimer.on_state_change.append(self.onStateChange)
self.onShown.append(self.updateState)
def createSummary(self):
return PowerTimerEditListSummary
def up(self):
self["timerlist"].instance.moveSelection(self["timerlist"].instance.moveUp)
self.updateState()
def down(self):
self["timerlist"].instance.m... |
romain-li/edx-platform | cms/djangoapps/contentstore/tests/test_utils.py | Python | agpl-3.0 | 26,121 | 0.002948 | """ Tests for utils. """
import collections
from datetime import datetime, timedelta
from pytz import UTC
from django.test import TestCase
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
from xmodule.modulestore.tests.django_utils import Module... | link = utils.get_lms_link_for_item(location, True)
self.assertEquals(
link,
"//preview.localhost/courses/mitX/ | 101/test/jump_to/i4x://mitX/101/vertical/contacting_us"
)
# now test with the course' location
location = course_key.make_usage_key('course', 'test')
link = utils.get_lms_link_for_item(location)
self.assertEquals(link, "//localhost:8000/courses/mitX/101/test/jump_to/i4x://mitX/1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.