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 |
|---|---|---|---|---|---|---|---|---|
openmb/openblackhole-enigma2 | lib/python/Components/About.py | Python | gpl-2.0 | 2,999 | 0.037012 | # -*- coding: utf-8 -*-
import sys, os, time
from Tools.HardwareInfo import HardwareInfo
def getVersionString():
return getImageVersionString()
def getImageVersionString():
try:
if os.path.isfile('/var/lib/opkg/status'):
st = os.stat('/var/lib/opkg/status')
else:
st = os.stat('/usr/lib/ipkg/status')
tm ... | trip() for x in line.strip().split(":")]
if line[0] in ("system type", "model name"):
processor = line[1].split()[0]
elif line[0] == "cpu MHz":
cpu_speed = "%1.0f" % float(line[1])
elif line[0] == "processor":
cpu_count += | 1
if not cpu_speed:
try:
cpu_speed = int(open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq").read()) / 1000
except:
cpu_speed = "-"
if os.path.isfile('/proc/stb/fp/temp_sensor_avs'):
temperature = open("/proc/stb/fp/temp_sensor_avs").readline().replace('\n','')
return "%s %s MHz (%s) ... |
bburns/PyVoyager | src/vgComposite.py | Python | mit | 10,684 | 0.007675 |
"""
vg composite command
Build composite images from centered images, based on records in composites.csv.
See also vgInitComposites.py, which builds initial pass at composites.csv.
Note: even single channel images get a composite image (bw).
Uses centered image if available, otherwise uses the plain adjusted image.
... | rite(outfilepath, im)
# if -align: update channels x | ,y etc
if optionAlign:
# make sure all the rows have all their columns
for row in channelRows:
while len(row)<=config.colCompositesY:
row.append('')
# find each row in channelRows and update weights and x,y translati... |
ConnectBox/wifi-test-framework | ansible/plugins/mitogen-0.2.3/tests/local_test.py | Python | mit | 1,663 | 0 |
import os
import sys
import unittest2
import mitogen
import mitogen. | ssh
import mitogen.utils
import testlib
import plain_old_module
def get_sys_executable():
return sys.executable
def get_os_environ():
return dict(os.environ)
class LocalTest(testlib.RouterMixin, unittest2.TestCase):
stream_class = mitogen.ssh.Stream
def test_stream_name(self):
context = ... | test2.TestCase):
stream_class = mitogen.ssh.Stream
def test_inherited(self):
context = self.router.local()
self.assertEquals(sys.executable, context.call(get_sys_executable))
def test_string(self):
os.environ['PYTHON'] = sys.executable
context = self.router.local(
... |
nsnam/ns-3-dev-git | src/wifi/examples/reference/bianchi11ax.py | Python | gpl-2.0 | 6,874 | 0.010038 | #
# Copyright 2020 University of Washington
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation;
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARR... | result, i, 40)
fo.write(str_s)
for i in range(len(data_rates_80MHz)):
bianchi_result = bianchi_ax(data_rates_80MHz[i], ack_rates_80MHz[i], k, difs)
str_s = str_result(bianchi_result, i, 80)
fo.write(str_s)
for i in range(len(data_rates_160MHz)):
bianchi_result = bianchi_ax(data_rates_160MHz[i], ack_... | tes_20MHz)):
bianchi_result = bianchi_ax(data_rates_20MHz[i], ack_rates_20MHz[i], k, difs)
str_s = str_result(bianchi_result, i, 20)
fo.write(str_s)
for i in range(len(data_rates_40MHz)):
bianchi_result = bianchi_ax(data_rates_40MHz[i], ack_rates_40MHz[i], k, difs)
str_s = str_result(bianchi_result,... |
pisskidney/dota | dota/urls.py | Python | mit | 222 | 0.004505 | from django.conf.urls import | patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('ebets.urls')),
url( | r'^admin/', include(admin.site.urls)),
)
|
derNarr/synchronicity | experiment/sessions/ses_vp48.py | Python | mit | 5,332 | 0.001313 | # vpnr 48
run_trial(hori2, duration=4.000, speed=300)
run_trial(rws[2], duration=8.0)
run_trial(rbs[12], duration=8.0)
run_trial(rws[6], duration=8.0)
run_trial(rbs[22], duration=8.0)
run_trial(cm200, duration=8.0, speed=150)
run_trial(cm200, duration=8.0, speed=800)
run_trial(rbs[6], duration=8.0)
run_trial(msm0, dura... | (u'Machen Sie eine kurze Pause.\n\nWeiter mit Leertaste.', wait_keys=('space',))
run_trial(mem0, duration=5.000, speed=300)
run_trial(hori2, duration=6.000, speed=200)
run_trial(msm0, duration=5.000, speed=300)
run_trial(rws[22], duration=8.0)
run_trial(cm100, duration=8.0, speed=300)
run_trial(mem0, duration=9.000, s... | _trial(rws[23], duration=8.0)
run_trial(rws[14], duration=8.0)
run_trial(rws[24], duration=8.0)
run_trial(msm1, duration=7.000, speed=200)
run_trial(rws[3], duration=8.0)
run_trial(cm100, duration=8.0, speed=800)
run_trial(hori2, duration=3.000, speed=400)
run_trial(rbs[20], duration=8.0)
run_trial(hori1, duration=3.00... |
frostblooded/kanq | api/tests/test_user_service.py | Python | mit | 1,237 | 0.000808 | from django.test import TestCase
from api.helpers import user_service
from api.factories import UserFactory, PostFac | tory
class UserServiceTest(TestCase):
POSTS_PER_USER = 10
def setUp(self):
self.main_user = UserFactory()
self.follower = UserFactory()
self.test_user = UserFactory()
self.main_user.followers.add(self.follower)
self.follower.following.add(se | lf.main_user)
for i in range(0, self.POSTS_PER_USER):
PostFactory(creator=self.main_user)
PostFactory(creator=self.test_user)
PostFactory(creator=self.follower)
def test_user_feed_returns_posts_from_correct_users(self):
posts = user_service.get_user_feed(self.fo... |
MrNuggelz/sklearn-glvq | sklearn_lvq/lmrslvq.py | Python | bsd-3-clause | 15,649 | 0.000511 | # -*- coding: utf-8 -*-
# Author: Joris Jensen <jjensen@techfak.uni-bielefeld.de>
#
# License: BSD 3 clause
from __future__ import division
import numpy as np
from scipy.optimize import minimize
from sklearn.utils import validation
from .rslvq import RslvqModel
class LmrslvqModel(RslvqModel):
"""Localized Mat... | numbers per class.
initial_prototypes : array-like, shape = [n_prototypes, n_features + 1],
optional
Prototypes to start with. If not given initialization near the class
means. Class label must be placed as last entry of each prototype.
initial_matrices : list of array-like, optional
| Matrices to start with. If not given random initialization
regularization : float or array-like, shape = [n_classes/n_prototypes],
optional (default=0.0)
Values between 0 and 1. Regularization is done by the log determinant
of the relevance matrix. Without regularization relevances may
... |
alexei-matveev/ccp1gui | jobmanager/winprocess.py | Python | gpl-2.0 | 7,039 | 0.001421 | """
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 20... | PId, self.TId = procHandles
def wait(self, mSec=None):
"""
| Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process. Try for an... |
thedeadparrot/ficbot | twitterbot.py | Python | mit | 555 | 0.003604 | from __future__ import pri | nt_function
from twython import Twython
import util
class TwitterBot(util.SocialMediaBot):
""" Social Media Bot for posting updat | es to Tumblr """
NAME = "twitter"
def __init__(self, **kwargs):
super(TwitterBot, self).__init__(**kwargs)
self.client = Twython(*self.oauth_config)
def post_update(self):
text = self.generate_text(limit_characters=140)
self.client.update_status(status=text)
if __name__ =... |
d9w/6858-android-intents | analyzer/androguard/core/bytecodes/dvm.py | Python | mit | 232,587 | 0.025272 | # This file is part of Androguard.
#
# Copyright (C) 2012, Anthony Desnos <desnos at t0t0.fr>
# All rights reserved.
#
# Androguard 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 of th... |
#
# You should have received a copy of the GNU Lesser General Public License
# along with Androguard. If not, see <http://www.gnu.org/licenses/>.
from androguard.core import bytecode
from androguard.core.androconf import CONF, debug
import sys, re
from struct import pack, unpack, calcsize
DEX_FILE_MAGIC = 'dex\n03... | 0x1 : "TYPE_STRING_ID_ITEM",
0x2 : "TYPE_TYPE_ID_ITEM",
0x3 : "TYPE_PROTO_ID_ITEM",
0x4 : "TYPE_FIELD_ID_ITEM",
0x5 : "TYPE_METHOD_ID_ITEM",
0x6 : "TY... |
SimpleTax/merchant | billing/__init__.py | Python | bsd-3-clause | 135 | 0 | from gatew | ay import Gateway, get_gateway
from integration import Integration, get_integration
from | utils.credit_card import CreditCard
|
btenaglia/hpc-historias-clinicas | hpc-historias-clinicas/diagnosticos/models.py | Python | bsd-3-clause | 945 | 0.003181 | # -*- coding: utf-8 -*-
from datetime import datetime
from django.db import models
from django.core.urlresolvers import reverse
from ..core.models import TimeS | tampedModel
class TipoDiagnosticos(TimeStampedModel):
nombre = models.CharField(max_length=150, blank=False, null=False, verbose_name=u'Diagnóstico')
def get_absolute_url(self):
return reverse('diagnosticos:list')
def __unicode__(self):
return self.nombre
class Diagnosticos(TimeStamped... | cha = models.DateField(blank=False, null=False,
help_text=u'Formato: dd/mm/yyyy',
default=datetime.now())
hora = models.TimeField(blank=False, null=False,
help_text=u'Formato: hh:mm', default=datetime.now())
|
midhun3112/restaurant_locator | Restaurant_Finder_App/restaurant_finder_app/restaurant_finder_app/restaurant/migrations/0015_auto_20170213_1116.py | Python | apache-2.0 | 766 | 0.002611 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-13 11:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('restau | rant', '0014_remove_menuimage_menu_name'),
]
operations = [
migrations.AlterModelOptions(
name='menuimage',
options={'verbose_name': 'MenuImage', 'verbose_name_plural': 'MenuImages'},
),
migrations.AlterField(
model_name='menuimage',
name=... | .models.deletion.CASCADE, related_name='menu_image', to='restaurant.Restaurant'),
),
]
|
onelab-eu/myslice | forge/script/PlcApi/showKeys.py | Python | gpl-3.0 | 224 | 0.026786 | #!/us | r/bin/env python
from Auth import *
keyId = plc_api.GetKeys(auth, {'person_id': 249241}, ['key_id', 'key'])
for key in keyId:
print "A new key:"
| print "Key value ->", key['key']
print "Key id ->",key['key_id']
|
kg-bot/SupyBot | plugins/TwitterStream/__init__.py | Python | gpl-3.0 | 2,725 | 0.000734 | ###
# Copyright (c) 2012, Valentin Lorentz
# 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 notice,
# this list of conditi... | ted to the user inside the wizard)
here. This should describe *what* the plugin does.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
__version__ = ""
# XXX Replace th... | ot.Author instances to lists of
# contributions.
__contributors__ = {}
# This is a url where the most recent plugin package can be downloaded.
__url__ = '' # 'http://supybot.com/Members/yourname/TwitterStream/download'
from . import config
from . import plugin
from imp import reload
reload(plugin) # In case we're bei... |
UltraNurd/tweetworks-py | tweetworks/User.py | Python | gpl-3.0 | 3,623 | 0.002762 | # -*- coding: utf-8 -*-
"""
Read Tweetworks API users from XML responses.
Nicolas Ward
@ultranurd
ultranurd@yahoo.com
http://www.ultranurd.net/code/tweetworks/
2009.06.19
"""
"""
This file is part of the Tweetworks Python API.
Copyright © 2009 Nicolas Ward
Tweetworks Python API is free software: you can redistribut... | ion.
Tweetworks Python API 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 should have received a copy of the GNU General Public License
alon... | ight © 2009 Tweetworks, LLC and is used
under license. See http://www.tweetworks.com/pages/terms
The use of this software requires a unique Tweetworks API key. You must be a
registered Tweetworks user, and have received an API key after requesting one
via http://www.tweetworks.com/pages/contact.
The term "Twitter" is... |
Azure/azure-sdk-for-python | sdk/storagepool/azure-mgmt-storagepool/setup.py | Python | mit | 2,679 | 0.001493 | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | different name
PACKAGE_NAME = "azure-mgmt-storagepool"
PACKAGE_PPRINT_NAME = "Storage Pool Management"
# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# Version extraction inspired from 'requests'
with open(os.path.join(package_fol... | ath, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.... |
steakunderscore/Bandwidth-Monitoring | src/user.py | Python | gpl-3.0 | 4,271 | 0.012175 | '''
Created on 5/02/2010
@author: henry@henryjenkins.name
'''
import datetime
class user(object):
'''
classdocs
'''
dataUp = None
dataDown = None
macAddress = ""
name = ""
def __init__(self, mac="", name=""):
'''
Constructor
'''
self.name = name
... | dataTotal += data['on'][type]
dataTotal += data['off'][type]
return dataTotal
def addData(self, date=None, data=0, pkts=0, | peak='on', direction='up'):
if direction == 'up':
self.addUpData(date, data, pkts, peak)
elif direction == 'down':
self.addDownData(date, data, pkts, peak)
def addUpData(self, date=None, data=0, pkts=0, peak='on'): #TODO store packets
date = self.__checkDate(date)
... |
ntt-sic/cinder | cinder/volume/volume_types.py | Python | apache-2.0 | 5,726 | 0.000175 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 Zadara Storage Inc.
# Copyright (c) 2011 OpenStack Foundation
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright (c) 2010 Citrix Systems, Inc.
# Copyright 2011... | er import db
from cinder import exception
from cinder.openstack.common.db import exception as db_exc
from cinder.openstack.common import log as logging
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
def create(context, name, extra_specs={}):
"""Creates volume typ | es."""
try:
type_ref = db.volume_type_create(context,
dict(name=name,
extra_specs=extra_specs))
except db_exc.DBError as e:
LOG.exception(_('DB error: %s') % e)
raise exception.VolumeTypeCreateFailed(n... |
zzeleznick/zDjango | venv/lib/python2.7/site-packages/pystache/tests/test_simple.py | Python | mit | 2,785 | 0.002154 | import unittest
import pystache
from pystache import Renderer
from examples.nested_context import NestedContext
from examples.complex import Complex
from examples.lambdas import Lambdas
from examples.template_partial import TemplatePartial
from examples.simple import Simple
from pystache.tests.common import EXAMPLES_... | ue_renders_blank(self):
view = Simple()
template = '{{not_set}} {{blank}}'
self.assertEqual(pystache.Renderer().render(template), ' ')
def test_template_partial_extension(self):
"""
Side note:
From the spec--
Partial tags SHOULD be treated as | standalone when appropriate.
In particular, this means that trailing newlines should be removed.
"""
renderer = Renderer(search_dirs=EXAMPLES_DIR, file_extension='txt')
view = TemplatePartial(renderer=renderer)
actual = renderer.render(view)
self.assertString(actual,... |
JaneliaSciComp/Neuroptikon | Source/lib/CrossPlatform/networkx/readwrite/leda.py | Python | bsd-3-clause | 2,097 | 0.023367 | """
Read graphs in LEDA format.
See http://www.algorithmic-solutions.info/leda_guide/graphs/leda_native_graph_fileformat.html
"""
# Original author: D. Eppstein, UC Irvine, August 12, 2003.
# The original code at http://www.ics.uci.edu/~eppstein/PADS/ is public domain.
__author__ = """Aric Hagberg (hagberg@lanl.gov)""... | directed, -2 undirected
if du==-1:
G = networkx.DiGraph()
else:
G = networkx.Graph()
# Nodes
n =int(lines.next()) # number of vertices
node={}
for i in range(1,n+1): # LEDA counts from 1 to n
symbol=lines.next().rstrip().strip('|{}| ')
if symbol=="": s... | Edges
m = int(lines.next()) # number of edges
for i in range(m):
try:
s,t,reversal,label=lines.next().split()
except:
raise NetworkXError,\
'Too few fields in LEDA.GRAPH edge %d' % (i+1)
# BEWARE: no handling of reversal edges
G.add_edge... |
Lana-Pa/Python-training | test/test_delete_contact_from_group.py | Python | apache-2.0 | 1,311 | 0.006865 | from model.contact import Contact
from model.group import Group
from fixture.orm import ORMFixture
import random
def test_del_contact_from_group(app):
orm = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
# check for existing any group
if len(orm.get_group_list()) == 0:
a... | old_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id))
contact_in_group = random.choice(old_contacts_in_group) # choose random contact from list
app.contact.delete_contact_from_group_by_id(contact_in_group.id, group.id)
new_contacts_in_group = orm.get_contacts_in_group(Group(id=group.id))
... | ) == sorted(new_contacts_in_group, key=Contact.id_or_max)
|
freevo/freevo2 | src/plugins/jsonrpc/__init__.py | Python | gpl-2.0 | 8,340 | 0.003357 | # -*- coding: iso-8859-1 -*-
# -----------------------------------------------------------------------
# jsonrpc - jsonrpc interface for XBMC-compatible remotes
# -----------------------------------------------------------------------
# $Id$
#
# JSONRPC and XBMC eventserver to be used for XBMC-compatible
# remotes. Onl... | eld kaa.inprogress(thumbnail.create(priority=kaa.beacon.Thumbnail.PRIORITY_HIGH))
filename = thumbnail.large
if filename:
if os.path.is | file(filename):
yield open(filename).read(), None, None
log.error('no file: %s' % filename)
yield None
else:
yield None
def Application_GetProperties(self, properties):
"""
JsonRPC Callback Application.GetProperties
"""
res... |
JohannesFeldmann/pism | examples/storglaciaren/sg_create_3d.py | Python | gpl-2.0 | 7,325 | 0.006416 | #!/usr/bin/env python
#
# Copyright (C) 2011 Andy Aschwanden
#
# This file is part of PISM.
#
# PISM is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any l... | "lat lon"
thk_var[:] = thk
dem_var = def_var(nc, "usurf_from_dem", "m", fill_value)
dem_var.standard_name = "surface_altitude"
dem_var.coordinates = "lat lon"
dem_var[:] = dem
# gen | erate (somewhat) reasonable acab
acab_max = 2.5 # m/a
acab_min = -3.0 # m/a
acab_up = easting.min() + 200 # m; location of upstream end of linear acab
acab_down = easting.max() - 600 # m;location of downstream end of linear acab
acab = np.ones_like(dem)
acab[:] = acab_max - (acab_max-acab_min) * (easting - acab_up) /... |
amolenaar/gaphor | examples/list_classes.py | Python | lgpl-2.1 | 1,239 | 0 | #!/usr/bin/python
"""This script lists classes and optionally attributes from UML model created
with Gaphor."""
import optparse
import sys
from gaphor import UML
from gaphor.application import Session
# Setup command line options.
usage = "usage: %prog [options] file.gaphor"
def main():
parser = optparse.Opti... | model file to load.
model = args[0]
# Create the Gaphor application object.
session = Session()
# Get services we need.
element_factory = session.get_service("element_factory")
file_manager = session.get_service("file_manager")
# Load model from file.
file_manager.load(model)
# ... | print(f"Found class {cls.name}")
if options.attrs:
for attr in cls.ownedAttribute:
print(f" Attribute: {attr.name}")
if __name__ == "__main__":
main()
|
auth0/auth0-python | auth0/v3/management/rules.py | Python | mit | 4,742 | 0.002109 | from .rest import RestClient
class Rules(object):
"""Rules endpoint implementation.
Args:
domain (str): Your Auth0 domain, e.g: 'username.auth0.com'
token (str): Management API v2 Token
telemetry (bool, optional): Enable or disable Telemetry
(defaults to True)
t... | n include_fields) from the result. Leave empty to
retrieve all fields.
include_f | ields (bool, optional): True if the fields specified are
to be included in the result, False otherwise. Defaults to True.
page (int, optional): The result's page number (zero based). When not set,
the default value is up to the server.
per_page (int, optional): ... |
iNecas/katello | cli/test/katello/tests/core/template/template_delete_test.py | Python | gpl-2.0 | 1,936 | 0.002583 | import unittest
import os
from katello.tests.core.action_test_utils import CLIOptionTestCase, CLIActionTestCase
from katello.tests.core.organization import organization_data
from katello.tests.core.template import template_data
import katello.client.core.template
from katello.client.core.template import Delete
from k... | disallowed_options = [
('--environment=dev', '--name=template_1'),
| ('--environment=dev', '--org=ACME'),
]
allowed_options = [
('--org=ACME', '--name=template_1'),
('--org=ACME', '--environment=dev', '--name=template_1'),
]
class TemplateInfoTest(CLIActionTestCase):
ORG = organization_data.ORGS[0]
ENV = organization_data.ENVS[0]
TPL = tem... |
alphagov/notifications-api | app/performance_dashboard/rest.py | Python | mit | 3,531 | 0.003398 | from datetime import datetime
from flask import Blueprin | t, jsonify, request
from app.dao.fact_notification_status_dao import (
get_total_notifications_for_date_range,
)
from app.dao.fact_processing_time_dao import (
get_processing_time_percentage_for_date_range,
)
from app.dao.services_dao import get_live_services_with_organisation
from app.errors | import register_errors
from app.performance_dashboard.performance_dashboard_schema import (
performance_dashboard_request,
)
from app.schema_validation import validate
performance_dashboard_blueprint = Blueprint('performance_dashboard', __name__, url_prefix='/performance-dashboard')
register_errors(performance_d... |
dpogue/korman | korman/properties/modifiers/logic.py | Python | gpl-3.0 | 5,501 | 0.003272 | # This file is part of Korman.
#
# Korman 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.
#
# Korman is distributed i... | bpy.types.PropertyGroup):
name = StringProperty(name="Name")
version = EnumProperty(name="Version",
description="Plasma versions this node tree exports under",
items=game_versions,
options={"ENUM_FLAG"},
| default=set(list(zip(*game_versions))[0]))
node_tree = PointerProperty(name="Node Tree",
description="Node Tree to export",
type=bpy.types.NodeTree)
node_name = StringProperty(name="Node Ref",
descript... |
ganeshchand/python3 | advanced/regular_expression/regular_expresion_anchors.py | Python | apache-2.0 | 1,306 | 0.011485 | __author__ = 'ganeshchand'
import re
def regex_search(pattern_string, string_source):
if re.search(pattern_string,string_source):
print("%s matched %s" % (pattern_string, string_source))
else:
print("%s did not match %s" % (pattern_string, string_source))
# matching a pattern in one string
... | eed to represent its special meaning.
# It is an anchor reserved character - it marks the end of the string
# that means, if you say aab$ , you are looking for a string that that ends with pattern aab
# there shoul... | ond aab
regex_search(pattern_withoutanchors, mystring_anchors)
pattern_withanchors = r'defg$'
regex_search(pattern_withanchors, mystring_anchors)
# patterns to be matched
patterns = ["defg$", "^d", "^a", "^a*!"]
# defg$ : string must end with defg
# ^d: must begin with d
# ^a: must begin with
# ^a*!: must begi... |
souravsingh/khmer | sandbox/sweep-reads2.py | Python | bsd-3-clause | 3,734 | 0.000268 | #!/usr/bin/env python
# This file is part of khmer, https://github.com/dib-lab/khmer/, and is
# Copyright (C) 2012-2015, Michigan State University.
# Copyright (C) 2015, The Regents of the University of California.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted prov... | int('loading input reads from', inp)
ht.consume_seqfile(inp)
print('starting sweep.')
m = 0
K = ht.ksize()
instream = screed.open(readsfil | e)
for n, is_pair, read1, read2 in broken_paired_reader(instream):
if n % 10000 == 0:
print('...', n, m)
if is_pair:
count1 = ht.get_median_count(read1.sequence)[0]
count2 = ht.get_median_count(read2.sequence)[0]
if count1 or count2:
m... |
iw518/fernando | app/main/hr/views.py | Python | gpl-3.0 | 859 | 0.001164 | #!/usr/bin/env python
# encoding: utf-8
# -------------------------------------------------------------------------------
# version: ??
# author: fernando
# | license: MIT License
# contact: iw518@163.com
# purpose: views
# date: 2016-12-14
# copyright: copyright 2016 Xu, Aiwu
# --------------------------------- | ----------------------------------------------
from flask import redirect, url_for, render_template
from app.model.models import Team
from . import hr
from .forms import RegisterForm
@hr.route('/team_manage', methods=['POST', 'GET'])
def team_manage():
form = RegisterForm()
if form.validate_on_submit():
... |
zonble/lyg0vtw_client.py | lyg0vtw_client/lyg0vtw_client.py | Python | gpl-2.0 | 5,779 | 0.029071 | #!/usr/bin/env python
# encoding: utf-8
'A simple client for accessing api.ly.g0v.tw.'
import json
import unittest
try:
import urllib.request as request
import urllib.parse as urlparse
except:
import urllib2 as request
import urllib as urlparse
def assert_args(func, *args):
def inner(*args):
required_arg = ar... |
self.assertTrue(isinstance(item['type'], str) or \
| isinstance(item['type'], unicode))
self.assertTrue(len(item['content']) > 0)
self.assertTrue(isinstance(item['content'], list))
for content in item['content']:
self.assertTrue(isinstance(content, list))
for line in content:
self.assertTrue(isinstance(line, str))
self.assertTrue(len(item['hea... |
gdelt-analysis/worker | src/HeatMap.py | Python | gpl-3.0 | 1,473 | 0.002716 | import redis
class BetaRedis(redis.StrictRedis):
def georadius(self, name, *values):
return self.execute_command('GEORADIUS', name, *values)
def geoadd(self, name, *values):
return self.execute_command('GEOADD', name, *values)
def geopos(self, name, *values):
return self.execute_... | = REDIS_KEY + '_G | EO'
REDIS_KEY_HASH = REDIS_KEY + '_HASH'
def __init__(self, host='localhost', port=6379, db=0):
self.r = BetaRedis(host=host, port=port, db=db)
self.r.flushdb()
def gen(self, data, distance=200000, min_sum=1):
for point in data:
try:
res = self.r.georadi... |
puttarajubr/commcare-hq | corehq/pillows/reportcase.py | Python | bsd-3-clause | 1,031 | 0.00582 | import copy
from corehq.pillows.case import CasePillow
from corehq.pillows.mappings.reportcase_mapping import REPORT_CASE_MAPPING, REPORT_CASE_INDEX
from django.conf import settings
from .base import convert_property_dict
class ReportCasePillow(CasePillow):
"""
Simple/Common Case properties Indexer
an ext... | LL_INDEX_DOMAINS', []):
#full indexing is only enabled for select domains on an opt-in basis
return None
doc_ret = copy.deepcopy(doc_dict)
convert | _property_dict(doc_ret, self.default_mapping, override_root_keys=['_id', 'doc_type', '_rev', '#export_tag'])
return doc_ret
|
rg3915/orcamentos | orcamentos/urls.py | Python | mit | 341 | 0.002933 | from django.ur | ls import include, path
from django.contrib import admin
urlpatterns = [
path('', include('orcamentos.core.urls', namespace='core')),
path('crm/', include('orcamentos.crm.urls', namespace='crm')) | ,
path('proposal/', include('orcamentos.proposal.urls', namespace='proposal')),
path('admin/', admin.site.urls),
]
|
wagtail/wagtail | wagtail/images/views/serve.py | Python | bsd-3-clause | 2,857 | 0.0014 | import imghdr
from wsgiref.util import FileWrapper
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.http import (
HttpResponse,
HttpResponsePermanentRedirect,
StreamingHttpResponse,
)
from django.shortcuts import get_object_or_404
from django.urls import reverse
from dj... | spec, key)
url = reverse(viewname, args=(signature, image.id, filter_spec))
url += image.file.name[len("original_images/") :]
return url
class ServeView(View):
model = get_image_model()
action = "serve"
key = No | ne
@classonlymethod
def as_view(cls, **initkwargs):
if "action" in initkwargs:
if initkwargs["action"] not in ["serve", "redirect"]:
raise ImproperlyConfigured(
"ServeView action must be either 'serve' or 'redirect'"
)
return supe... |
grubbcode/minplot | svgdatashapes_dt.py | Python | mit | 9,956 | 0.028726 | #
# SVGdatashapes_dt 0.3.6 SVGdatashapes.com github.com/pepprseed/svgdatashapes
# Copyright 2016-8 Stephen C. Grubb stevegrubb@gmail.com MIT License
#
# This module provides date / time support for svgdatashapes
#
import svgdatashapes
from svgdatashapes import p_dtformat
import collections
import datet... | dtcur.strftime( stub2format )
if stub2place == "prepend": stub | = stub2 + stub
elif stub2place == "replace": stub = stub2
else: stub = stub + stub2
stublist.append( [utime, stub] )
while iloop < 500: # sanity backstop
yr = dtcur.year
mon = dtcur.month
day = dtcur.day
if inc == "mont |
jsonbrazeal/tictactoe | tictactoe/urls.py | Python | mit | 1,037 | 0 | """tictactoe URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-bas... | rls import include, path
2. Add a URL to urlpatterns: path('blog/', incl | ude('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from tictactoe import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('tictactoe/', include('tictactoe.game.urls'), name='game'),
] + static(settings.STATIC_UR... |
wildchildyn/autism-website | yanni_env/lib/python3.6/site-packages/sqlalchemy/testing/schema.py | Python | gpl-3.0 | 3,556 | 0 | # testing/schema.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from . import exclusions
from .. import schema, event
from . import config
__all_... | e issues around seleting self-refs too.
if exclusions.against(config._current, 'firebird'):
table_name = args[0]
unpack = (config.db.di | alect.
identifier_preparer.unformat_identifiers)
# Only going after ForeignKeys in Columns. May need to
# expand to ForeignKeyConstraint too.
fks = [fk
for col in args if isinstance(col, schema.Column)
for fk in col.foreign_keys]
for fk ... |
Som-Energia/invoice-janitor | admin/Baixa_Socis/unsubscribe_members.py | Python | agpl-3.0 | 4,279 | 0.002104 | # -*- encoding: utf-8 -*-
import argparse
import sys
import traceback
from hashlib import md5
import mailchimp_marketing as MailchimpMarketing
import requests
from consolemsg import step, error, success
from erppeek import Client
import time
import configdb
ERP_CLIENT = Client(**configdb.erppeek)
MAILCHIMP_CLIENT =... | = ResPartnerAddress.search(
[('partner_id', 'in', not_members_partner_ids)]
)
emails_list = | [
address.get('email', 'not found')
for address in ResPartnerAddress.read(address_list, ['email'])
]
return emails_list
def get_mailchimp_list_id(list_name):
all_lists = MAILCHIMP_CLIENT.lists.get_all_lists(
fields=['lists.id,lists.name'],
count=100
)['lists']
for... |
yordan-desta/QgisIns | python/plugins/processing/gui/ScriptEditorDialog.py | Python | gpl-2.0 | 7,417 | 0.000404 | # -*- coding: utf-8 -*-
"""
***************************************************************************
EditScriptDialog.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
*******... | def saveScript(self, saveAs):
if self.filename is None or saveAs:
if self.algType == self.SCRIPT_PYTHON:
scriptDir = ScriptUtils.scriptsFolder()
filterName = self.tr('Python scripts (*.py)')
elif self.algType == self.SCRIPT_R:
scriptDir ... | code(QFileDialog.getSaveFileName(self,
self.tr('Save script'), scriptDir,
filterName))
if self.filename:
if self.algType == self.SCRIPT_PYTHON \
and not self.filename.lower().endswith('.py'):
... |
piger/managesieve-cli | managesieve/sieveshell.py | Python | gpl-3.0 | 13,053 | 0.003601 | #!/usr/bin/python
"""
sieveshell - remotely manipulate sieve scripts
SYNOPSIS
sieveshell [--user=user] [--authname=authname] [--realm=realm]
[--exec=script] [--auth-mech=mechanism] server
sieveshell --help
sieveshell allows users to manipulate their scripts on a remote server.
It works via MANAG... | ult %s):' % scriptname)
filename = sys.stdin.readline().strip()
if filename == '':
filename = scriptname
scriptdata = open(tmpname).read()
open(filename, 'w').write(scriptdata)
res, scripts = sieve.listscripts()
if res != 'OK': return res
for name, active in scri... | = scriptname:
res, scriptdata = sieve.getscript(scriptname)
if res != 'OK': return res
break
else:
if not YesNoQuestion('Script not on server. Create new?'):
return 'OK'
# else: script will be created when saving
scriptdata = ''
im... |
COSMOGRAIL/PyCS | pycs/gen/spl.py | Python | gpl-3.0 | 40,478 | 0.046766 | """
Module defining the Spline class, something easy to wrap around SciPy splines.
Includes BOK algorithms (Mollinari et al)
Some rules of splrep (k = 3)
- do not put more then 2 knots between data points.
- splrep wants inner knots only, do not give extremal knots, even only "once".
"""
import numpy as np
import ... | you can skip them.
You cannot specify a mask, I do this myself. (co | uld be done in principle).
stab : do you want stabilization points ?
Don't forget to run splitup, sort, and addstab again if you change the data !
"""
self.jds = jds
self.mags = mags
self.magerrs = magerrs
self.stab = stab
self.stabext = stabext
self.stabgap = stabgap
self.stabstep = stabst... |
luofei98/qgis | python/plugins/processing/algs/qgis/ftools/FixedDistanceBuffer.py | Python | gpl-2.0 | 3,213 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
FixedDistanceBuffer.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*******************... | elf.getParameterValue(self.SEGMENTS))
| writer = self.getOutputFromName(
self.OUTPUT).getVectorWriter(layer.pendingFields().toList(),
QGis.WKBPolygon, layer.crs())
buff.buffering(progress, writer, distance, None, False, layer,
dissolve, segments)
|
phil-lopreiato/the-blue-alliance | models/event.py | Python | mit | 20,440 | 0.002544 | import datetime, json, re
from consts.playoff_type import PlayoffType
from consts.district_type import DistrictType
from consts.event_type import EventType
from google.appengine.ext import ndb
from google.appengine.ext.ndb.tasklets import Future
from models.district import District
from models.event_details import E... | time = time - tz.utcoffset(time)
except (pytz.NonExistentTimeError, pytz.AmbiguousTimeError): # may happen during DST
time = time - tz.utcoffset(time + datetime.timedelta(hours=1)) # add offset to get out of non-existant time
return time
def local_time(self):
... |
now = now + tz.utcoffset(now)
except (pytz.NonExistentTimeError, pytz.AmbiguousTimeError): # may happen during DST
now = now + tz.utcoffset(now + datetime.timedelta(hours=1)) # add offset to get out of non-existant time
return now
def withinDays(self, negative... |
openstack/python-designateclient | designateclient/v2/utils.py | Python | apache-2.0 | 2,334 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Author: Endre Karlson <endre.karlson@hp.com>
#
# 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/lice... | msg = "Multiple matches found for %s, please use ID instead." % name
raise exceptions.NoUniqueMatch(msg)
def parse_query_from_url(url):
"""
Helper to get key bits of data from the "next" url returned
from the API on collections
:param url:
:return: dict
"""
values = parse_qs... | in values.keys()}
def get_all(function, criterion=None, args=None):
"""
:param function: Function to be called to get data
:param criterion: dict of filters to be applied
:param args: arguments to be given to the function
:return: DesignateList()
"""
criterion = criterion or {}
args ... |
IsCoolEntertainment/debpkg_python-wheel | wheel/test/test_tool.py | Python | mit | 746 | 0.013405 | from .. import tool
def test_keygen():
def get_keyring():
WheelKeys, keyring = tool.get_keyring()
class WheelKeysTest(WheelKeys):
def save(self):
pass
class ke | yringTest:
backend = keyring.backend
@classmethod
def get_keyring(cls):
class keyringTest2:
pw = None
de | f set_password(self, a, b, c):
self.pw = c
def get_password(self, a, b):
return self.pw
return keyringTest2()
return WheelKeysTest, keyringTest
tool.keygen(get_keyring=get_keyring)
|
pexip/os-foolscap | foolscap/crypto.py | Python | mit | 4,123 | 0.003638 | # -*- test-case-name: foolscap.test.test_crypto -*-
available = False # hack to deal with half-broken imports in python <2.4
from OpenSSL import SSL
# we try to use ssl support classes from Twisted, if it is new enough. If
# not, we pull them from a local copy of sslverify. The funny '_ssl' import
# stuff is used to... | V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
19, # X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
)
if errno in things_ | are_ok:
return 1
# TODO: log the details of the error, because otherwise they get
# lost in the PyOpenSSL exception that will eventually be raised
# (possibly OpenSSL.SSL.Error: certificate verify failed)
# I think that X509_V_ERR_CERT_SIGNATURE_FAILURE i... |
redhat-openstack/python-neutronclient | quantumclient/tests/unit/test_casual_args.py | Python | apache-2.0 | 2,739 | 0 | # Copyright 2012 OpenStack LLC.
# 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... |
class CLITestArgs(unittest.TestCase):
def test_empty(self):
_mydict = quantumV20.parse_args_to_dict([])
self.assertEqual({}, _mydict)
def test_default_bool(self):
_specs = ['--my_bool', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs)
self.assertTr... | parse_args_to_dict(_specs)
self.assertTrue(_mydict['my_bool'])
def test_bool_false(self):
_specs = ['--my_bool', 'type=bool', 'false', '--arg1', 'value1']
_mydict = quantumV20.parse_args_to_dict(_specs)
self.assertFalse(_mydict['my_bool'])
def test_nargs(self):
_specs =... |
live4thee/zstack-utility | kvmagent/kvmagent/plugins/prometheus.py | Python | apache-2.0 | 4,603 | 0.008473 | from kvmagent import kvmagent
from zstacklib.utils import jsonobject
from zstacklib.utils import http
from zstacklib.utils import log
from zstacklib.utils.bash import *
from zstacklib.utils import linux
from zstacklib.utils import thread
from jinja2 import Template
import os.path
import re
import time
import traceback
... | ue
elif eth.startswith('br_'): continue
elif not eth: continue
else:
interfaces.append(eth)
conf_path = os.path.join(os.path.dirname(cmd.binaryPath), 'collectd.conf')
conf = '''Int | erval {{INTERVAL}}
FQDNLookup false
LoadPlugin syslog
LoadPlugin aggregation
LoadPlugin cpu
LoadPlugin disk
LoadPlugin interface
LoadPlugin memory
LoadPlugin network
LoadPlugin virt
<Plugin aggregation>
<Aggregation>
#Host "unspecified"
Plugin "cpu"
#PluginInstance "unspecified"
Type "cpu"
#TypeInstance "u... |
paulrouget/servo | tests/wpt/web-platform-tests/webdriver/tests/perform_actions/validity.py | Python | mpl-2.0 | 2,188 | 0 | import pytest
from tests.support.asserts import assert_error, assert_success
def perform_actions(session, actions):
return session.transport.send(
"POST",
"/session/{session_id}/actions".format(session_id=session.session_id),
{"actions": actions})
@pytest.mark.parametrize("action_type",... | nse, "invalid argument")
@pytest.mark.parametrize("action_type", ["none", "key", "pointer"])
def test_pause_invalid_types(session, action_type):
for invalid_type in [0.0, None, "foo", True, [], {}]:
actions = [{
| "type": action_type,
"id": "foobar",
"actions": [{
"type": "pause",
"duration": invalid_type
}]
}]
response = perform_actions(session, actions)
assert_error(response, "invalid argument")
@pytest.mark.parametrize("action_typ... |
cmezh/PokemonGo-Bot | pokemongo_bot/cell_workers/pokemon_hunter.py | Python | mit | 6,128 | 0.003427 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
from geopy.distance import great_circle
from s2sphere import Cell, CellId, LatLng
from pokemongo_bot import inventory
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.item_list import Item
from pokemongo_bot.walkers.polyline_w... | = None
else:
self.logger.info("Now searching for %(name)s", self.destination)
self.walker = StepWalker(self.bot, self.search_points[0][0], self.search_points[0][1])
self.search_points = self.search_points[1:] + sel | f.search_points[:1]
elif self.no_log_until < now:
distance = great_circle(self.bot.position, (self.walker.dest_lat, self.walker.dest_lng)).meters
self.logger.info("Moving to destination at %s meters: %s", round(distance, 2), self.destination["name"])
self.no_log_until = now +... |
xbmcmegapack/plugin.video.megapack.dev | resources/lib/menus/home_languages_persian.py | Python | gpl-3.0 | 1,111 | 0.002705 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
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 Softwar... | uld have received a co | py of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Languages_Persian():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
... |
henry-ngo/VIP | vip_hci/negfc/simplex_optim.py | Python | mit | 16,676 | 0.010794 | #! /usr/bin/env python
"""
Module with simplex (Nelder-Mead) optimization for defining the flux and
position of a companion using the Negative Fake Companion.
"""
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize
from .simplex_fmerit import c... |
out : scipy.optimize.minimize solution object
The solution of th | e minimization algorithm.
"""
if verbose:
print('')
print('{} minimization is running...'.format(options.get('method','Nelder-Mead')))
if p_ini is None:
p_ini = p
solu = minimize(chisquare, p, args=(cube, angs, plsc, psf, fwhm, annulus_width,
... |
jzitelli/yawvrb.js | test/tornado_server.py | Python | mit | 1,909 | 0.00681 | import os.path
import logging
_logger = logging.getLogger(__name__)
from operator import itemgetter
from tornado.web import Application, RequestHandler, StaticFileHandler
from tornado.ioloop import IOLoop
config = {
'DEBUG': True,
'PORT' : 5000
}
HANDLERS = []
ROOT_DIR = os.path.abspath(os.path.join(os.pa... | ****
*********************************
STARTING TORNADO APP!!!!!!!!!!!!!
*********************************
*************************
Y | A W V R B
-----------
""" % port)
IOLoop.instance().start()
if __name__ == "__main__":
logging.basicConfig(level=(logging.DEBUG if config.get('DEBUG') else logging.INFO),
format="%(asctime)s: %(levelname)s %(name)s %(funcName)s %(lineno)d: %(message)s")
main()
|
zeroonegit/python | python_programming/password1.py | Python | mit | 786 | 0.005089 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
####################################################################### | ########
# Author: Quincey Sun
# Mail: zeroonegit@gmail.com
# Created Time: 2016-06-21 23:14:26
###############################################################################
## This programs asks a us | er for a name and a password.
# It then checks them to make sure that the user is allowed in .
# Note that this is a simple and insecure example,
# real password code should never be implemented this way.
name = input("What is your name? ")
password = input("What is the password? ")
if name == "Josh" and password == "... |
fernandoe/the-comics | tests/marvel/iterables/test_baseIterable.py | Python | gpl-3.0 | 816 | 0 | import os
from unittest import TestCase
import mock
from marvel.iterabl | es import BaseIterable
class FooIterable(BaseIterable):
def | __init__(self):
self.total_pages = 20
super(FooIterable, self).__init__()
def get_items(self):
if self.total_pages == 0:
raise StopIteration
else:
self.total_pages = self.total_pages - 1
return [self.total_pages]
class TestBaseIterable(TestCase... |
rdiaz82/mqttSqlLite | mqttsqlite/core/topics_controller.py | Python | mit | 2,034 | 0.00295 | from mqttsqlite.orm.models import Topic
import json
from mqttsqlite.settings.private_settings import MANAGEMENT_PASSWORD, QUERY_PASSWORD
from .utils import Payload, Utils
class TopicsController (object):
def add_topic(self, msg):
received_data = json.loads(msg.payload)
payload = Utils().validate_... | _instance()
else:
payload.result = 'KO'
payload.error = 'Topic not found'
saved_topics = []
for topic in Topic.select():
saved_topics.append(topic.name)
payload.topics = saved_topics
return payload.get_json()
de... | Utils().validate_data(received_data, QUERY_PASSWORD, ['password', 'client'], topic=False)
if payload.result == 'OK':
saved_topics = []
for topic in Topic.select():
saved_topics.append(topic.name)
payload.topics = saved_topics
return payload.get_json()
... |
ZhangXinNan/tensorflow | tensorflow/python/kernel_tests/control_flow_ops_py_test.py | Python | apache-2.0 | 121,396 | 0.014259 | # Copyright 2015 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... | .ops import gen_array_ops
from tensorflow.python.ops import gen_control_flow_ops
from tensorflow.python.ops import gen_data_flow_ops
from tensorflow.python.ops import gen_logging_ops
from tensorflow.python.ops import gen_state_ops
from tensorflow.python.ops import | gradients_impl
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_grad # pylint: disable=unused-import
from tensorflow.python.ops import nn_ops
from tensorf... |
AutorestCI/azure-sdk-for-python | azure-batch/azure/batch/models/job_get_options.py | Python | mit | 3,278 | 0.000305 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MI | T License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serializa... | rt Model
class JobGetOptions(Model):
"""Additional parameters for get operation.
:param select: An OData $select clause.
:type select: str
:param expand: An OData $expand clause.
:type expand: str
:param timeout: The maximum time that the server can spend processing the
request, in secon... |
BD2KGenomics/cactus | src/progressiveCactus.py | Python | gpl-3.0 | 16,648 | 0.003844 | #!/usr/bin/env python
# Progressive Cactus Package
# Copyright (C) 2009-2012 by Glenn Hickey (hickey@soe.ucsc.edu)
# and Benedict Paten (benedictpaten@gmail.com)
# 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... | "ktserver (this just specifies where nodes will attempt"
" to find the server, *not* where the ktserver will be"
" run)",
default=None)
ktGroup.add_option("--ktType", dest="ktType",
help="Kyoto Tycoon server type "... | "(memory, snapshot, or disk)"
" [default: %default]",
default='memory')
# sonlib doesn't allow for spaces in attributes in the db conf
# which renders this options useless
#ktGroup.add_option("--ktOpts", dest="ktOpts",
# ... |
rcocetta/kano-toolset | kano/profiling_late.py | Python | gpl-2.0 | 3,436 | 0.00291 | # profiling_late.py
#
# Copyright (C) 2015 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
#
'''
Module to enable profiling timepoints. This module is loaded
only if the configuration file exists, see profiling.py for more information
'''
import os
import sys
imp... | filing conf | file doesnt include point:{} for app {}'.format(name, app_name))
else:
logger.info('Profiling conf file doesnt include app:{}'.format(app_name))
logger.debug('timepoint '+name, transition=name, isStart=isStart, cmd=cmd, pythonProfile=pythonProfile)
|
jradavenport/cubehelix | setup.py | Python | bsd-2-clause | 605 | 0 | #!/usr/bin/env python
# encoding: utf-8
import os
from setuptools import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="cubehelix",
version="0.1.0",
author="James Davenport",
# author_email="",
description="Cubehelix colormaps for matp... | "BSD",
py_modules=['cubehelix'],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Scientific/Engineering :: Visualization",
# "Li | cense :: OSI Approved :: BSD License",
]
)
|
Azure/azure-sdk-for-python | sdk/synapse/azure-mgmt-synapse/azure/mgmt/synapse/aio/operations/_data_masking_rules_operations.py | Python | mit | 12,027 | 0.004074 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | kingRule",
**kwargs: Any
) -> "_models.DataMaskingRule":
"""Creates or upd | ates a Sql pool data masking rule.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param workspace_name: The name of the workspace.
:type workspace_name: str
:param sql_pool_name: SQL pool name.
:t... |
lablup/sorna-agent | src/ai/backend/kernel/python/sitecustomize.py | Python | lgpl-3.0 | 1,693 | 0.000591 | import os
import socket
import sys
input_host = '127.0.0.1'
input_port = 65000
batch_enabled = int(os.environ.get('_BACKEND_BATCH_MODE', '0'))
if batch_enabled:
# Since latest Python 2 has `builtins`and `input`,
# we cannot detect Python 2 with the existence of them.
if sys.version_info.major > 2:
... | )
| except ConnectionRefusedError:
userdata = b'<user-input-unavailable>'
return userdata.decode()
builtins._input = input # type: ignore
builtins.input = _input
else:
# __builtins__ is an alias dict for __builtin__ in modules other than __main__.
... |
TshepangRas/tshilo-dikotla | td_maternal/admin/maternal_arv_post_admin.py | Python | gpl-2.0 | 4,570 | 0.004376 | from collections import OrderedDict
from django.contrib import admin
from edc_export.actions import export_as_csv_action
from edc_base.modeladmin.admin import BaseTabularInline
from ..forms import MaternalArvPostForm, MaternalArvPostMedForm, MaternalArvPostAdhForm
from ..models import MaternalVisit, MaternalArvPost,... | nal_arv_post__on_arv_since',
'on_arv_reason': 'maternal_arv_post__on_arv_reason',
'on_arv_reason_other': 'maternal_arv_post__on_arv_reason_other',
'arv_status': 'maternal_arv_post__arv_status',
}),
)]
admin.site.register(MaternalArvPostMed, Ma... |
class MaternalArvPostAdmin(BaseMaternalModelAdmin):
form = MaternalArvPostForm
fields = (
"maternal_visit",
"on_arv_since",
"on_arv_reason",
"on_arv_reason_other",
"arv_status")
radio_fields = {
"on_arv_since": admin.VERTICAL,
"on_arv_reason": ad... |
yujikato/DIRAC | src/DIRAC/Interfaces/scripts/dirac_admin_sync_users_from_file.py | Python | gpl-3.0 | 1,909 | 0.012572 | #!/usr/bin/env python
########################################################################
# File : dirac-admin-sync-users-from-file
# Author : Adrian Casajus
########################################################################
"""
Sync users in Configuration with the cfg contents.
Usage:
dirac-admin-syn... | ort Script
from DIRAC.Core.Utilities.DIRACScript import DIRACScript
__RCSID__ = "$Id$"
@DIRACScript()
def main():
Script.registerSwitch("t", "test", "Only | test. Don't commit changes")
Script.parseCommandLine(ignoreErrors=True)
args = Script.getExtraCLICFGFiles()
if len(args) < 1:
Script.showHelp()
from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
diracAdmin = DiracAdmin()
exitCode = 0
testOnly = False
errorList = []
for unprocSw in Script.... |
Jinwithyoo/han | hangulize/langs/fin/__init__.py | Python | bsd-3-clause | 3,370 | 0 | # -*- coding: utf-8 -*-
from hangulize import *
class Finnish(Language):
"""For transcribing Finnish."""
__iso639__ = {1: 'fi', 2: 'fin', 3: 'fin'}
__tmp__ = ',;%'
vowels = 'aAeioOuy'
ob = 'bdfgkpstT'
notation = Notation([
# Convention: A = ä, O = ö
('å', 'o'),
('ä', ... | (L)),
('m,', Jongseong(M)),
('m', Choseong(M)),
('n,', Jongseong(N)),
('n', Choseong(N)),
('N', Jongseong(NG)),
('p,', Jongseong(B)),
('p', Choseong(P)),
('r', Choseong(L)),
('s', Choseong(S)),
('t,', Jongseong(S)),
('t | ', Choseong(T)),
('T', Choseong(C)),
('v', Choseong(B)),
('%', Choseong(NG)),
('Ja', Jungseong(YA)),
('JA', Jungseong(YAE)),
('Je', Jungseong(YE)),
('Ji', Jungseong(I)),
('Jo', Jungseong(YO)),
('JO', Jungseong(OE)),
('Ju', Jungseong(YU)),
... |
wyqwyq/mit6858-lab | submit.py | Python | mit | 1,330 | 0.003008 | #!/usr/bin/python
import os.path
import subprocess
import sys
import urllib
KEY_FILE = "submit.token"
def main(filename):
# Prompt for key if missing
if not os.path.exists(KEY_FILE):
print "Please visit http://css.csail.mit.edu/6.858/2014/labs/handin.html"
print "and enter your API key."
... | tten to %s" % KEY_FILE
# Read the key.
with open(KEY_FILE) as f:
key = f.read().strip()
# Shell out to curl. urllib2 doesn't deal with multipart attachments. Throw
# away the output; you just get a random HTML page.
with open("/dev/null", "a") as null:
subprocess.check_call([" | curl", "-f",
"-F", "file=@%s" % filename,
"-F", "key=%s" % key,
"http://6858.scripts.mit.edu/submit/handin.py/upload"],
stdout=null, stderr=null)
print "Submitted %s." % filename
print "Ple... |
ddurieux/alignak | test/test_service_description_inheritance.py | Python | agpl-3.0 | 2,454 | 0.00163 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2015: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... | without even the | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
#
# This file is used to test re... |
kylepjohnson/cltk | src/cltk/morphology/utils.py | Python | mit | 1,473 | 0.001358 | """Misc helper functions for extracting morphological
info from CLTK data structures.
"""
from typing import List, Optional, Tuple, Union
from cltk.core.data_types import Word
from cltk.core.exceptions import CLTKException
from cltk.morphology.universal_dependencies_features import (
NOMINAL_FEATURES,
VERBAL_... | sible_feature in ALL_POSSIBLE_FEATURES:
feature_variables.append(str(possible_feature).lower())
| if not word:
features_present.append(None)
continue
try:
feat = word.__getattr__(possible_feature)[0] # type: MorphosyntacticFeature
features_present.append(str(feat.name))
except CLTKException:
features_present.append(None)
if prepend_t... |
xrotwang/pyimeji | pyimeji/api.py | Python | apache-2.0 | 4,739 | 0.002532 | """A client for the REST API of imeji instances."""
import logging
from collections import OrderedDict
import requests
from six import string_types
from pyimeji import resource
from pyimeji.config import Config
log = logging.getLogger(__name__)
class ImejiError(Exception):
def __init__(self, message, error):
... | :param kw: Additional keyword parameters will be handed through to the \
appropriate function of the requests library.
:return: The return value of the function of the requests library or a decoded \
JSON object/array.
"""
| method = getattr(self.session, method.lower())
res = method(self.service_url + '/rest' + path, **kw)
status_code = res.status_code
if json:
try:
res = res.json()
except ValueError: # pragma: no cover
log.error(res.text[:1000])
... |
bluecap-se/yarr.client | tests/app_tests.py | Python | mit | 539 | 0.001855 | # -*- coding: utf-8 -*-
import pytest
from flask import url_for
def test_config(app):
assert ap | p.debug, 'App is in debug mode'
assert not app.config.get('MINIFY_HTML'), 'App does minify html'
as | sert app.config.get('ASSETS_DEBUG'), 'App does build assets'
assert app.config.get('YARR_URL'), 'App doesn\'t have Yarr! URL specified'
def test_routes(client):
assert client.get(url_for('index')).status_code == 200
assert client.get(url_for('search')).status_code == 302, 'Empty query should throw redi... |
alanjw/GreenOpenERP-Win-X86 | python/Lib/test/test_urllibnet.py | Python | agpl-3.0 | 8,057 | 0.001614 | #!/usr/bin/env python
import unittest
from test import test_support
import socket
import urllib
import sys
import os
import time
mimetools = test_support.import_module("mimetools", deprecated=True)
def _open_with_retry(func, host, *args, **kwargs):
# Connecting to remote hosts is flaky. Make it... | ()
os.unlink(file_location)
def test_header(self):
# Make sure header returned as 2nd value from urlretrieve is good.
file_location, header = self.urlretrieve("http://www.python.org/")
os.unlink(file_location)
self.assertIsInstance(header, mimetoo | ls.Message,
"header is not an instance of mimetools.Message")
def test_data_header(self):
logo = "http://www.python.org/community/logos/python-logo-master-v3-TM.png"
file_location, fileheaders = self.urlretrieve(logo)
os.unlink(file_location)
dat... |
sjkingo/python-auspost-pac | setup.py | Python | bsd-2-clause | 900 | 0.001111 | from setuptools import find_packages, setup
from auspost_pac import __version__ as version
setup(
name='python-auspost-pac',
version=version,
license='BSD',
author='Sam Kingston',
author_email='sam@sjkwi.com.au',
description='Python API for Australia Post\'s Postage Assessment Calculator (pac)... | rty',
'frozendict',
'requests',
],
packages=find_packages(),
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independ... | ,
'Programming Language :: Python',
],
)
|
jiadaizhao/LeetCode | 0801-0900/0865-Smallest Subtree with all the Deepest Nodes/0865-Smallest Subtree with all the Deepest Nodes.py | Python | mit | 610 | 0 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def dfs(root):
if root is None:
return N... | return right, rd + 1
elif ld > rd:
return left, ld + 1
else:
return ro | ot, ld + 1
return dfs(root)[0]
|
j2a/django-simprest | simprest/emitters.py | Python | bsd-3-clause | 1,874 | 0.001601 | try:
from cStringIO import StringIO
exce | pt ImportError:
from StringIO import StringIO
from d | jango.utils import simplejson
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.encoding import smart_unicode
EMITTERS = {}
def get_emitter(format):
try:
return EMITTERS[format]
except KeyError:
raise Value... |
kevinconway/venvctrl | venvctrl/venv/relocate.py | Python | mit | 3,455 | 0 | """Virtual environment relocatable mixin."""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import shutil
class RelocateMixin(object):
"""Mixin which adds the ability to relocate a virtual environmen... | e either at the root of the
# site- | packages, bundled within an egg directory, or both.
original_path = self.path
original_abspath = self.abspath
dirs = [self]
while dirs:
current = dirs.pop()
dirs.extend(current.dirs)
for file_ in current.files:
if file_.abspath.endswith... |
linktlh/Toontown-journey | toontown/toon/DistributedNPCBanker.py | Python | apache-2.0 | 3,769 | 0.001592 | from dir | ect.distributed.ClockDelta import *
from direct.interval.IntervalGlobal import *
from pandac.PandaModules import *
from DistributedNPCToonBase import *
from toontown.chat.ChatGlobals import *
from toontown.estate import BankGUI, BankGlobals
from toontown.nametag.NametagGlobals import *
from toontown.toonbase import TT... | def __init__(self, cr):
DistributedNPCToonBase.__init__(self, cr)
self.jellybeanJar = None
self.bankGUI = None
def disable(self):
self.ignoreAll()
taskMgr.remove(self.uniqueName('popupBankingGUI'))
taskMgr.remove(self.uniqueName('lerpCamera'))
if self.ban... |
beckjake/python3-hglib | tests/test-branches.py | Python | mit | 674 | 0.001484 | from . import common
import hglib
class test_branches(common.basetest):
def test_empty(self):
self.assertEquals(self.client.branches(), [])
def test_basic(self):
| self.append('a', 'a')
rev0 = self.client.commit('first', addremove=True)
self.client.branch('foo')
self.append('a', 'a')
rev1 = self.client.commit('second')
branches = self.client.branches()
expected = []
for r, n in (rev1, rev0):
r = self.clie... | closed(self):
pass
|
macs03/autoservicio | clientes/urls.py | Python | mit | 293 | 0.006826 | from django.conf.u | rls import patterns, include, url
urlpatterns = [
url(r'^$', 'clientes.views.clientes', name='clientes'),
url(r'^edit/(\d+)$', 'clientes.views.clientes_edit', name='editCliente'),
url(r'^delete/(\d+)$', 'clientes.views.clientes_delete', name='deleteCliente | '),
] |
stephengroat/miasm | miasm2/arch/msp430/disasm.py | Python | gpl-2.0 | 242 | 0 | from miasm2.core.asmblock import disasmEngine
from m | iasm2.arch.msp430.arch import mn_msp430
class dis_msp430(disasmEngine):
def __init__(self, bs=None, **kwargs):
super(dis_msp430, self).__init__(mn_msp430, None, bs, **kwa | rgs)
|
spl0k/supysonic | supysonic/api/radio.py | Python | agpl-3.0 | 1,836 | 0.000545 | # This file is part of Supysonic.
# Supysonic is a Python implementation of the Subsonic server API.
#
# Copyright (C) 2020 Alban 'spl0k' Féron
#
# Distributed under terms of the GNU AGPLv3 license.
from flask import request
from ..db import RadioStation
from . import get_entity, api_routing
from .exceptions import ... | gParameter
@api_routing("/getInternetRadioStations")
def get_radio_stations():
query = RadioStation.select().sort_by(RadioStation.name)
return request.formatter(
"internetRadioStations",
{"internetRadioStation": [p.as_subsonic_station | () for p in query]},
)
@api_routing("/createInternetRadioStation")
def create_radio_station():
if not request.user.admin:
raise Forbidden()
stream_url, name, homepage_url = map(
request.values.get, ("streamUrl", "name", "homepageUrl")
)
if stream_url and name:
RadioStatio... |
editxt/editxt | resources/syntax/sml.syntax.py | Python | gpl-3.0 | 1,797 | 0.003339 | # -*- coding: UTF-8 -*-
# Syntax definition automatically generated by hljs2xt.py
# source: sml.js
name = 'SML'
file_patterns = ['*.sml', '*.ml']
built_in = """
array bool char exn int list option order real ref string substring
vector unit word
""".split()
keyword = """
abstype and andalso as case da... | "\b(?:0[xX][a-fA-F0-9_]+[Lln]?|0[oO][0-7_]+[Lln]?|0[bB][01_]+[Lln]?|[0-9][0-9_]*(?:[Lln]|(?:\.[0-9_]*)?(?:[eE][-+]?[0-9_]+)?)?)"),
]
rules = [
('built_in', built_in),
('keyword', keyword),
('literal', literal),
('literal', [RE(r"\[(?:\|\|)?\]|\(\)")]),
('comm | ent', RE(r"\(\*"), [RE(r"\*\)")], comment),
('symbol', [RE(r"'[A-Za-z_](?!')[\w']*")]),
('type', [RE(r"`[A-Z][\w']*")]),
('type', [RE(r"\b[A-Z][\w']*")]),
# ignore {'begin': "[a-z_]\\w*'[\\w']*"},
('string', RE(r"'"), [RE(r"'")], string),
('string', RE(r"\""), [RE(r"\"")], string),
('number'... |
drcoms/drcom-generic | custom/drcom_for_dlnu_520(x).py | Python | agpl-3.0 | 12,107 | 0.016519 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket, struct, time
from hashlib import md5
import sys
import os
import random
# CONFIG
server = '172.16.192.111'
username=''
password=''
CONTROLCHECKSTATUS = '\x00'
ADAPTERNUM = '\x00'
host_ip = '0.210.30.0'
IPDOG = '\x00'
host_name = 'DRCOMFUCKER'
PRIMARY_DNS = '... | -1].encode('hex'), 16)
ret = (1968 * ret) & 0xffffffff
return struct.pack('<I', ret)
def mkpkt(salt, usr, pwd, mac):
data = '\x03\x | 01\x00'+chr(len(usr)+20)
data += md5sum('\x03\x01'+salt+pwd)
data += usr.ljust(36, '\x00')
data += CONTROLCHECKSTATUS
data += ADAPTERNUM
data += dump(int(data[4:10].encode('hex'),16)^mac).rjust(6,'\x00') #mac xor md51
data += md5sum("\x01" + pwd + salt + '\x00'*4) #md52
data += '\x01' # numb... |
jcsp/manila | manila/api/contrib/services.py | Python | apache-2.0 | 3,444 | 0 | # Copyright 2012 IBM Corp.
# 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 app... | 'status': 'disabled' if service['disabled'] else 'enabled',
'state': 'up' if utils.service_is_up(service) else 'down',
'updated_at': service['updated_at'],
}
services.append(service)
search_opts = [
'host',
' | binary',
'zone',
'state',
'status',
]
for search_opt in search_opts:
value = ''
if search_opt in req.GET:
value = req.GET[search_opt]
services = [s for s in services if s[search_opt] == value]
if len(... |
alexholcombe/spatiotopic-motion | dotLocalize.py | Python | mit | 26,405 | 0.023859 | from __future__ import print_function
from psychopy import sound, monitors, core, visual, event, data, gui, logging, info
import numpy as np
from copy import deepcopy
from math import atan, cos, sin, pi, sqrt, pow
import time, sys, platform, os, StringIO
from pandas import DataFrame
from calcUnderOvercorrect import cal... | cr"]:
print("Your window is full-screen, which is good for timing.")
print('Possible issues: internet / wireless? bluetooth? recent startup (not finished)?')
#if len(runInfo['systemUserProcFlagged']): #doesnt work if no internet
# print... |
medianHz = 1000./runInfo['windowRefreshTimeMedian_ms']
refreshMsg1= 'Median frames per second ~='+ str( np.round(medianHz,1) )
refreshRateTolerancePct = 3
pctOff = abs( (medianHz-refreshRate) / refreshRate )
refreshRateWrong = pctOff > (refreshRat... |
justyns/home-assistant | homeassistant/components/switch/rfxtrx.py | Python | mit | 5,695 | 0 | """
Support for RFXtrx switches.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.rfxtrx/
"""
import logging
import homeassistant.components.rfxtrx as rfxtrx
from homeassistant.components.rfxtrx import (
ATTR_FIREEVENT, ATTR_NAME, ATTR_PACKETID... | entity_name = "%s : %s" % (device_id, pkt_id)
datas = {ATTR_STATE: False, ATTR_FIREEVENT: False}
signal_repetitions = config.get('signal_repetitions',
SIGNAL_REPETITIONS)
new_switch = RfxtrxSwitch(entity_name, event, datas,
... | titions)
rfxtrx.RFX_DEVICES[device_id] = new_switch
add_devices_callback([new_switch])
# Check if entity exists or previously added automatically
if device_id in rfxtrx.RFX_DEVICES:
_LOGGER.debug(
"EntityID: %s switch_update. Command: %s",
... |
lagadic/ViSP-images | Gaussian-filter/Gaussian_filter.py | Python | gpl-2.0 | 838 | 0.008353 | from __future__ import print_functi | on
from scipy.ndimage import gaussian_filter
import numpy as np
from PIL import Image
img = np.asarray(Image.open('../Klimt/Klimt.ppm'))
img_gray = np.asarray(Image.open('../Klimt/Klimt.pgm'))
print('img:', img.shape)
sigmas = [0.5, 2, 5, 7]
for sigma in sigmas:
print('sigma:', sigma)
# # do not f | ilter across channels
# https://github.com/scikit-image/scikit-image/blob/fca9f16da4bd7420245d05fa82ee51bb9677b039/skimage/filters/_gaussian.py#L12-L126
img_blur = Image.fromarray(gaussian_filter(img, sigma=(sigma, sigma, 0), mode = 'nearest'))
img_blur.save('Klimt_RGB_Gaussian_blur_sigma={:.1f}.png'.format... |
eddieruano/Sentinel | assist/Adafruit_Python_MPR121/examples/simpletest.py | Python | apache-2.0 | 3,622 | 0.002485 | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# 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, m... | vic | e, and
# default I2C address (0x5A). On BeagleBone Black will default to I2C bus 0.
if not cap.begin():
print('Error initializing MPR121. Check your wiring!')
sys.exit(1)
#cap.set_thresholds(6, 12)
# Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
# 0x5C (ADDR tied to SDA), or 0x... |
soltraconpotprojectNLDA/SoltraConpot | conpot/protocols/kamstrup/usage_simulator.py | Python | gpl-2.0 | 4,667 | 0.000214 | # Copyright (C) 2014 Johnny Vestergaard <jkv@unixcluster.dk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This... | wres)
energy_out_register = 'register_14'
self.energy_out = databus.get_value(energy_out_register)
databus.set_value(energy_out_register, self._get_energy_out)
databus.set_value('register_2', self._get_energy_out_lowres)
volt_1_register = 'register_1054'
| self.voltage[0] = databus.get_value(volt_1_register)
databus.set_value(volt_1_register, self._get_voltage_1)
volt_2_register = 'register_1055'
self.voltage[1] = databus.get_value(volt_2_register)
databus.set_value(volt_2_register, self._get_voltage_2)
volt_3_register = '... |
madoodia/codeLab | pyside/signal_slot_tests/test_signal_slot.py | Python | mit | 752 | 0.00133 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
In this example, we connect a signal
of a QSlider to a slot
of a QLCDNumber.
"""
import sys
from PySide.QtGui import *
from PySide.QtCore import *
class Example(QWidget):
def __init__(self):
super(Example, self).__init__()
lcd = QLCDNumber()
... | Widget(lcd)
vbox.addWidget(sld)
sld.valueChanged.connect(lcd.display)
self.setLayout(vbox)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Signal & slot')
def main():
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_( | ))
if __name__ == '__main__':
main()
|
incnone/necrobot | necrobot/ladder/__init__.py | Python | mit | 678 | 0.004425 | """
Package for managing a ranked lad | der, which is a special kind of ongoing League.
Package Requirements
--------------------
botbase
match
user
Dependencies
------------
cmd_ladder
botbase/
commandtype
ladder/
ratingsdb
match/
cmd_match
matchinfo
user/
userlib
ladder
util/
server
la... | cmd_ladder
race/
cmd_racestats
user/
cmd_user
rating
ratingsdb
database/
dbconnect
ladder/
rating
ratingutil
ratingutil
ladder/
rating
util/
console
""" |
monetate/sqlalchemy | test/orm/inheritance/test_abc_polymorphic.py | Python | mit | 3,596 | 0 | from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.te... | )
c = Table(
"c",
metadata,
Column("id", Integer, ForeignKey("b.id"), primary_key=True) | ,
Column("cdata", String(30)),
)
@testing.combinations(("union",), ("none",))
def test_abc_poly_roundtrip(self, fetchtype):
class A(fixtures.ComparableEntity):
pass
class B(A):
pass
class C(B):
pass
if fetchtype == "unio... |
rjschwei/azure-sdk-for-python | azure-mgmt-logic/azure/mgmt/logic/operations/integration_account_schemas_operations.py | Python | mit | 14,610 | 0.002806 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | version = "2015-08-01-preview"
self.config = config
def list(
| self, resource_group_name, integration_account_name, top=None, filter=None, custom_headers=None, raw=False, **operation_config):
"""Gets a list of integration account schemas.
:param resource_group_name: The resource group name.
:type resource_group_name: str
:param integration_... |
ininex/geofire-python | resource/lib/python2.7/site-packages/gcloud/monitoring/test_timeseries.py | Python | mit | 6,799 | 0 | # Copyright 2016 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 agree... | : VALUE},
},
],
}
series = self._getTargetClass()._from_dict(info)
| self.assertEqual(series.metric.type, METRIC_TYPE)
self.assertEqual(series.metric.labels, METRIC_LABELS)
self.assertEqual(series.resource.type, RESOURCE_TYPE)
self.assertEqual(series.resource.labels, RESOURCE_LABELS)
self.assertEqual(series.metric_kind, METRIC_KIND)
self.asser... |
rooshilp/CMPUT410Lab6 | virt_env/virt1/lib/python2.7/site-packages/django/core/handlers/wsgi.py | Python | apache-2.0 | 9,514 | 0.000736 | from __future__ import unicode_literals
import cgi
import codecs
import logging
import sys
from io import BytesIO
from threading import Lock
import warnings
from django import http
from django.conf import settings
from django.core import signals
from django.core.handlers import base
from django.core.urlresolvers impo... | s been used, returns what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
set (to anything).
"""
if settings.FORCE_ | SCRIPT_NAME is not None:
return force_text(settings.FORCE_SCRIPT_NAME)
# If Apache's mod_rewrite had a whack at the URL, Apache set either
# SCRIPT_URL or REDIRECT_URL to the full resource URL before applying any
# rewrites. Unfortunately not every Web server (lighttpd!) passes this
# informati... |
0verchenko/Addressbook | fixture/db.py | Python | apache-2.0 | 1,388 | 0.005043 | import mysql.connector
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, dbname, username, password):
self.host = host
self.dbname = dbname
self.username = username
self.password = password
self.connection = mysql.conn... | ame, password=password)
self.connection.autocommit = True
def get_group_list(self):
list = []
cursor = self.connection.cursor()
try:
cursor.execute("select group_id, | group_name, group_header, group_footer from group_list")
for row in cursor:
(id, name, header, footer) = row
list.append(Group(id=str(id), name=name, header=header, footer=footer))
finally:
cursor.close()
return list
def get_contact_list(self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.