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 |
|---|---|---|---|---|---|---|---|---|
hedmo/compizconfig-python | setup.py | Python | gpl-2.0 | 5,125 | 0.025171 | # -*- coding: utf-8 -*-
from distutils.core import setup
from distutils.command.build import build as _build
from distutils.command.install import install as _install
from distutils.command.install_data import install_data as _install_data
from distutils.command.sdist import sdist as _sdist
from distutils.extension imp... | l, 'w')).communicate ()[0]
if len (pkgconfig_libs) is 0:
print ("CompizConfig Python [ERROR]: No libcompizconfig.pc found in the pkg-config search path")
print ("Ensure that libcompizonfig is installed o | r libcompizconfig.pc is in your $PKG_CONFIG_PATH")
exit (1);
libs = pkgconfig_libs[2:].split (" ")[0]
INSTALLED_FILES = "installed_files"
class install (_install):
def run (self):
_install.run (self)
outputs = self.get_outputs ()
length = 0
if self.root:
length += le... |
thisisshi/cloud-custodian | tools/ops/logsetup.py | Python | apache-2.0 | 2,623 | 0.000381 | # Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
"""Cloud Watch Log Subscription Email Relay
"""
import argparse
import itertools
import logging
import sys
from c7n.credentials import SessionFactory
from c7n.mu import LambdaManager
from c7n.ufuncs import logsub
log = logging.getLog | ger("custodian.logsetup")
def setup_parser():
parser = argparse.ArgumentParser()
parser.add_argument("--role", required=True)
# Log Group match
parser.add_argument("--prefix", default=None)
parser.add_argument("-g", "--group", action="append")
parser.add_argument("--pattern", default="Traceba... | ")
# Delivery
parser.add_argument("--topic", required=True)
parser.add_argument("--subject", default="Custodian Ops Error")
return parser
def get_groups(session_factory, options):
session = session_factory()
logs = session.client('logs')
params = {}
if options.prefix:
params... |
wwright2/dcim3-angstrom1 | sources/openembedded-core/meta/lib/oeqa/runtime/parselogs.py | Python | mit | 7,183 | 0.007379 | import os
import unittest
from oeqa.oetest import oeRuntimeTest
from oeqa.utils.decorators import *
#in the future these lists could be moved outside of module
errors = ["error", "cannot", "can\'t", "failed"]
common_errors = [
'(WW) warning, (EE) error, (NI) not implemented, (??) unknown.',
'dma timeout',
... | rseLogsTest(oeRuntimeTest):
@classmethod
def setUpClass(self):
self.errors = errors
self.ignore_errors = ignore_errors
self.log_locations = log_locations
self.msg = ""
def getMachine(self):
(status, output) = self.target.run("uname -n")
return output
#g... | . This info might be useful in some cases.
def getHardwareInfo(self):
hwi = ""
(status, cpu_name) = self.target.run("cat /proc/cpuinfo | grep \"model name\" | head -n1 | awk 'BEGIN{FS=\":\"}{print $2}'")
(status, cpu_physical_cores) = self.target.run("cat /proc/cpuinfo | grep \"cpu cores\" |... |
papedaniel/oioioi | oioioi/disqualification/__init__.py | Python | gpl-3.0 | 149 | 0 | """This ap | plication provides a framework for disqualifying users for variou | s
reasons, as well as simple modeling of any custom disqualification.
"""
|
GaretJax/pop-analysis-suite | pas/bin/pas.py | Python | mit | 4,689 | 0.001493 | #!/usr/bin/env python
"""
Main command line script of the pas package.
The main function contained in this module is used ai main entry point for the
pas command line utility.
The script is automatically created by setuptool, but this file can be
directly invoked with `python path/to/pas.py` or directly if its execut... | parser = commands.build_mainparser()
arguments = itertools.takewhile(lambda x: x.startswith('-'), sys.argv[1:])
arguments = (arg for arg in arguments if arg not in ('-h', '--help'))
command_line = sys.argv[:1] + list(arguments)
|
# Parse the base arguments (verbosity and settings)
args, remaining = parser.parse_known_args(command_line)
buffered_handler.setTarget(file_handler)
# Get the verbosity level
verbosity = max(1, VERBOSITY - 10 * (len(args.verbose) - len(args.quiet)))
console_handler.setLevel(verbosity)
fil... |
openstack/python-tripleoclient | tripleoclient/tests/v1/tripleo/test_tripleo_upgrade.py | Python | apache-2.0 | 5,026 | 0 | # Copyright 2018 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | ['--local-ip', '127.0.0.1',
| '--templates', '/tmp/thtroot',
'--stack', 'undercloud',
'--output-dir', '/my',
'-e', '/tmp/thtroot/puppet/foo.yaml',
'-e', ... |
krimkus/stipplebot | solenoid.py | Python | unlicense | 1,215 | 0.000823 | #!/usr/bin/env python
"""
Deprecated since the solenoid was not strong enough.
Was using: https://www.sparkfun.com/products/11015
5v, 4.5mm throw
"""
# Import required libraries
import time
import RPi.GPIO as GPIO
# Use BC | M GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# Base class for a solenoid motor controller using a stepper ULN2003 controller
class SolenoidMotor(object):
# # Define GPIO signals to use
# Pin 13, GPIO27
pin = 27
wait_time = .01
wa | it_time = .1
def __init__(self, **kwargs):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self, key, kwargs[key])
# Set pin as output
print "Setup pin"
GPIO.setup(self.pin, GPIO.OUT)
GPIO.output(self.pin, False)
def tap(self):
... |
ad-m/claw | tests/utils_test.py | Python | apache-2.0 | 242 | 0 | # -*- coding: utf-8 -*-
from nose.tools import *
from claw import util | s
def test_get_delimite | r():
eq_('\r\n', utils.get_delimiter('abc\r\n123'))
eq_('\n', utils.get_delimiter('abc\n123'))
eq_('\n', utils.get_delimiter('abc'))
|
RKD314/yumstat | yumstat/oauth2client/clientsecrets.py | Python | mit | 4,405 | 0.006583 | # Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | ion needed to interact with
an OAuth 2.0 protected service.
"""
__author__ = '[email protected] (Joe Gregorio)'
from anyjson import simplejson
# Properties that make a client_secrets.json file valid.
TYPE_WEB = 'web'
TYPE_INSTALLED = 'installed'
VALID_CLIENT = {
TYPE_WEB: {
'required': [
... | ],
'string': [
'client_id',
'client_secret',
],
},
TYPE_INSTALLED: {
'required': [
'client_id',
'client_secret',
'redirect_uris',
'auth_uri',
'token_uri',
],
'string': [
'clie... |
Linaro/lava-dispatcher | lava_dispatcher/actions/test/monitor.py | Python | gpl-2.0 | 8,107 | 0.00259 | # Copyright (C) 2014 Linaro Limited
#
# Author: Tyler Baker <[email protected]>
#
# This file is part of LAVA Dispatcher.
#
# LAVA Dispatcher 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... | etval = test_connection.expect(list(self.patterns.values()), timeout=timeout)
return self.check_patterns(list(self.patterns.keys())[retval], test_connection)
def check_patterns(self, event, test_connection): # pylint: disable=too-many-branches
"""
Defines the base set of pattern responses.... | lts of testcases inside the TestAction
Call from subclasses before checking subclass-specific events.
"""
ret_val = False
if event == "end":
self.logger.info("ok: end string found, lava test monitoring stopped")
self.results.update({'status': 'passed'})
el... |
alex/django-old | tests/regressiontests/requests/tests.py | Python | bsd-3-clause | 3,959 | 0.003031 | from datetime import datetime, timedelta
import time
import unittest
from django.http import HttpRequest, HttpResponse, parse_cookie
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.modpython import ModPythonRequest
from django.utils.http import cookie_date
class RequestsTests(unittest.Test... | datetime_cookie = response.cookies['datetime']
self.assertEqual(datetime_cookie['max-age'], 10)
def test_far_expiration(self):
"Cookie will expire when an distant expiration time is provided"
response = HttpResponse | ()
response.set_cookie('datetime', expires=datetime(2028, 1, 1, 4, 5, 6))
datetime_cookie = response.cookies['datetime']
self.assertEqual(datetime_cookie['expires'], 'Sat, 01-Jan-2028 04:05:06 GMT')
def test_max_age_expiration(self):
"Cookie will expire if max_age is provided"
... |
nicfit/Clique | clique/app/keygen.py | Python | lgpl-3.0 | 2,677 | 0 | # -*- coding: utf-8 -*-
import json
import nicfit
from pathlib import Path
from .utils import prompt
from ..common import thumbprint, CLIQUE_D
from .. import Identity, keystore
DEFAULT_KEYFILE = None
@nicfit.command.register
class keygen(nicfit.Command):
HELP = "Generate Clique (i.e. EC 256) encryption keys."
... | f keyfile.exists():
print("{} already exists.".format(keyfile))
if prompt("Overwrite (y/n)? ") != "y":
return 0
keyfile_pub = Path(str(keyfile) + ".pub")
indent = 2 if not self.args.compact else None
p | rint("Generating public/private P256 key pair.")
jwk = Identity.generateKey()
# TODO: Adding comments needs to be supported natively else it is too
# easy to lose them along the way.
'''
cmt = self.args.comment or prompt("Comment (optional): ", default=None)
if cmt:
... |
liampauling/flumine | tests/test_responses.py | Python | mit | 1,654 | 0 | import unittest
from unittest import mock
from flumine.order.responses import Responses
class ResponsesTest(unittest.TestCase):
def setUp(self):
self.responses = Responses()
def test_init(self):
self.assertIsNotNone(self.responses.date_time_created)
self.assertIsNone(self.responses.p... |
def test_date_time_placed(self):
self.assertIsNone(self.responses.date_time_placed)
self.responses._date_time_placed = 1
self.responses.current_order = mock.Mock(placed_date=2)
self.assertEqual(self.responses.date_time_p | laced, 1)
self.responses._date_time_placed = None
self.assertEqual(self.responses.date_time_placed, 2)
|
jboeuf/grpc | examples/python/data_transmission/server.py | Python | apache-2.0 | 4,492 | 0.001205 | # Copyright 2019 gRPC 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 to in writing... | lient(%d), message= %s" %
(request.client_id, request.request_data))
t = Thread(target=parse_request)
t.start()
for i in ran | ge(5):
yield demo_pb2.Response(
server_id=SERVER_ID,
response_data=("send by Python server, message= %d" % i))
t.join()
def main():
server = grpc.server(futures.ThreadPoolExecutor())
demo_pb2_grpc.add_GRPCDemoServicer_to_server(DemoServer(), server)
s... |
DBuildService/atomic-reactor | tests/plugins/test_group_manifests.py | Python | bsd-3-clause | 23,328 | 0.001715 | """
Copyright (c) 2017, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from functools import partial
import pytest
import json
import re
import responses
from tempfile import mkdtemp
import os
import reques... | self._get_manifest)
self._add_pattern(responses.HEAD, r'/v2/(.*)/manifests/([^/]+)',
| self._get_manifest)
self._add_pattern(responses.PUT, r'/v2/(.*)/manifests/([^/]+)',
self._put_manifest)
self._add_pattern(responses.GET, r'/v2/(.*)/blobs/([^/]+)',
self._get_blob)
self._add_pattern(responses.HEAD, r'/v2/(... |
Ophiuchus1312/enigma2-master | lib/python/Components/VolumeControl.py | Python | gpl-2.0 | 2,618 | 0.030558 | from enigma import eDVBVolumecontrol, eTimer
from Tools.Profile import profile
from Screens.Volume import Volume
from Screens.Mute import Mute
from GlobalActions import globalActionMap
from config import config, ConfigSubsection, ConfigInteger
from Components.HdmiCec import HdmiCec
profile("VolumeControl")
#TODO .. mo... | e = self
config.audio = ConfigSubsection()
config.audio.volume = ConfigInteger(default = 50, limits = (0, 100))
self.volumeDialog = session.instantiateDialog(Volume)
self.muteDialog = session.instantiateDialog(Mute)
self.hideVolTimer = eTimer()
self.hideVolTimer.callback.append(self.volHide)
vol = con... | lue()
self.volumeDialog.setValue(vol)
self.volctrl = eDVBVolumecontrol.getInstance()
self.volctrl.setVolume(vol, vol)
def volSave(self):
if self.volctrl.isMuted():
config.audio.volume.setValue(0)
else:
config.audio.volume.setValue(self.volctrl.getVolume())
config.audio.volume.save()
def volUp(self... |
gamernetwork/gn-django | gn_django/db/db_routers.py | Python | mit | 1,915 | 0.004178 | from gn_django.exceptions import ImproperlyConfigured
class AppsRouter:
"""
A router to route DB operations for one or more django apps to a particular
database.
Requires class attributes to be specified:
- `APPS` - an iterable of django app labels
- `DB_NAME` - a string for the DB to rou... | message = "There was no `DB_NAME` attribute specified for the db router '%s'" % (self.__class__.__name__)
raise ImproperlyConfigured(message)
def db_for_read(self, model, **hints):
"""
Attempts to read app models route to the named DB.
"""
if model._meta.app... | :
"""
Attempts to write app models go to the named DB.
"""
if model._meta.app_label in self.APPS:
return self.DB_NAME
return None
def allow_relation(self, obj1, obj2, **hints):
"""
Allow relations if a model in any of the apps this router manages ... |
mbalasso/mynumpy | numpy/lib/tests/test_utils.py | Python | bsd-3-clause | 1,046 | 0.008604 | from numpy.testing import *
import numpy.lib.utils as utils
from numpy.lib import deprecate
from StringIO import StringIO
def test_lookf | or():
out = StringIO()
utils.lookfor('eigenvalue', module='numpy', output=out,
import_modules=False)
out = out.getvalue()
assert_('numpy.linalg.eig' in out)
@deprecate
def old_func(self, x):
return x
@deprecate(message="Rather use new_func2")
def old_func2(self, x):
return x... | cate(old_func3, old_name="old_func3", new_name="new_func3")
def test_deprecate_decorator():
assert_('deprecated' in old_func.__doc__)
def test_deprecate_decorator_message():
assert_('Rather use new_func2' in old_func2.__doc__)
def test_deprecate_fn():
assert_('old_func3' in new_func3.__doc__)
assert_... |
luogangyi/Ceilometer-oVirt | build/lib/ceilometer/tests/mytest.py | Python | apache-2.0 | 307 | 0.013029 | #!/usr/bin/python
# PBR Generated from u'console_scripts'
import sys
|
#from ceilometer.cmd.agent_compute import main
#from ceilometer.cmd.agent_notification import main
#from ceilometer.cmd.coll | ector import main
from ceilometer.cmd.agent_central import main
if __name__ == "__main__":
sys.exit(main()) |
dimagi/django-digest | django_digest/test/methods/basic.py | Python | bsd-3-clause | 744 | 0.001344 | from __future__ import absolute_import
from __future__ import unicode_literals
from base64 import b64encode
from django_digest.test.methods imp | ort WWWAuthenticateError, BaseAuth
class BasicAuth(BaseAuth):
def authorization(self, request, response):
if response is not None:
challenges = self._authenticate_headers(response)
if 'Basic' not in challenges:
raise WWWAuthenticateError(
'Basic ... | uest['REQUEST_METHOD'],
response.request['PATH_INFO'])
)
return 'Basic %s' % b64encode((self.username + ':' + self.password).encode('utf-8')).decode('utf-8')
|
onepesu/django_transmission | settings/common.py | Python | mit | 93 | 0 | from set | tings.django import *
from settings.constants import *
from se | ttings.emails import *
|
indashnet/InDashNet.Open.UN2000 | android/external/chromium_org/third_party/WebKit/Tools/Scripts/webkitpy/layout_tests/lint_test_expectations_unittest.py | Python | apache-2.0 | 6,145 | 0.001627 | # Copyright (C) 2012 Google Inc. 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 conditions and the ... | ', 'debug_rwt_logging': False})
host = MockHost()
# FIXME: incorrect complaints about spacing pylint: disable=C0322
port = host.port_factory.get(options.platform, options=options)
port.expectations_dict = lambda: {'foo': '-- syntax error1', 'bar': '-- syntax error2'}
host.port_... | IO()
res = lint_test_expectations.lint(host, options, logging_stream)
self.assertEqual(res, -1)
self.assertIn('Lint failed', logging_stream.getvalue())
self.assertIn('foo:1', logging_stream.getvalue())
self.assertIn('bar:1', logging_stream.getvalue())
class MainTest(unittest.... |
popoffka/ponydraw | server/storage/FileStorage.py | Python | mit | 1,715 | 0.030338 | # -*- coding: utf-8 -*-
# © 2012 Aleksejs Popovs <[email protected]>
# Licensed under MIT License. See ../LICENSE for more info.
from BaseStorage import BaseStorage
try:
import cPickle as pickle
except ImportError:
import pickle
import os
class FileStorage(BaseStorage):
def __init__(self):
self.path = None
self.i... |
def saveRoom(self, room):
if not self.isOpen:
raise Exception('File | Storage is not open')
f = open(self.path + os.sep + room.name + os.extsep + 'pdd', 'wb')
pickle.dump(room, f, -1)
def getRoom(self, roomName):
if not self.isOpen:
raise Exception('FileStorage is not open')
if not self.roomInStorage(roomName):
raise Exception('No such room in storage')
f = open(self... |
vcavallo/letsencrypt | letsencrypt/tests/achallenges_test.py | Python | apache-2.0 | 1,096 | 0 | """Tests for letsencrypt.achallenges."""
import unittest
import mock
from acme import challenges
from acme import jose
from letsencrypt.tests import acme_util
from letsencrypt.tests import test_util
class DVSNITest(unittest.TestCase):
"""Tests for letsencrypt.achallenges.DVSNI."""
def setUp(self):
... | achall.token)
def test_gen_cert_and_response(self):
response, cert_pem, key_pem = self.achall | .gen_cert_and_response()
self.assertTrue(isinstance(response, challenges.DVSNIResponse))
self.assertTrue(isinstance(cert_pem, bytes))
self.assertTrue(isinstance(key_pem, bytes))
if __name__ == "__main__":
unittest.main() # pragma: no cover
|
NendoTaka/CodeForReference | CodeWars/8kyu/planetName.py | Python | mit | 231 | 0.008658 | def get_planet_name(id):
switch = {
| 1: "Mercury",
2: "Venus",
3: "Earth",
4: "Mars",
5: "Jupiter",
| 6: "Saturn",
7: "Uranus" ,
8: "Neptune"}
return switch[id]
|
vicyangworld/AutoOfficer | CmdFormat.py | Python | mit | 2,619 | 0.0126 | import ctypes
import os
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE= -11
STD_ERROR_HANDLE = -12
FOREGROUND_BLACK = 0x0
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color ... | end='\n'):
self.set_cmd_color(6 | 8)
print(print_text,end=end)
self.reset_color()
def print_blue_text(self, print_text,end='\n'):
self.set_cmd_color(1 | 10)
print(print_text,end=end)
self.reset_color()
if __name__ == '__main__':
clr = CmdFormat("Windo... | clr.set_cmd_color(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY)
clr.print_red_text('red')
clr.print_green_text("green")
clr.print_green_input_text("input: ")
clr.print_blue_text('blue')
clr.print_yellow_text('yellow')
input() |
overfl0/Bulletproof-Arma-Launcher | tests/utils/event_bridge_test.py | Python | gpl-3.0 | 1,873 | 0.004805 | # Bulletproof Arma Launcher
# Copyright (C) 2016 Sascha Ebert
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# bu... | def tearDown(self):
sys.modules["__main__"] = self.old_main
sys.modules[" | __main__"].__file__ = self.old_main_file
def test_connection_can_hold_more_than_one_msg(self):
parent_conn, child_conn = Pipe()
p = Process(target=worker_func, args=(child_conn,))
p.start()
# time.sleep(2)
self.assertEqual(parent_conn.recv(), 'test1')
self.assertEqu... |
DeDop/dedop | tests/util/__init__.py | Python | gpl-3.0 | 38 | 0 | __author__ = ' | DeDop Development Team | '
|
sunlightlabs/tcamp | tcamp/sked/utils.py | Python | bsd-3-clause | 218 | 0.013761 | _cur | rent_event = None
def get_current_event():
global _current_event
if not _current_event:
from sked.mod | els import Event
_current_event = Event.objects.current()
return _current_event |
jeromecc/doctoctocbot | src/conversation/migrations/0029_tweetdj_retweeted_by.py | Python | mpl-2.0 | 478 | 0.002092 | # Generated by Django 2.2.10 on 2020-03-11 20:13
from django.db import migrations, models
class Migration(migrations.Migration):
depend | encies = [
('moderation', '0039_auto_20200226_0322'),
('conversation', '0028_retweeted_retweet'),
]
operations = [
migrations.AddField(
model_name='tweetdj',
name='retweeted_by',
field=models.ManyToManyField(blank=True, to='moderation.SocialUser'),
... | ]
|
Tao4free/QGIS_plugins | SuperLabeling3/ui.py | Python | gpl-3.0 | 4,461 | 0.001793 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SuperLabeling.ui'
#
# Created by: PyQt5 UI code generator 5.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
... | ridLayout.setObjectName("gridLayout")
self.lbLayer = QtWidgets.QLab | el(Dialog)
self.lbLayer.setObjectName("lbLayer")
self.gridLayout.addWidget(self.lbLayer, 0, 0, 1, 1)
self.txLayer = QtWidgets.QLineEdit(Dialog)
self.txLayer.setObjectName("txLayer")
self.gridLayout.addWidget(self.txLayer, 0, 1, 1, 5)
self.lbStep1 = QtWidgets.QLabel(... |
bhanu-mnit/EvoML | evoml/subsampling/test_auto_segmentEG_FEMPO.py | Python | gpl-3.0 | 1,357 | 0.022108 | import pandas as pd
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor
from sklearn.cross_validation import train_test_split
from sklearn.metrics import mean_squared_error
from .auto_segment_FEMPO import BasicSegmenter_FEMP... | est, unseen_y = y_test)
clf.fit(X_tra | in, y_train)
print clf.score(X_test,y_test)
y = clf.predict(X_test)
print mean_squared_error(y, y_test)
print y.shape
return clf, X_test, y_test
|
quozl/sugar | src/jarabe/model/shell.py | Python | gpl-3.0 | 28,028 | 0 | # Copyright (C) 2006-2007 Owen Williams.
# Copyright (C) 2006-2008 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... | indow:
self.close_window()
def close_window(self):
if self.get_window() is not None:
self.get_window().close(GLib.get_current_time())
for w in self._shell_windows:
| w.destroy()
def remove_window_by_xid(self, xid):
"""Remove a window from the windows stack."""
for wnd in self._windows:
if wnd.get_xid() == xid:
self._windows.remove(wnd)
return True
return False
def get_service(self):
"""Get t... |
DBuildService/atomic-reactor | atomic_reactor/plugins/pre_download_remote_source.py | Python | bsd-3-clause | 5,554 | 0.001981 | """
Copyright (c) 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
Downloads and unpacks the source code archive from Cachito and sets appropriate build args.
"""
import base64
import os
import tarfile
from shle... | .path.join(self.workflow.builder.df_dir, self.REMOTE_SOURCE)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
else:
raise RuntimeError('Conflicting path {} al | ready exists in the dist-git repository'
.format(self.REMOTE_SOURCE))
with tarfile.open(archive) as tf:
tf.extractall(dest_dir)
config_files = (
self.get_remote_source_config(session, self.remote_source_conf_url, insecure_ssl_conn)
if ... |
dajohnso/cfme_tests | cfme/tests/cloud_infra_common/test_tag_visibility.py | Python | gpl-2.0 | 2,733 | 0.002561 | import fauxfactory
import pyte | st
import cfme.configure.access_control as ac
from cfme import test | _requirements
from cfme.base.credential import Credential
from cfme.common.vm import VM
from cfme.configure.configuration import Tag, Category
from utils import testgen
def pytest_generate_tests(metafunc):
argnames, argvalues, idlist = testgen.all_providers(metafunc, required_fields=['ownership_vm'])
testgen.... |
diego-d5000/MisValesMd | env/lib/python2.7/site-packages/django/contrib/auth/hashers.py | Python | mit | 17,840 | 0.000673 | from __future__ import unicode_literals
import base64
import binascii
import hashlib
import importlib
from collections import OrderedDict
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import rece... | raise ValueError("Unknown password hashing algorithm '%s'. "
"Did you specify it in the PASSWORD_HASHERS "
"setting?" % algorithm)
def identify_hasher(encoded):
"""
Returns an instance of a loaded password hasher.
Identifies hasher ... | er is not loaded.
"""
# Ancient versions of Django created plain MD5 passwords and accepted
# MD5 passwords with an empty salt.
if ((len(encoded) == 32 and '$' not in encoded) or
(len(encoded) == 37 and encoded.startswith('md5$$'))):
algorithm = 'unsalted_md5'
# Ancient ve... |
JiaKang0615/Group-Projects | Unemployment vs. campus crime rate.py | Python | cc0-1.0 | 2,534 | 0.028019 | from pandas import DataFrame, Series
import pandas as pd
import numpy as np
import random as r
from scipy import stats
import scipy
import math
# Calculate crime_y12_y12 rate
un_rate=pd.read_csv('Zip_county.csv')
Unemp=pd.read_csv('crate_year.csv')
crime=pd.read_csv('Python_totalsheet.csv')
crime=crime[[... | ppa_11"]+crime["ppc_11"]+crime["ppd_11"]
crime['Rate11']=crime['Crime11']/crime["Total"]
#groupby institutions
sub_group1 = crime.iloc[:,0:4]
sub_grouped1 = sub_group1.groupby('INSTNM',as_index = False).mean()
# groupby to get num of crime
sub_group2 = crime.iloc[:,1:2]
sub_group2['Crime11'] = crime['Crim... | otal']
#match county to zip code
data['ZIP_county'] = data['ZIP'].astype(str).str[:5]
data['ZIP_county'] = data['ZIP_county'].str.replace('.','').astype(int)
#match county unemp data to campus
un_rate['ZIP_county']=un_rate['ZIP']
result1 = pd.merge(data,un_rate, how='inner', on ='ZIP_county')
result2 = pd.me... |
szredinger/graph-constr-group-testing | graph_constr_group_testing/core/base_types.py | Python | mit | 5,126 | 0.005267 | """
Contains base data structures for defining graph constrained group testing problem,
and interfaces to operate on them.
Basic structure to exchange graph constrained group testing problem definition is :class:`Problem`.
It consists of enumeration of faulty elements, graph of links between elements and natural langu... | for each problem and solver statisti | cs object is gathered
"""
def __init__(self, rendererMapping):
self._renderers = rendererMapping or {}
for k, v in self._renderers.iteritems():
if v is None:
self._renderers[k] = lambda x: x.toDict()
self.results = []
self.headers = set({})
def ... |
saeki-masaki/cinder | cinder/volume/drivers/netapp/eseries/library.py | Python | apache-2.0 | 46,616 | 0.000021 | # Copyright (c) 2015 Alex Meade
# Copyright (c) 2015 Rushil Chugh
# Copyright (c) 2015 Navneet Singh
# Copyright (c) 2015 Yogesh Kshirsagar
# 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
... | 'solaris_v10': 'Solaris',
'vmware': 'VmwTPGSALUA',
'windows':
'Windows 2000/Server 2003/Server 2008 Non-Clustered',
'windows_atto': 'WinTPGSALUA',
'windows_clustered':
'Windows 2000/Server 2003/Serv... | # to the cinder scheduler.
SSC_DISK_TYPE_MAPPING = {
'scsi': 'SCSI',
'fibre': 'FCAL',
'sas': 'SAS',
'sata': 'SATA',
}
SSC_UPDATE_INTERVAL = 60 # seconds
WORLDWIDENAME = 'worldWideName'
DEFAULT_HOST_TYPE = 'linux_dm_mp'
def __init__(self, driver_name, driver_pro... |
grahamhayes/designate | designate/objects/adapters/api_v2/zone.py | Python | apache-2.0 | 2,504 | 0 | # Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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 requir... | eated_at": {},
"updated_at": {},
"transferred_at": {},
},
'options': {
'links': True,
| 'resource_name': 'zone',
'collection_name': 'zones',
}
}
@classmethod
def _parse_object(cls, values, object, *args, **kwargs):
if 'masters' in values:
object.masters = objects.adapters.DesignateAdapter.parse(
cls.ADAPTER_FORMAT,
... |
hazelcast/hazelcast-python-client | hazelcast/protocol/codec/custom/sql_column_metadata_codec.py | Python | apache-2.0 | 1,925 | 0.003636 | from hazelcast.protocol.builtin import FixSizedTypesCodec, CodecUtil
from hazelcast.serialization.bits import *
from hazelcast.protocol.client_message import END_FRAME_BUF, END_FINAL_FRAME_BUF, SIZE_OF_FRAME_LENGTH_AND_FLAGS, create_initial_buffer_custom
from hazelcast.sql import SqlColumnMetadata
from hazelcast.protoc... | od
def decode(msg):
msg.next_frame()
initial_frame = msg.next_frame()
type = FixSizedTypesCodec.decode_int(initial | _frame.buf, _TYPE_DECODE_OFFSET)
is_nullable_exists = False
nullable = False
if len(initial_frame.buf) >= _NULLABLE_DECODE_OFFSET + BOOLEAN_SIZE_IN_BYTES:
nullable = FixSizedTypesCodec.decode_boolean(initial_frame.buf, _NULLABLE_DECODE_OFFSET)
is_nullable_exists = True
... |
sburnett/seattle | seattlegeni/website/xmlrpc/dispatcher.py | Python | mit | 2,429 | 0.007822 | """
<Program>
dispatcher.py
<Started>
6 July 2009
<Author>
Justin Samuel
<Purpose>
XMLRPC handler for django.
Nothing in this file needs to be modified when adding/removing/changing
public xmlrpc methods. For that, see the views.py file in the same directory.
This xml | rpc dispatcher for django is modified from the version at:
http://code.djangoproject.com/wiki/XML-RPC
"""
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse
from seattlegeni.website.xmlrpc.views import PublicXMLRPCFunctions
from django.views.decorators.csrf import csrf_exempt... |
# This is the url that will be displayed if the xmlrpc service is requested
# directory through a web browser (that is, through a GET request).
SEATTLECLEARINGHOUSE_XMLRPC_API_DOC_URL = "https://seattle.cs.washington.edu/wiki/SeattleGeniApi"
# Create a Dispatcher. This handles the calls and translates info to functi... |
Pipe-s/dynamic_machine | dynamic_machine/cli_ssh.py | Python | mit | 5,503 | 0.008177 | '''
Created on Jun 16, 2014
@author: lwoydziak
'''
import pexpect
import sys
from dynamic_machine.cli_com | mands import assertResultNotEquals, Command
class SshCli(object):
LOGGED_IN = 0
def __init__(self, host, loginUser, debug = False, trace = False, log=None, port=22, pexpectObject=None):
self.pexpect = pexpect if not pexpectObject else pexpectObject
self.debug = debug
self.trace... | f._port = port
self._connection = None
self.modeList = []
self._log = log
self._bufferedCommands = None
self._bufferedMode = None
self._loginUser = loginUser
self._resetExpect()
def __del__(self):
self.closeCliConnectionTo()
def s... |
PersianWikipedia/pywikibot-core | tests/uploadbot_tests.py | Python | mit | 1,769 | 0 | # -*- coding: utf-8 -*-
"""
UploadRobot test.
These tests write to the wiki.
"""
#
# (C) Pywikibot team, 2014-2019
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, division, unicode_literals
import os
from pywikibot.specialbots import UploadRobot
from tests import join_i... | =[join_images_path('MP_sounds.png')],
targetSite=self.get_site(), **self.params)
bot.run()
def | test_png_url(self):
"""Test uploading a png from url using upload.py."""
link = 'https://upload.wikimedia.org/'
link += 'wikipedia/commons/f/fc/MP_sounds.png'
bot = UploadRobot(url=[link], targetSite=self.get_site(),
**self.params)
bot.run()
if __name_... |
dmisdani/netspeed_indicator | netspeed-indicator2.py | Python | gpl-3.0 | 13,609 | 0.047054 | #/usr/bin/env python
# -*- coding: utf-8 -*-
#Indicator-Netspeed
#
#Author: Dimitris Misdanitis
#Date: 2014
#Version 0.1
#⇧ 349 B/s ⇩ 0.0 B/s
#
#▲▼ ↓↑ ✔ ⬆⬇ ⇩⇧
import commands
from gi.repository import GObject,GLib
import gtk
import appindicator
import time
import urllib2
import os, subprocess
import io
import threa... | #300KB
self.parent.ind.set_icon("medium")
#print "medium"
elif summ>307200 and summ<=819200: #800
self.parent.ind.set_icon("high")
#print "high"
else:
self.parent.ind.set_icon("full")
#print "full"
return "%s%s %s%s"%(upformatted,uparrow,downformatted,downarrow)
#this is the thread. We al... | ata = self._fetch_speed()
self.parent.ind.set_label(data,'⬆8888 MB/s ⬇8888 MB/s')
time.sleep(1)
class indicatorNetspeed:
interfaces = [] #This list stores the interfaces.
active_interface = 'All' #Which device is monitored? The default is All (except lo)
proc_rows = []
menu_process=[] #This lis... |
MingStar/python-pinyin | tools/small_phrases.py | Python | mit | 562 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from pypinyin.phrases_dict import phrases_dict
from pypinyin import pinyin, TONE
phrases_list = set()
phrases_same = set()
for han, pys in phrases_dict.items():
if pinyin(han, style=TONE, heteronym=True) != pys:
phrases_list.add(han)
else:
phrase... | ain__':
with open('phrases_same.txt', 'w') as f:
for x in phrases_same:
f.write(u'%s\n' % x)
print(len(phrases | _dict))
print(len(phrases_same))
print(len(phrases_list))
|
mellenburg/dcos | packages/dcos-integration-test/extra/test_endpoints.py | Python | apache-2.0 | 11,490 | 0.001218 | import ipaddress
import urllib.parse
import bs4
import pytest
from requests.exceptions import ConnectionError
from retrying import retry
__maintainer__ = 'vespian'
__contact__ = '[email protected]'
def test_if_dcos_ui_is_up(dcos_api_session):
r = dcos_api_session.get('/')
assert r.status_code == ... | ):
r = dcos_api_sess | ion.get('/dcos-history-service/ping')
assert r.status_code == 200
assert 'pong' == r.text
def test_if_marathon_is_up(dcos_api_session):
r = dcos_api_session.get('/marathon/v2/info')
assert r.status_code == 200
response_json = r.json()
assert "name" in response_json
assert "marathon" == r... |
wangwei7175878/tutorials | tkinterTUT/tk6_scale.py | Python | mit | 643 | 0.009331 | # View more python learning tutorial on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutor | ial: http://i.youku.com/pythontutorial
import tkinter as tk
window = tk.Tk()
window.title('my window')
window.geometry('200x200')
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()
def print_selection | (v):
l.config(text='you have selected ' + v)
s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()
window.mainloop() |
googleapis/python-aiplatform | google/cloud/aiplatform_v1/types/model_service.py | Python | apache-2.0 | 17,689 | 0.000735 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | to obtain that page.
"""
@property
def raw_page(self):
return self
models = proto.RepeatedField(proto.MESSAGE, number=1, message=gca_model.Model,)
next_page_token = proto.Field(proto.STRING, number=2,)
class UpdateModelRequest(proto.Message):
r"""Request message for
[Mod... | Required. The Model which replaces the
resource on the server.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Required. The update mask applies to the resource. For the
``FieldMask`` definition, see
[google.protobuf.FieldMask][google.protobuf.FieldMask].... |
pcn/filechunkio | setup.py | Python | mit | 582 | 0.003436 | #!/usr/bin/env python
import sys
from distutils.core import setup
from filechunkio import __version_ | _
PY3 = sys.version_info[0] == 3
_unicode = str if PY3 else unicode
setup(
name="filechunkio",
version=_unicode(__version__),
description="FileChunkIO represents a chunk of an OS-level file "\
"containing bytes data",
long_description=open("README", 'r').read(),
author="Fabian Topfstedt",... | /filechunkio",
license="MIT license",
packages=["filechunkio"],
)
|
mattBrzezinski/Hydrogen | robot-controller/UI/__init__.py | Python | mit | 632 | 0.001582 | from AboutWindow import AboutWindow as AboutWindow
from ActionListWidget import ActionListWidget as ActionListWidget
from ActionPushButton import ActionPushButton as ActionPushButton
from CameraWidget import CameraWidget as CameraWidget
from ConnectDialog import ConnectDialog as ConnectDialog
from MainWindow import Mai... | ow
from MovementWidget import MovementWidget as MovementWidget
from Spee | chWidget import SpeechWidget as SpeechWidget
from SubmittableTextEdit import SubmittableTextEdit as SubmittableTextEdit
from SudokuBoard import SudokuBoard as SudokuBoard
from TimerWidget import TimerWidget as TimerWidget |
codeb2cc/weather | conf.py | Python | mit | 436 | 0.002577 | # -*- coding:utf-8 -*-
from __future__ import absolute_import, division, print_function, with_statement
import os
WEIBO_KEY = '2250230588'
WEIBO_SECRET = os.environ['WEIBO_SECRET']
# 未审核应用绑定开发者帐号Token有效期为五年, 无需动态更新
WEIBO_UID = '1652592967'
WEIBO_TOKEN = os.environ['WEIBO_TOKEN']
OAUTH2_URL = 'http://localhost.com/... | .0.0.1:11211', ]
MEMCACHED_PREFIX | = '#W#'
|
hryamzik/ansible | lib/ansible/plugins/cache/pickle.py | Python | gpl-3.0 | 2,016 | 0.001984 | # (c) 2017, Brian Coca
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
cache: pickle
short_descript... | seFileCacheModule
class CacheModule(BaseFileCacheModule):
"""
A caching module backed by pickle files.
"""
def _load(self, filepath):
# Pickle is a binary format
with open(filepath, 'rb') as f:
if PY3:
| return pickle.load(f, encoding='bytes')
else:
return pickle.load(f)
def _dump(self, value, filepath):
with open(filepath, 'wb') as f:
# Use pickle protocol 2 which is compatible with Python 2.3+.
pickle.dump(value, f, protocol=2)
|
garlick/flux-core | t/resource/get-xml-test.py | Python | lgpl-3.0 | 2,102 | 0.000476 | ###############################################################
# Copyright 2020 Lawrence Livermore National Security, LLC
# (c.f. AUTHORS, NOTICE.LLNS, COPYING)
#
# This file is part of the Flux resource manager framework.
# For details, see https://github.com/flux-framework.
#
# SPDX-License-Identifier: LGPL-3.0
####... | ure get-xml initially blocks
delay = 0.5
log.info("waiting up to %.2f | s for get-xml (should block)", delay)
try:
future.wait_for(delay)
except OSError as err:
if err.errno == errno.ETIMEDOUT:
pass
else:
raise err
if future.is_ready():
log.error("resource.get-xml returned before expected")
sys.exit(1)
log.info("loading resource module on rank %d", siz... |
linkedin/naarad | src/naarad/metrics/gc_metric.py | Python | apache-2.0 | 15,945 | 0.008028 | # coding=utf-8
"""
Copyright 2013 LinkedIn 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 applicable l... | Pause (seconds)',
'g1-pause-remark': 'G1 Remark Pause (seconds)',
'g1-pause-cleanup': 'G1 Cleanup Pau | se (seconds)',
'g1-pause-remark.ref-proc': 'G1 Remark: Reference Processing (seconds)',
'g1-pause-young.parallel': 'G1 Young GC Pause: Parallel Operations (ms)',
'g1-pause-young.parallel.gcworkers': 'G1 Young GC Pause: Number of Parallel GC Workers',
'g1-pause-young.parallel.gc-worker-st... |
Seanmcn/poker | poker/website/pokerstars.py | Python | mit | 2,318 | 0.014668 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
from collections import namedtuple
from dateutil.parser import parse as parse_date
import requests
from lxml import etree
__all__ = ['get_current_tournaments', 'get_status', 'WEBSITE_URL', 'TOURNAMENTS_XML_URL'... | tatus: players online, number of tables, etc."""
res = requests.get(STATUS_URL)
status = res.json()['tournaments']['summary']
# move all sites under sites attribute, including play money
sites = status.pop('site')
play_money = status.pop('play_money')
play_money['id'] = 'Play Money'
sites.... | le(_SiteStatus(**site) for site in sites)
updated = parse_date(status.pop('updated'))
return _Status(sites=sites, updated=updated, **status)
|
carlmjohnson/django-json-form | jsonform_example/forms.py | Python | mit | 218 | 0.004587 | from django import forms
class ExampleForm(forms.Form):
non_blank_field = forms.CharField(max_length=100,
widget=forms.TextInput(attrs={
'placeholder': "Must not be bla | nk!",
}),
)
| |
gam17/QAD | qad_highlight.py | Python | gpl-3.0 | 4,234 | 0.021749 | # -*- coding: utf-8 -*-
"""
/***************************************************************************
QAD Quantum Aided Design plugin
Classe per gestire l'evidenziazione delle geometrie
-------------------
begin : 2015-12-12
copyright ... | : bbbbb aaaaa ggggg
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribut... | e GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
************************************... |
dlutxx/cement | releases/2014-06-24 22 59.py | Python | mit | 60,847 | 0.048787 | #!python
#-*- encoding=utf-8 -*-
import sys, sqlite3, logging, os, os.path
import wx, time, re, copy, webbrowser
import wx.grid, wx.html
import json, math
# cfg start #
class Config:
def __init__(self):
self.environment = ('production','dev')[1]
self.expiration = 20
self.rootdir = r'C:\xux'
self.... | tc.SetFocus()
tc.S | etBackgroundColour("pink")
tc.Refresh()
return False
def cnNumber( flt ):
'''
123[.123] flt
'''
if ''==flt:
return ''
NUMBERS = u'零壹贰叁肆伍陆柒捌玖'
UNITS = u' 拾佰仟万拾佰仟亿'
ret = ''
flt = float(flt)
left, rite = str(flt).split('.')
if not left and not rite or len(left)>9:
return ''
left = ''.... |
shashisp/blumix-webpy | app/gluon/storage.py | Python | mit | 8,573 | 0.001283 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <[email protected]>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary ... | to `obj['foo']`, and setting obj.foo = None deletes item foo.
Exam | ple::
>>> o = Storage(a=1)
>>> print o.a
1
>>> o['a']
1
>>> o.a = 2
>>> print o['a']
2
>>> del o.a
>>> print o.a
None
"""
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getite... |
nfscan/fuzzy_cnpj_matcher | service/sequential_search.py | Python | mit | 2,341 | 0.003417 | import time
from fuzzyset import FuzzySet
__author__ = 'paulo.rodenas'
class SequentialFuzzyCnpjMatcher:
"""
Class that performs fuzzy string matching on CNPJs sequentially. For small
fuzzyset this class is the easiest way to get started. However if you going
for a large fuzzyset we strongly recommen... | is None:
for m in match:
best_matches.append(m[1])
# Performing Fuzzy string match | on the best results of each cnpj base file
self.__fuzzy_matcher = FuzzySet(best_matches)
return self.__fuzzy_matcher.get(cnpj)[0]
def __log(self, msg, debug=False):
"""
Prints a message to console depending on debug variable
:param msg: a message string
:param debug:... |
stafur/pyTRUST | paypal-rest-api-sdk-python/samples/subscription/billing_agreements/suspend_and_re_activate.py | Python | apache-2.0 | 1,184 | 0.004223 | from paypalrestsdk import BillingAgreement
import logging
BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ"
try:
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state))
suspend_note = {
"note": "Suspendin... | te_note = {
"note": "Reactivating the agreement"
}
if billing_agreement.reactivate(reactivate_note):
# Would expect state has changed to Active
billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID)
print("Billing Agreement [%s] has state %s" % (bi... | _agreement.error)
except ResourceNotFound as error:
print("Billing Agreement Not Found")
|
isaachenrion/jets | src/architectures/nmp/message_passing/__init__.py | Python | bsd-3-clause | 440 | 0.002273 | from .message_passing_layers import MP_LAYE | RS
#from .adjacency import construct_adjacency_matrix_layer
'''
This module implements the core message passing operations.
###adjacency.py <-- compute an adjacency matrix based on vertex data.
message_passing.py <-- run a single iteration of message passing.
message.py <-- compute a mes | sage, given a hidden state.
vertex_update.py <-- compute a vertex's new hidden state, given a message.
'''
|
ZackYovel/studybuddy | server/studybuddy/discussions/migrations/0006_auto_20150430_1648.py | Python | mit | 428 | 0 | # -*- coding: utf-8 -*-
from __future__ import unic | ode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('discussions', '0005_auto_20150430_1645'),
]
operations = [
migrations.AlterField(
model_name='post',
name='replays_to',
fie | ld=models.ForeignKey(to='discussions.Post', null=True),
),
]
|
MariusWirtz/TM1py | TM1py/Objects/NativeView.py | Python | mit | 9,988 | 0.001902 | # -*- coding: utf-8 -*-
import json
from TM1py.Objects.Axis import ViewAxisSelection, ViewTitleSelection
from TM1py.Objects.Subset import Subset, AnonymousSubset
from TM1py.Objects.View import View
class NativeView(View):
""" Abstraction of TM1 NativeView (classic cube view)
:Notes:
Complet... | :param selection: name of an element.
:param subset: instance of TM1py.Subset. Can be None instead.
:return:
"""
view_title_selection = ViewTitleSelection(dimension_name, subset, selection)
self._titles.append(view_title_selection)
def remove_title(self, dimension_name):
... |
for title in self._titles:
if title.dimension_name == dimension_name:
self._titles.remove(title)
@classmethod
def from_json(cls, view_as_json, cube_name=None):
""" Alternative constructor
:Parameters:
`view_as_json` : string, JSON... |
fghaas/django-oscar-vat_moss | setup.py | Python | bsd-3-clause | 1,343 | 0 | #!/usr/bin/env python
from setuptools import setup, find_packages
from oscar_vat_moss import get_version
setup(
name='django-oscar-vat_moss',
version=get_version(),
| url='https://github.com/hastexo/djang | o-oscar-vat_moss',
description=(
"EU VATMOSS support for django-oscar"),
long_description=open('README.rst').read(),
keywords="VATMOSS, Tax, Oscar",
license=open('LICENSE').read(),
platforms=['linux'],
packages=find_packages(exclude=['sandbox*', 'tests*']),
include_package_data=True,... |
biothings/biothings_explorer | tests/test_apis/test_corddisease.py | Python | apache-2.0 | 4,836 | 0.000207 | import unittest
from biothings_explorer.registry import Registry
from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher
from .utils import get_apis
reg = Registry()
class TestSingleHopQuery(unittest.TestCase):
def test_disease2protein(self):
"""Test gene-protein"""
seqd = ... | eEdgeQueryDispatcher(
output_cls="CellularComponent",
inp | ut_cls="Disease",
input_id="DOID",
output_id="GO",
values="DOID:0001816",
)
seqd.query()
self.assertTrue("GO:0030017" in seqd.G)
edges = seqd.G["DOID:DOID:0001816"]["GO:0030017"]
self.assertTrue("CORD Disease API" in get_apis(edges))
def t... |
rodrigolucianocosta/ControleEstoque | rOne/Storage101/django-localflavor/django-localflavor-1.3/localflavor/mk/forms.py | Python | gpl-3.0 | 3,600 | 0.001667 | from __future__ import unicode_literals
import datetime
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from .mk_choices import MK_MUNICIPALITIES
class MKIdentityCardN... | self).clean(value)
if value in EMPTY_VALUES:
return ''
if not self._validate_date_part(value):
raise ValidationError(self.error_messages['date'])
if self._validate_checksum | (value):
return value
else:
raise ValidationError(self.error_messages['checksum'])
def _validate_checksum(self, value):
a, b, c, d, e, f, g, h, i, j, k, l, K = [
int(digit) for digit in value]
m = 11 - ((7 * (a + g) + 6 * (b + h) + 5 * (
c + i... |
smmribeiro/intellij-community | plugins/hg4idea/testData/bin/hgext/git/gitutil.py | Python | apache-2.0 | 1,109 | 0 | """utilities to assist in working with pygit2"""
from __future__ import absolute_import
from mercurial.node import bin, hex, sha1nodeconstants
from mercurial import pycompat
pygit2_module = None
| def get_pygit2():
global pygit2_module
if pygit2_module is None:
try:
import pygit2 as pygit2_module
pygit2_module.InvalidSpecError
except (ImportError, AttributeError):
pass
return pygit2_module
def pygit2_version():
mod = get_pygit2()
v = "N/A... | except AttributeError:
pass
return b"(pygit2 %s)" % v.encode("utf-8")
def togitnode(n):
"""Wrapper to convert a Mercurial binary node to a unicode hexlified node.
pygit2 and sqlite both need nodes as strings, not bytes.
"""
assert len(n) == 20
return pycompat.sysstr(hex(n))
def... |
m038/superdesk-content-api | content_api/items/service.py | Python | agpl-3.0 | 17,471 | 0.000114 | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import funct... | )
def _process_fetched_object(self, document):
"""Does some processing on the raw document fetched from database.
It sets the item's `uri` field and removes all the fields added by the
`Eve` framework that are not part of the NINJS standard (except for
the HATEOAS `_lin... | MongoDB document to process
"""
document['uri'] = self._get_uri(document)
for field_name in ('_id', '_etag', '_created', '_updated'):
document.pop(field_name, None)
if 'renditions' in document:
for _k, v in document['renditions'].items():
if 'me... |
IvIePhisto/Ancestration | tests/adopt_into_b.py | Python | mit | 181 | 0.005525 | class ClassC(object):
FAMILY_INHERIT = {'a'}
def c(self):
| return 'family_b: C'
@classmethod
def super_family(cls):
return cls.module.super_famil | y
|
opencast/pyCA | pyca/ui/jsonapi.py | Python | lgpl-3.0 | 9,716 | 0 | # -*- coding: utf-8 -*-
from flask import jsonify, make_response, request
from pyca.config import config
from pyca.db import Service, ServiceStatus, UpcomingEvent, \
RecordedEvent, UpstreamState
from pyca.db import with_session, Status, ServiceStates
from pyca.ui import app
from pyca.ui.utils import requires_auth, ... | api', uid)
events = db.query(RecordedEvent).filter(RecordedEvent.uid == uid)
if not events.count():
return make_error_response('No event with specified uid', 404)
hard_delete = request.args.get('hard', 'false')
if hard_delete == 'true':
logger.info('deleting recorded files at %s', events... |
@app.route('/api/events/<uid>', methods=['PATCH'])
@requires_auth
@jsonapi_mediatype
@with_session
def modify_event(db, uid):
'''Modify an event specified by its uid. The modifications for the event
are expected as JSON with the content type correctly set in the request.
Note that this method works for re... |
BertrandBordage/django-terms | terms/tests/__init__.py | Python | bsd-3-clause | 41 | 0 | from . | html im | port *
from .terms import *
|
dbk138/ImageRegionRecognition-FrontEnd | app/python - Copy/Helpers.py | Python | mit | 4,339 | 0.021203 | __author__ = 'jhala'
import types
import os.path, time
import json
import logging
import logging.config
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(__name__)
import re
appInfo='appinfo.json'
''' Helper Functions '''
''' get the file as an array of arrays ( header + rows and columns) '''
def... | eArr):
for rowOne in fileArr:
return rowOne
def fileLastTouchedTime(fileName):
mtim= int(os.path.getmtime(fileName))
ctim= int(os.pat | h.getctime(fileName))
tims = [ mtim, ctim]
tims.sort()
return tims[len(tims)-1]
def getImageLocation():
f=open(appInfo,'r')
loc=json.load(f)
return loc['imageLocation']
def getImageDataLocation():
f=open(appInfo,'r')
loc=json.load(f)
return loc['imageData']
def getMatLabFeatureEx... |
bk1285/rpi_wordclock | wordclock_interfaces/web_interface.py | Python | gpl-3.0 | 11,610 | 0.002929 | from flask import Flask, render_template
import _thread
import logging
from flask_restx import Api, Resource, fields
import wordclock_tools.wordclock_colors as wcc
import wordclock_tools.wordclock_display as wcd
import datetime
class web_interface:
app = Flask(__name__)
api = Api(app,
... | web_interface.api.payload.get('type')
supplied_type = 'all' if supplied_type is | None else supplied_type
default_plugin_idx = web_interface.app.wclk.default_plugin
web_interface.app.wclk.runNext(default_plugin_idx)
default_plugin = web_interface.app.wclk.plugins[default_plugin_idx]
if supplied_type == 'all':
default_plugin.bg_color = wcc.BLACK
... |
JIC-CSB/jobarchitect | jobarchitect/agent.py | Python | mit | 1,898 | 0 | """Jobarchitect agent."""
import os
import argparse
import subprocess
from jobarchitect.utils import (
output_path_from_hash,
mkdir_parents
)
class Agent(object):
"""Class to create commands to analyse data."""
def __init__(
self,
tool_path,
dataset_path,
output_root... | _from_hash(
self.dataset_path, identifier, self.output_root)
mkdir_parents(output_path)
cmd = ["python",
self.tool_path,
"--dataset-path", self.dataset_path,
"--identifier", identifier,
"--output-directory", output_path]
sub... | ntifiers):
"""Run analysis on identifiers.
:param tool_path: path to tool
:param dataset_path: path to input dataset
:param output_root: path to output root
:identifiers: list of identifiers
"""
agent = Agent(tool_path, dataset_path, output_root)
for i in identifiers:
agent.run_... |
caronc/newsreap | bin/nr.py | Python | gpl-3.0 | 11,500 | 0.001652 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# NewsReap Command Line Interface (CLI)
#
# Copyright (C) 2015-2016 Chris Caron <[email protected]>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software... | os.path import isfile
# Path
try:
from newsreap.NNTPSettings import CLI_PLUGINS_MAPPING
except ImportError:
sys.path.insert(0, dirname(dirname(abspath(__file__))))
from newsreap.NNTPSettings imp | ort CLI_PLUGINS_MAPPING
# Import our file based paths
from newsreap.NNTPSettings import DEFAULT_CLI_PLUGIN_DIRECTORIES
from newsreap.NNTPSettings import NNTPSettings
from newsreap.NNTPManager import NNTPManager
from newsreap.Utils import scan_pylib
from newsreap.Utils import load_pylib
# Logging
from newsreap.Logging... |
lmazuel/azure-sdk-for-python | azure-mgmt-web/azure/mgmt/web/operations/domains_operations.py | Python | mit | 52,494 | 0.002534 | # 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 ... | 'NameIdentifier')
# Construct and send request
request = self._client.post(url, quer | y_parameters)
response = self._client.send(
request, header_parameters, body_content, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
... |
NickPresta/sentry | src/sentry/coreapi.py | Python | bsd-3-clause | 10,660 | 0.00075 | """
sentry.coreapi
~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# TODO: We should make the API a class, and UDP/HTTP just inherit from it
# This will make it so we can more easily control logging with various
# m... | format = '%Y-%m-%dT%H:%M:%S.%f'
else:
format = '%Y-%m-%dT%H:%M:%S'
if | 'Z' in data['timestamp']:
# support UTC market, but not other timestamps
format += 'Z'
try:
data['timestamp'] = datetime.strptime(data['timestamp'], format)
except Exception:
raise InvalidTimestamp('Invalid value for timestamp: %r' % data['timestamp'])
... |
hawkowl/axiom | axiom/test/historic/test_parentHook2to3.py | Python | mit | 1,325 | 0.002264 |
"""
Test upgrading L{_SubSchedulerParentHook} from version 2 to 3.
"""
from axiom.test.historic.stubloader import StubbedTest
from axiom.scheduler import _SubSchedulerParentHook
from axiom.substore import SubStore
from axiom.dependency import _DependencyConnector
class SubSchedulerParentHookUpgradeTests(StubbedTes... | lf.assertIdentical(
self.hook.subStore, self.store.findUnique(SubStore))
def test_uninstalled(self):
"""
The record of the installation of L{_SubSchedulerParentHook} on the
store is deleted in the upgrad | e to schema version 4.
"""
self.assertEquals(
list(self.store.query(
_DependencyConnector,
_DependencyConnector.installee == self.hook)),
[])
|
theju/urlscript | urlscript/settings.py | Python | mit | 3,699 | 0.001081 | """
Django settings for urlscript project.
Generated by 'django-admin startproject' using Django 1.9.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
... | 'django.con | trib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'urlscript.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'd... |
eleftherioszisis/NeuroM | neurom/fst/_neuronfunc.py | Python | bsd-3-clause | 10,088 | 0.000991 | # Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project
# All rights reserved.
#
# This file is part of NeuroM <https://github.com/BlueBrain/NeuroM>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are ... | of the somata in a population of neurons
Note:
If a single neuron is passed, a single element list with the volume
of its soma member is returned.
'''
nrns = neuron_population(nrn_pop)
return [soma_volume(n) for n in nrns]
def soma_surface_area(nrn, neurite_type=NeuriteType.soma):
... | soma, 'Neurite type must be soma'
return 4 * math.pi * nrn.soma.radius ** 2
def soma_surface_areas(nrn_pop, neurite_type=NeuriteType.soma):
'''Get the surface areas of the somata in a population of neurons
Note:
The surface area is calculated by assuming the soma is spherical.
Note:
I... |
release-monitoring/anitya | anitya/tests/lib/versions/test_base.py | Python | gpl-2.0 | 8,780 | 0.000456 | # -*- coding: utf-8 -*-
#
# Copyright © 2017-2020 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions
# of the GNU General Public License v.2, or (at your option) any later
# version. This program is distributed ... | rsion(version="1.0.0")
self.assertEqual("1.0.0", versi | on.parse())
def test_parse_leading_v(self):
"""Assert parsing a version with a leading 'v' works."""
version = base.Version(version="v1.0.0")
self.assertEqual("1.0.0", version.parse())
def test_parse_odd_version(self):
"""Assert parsing an odd version works."""
version ... |
igemsoftware2017/USTC-Software-2017 | biohub/core/tasks/payload.py | Python | gpl-3.0 | 1,411 | 0 | from biohub.core.tasks.exceptions import TaskInstanceNotExists
from biohub.core.tasks.result import AsyncResult
class TaskPayload(object):
"""
A task payload carries information related to a specific task instance,
including task_id, arguments, options, etc.
"""
__slots__ = ['task_name', 'task_id... | (cls, packed_data):
"""
A factory function to create a payload from a tuple.
"""
return cls(*packed_data)
@c | lassmethod
def from_task_id(cls, task_id):
"""
A factory function to fetch task payload through a given task_id.
"""
packed_data = AsyncResult(task_id).payload
if packed_data is None:
raise TaskInstanceNotExists(task_id)
return cls.from_packed_data(packe... |
XeCycle/indico | indico/web/menu.py | Python | gpl-3.0 | 7,214 | 0.001109 | # This file is part of Indico.
# Copyright (C) 2002 - 2015 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... | self._sorted_items = None
self._items.add(item)
@property
def items(self):
if | self._sorted_items is None:
self._sorted_items = sorted(self._items, key=lambda x: (-x.weight, x.title))
return self._sorted_items
@property
def active(self):
return self._active or any(item.active for item in self._items)
@return_ascii
def __repr__(self):
return f... |
ChristopherUC/cucmAxlWriter | setup.py | Python | gpl-3.0 | 494 | 0 | from distutils.core import setup
setup(name='cucmAxlWriter',
version='0.4',
description='cucm object writer using AXL',
author= | 'Christopher Phillips',
author_email='[email protected]',
url='https://github.com/ChristopherUC/cucmAxlWriter',
license='GNU GENERAL PUBLIC LICENSE Version 3',
py_modules=['appConfig', 'ucAppConfig', 'configCreator', 'cucmAxlWriter',
'cucmJabberWr | iter', 'cupiRestWriter'],
)
|
evhub/coconut | coconut/command/util.py | Python | apache-2.0 | 20,011 | 0.001299 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------------------------------------------------
# INFO:
# -----------------------------------------------------------------------------------------------------------------------
"""
Authors: Evan Hu... | ecute it." | ""
try:
result = eval(code, in_vars)
except SyntaxError:
pass # exec code outside of exception context
else:
if result is not None:
print(ascii(result))
return # don't also exec code
exec_func(code, in_vars)
@contextmanager
def handling_broken_process_pool... |
genome/flow-workflow | flow_workflow/entities/converge/future_nets.py | Python | agpl-3.0 | 1,639 | 0.006101 | from flow.petri_net.future import FutureAction
from flow_workflow.entities.converge.actions import ConvergeAction
from flow_workflow.future_nets import WorkflowNetBase
from flow_workflow.historian import actions
class ConvergeNet(WorkflowNetBase):
def __init__(self, operation_id, name, input_property_order,
... | self.succeeding_place = self.bridge_transitions(
self.converge_transition,
self.internal_success_transition,
name='succeeding')
self.observe_transition(self.internal_star | t_transition,
FutureAction(actions.UpdateOperationStatus,
operation_id=operation_id, status='running',
calculate_start_time=True))
self.observe_transition(self.internal_success_transition,
FutureAction(actions.UpdateOperationStatus,
... |
kawamon/hue | desktop/core/ext-py/docutils-0.14/test/functional/tests/standalone_rst_docutils_xml.py | Python | apache-2.0 | 461 | 0 | exec(open('functional/test | s/_standalone_rst_defaults.py').read())
# Source and destination file names.
test_source = "standalone_rst_docutils_xml.txt"
test_destination = "standalone_rst_docutils_xml.xml"
# Keyword parameters passed to publish_file.
writer_name = "docutils_xml"
# Settings
# enable INFO-level system messages in this test:
sett... | des['indents'] = True
|
editxt/editxt | editxt/theme.py | Python | gpl-3.0 | 3,505 | 0 | # -*- coding: utf-8 -*-
# EditXT
# Copyright 2007-2015 Daniel Miller <[email protected]>
#
# This file is part of EditXT, a programmer's text editor for Mac OS X,
# which can be found at http://editxt.org/.
#
# EditXT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Publ... | ived theme value that can be overridden in the config
"""
value = config.get("theme.selection_secondary_color", Color(None))
if value is None:
color = hex_value(config["theme.selection_color"])
value = get_color(rgb2gray(color))
return valu... | self.config = config
self.cached = set()
self.reset()
def reset(self):
self.syntax = self.config.lookup("theme.syntax", True)
self.default = self.syntax.get("default", {})
assert self.default is not self.config.get("theme.syntax.default"), \
"{!r} will be... |
gov-cjwaszczuk/notifications-admin | tests/app/main/test_permissions.py | Python | mit | 3,760 | 0.00133 | import pytest
from app.utils import user_has_permissions
from app.main.views.index import index
from werkzeug.exceptions import Forbidden, Unauthorized
from flask import request
def _test_permissions(
client,
usr,
permissions,
service_id,
will_succeed,
any_=False,
admin_override=False,
):
... | )
def | test_user_has_permissions_or(
client,
mocker,
):
user = _user_with_permissions()
mocker.patch('app.user_api_client.get_user', return_value=user)
_test_permissions(
client,
user,
['send_texts', 'manage_users'],
'',
True,
any_=True)
def test_user_has_p... |
bosscha/alma-calibrator | notebooks/selecting_source/allskymap.py | Python | gpl-2.0 | 16,580 | 0.007419 | from __future__ import unicode_literals
"""
AllSkyMap is a subclass of Basemap, specialized for handling common plotting
tasks for celestial data.
It is essentially equivalent to using Basemap with full-sphere projections
(e.g., 'hammer' or 'moll') and the `celestial` keyword set to `True`, but
it adds a few new metho... | ridians with their longitude values;
* geodesic, a replacement for Basemap.drawgreatcircle, that can correctly
handle geodesics that cross the limb of the map, and providing the user
easy control over clipping (which affects thick lines at or near the limb);
* tissot, which overrides Base | map.tissot, correctly handling geodesics that
cross the limb of the map.
Created Jan 2011 by Tom Loredo, based on Jeff Whitaker's code in Basemap's
__init__.py module.
"""
from numpy import *
import matplotlib.pyplot as pl
from matplotlib.pyplot import *
from mpl_toolkits.basemap import Basemap
import pyproj
from p... |
50thomatoes50/blender.io_mqo | io_scene_mqo/__init__.py | Python | gpl-2.0 | 8,539 | 0.01136 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# 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 program is distrib... | Property(
name = "Export Vertex Colors",
description="Export vertex colors",
default = True)
def execute(self, context):
msg = ".mqo export: Executing"
self.report({'INFO'}, msg)
print(msg)
if self.scale < 1:
s = "%.0f times smaller" % 1.0/self.sc... | er" % self.scale
else:
s = "same size"
msg = ".mqo export: Objects will be %s"%(s)
print(msg)
self.report({'INFO'}, msg)
from . import export_mqo
meshobjects = [ob for ob in context.scene.objects if ob.type == 'MESH']
export_mqo.export_mqo(self,
... |
fosstp/fosstp | fosstp/views/news.py | Python | mit | 2,170 | 0.002765 | from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
from pyramid_sqlalchemy import Session
from ..forms.news import NewsAddForm, NewsForm
from ..models.news import NewsModel
@view_config(route_name='news', renderer='templates/news.jinja2')
def news_view(request):
news = Session.query(... | 'news_edit', renderer='templates/news_edit.jinja2', request_method='GET', permission='admin')
def news_edit_view_get(request):
news_id = int(request.matchdict['id'])
news = Session.query(NewsModel).get(news_id)
form = NewsForm(obj=news)
return {'form': form}
@view_config(route_name='news_edit', render... | rmission='admin')
def news_edit_view_post(request):
import transaction
form = NewsForm(request.POST)
if form.validate():
news_id = int(request.matchdict['id'])
with transaction.manager:
news = Session.query(NewsModel).get(news_id)
form.populate_obj(news)
... |
tomaslaz/KLMC_Analysis | thirdparty/JPype-0.5.4.2/test/jpypetest/exc.py | Python | gpl-3.0 | 2,462 | 0.029651 | #*****************************************************************************
# Copyright 2004-2008 Steve Menard
#
# 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://... | bases__[0].__bases__
print JavaException
assert False
print 'if here, everything is fine'
def testExceptionByJavaClass(self) :
try :
self.jpype.exc.ExceptionTest.throwRuntime()
assert False
except JException(java.lang.RuntimeException), ex :
print "Caught the exception", ex.mess... | testThrowException(self) :
# d = {"throwIOException" : throwIOException, }
# p = JProxy(self.jpype.exc.ExceptionThrower, dict=d)
#
# assert self.jpype.exc.ExceptionTest.delegateThrow(p)
def testThrowException3(self) :
d = {"throwIOException" : throwByJavaException, }
p = JProxy(self.jpype.exc.Excepti... |
henriquebastos/itauscraper | itauscraper/converter.py | Python | lgpl-3.0 | 2,425 | 0.001249 | """Funções de conversão usada pelo scraper do Itaú."""
import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from decimal import Decimal
def date(s):
"""Converte strings 'DD/MM' em datetime.date.
Leva em consideração ano anterior para meses maiores que o mês corren... | LIBERAR',
'SALDO FINAL DISPONIVEL',
'SALDO ANTERIOR')
def statements(iterable):
"""Converte dados do extrato de texto para tipos Python.
Linhas de saldo são | ignoradas.
Entrada: (('21/07', 'Lançamento', '9.876,54-'), ...)
Saída..: ((datetime.date(2017, 7, 21), 'Lançamento', Decimal('-9876.54')), ...)
"""
return ((date(a), b, decimal(c)) for a, b, c in iterable if not is_balance(b))
def card_statements(iterable):
"""Converte dados do extrato do cartão ... |
gis-support/DIVI-QGIS-Plugin | widgets/ImageViewerQt.py | Python | gpl-2.0 | 9,390 | 0.005538 | # -*- coding: utf-8 -*-
""" ImageViewer.py: PyQt image viewer widget for a QPixmap in a QGraphicsView scene with mouse zooming and panning. """
import os.path
from PyQt5.QtCore import Qt, QRectF, pyqtSignal, QT_VERSION_STR
from PyQt5.QtGui import QImage, QPixmap, QPainterPath, QWheelEvent
from PyQt5.QtWidgets import Q... | "
scenePos = self.mapToScene(event.pos())
if event.button() == Qt.LeftButton:
if self.canPan:
self.setDragMode(QGraphicsView.ScrollHandDrag)
self.leftMouseButtonPressed.emit(scenePos.x(), scenePos.y())
elif event.button() == Qt.RightButton:
if ... | self.rightMouseButtonPressed.emit(scenePos.x(), scenePos.y())
QGraphicsView.mousePressEvent(self, event)
def mouseReleaseEvent(self, event):
""" Stop mouse pan or zoom mode (apply zoom if valid).
"""
QGraphicsView.mouseReleaseEvent(self, event)
scenePos = self.mapTo... |
15klli/WeChat-Clone | main/plugins/weather.py | Python | mit | 4,482 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .. import app, celery
import hashlib
import hmac
import time
import requests
from . import wechat_custom
@celery.task
def get(openid):
"""获取天气与空气质量预报"""
content = []
current_hour = time.strftime('%H')
try:
pm_25_info = get_pm2_5_info()
ex... | rftime('%w')) + offset
day | s = [u'周日', u'周一', u'周二', u'周三', u'周四', u'周五', u'周六',
u'周日', u'周一']
prefix = [u'今天', u'明天', u'后天']
return prefix[offset] + days[day_of_week]
def weather_code_to_text(code):
"""转换天气代码为文字"""
weather_list = [u'晴', u'多云', u'阴', u'阵雨', u'雷阵雨', u'雷阵雨伴有冰雹',
u'雨夹雪', u'小雨', u'中雨... |
bohdon/maya-pulse | src/pulse/scripts/pulse/actions/joints/twist_joints_pulseaction.py | Python | mit | 3,957 | 0.004802 | import pymel.core as pm
import pulse.nodes
import pulse.utilnodes
from pulse.buildItems import BuildAction, BuildActionError
class TwistJointsAction(BuildAction):
def validate(self):
if not self.twistJoint:
raise BuildActionError('twistJoint must be set')
if not self.alignJoint:
... | # TODO: might want to expose an option for | selecting the parent node explicitly.
align_parent = self.alignJoint.getParent()
if align_parent:
# get align joint matrix relative to it's parent,
# don't trust the local matrix since inheritsTransform may not be used
offset_mtx = self.alignJoint.... |
tdyas/pants | src/python/pants/base/parse_context.py | Python | apache-2.0 | 3,532 | 0.003398 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import threading
class Storage(threading.local):
def __init__(self, rel_path):
self.clear(rel_path)
def clear(self, rel_path):
self.rel_path = r... | alias using the given args and kwargs.
NB: aliases may be the alias' object type itself if that type is known.
:API: public
:param alias: Either the type alias or the type itself.
:type alias: string|type
:param *args: These pass through to the underlying callable object.
... | e object.
:returns: The created object, or an existing object with the same `name`.
"""
if name is None:
raise ValueError("Method requires an object `name`.")
obj_creator = functools.partial(self.create_object, alias, name=name, *args, **kwargs)
return self._storage.a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.