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 |
|---|---|---|---|---|---|---|---|---|
pasztorpisti/json-cfg | src/jsoncfg/parser_listener.py | Python | mit | 5,570 | 0.005027 | from kwonly_args import kwonly_defaults
from .parser import ParserListener
class ObjectBuilderParams(object):
# By creating a subclass of this class and overriding these
# attributes you can change the default values of __init__().
default_object_creator = None
default_array_creator = None
defaul... | nything else (eg: a number: "1.564") and it's up to you how to interpret
it. You can define your own constant scalar literals if you want like interpreting
the unquoted "yes" and "no" literals as boolean values.
In case of conversion error you should call listener.error() with an error message a... | class attributes are often simple
# functions and we don't want to convert them to instance methods by retrieving them
# with self.X statements.
return type(self).__dict__[name]
self.object_creator = object_creator or get_default('default_object_creator')
self.array_... |
lmazuel/azure-sdk-for-python | azure-mgmt-network/azure/mgmt/network/v2017_06_01/models/subnet_paged.py | Python | mit | 922 | 0.001085 | # 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 cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.paging import Paged
class SubnetPaged(Paged):
"""
A paging container for iterating over a list of :class:`Subnet <azure.mgmt.network.v2017_06_01... | 'next_link': {'key': 'nextLink', 'type': 'str'},
'current_page': {'key': 'value', 'type': '[Subnet]'}
}
def __init__(self, *args, **kwargs):
super(SubnetPaged, self).__init__(*args, **kwargs)
|
charles-dyfis-net/koan | koan/xencreate.py | Python | gpl-2.0 | 5,855 | 0.008027 | """
Virtualization installation functions.
Currently somewhat Xen/paravirt specific, will evolve later.
Copyright 2006-2008 Red Hat, Inc.
Michael DeHaan <mdehaan@redhat.com>
Original version based on virtguest-install
Jeremy Katz <katzj@redhat.com>
Option handling added by Andrew Puch <apuch@redhat.com>
Simplified ... |
intf_bridge = intf["virt_bridge"]
if intf_bridge == "":
| if profile_bridge == "":
raise koan.InfoException("virt-bridge setting is not defined in cobbler")
intf_bridge = profile_bridge
else:
if bridge.find(",") == -1:
intf_bridge = bridge
else:
b... |
tobykurien/MakerDroid | assetsrc/public.mp3/skeinforge/skeinforge_utilities/skeinforge_craft.py | Python | gpl-3.0 | 7,636 | 0.043609 | """
Craft is a script to access the plugins which craft a gcode file.
The plugin buttons which are commonly used are bolded and the ones which are rarely used have normal font weight.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where rela... | file."
text = gcodec.getFileText( fileName )
procedures = getProcedures( procedure, text )
return getChainTextFromProcedures( fileName, procedures, text )
def getChainTextFromProcedures( fileName, procedures, text ):
"Get a crafted sh | ape file from a list of procedures."
lastProcedureTime = time.time()
for procedure in procedures:
craftModule = getCraftModule( procedure )
if craftModule != None:
text = craftModule.getCraftedText( fileName, text )
if gcodec.isProcedureDone( text, procedure ):
print( '%s procedure took %s seconds.' % (... |
CollabQ/CollabQ | administration/views.py | Python | apache-2.0 | 8,027 | 0.017815 | # Copyright 2010 http://www.collabq.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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | est, locals())
return render_to_response('administration/templates/install.html', c)
@decorator.gae_admin_required
def admin(request):
page = 'admin'
group_menuitem = | 'admin'
title = 'Administration'
c = template.RequestContext(request, locals())
return render_to_response('administration/templates/admin.html', c)
@decorator.gae_admin_required
def admin_site(request):
page = 'site'
title = 'Site Settings'
site_name = util.get_metadata('SITE_NAME')
tagline = util.get... |
Microvellum/Fluid-Designer | win64-vc/2.78/Python/bin/2.78/scripts/addons/modules/extensions_framework/validate.py | Python | gpl-3.0 | 6,509 | 0.002612 | # -*- coding: utf-8 -*-
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
# --------------------------------------------------------------------------
# Blender 2.5 Extensions Framework
# --------------------------------------------------------------------------
#
# Authors | :
# Doug Hammond
#
# 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 distributed in the hope that it w... | s.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
#
# ***** END GPL LICENCE BLOCK *****
#
"""
Pure logic and validation class.
By using a Subject object, and a dict of described logic tests, it
is possible to arrive at a True... |
Acehaidrey/incubator-airflow | tests/providers/amazon/aws/operators/test_glue_crawler.py | Python | apache-2.0 | 3,458 | 0.001735 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | [
{
'Connec | tionName': 'test-jdbc-conn',
'Path': 'test_db/test_table>',
'Exclusions': [
'string',
],
}
],
'MongoDBTargets': [
{'ConnectionName': 'test-mongo-conn', 'Path': 'test_db/test_collection', 'ScanAll': True}
... |
Dwolla/arbalest | test/pipeline/test_s3_sorted_data_sources.py | Python | mit | 5,292 | 0.000189 | import json
import unittest
from boto.s3.key import Key
from mock import create_autospec, Mock, call
from arbalest.s3 import Bucket
from arbalest.pipeline import S3SortedDataSources
def mock_key(name):
return Key(Mock(), name)
class S3SortedDataSourcesShould(unittest.TestCase):
def setUp(self):
pa... | t = Mock(
side_effect=[[mock_key(key) for key in parents],
[mock_key(key) for key in first_children],
[mock_key(key) for key in second_children]])
def test_have_source_journal_key(self):
source = S3SortedDataSources('', 'event.entity.created', s... | ual('/event.entity.created_source_journal.json',
source.source_journal_key)
def test_get_all_dates_as_sources(self):
source = S3SortedDataSources('', 'event.entity.created', self.bucket)
self.assertEqual(['event.entity.created/2014-11-03',
'event.... |
dbrumley/recfi | llvm-3.3/utils/lit/lit/main.py | Python | mit | 15,230 | 0.00499 | #!/usr/bin/env python
"""
lit - LLVM Integrated Tester.
See lit.pod for more information.
"""
import math, os, platform, random, re, sys, time, threading, traceback
import ProgressBar
import TestRunner
import Util
import LitConfig
import Test
import lit.discovery
class TestingProgressDisplay:
def __init__(se... | def handleUpdate(self, test):
self.co | mpleted += 1
if self.progressBar:
self.progressBar.update(float(self.completed)/self.numTests,
test.getFullName())
if self.opts.succinct and not test.result.isFailure:
return
if self.progressBar:
self.progressBar.clear()
... |
suoto/hdlcc | setup.py | Python | gpl-3.0 | 3,321 | 0.014453 | # This file is part of HDL Checker.
#
# Copyright (c) 2015 - 2019 suoto (Andre Souto)
#
# HDL Checker 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 ... | 'future>=0.14.0',
'futures; python_version<"3.2"',
| 'prettytable>=0.7.2',
'pygls==0.9.1',
'requests>=2.20.0',
'six>=1.10.0',
'tabulate>=0.8.5',
'typing>=3.7.4',
... |
TaskEvolution/Task-Coach-Evolution | taskcoach/taskcoachlib/thirdparty/src/reportlab/graphics/barcode/test.py | Python | gpl-3.0 | 9,268 | 0.007769 | #!/usr/pkg/bin/python
import os, sys, time
from reportlab.graphics.barcode.common import *
from reportlab.graphics.barcode.code39 import *
from reportlab.graphics.barcode.code93 import *
from reportlab.graphics.barcode.code128 import *
from reportlab.graphics.barcode.usps import *
from reportlab.graphics.barcode.usps... | append(Paragraph('Label Size', styleN))
story.append(XBox((1.75)*inch, .5 * inch, '1/2x1-3/4"'))
c = Canvas('out.pdf')
f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1 | )
f.addFromList(story, c)
c.save()
print 'saved out.pdf'
def fullTest(fileName="test_full.pdf"):
"""Creates large-ish test document with a variety of parameters"""
story = []
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
styleH2 = styles['Hea... |
allotory/basilinna | app/main/upload_file.py | Python | mit | 1,433 | 0.007774 | # -*- coding: utf-8 -*-
' 检查扩展名是否合法 '
__author__ = 'Ellery'
from app import app
import datetime, random
from PIL import Image
import os
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config.get('ALLOWED_EXTENSIONS')
def unique_name():
now_ti | me = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
random_num = random.randint(0, 100)
if random_num <= 10:
random_num = str(0) + str(random_num)
unique_num = str(now_time) + str(random_num)
return unique_num
def image_thumbnail(filename):
filepath = os.path.join(app.config.get('UPLOAD_F... | e)
im = Image.open(filepath)
w, h = im.size
if w > h:
im.thumbnail((106, 106*h/w))
else:
im.thumbnail((106*w/h, 106))
im.save(os.path.join(app.config.get('UPLOAD_FOLDER'),
os.path.splitext(filename)[0] + '_thumbnail' + os.path.splitext(filename)[1]))
def image_delete(file... |
dhowland/EasyAVR | keymapper/easykeymap/legacy.py | Python | gpl-2.0 | 6,758 | 0.001776 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# Easy AVR USB Keyboard Firmware Keymapper
# Copyright (C) 2018 David Howland
#
# 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 ... | cancodes
from .userdata import Map
legacy_layers = ["Default", "Layer 1", "Layer 2", "Layer 3", "Layer 4",
"Layer 5", "Layer 6", "Layer 7", "Layer 8", "Layer 9"]
class LegacySaveFileException(Exception):
"""Raised when an error is encountered while loading a legacy layout file."""
pass
de... | UserData object given by `user_data`.
"""
legacy_data = open_legacy(datfile)
convert_legacy(user_data, legacy_data)
def open_legacy(datfile):
"""Opens and decodes the pickled data in a legacy .dat save file. `datfile`
is a path to the file. The function returns a dictionary with an item for eac... |
mjenrungrot/competitive_programming | UVa Online Judge/v104/10433.py | Python | mit | 619 | 0 | # =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 10433.py
# Description: UVa Online Judge - 10433
# =============================================================================
while True:... | :
str_N = input()
except EOFError:
break
N = int(str_N)
N2 = N * N
str_N2 = str(N2)
len_N = len(str_N)
if str_N2[-len_N:] == st | r_N:
print("Automorphic number of {}-digit.".format(len_N))
else:
print("Not an Automorphic number.")
|
MattNolanLab/ei-attractor | grid_cell_model/simulations/007_noise/figures/cosyne2015-abstract/figure_gamma.py | Python | gpl-3.0 | 492 | 0 | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import copy
import matplotlib
from grid_cell_model.submitting import flagparse
import noisefigs
from noisefigs.env import NoiseEnvi | ronment
import config
parser = flagparse.FlagParser()
parser.add_flag('--gammaSweep')
args = parser.parse_args()
env = NoiseEnvironment(user_config=config.get_config())
if args.gammaSweep or args.all:
env.register_plotte | r(noisefigs.plotters.GammaSweepsPlotter)
env.plot()
|
uclouvain/OSIS-Louvain | base/tests/views/learning_units/external/test_update.py | Python | agpl-3.0 | 4,921 | 0.001829 | ############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core bu... | ase
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from waffle.testutils import override_flag
from base.models.enums.entity_type import FACULTY
from base.models.enums.learning_container_year_types import EXTERNAL
from base.m | odels.enums.organization_type import MAIN
from base.tests.factories.academic_calendar import generate_learning_unit_edition_calendars
from base.tests.factories.academic_year import create_current_academic_year
from base.tests.factories.entity import EntityWithVersionFactory
from base.tests.factories.external_learning_u... |
translate/amagama | amagama/application.py | Python | gpl-3.0 | 1,780 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2014 Zuza Software Foundation
#
# This file is part of amaGama.
#
# 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 ... | self)
def amagama_server_factory():
app = AmagamaServer("settings.py", __name__)
app | .register_blueprint(api.read_api, url_prefix='/tmserver')
app.register_blueprint(api.read_api, url_prefix='/api/v1')
if app.config['ENABLE_DATA_ALTERING_API']:
app.register_blueprint(api.write_api, url_prefix='/tmserver')
app.register_blueprint(api.write_api, url_prefix='/api/v1')
if app.c... |
dimven/SpringNodes | py/String.ReplaceIllegalChars.py | Python | mit | 557 | 0.028725 | # Copyright(c) 2017, Dimitar Venkov
# @5devene, dimita | r.ven@gmail.com
# www.badmonkeys.net
from itertools import imap, repeat
import System
badChars = set(System. | IO.Path.GetInvalidFileNameChars() )
def tolist(x):
if hasattr(x,'__iter__'): return x
else : return [x]
def fixName(n, rep="", badChars=badChars):
n1 = (c if c not in badChars else rep for c in iter(n) )
return ''.join(n1)
names = tolist(IN[0])
replacement = str(IN[1])
other = tolist(IN[2])
badChars.update(othe... |
codeforamerica/mdc-inspectors | manage.py | Python | bsd-3-clause | 1,026 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask_script import Manager, Shell, Server
from flask_script.commands import Clean, ShowUrls
from flask_migrate import MigrateCommand
from inspectors.app import create_app
from inspectors.settings import DevConfig, ProdConfig
from inspectors.database import ... | anager(app)
def _make_context():
"""Return context dict for a shell session so you can access
app, and db.
"" | "
return {'app': app, 'db': db}
@manager.command
def test():
"""Run the tests."""
import pytest
exit_code = pytest.main([TEST_PATH, '--verbose'])
return exit_code
manager.add_command('server', Server())
manager.add_command('shell', Shell(make_context=_make_context))
manager.add_command('db', Mig... |
taedori81/shoop | shoop_tests/notify/test_log_entries.py | Python | agpl-3.0 | 1,388 | 0.002161 | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
import pytest
from shoop.notify import Context
from shoop_tests.notify.fixt... | bject(target_obj):
event = get_initialized_test_event()
event.variable_values["order"] = target_obj # invalidate log target _before_ creating context
ctx = Context.from_event(event)
n_log_entries = ctx.log_entry_queryset.count()
ctx.add_log_entry_on_log_target("blap", "blorr")
assert ctx.log_en... | es # couldn't add :(
|
ucbvislab/radiotool | radiotool/algorithms/constraints.py | Python | isc | 27,809 | 0.000467 |
# constraints should be multiplicative so we can do them in any order
# ok, maybe not multiplicative. not sure yet.
# want to avoid plateaus in the space.
import copy
import numpy as np
from scipy.special import binom
import scipy
import librosa_analysis
import novelty
BEAT_DUR_KEY = "med_beat_duration"
class Co... | ePitchConstraint(Constraint):
def __init__(self, timbre_weight=1, chroma_weight=1,
context=0):
self.tw = timbre_weight
self.cw = chroma_weight
self.m = context
def apply(self, transition_cost, penalty, song, beat_names) | :
timbre_dist = librosa_analysis.structure(
np.array(song.analysis['timbres']).T)
chroma_dist = librosa_analysis.structure(
np.array(song.analysis['chroma']).T)
dists = self.tw * timbre_dist + self.cw * chroma_dist
if self.m > 0:
new_dists = np.copy(... |
dmsurti/mayavi | mayavi/filters/user_defined.py | Python | bsd-3-clause | 3,082 | 0.001622 | # Author: Prabhu Ramachandran <prabhu [at] aero . iitb . ac . in>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.
# Enthought library imports.
from tvtk.tools.tvtk_doc import TVTKFilterChooser, TVTK_FILTERS
# Local imports.
from mayavi.filters.filter_base import FilterBase
from mayavi.core.common import ... | t allows a
user to specify the class without writing any code.
"""
# The version of this class. Used for persistence.
__version__ = 0
input_info = PipelineInfo(datasets=['any'],
| attribute_types=['any'],
attributes=['any'])
output_info = PipelineInfo(datasets=['any'],
attribute_types=['any'],
attributes=['any'])
#############################################################... |
c1728p9/mbed-os | tools/host_tests/host_tests_plugins/module_copy_mbed.py | Python | apache-2.0 | 2,899 | 0.001725 | """
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 wr... |
Each capability may directly just call some command line
program or execute building pythonic function
"""
result = False
if self.check_parameters(capability, * | args, **kwargs) is True:
# Capability 'default' is a dummy capability
if capability == 'shutil':
image_path = kwargs['image_path']
destination_disk = kwargs['destination_disk']
program_cycle_s = kwargs['program_cycle_s']
# Wait for ... |
jiasir/openstack-trove | lib/charmhelpers/contrib/openstack/neutron.py | Python | mit | 7,812 | 0.000256 | # Various utilies for dealing with Neutron and the renaming from Quantum.
from subprocess import check_output
from charmhelpers.core.hookenv import (
config,
log,
ERROR,
)
from charmhelpers.contrib.openstack.utils import os_release
def headers_package():
"""Ensures correct linux-headers for running... | if kernel_ver | sion() >= (3, 13):
return []
else:
return ['openvswitch-datapath-dkms']
# legacy
def quantum_plugins():
from charmhelpers.contrib.openstack import context
return {
'ovs': {
'config': '/etc/quantum/plugins/openvswitch/'
'ovs_quantum_plugin.ini',
... |
fams/rabbitmq-tutorials | python-puka/receive_logs_direct.py | Python | apache-2.0 | 902 | 0 | #!/usr/bin/env python
import puka
import sys
client = p | uka.Client("amqp://localhost/")
promise = client.connect()
client.wait(promise)
promise = client.exchange_declare(exchange='direct_logs', type='direct')
client.wait(promise)
promise = client.queue_declare(exclusive=True)
queue_name = client.wait(promise)['queue']
severities = sys.argv[1:]
if not severities:
pri... | s:
promise = client.queue_bind(exchange='direct_logs', queue=queue_name,
routing_key=severity)
client.wait(promise)
print ' [*] Waiting for logs. To exit press CTRL+C'
consume_promise = client.basic_consume(queue=queue_name, no_ack=True)
while True:
msg_result = client.wai... |
PainNarrativesLab/IOMNarratives | IomDataModels.py | Python | mit | 13,627 | 0.001614 | """
Contains the database connection tools and sqlalchemy models for iom database
Created by adam on 11/11/15
In order to use this, import the module and
create a sqlalchemy engine named 'engine' then do:
# connect to db
from sqlalchemy.orm import sessionmaker
# ORM's handle to database at global level
Session = ses... | ind('db_user').text
self._db_name = credentials.find('db_name').text
self._password = credentials.find('db_password').text
def _make_engine(self):
"""
Creates the sqlalchemy engine and stores it in self.engine
"""
raise NotImplementedError
class MySqlConnec... | Connection):
"""
Uses the MySQL-Connector-Python driver (pip install MySQL-Connector-Python driver)
"""
def __init__(self, credential_file):
self._driver = '+mysqlconnector'
super().__init__(credential_file)
def _make_engine(self):
if self._port:
server = "%s:%s... |
lcc755/WorkTerm1 | 5Array/2Temp/Code/average.py | Python | apache-2.0 | 897 | 0.020067 | from nanpy import (ArduinoApi, SerialManager)
from time import sleep
#Connect to Arduino. Automatically finds serial port.
connection = SerialManager()
a = ArduinoApi(connection = connection)
sensor = 14 #Analog pin 0
a.pinMode(sensor, a.INPUT) #Setup sensor
while | True:
total = 0 #Each set of readings start with a total of 0
#Get all the readings:
for i in range(0, 24):
reading | = a.analogRead(sensor) #get reading
vol = (reading*(5.0/1024)) #relative voltage
temp = ((vol-0.5)*100) #find temp
readings[i] = temp #Place temp reading in i space of array
sleep(0.1) #Time between readings
#Add the readings:
for i in range(0,... |
akashlevy/Lyff | lyff_lambda/boto/s3/key.py | Python | mit | 83,034 | 0.000313 | # Copyright (c) 2006-2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2011, Nexenta Systems Inc.
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the... | IES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOF... | oto.utils
from boto.compat import BytesIO, six, urllib, encodebytes
from boto.exception import BotoClientError
from boto.exception import StorageDataError
from boto.exception import PleaseRetryException
from boto.provider import Provider
from boto.s3.keyfile import KeyFile
from boto.s3.user import User
from boto impor... |
OpenTransitTools/otp_client_py | ott/otp_client/otp_to_ott.py | Python | mpl-2.0 | 36,580 | 0.004265 | """ Convert an OpenTripPlanner json itinerary response into something that's more suitable for rendering via a webpage
"""
import re
import sys
import math
from decimal import *
import datetime
from datetime import timedelta
import simplejson as json
from ott.utils import object_utils
from ott.utils import date_utils
... | ['second']
dist = e['first']
points.append(round(elev, 2))
if len(points) > 0:
points_array = points
points_string = cls.make_point_string(points)
except Exception as e:
log.warning(e)
return points_array, p... | for list of elevation poi |
batxes/4Cin | SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/SHH_WT_models39351.py | Python | gpl-3.0 | 17,562 | 0.025111 | import _surface
import chimera
try:
import chimera.runCommand
except:
pass
from VolumePath import markerset as ms
try:
from VolumePath import Marker_Set, Link
new_marker_set=Marker_Set
except:
from VolumePath import volume_path_dialog
d= volume_path_dialog(True)
new_marker_set= d.new_marker_set
marker_set... | t('particle_30 geometry')
marker_sets["particle_30 geometry"]=s
s= marker_sets["particle_30 geometry"]
mark= | s.place_marker((6084.66, 5685.12, 6880.48), (0.7, 0.7, 0.7), 651.505)
if "particle_31 geometry" not in marker_sets:
s=new_marker_set('particle_31 geometry')
marker_sets["particle_31 geometry"]=s
s= marker_sets["particle_31 geometry"]
mark=s.place_marker((6675.68, 7281.04, 7241.44), (0.7, 0.7, 0.7), 718.042)
if "par... |
coyote240/zeroecks.com | zeroecks/handlers/base_handler.py | Python | mit | 1,495 | 0 | import redis
import psycopg2
from tornado.options import options
import tornadobase.handlers
class BaseHandler(tornadobase.handlers.BaseHandler):
def initialize(self):
self.dbref = psycopg2.connect(dbname=options.dbname,
| user=options.dbuser,
password=options.dbpass)
self.dbref.autocommit = True
self.redis = redis.StrictRedis(host='localhost',
port=6379,
db=0,
de... | ')
if session_id is not None:
return self.redis.hgetall(session_id)
return None
def get_current_user(self):
session_id = self.get_secure_cookie('__id')
if session_id is not None:
self.redis.expire(session_id, options.session_timeout)
return self.r... |
ZakDoesGaming/OregonTrail | lib/afflictionBox.py | Python | mit | 523 | 0.032505 | from pygame import Rect
class AfflictionBox():
def __init__(self, affliction, font, rectPosition = (0, 0)):
self.affliction = affliction
self.rectPosition = rectPosition
self.name = self.afflictio | n.name
self.font = font
self.textSize = self.font.size(self.name)
self.textRect = Rect(self.rectPosition, self.textSize)
def update(self, rectP | osition):
self.rectPosition = rectPosition
self.textRect.centerx = rectPosition[0] + self.textSize[0]
self.textRect.centery = rectPosition[1] + self.textSize[1] |
tao12345666333/Talk-Is-Cheap | ansible/plugins/callback/test.py | Python | mit | 3,110 | 0.000646 | #!/usr/bin/env python
# coding=utf-8
import requests
import time
import json
"""
ansible 运行结果回调
"""
class CallbackModule(object):
def v2_runner_item_on_ok(self, *args, **kwargs):
# time.sleep(10)
# print args
for i in dir(args[0]):
if not i.startswith('__'):
... | kwargs):
# print args
# print dir(args[0])
for i in dir(args[0]):
if not i.startswith('__'):
print i
# print args[0].changed, 'changed'
# print args[0].ok, 'ok'
# print args[0].dark, 'dark'
print args[0].failures, 'fail | ures'
# print args[0].increment, 'increment'
# print args[0].processed, 'processed'
# print args[0].skipped, 'skipped'
# print args[0].summarize, 'summarize'
# print kwargs
print 'on stats'
if __name__ == '__main__':
print 'callback'
|
antoinecarme/pyaf | tests/artificial/transf_Quantization/trend_PolyTrend/cycle_30/ar_/test_artificial_1024_Quantization_PolyTrend_30__20.py | Python | bsd-3-clause | 269 | 0.085502 | import pyaf.Bench.TS_da | tasets as tsds
import tests.artificial.proce | ss_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 30, transform = "Quantization", sigma = 0.0, exog_count = 20, ar_order = 0); |
ikasumi/chainer | tests/cupy_tests/test_ndarray_elementwise_op.py | Python | mit | 8,059 | 0 | import operator
import unittest
import numpy
import six
from cupy import testing
@testing.gpu
class TestArrayElementwiseOp(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_allclose()
def check_array_scalar_op(self, op, xp, dtype, swap=False):
... | self.check_array_scalar_op(operator.add, swap=True)
def test_iadd_scalar(self):
self.check_array_scalar_op(operator.iadd)
def test_sub_scalar(self):
self.check_array_scalar_op(operator.sub)
def test_rsub_scalar(self):
self.c | heck_array_scalar_op(operator.sub, swap=True)
def test_isub_scalar(self):
self.check_array_scalar_op(operator.isub)
def test_mul_scalar(self):
self.check_array_scalar_op(operator.mul)
def test_rmul_scalar(self):
self.check_array_scalar_op(operator.mul, swap=True)
def test_imu... |
harveyr/omni-api | omni_api/hackpad.py | Python | mit | 1,372 | 0 | from omni_api.base import ClientBase, DataItem
class HackpadClient(ClientBase):
| def __init__(self, client_id, secret):
self.auth = self.get_oauth_token(client_id, secret)
def get_url(self, url, ** | kwargs):
kwargs['auth'] = self.auth
return super(HackpadClient, self).get_url(
url,
load_json=True,
**kwargs
)
def search(self, query):
url = 'https://hackpad.com/api/1.0/search'
params = {
'q': query,
}
resul... |
ivandeex/dz | dz/tests/views.py | Python | mit | 3,249 | 0.003078 |
class ListViewTestsMixin(object):
def test_admin_users_can_access_all_tables(self):
for username in ('super', 'follow'):
with self.login_as(username):
for model_name in ('news', 'tip', 'crawl', 'user', 'schedule'):
self._test_table_view(username, model_name, ... | response, info, target, skin):
| msg = 'the page must load custom js/css' + info
for bundle in ('common', skin):
if target == 'prod':
bundle += '.min'
link_css = ('<link type="text/css" href="/static/%s/dz-%s.css?hash='
% (target, bundle))
self.assertContains(re... |
hada2/bingrep | bingrep_dump.py | Python | bsd-3-clause | 8,471 | 0.007909 | # BinGrep, version 1.0.0
# Copyright 2017 Hiroki Hada
# coding:UTF-8
import sys, os, time, argparse
import re
import pprint
#import pydot
import math
import cPickle
import ged_node
from idautils import *
from idc import *
import idaapi
def idascript_exit(code=0):
idc.Exit(code)
def get_short_function_name(functi... | "dx", "al", "bl", "cl", "dl", "ah", "bh", "ch", "dh", "esi", "edi", "si", "di", "esp", "ebp"]:
buf += "reg "
elif o[:3] == "xmm": buf += "reg "
elif o.find("[") >= 0: buf += "mem "
elif o[:6] == "offset": buf += "off "
... | f o[:4] == "sub_": buf += "sub "
elif o.isdigit(): buf += "num "
elif re.match("[\da-fA-F]+h", o): buf += "num "
elif o[:6] == "dword_": buf += "dwd "
else: buf += "lbl "
mnems.append(mne... |
tbielawa/Taboot | taboot/tasks/httpd.py | Python | gpl-3.0 | 805 | 0 | # -*- coding: utf-8 -*-
# Taboot - Client utility for performing deployments with Func.
# Copyright © 2009, Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener | al Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR P... | .
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""TODO: Decide what to do with this file"""
|
KhronosGroup/COLLADA-CTS | StandardDataSets/collada/library_geometries/geometry/mesh/polygons/one_geometry_one_polygons/one_geometry_one_polygons.py | Python | mit | 5,053 | 0.008114 | # Copyright (C) 2007 - 2009 Khronos Group
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the... | BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT O | F OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
# See Core.Logic.FJudgementContext for the information
# of the 'context' parameter.
#
# This sample judging object does the following:
#
# JudgeBaseline: verifies that app did not crash, the required steps have been performed,
# t... |
ismailsunni/healthsites | django_project/core/settings/dev_dodobas.py | Python | bsd-2-clause | 1,782 | 0 | # -*- coding: utf-8 -*-
from .dev import * # noqa
INSTALLED_APPS += (
'django_extensions',
)
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'healthsites_dev',
'USER': '',
'PASSWORD': '',
'HOST': 'localhost',
# Set to empt... | matters': {
# define output formats
'verbose': {
'format': (
'%(levelname)s %(name)s %(asctime)s %(module)s %(process)d '
'%(thre | ad)d %(message)s')
},
'simple': {
'format': (
'%(name)s %(levelname)s %(filename)s L%(lineno)s: '
'%(message)s')
},
},
'handlers': {
# console output
'console': {
'class': 'logging.StreamHandler',
'format... |
alfredfrancis/ai-chatbot-framework | app/entities/controllers.py | Python | mit | 1,963 | 0 | from bson.json_util import dumps, loads
from bson.objectid import ObjectId
from flask import Blueprint, request, Response
from app.commons import build_response
from app.commons.utils import update_document
from app.entities.models import Entity
entities_blueprint = Blueprint('entities_blueprint', __name__,
... | entities
:return:
"""
intents = Entity.objects.only('name', 'id')
return build_response.sent_json(intents.to_json())
@entities_blueprint.route('/<id>')
def read_entity(id):
"""
Find details for the given entity name
:param id:
:return:
"""
return Response(
response=dump... | 'PUT'])
def update_entity(id):
"""
Update a story from the provided json
:param id:
:return:
"""
json_data = loads(request.get_data())
entity = Entity.objects.get(id=ObjectId(id))
entity = update_document(entity, json_data)
entity.save()
return build_response.sent_ok()
@entitie... |
google-research/google-research | cascaded_networks/models/densenet.py | Python | apache-2.0 | 6,633 | 0.004975 | # coding=utf-8
# Copyright 2022 The Google Research 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 applicab... | orks.models import model_utils
class DenseNet(nn.Module):
"""Densenet."""
def __init__(self,
name,
block,
block_arch,
growth_rate=12,
reduction=0.5,
num_classes=10,
**kwargs):
"""Initialize dense net."""
... | arch
self._norm_layer_op = self._setup_bn_op(**kwargs)
self._build_net(block, block_arch, growth_rate,
reduction, num_classes, **kwargs)
def _build_net(self,
block,
block_arch,
growth_rate,
reduction,
n... |
dichenko/kpk2016 | Diff/dra.py | Python | gpl-3.0 | 442 | 0.011312 | #http://informatics.mccme.ru/mod/statements/view3.php?id=22783&chapterid=113362#1
n = int(input())
def sum_kv_cifr( | x):
su = 0
for i in str(x):
su += int(i)*int(i)
return su
maxi_power = 0
for i in range(1, n//2+1):
print('______',i)
for k in range(n//i, 0, -1):
power = sum_kv_cifr(i * k)
print('_', k, power)
if power > maxi_power:
| maxi_power = power
print(maxi_power)
|
lexrupy/gmate-editor | GMATE/status_position.py | Python | mit | 2,729 | 0.002566 | # -*- coding: utf-8 -*-
# GMate - Plugin Based Programmer's Text Editor
# Copyright © 2008-2009 Alexandre da Silva
#
# This file is part of Gmate.
#
# See LICENTE.TXT for licence information
import gtk
from GMATE import i18n as i
from GMATE.status_widget import StatusWidget
class StatusPosition(StatusWidget):
""... | if iter.get_char() == '\t':
col += (tabwidth - (col % tabwidth))
else:
col += 1
iter.forward_char()
self.line_position_number.set_text(str(row))
self.column_position_number.set_text(str(col+1))
return False
def __mark_set_c... | cursoriter, mark):
self.__changed_cb(buff)
return False
|
AntonKhorev/BudgetSpb | main.py | Python | bsd-2-clause | 1,072 | 0.041295 | #!/usr/bin/env python3
from linker import Linker
import htmlPage
import content.index,content.db,content.fincom
# TODO put into config
spbBudgetXlsPath='../spb-budget-xls'
if __name__=='__main__':
linker=Linker('filelists',{
'csv':['csv'],
'xls':['xls'],
'db':['zip','sql','xlsx'],
})
htmlPage.HtmlPage('inde... | html','Что можно найти на сайте Комитета финанс | ов',content.fincom.content,linker).write('output/fincom.html')
|
edoburu/django-fluent-blogs | setup.py | Python | apache-2.0 | 3,060 | 0.002614 | #!/usr/bin/env python
from setuptools import setup, find_packages
from os import path
import codecs
import os
import re
import sys
# When creating the sdist, make sure the django.mo file also exists:
if 'sdist' in sys.argv or 'develop' in sys.argv:
os.chdir('fluent_blogs')
try:
from django.core import... | /Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2... | : 3.5',
'Programming Language :: Python :: 3.6',
'Framework :: Django',
'Framework :: Django :: 1.10',
'Framework :: Django :: 1.11',
'Framework :: Django :: 2.0',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic ... |
maxwward/SCOPEBak | setup.py | Python | gpl-3.0 | 5,541 | 0.009024 | import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
import sys
#NOTE: if you want to develop askbot
#you might want to install django-debug-toolbar as well
import askbot
setup(
name = "askbot",
version = askbot.get_version(),#remember to manually set this correctly
descr... | script will automatically add missing columns, however it will not overwrite any existing columns. Please do back up your database before adding askbot to an existing site.
Included into askbot there are two forked apps: `django_authopenid` and `livesettings`. If you have these apps on your site, you may have trouble... | g askbot.
User registration and login system is bundled with Askbot. It is quite good though, it allows logging in with password and many authentication service providers, including popular social services and recover account by email.
If there are any other collisions, askbot will simply fail to install, it will not... |
guolivar/totus-niwa | service/thirdparty/featureserver/FeatureServer/WebFeatureService/FilterEncoding/LogicalOperators/LogicalOperator.py | Python | gpl-3.0 | 1,243 | 0.008045 | '''
Created on Apr 20, 2011
@author: michel
'''
import os
from lxml import etree
from FeatureServer.WebFeatureService.FilterEncoding.Operator import Operator
class LogicalOperator(Operator):
def __init__(self, node):
super(LogicalOperator, self).__init__(node)
self.type = 'LogicalOperator'
... | ement(self, datasource, operatorList):
logical = self.addOperators(operatorList)
xslt = etree.parse(os.path.dirname(os.path.abspa | th(__file__))+"/../../../../resources/filterencoding/logical_operators.xsl")
transform = etree.XSLT(xslt)
result = transform(logical, datasource="'"+datasource.type+"'", operationType="'"+str(self.node.xpath('local-name()'))+"'")
elements = result.xpath("//Statement")
if len(elements) > ... |
centrofermi/e3analysis | upgoingmu/beta_sanity_check.py | Python | lgpl-3.0 | 3,115 | 0.000642 | import os
import ROOT
from __common__ import *
OUTPUT_FILE_PATH = 'beta_sanity_check.root'
print 'Opening output file %s...' % OUTPUT_FILE_PATH
outputFile = ROOT.TFile(OUTPUT_FILE_PATH, 'RECREATE')
for station in STATIONS:
filePath = os.path.join(DATA_FOLDER, '%s_full_upgoingmu.root' % station)
f = ROOT.TFil... | eta^-1) distributions for straight tracks.
hname = 'hbetastraight_%s' % station
hbeta = ROOT.TH1F(hname, station, 200, 0, 3)
hbeta.SetXTitle('#beta')
hbeta.SetYTitle('Entries/bin')
t.Project(hname, BETA_EXPR, CUT_EXPR)
print 'Writing %s...' % hname
hbeta.Write()
print 'Do | ne.'
hname = 'hbetastraightinv_%s' % station
hbetainv = ROOT.TH1F(hname, station, 200, 0, 3)
hbetainv.SetXTitle('1/#beta')
hbetainv.SetYTitle('Entries/bin')
t.Project(hname, '1./(%s)' % BETA_EXPR, STRAIGHT_CUT_EXPR)
print 'Writing %s...' % hname
hbetainv.Write()
print 'Done.'
# Beta ... |
phase-dev/phase | libphase/tabs/vulnerabilities.py | Python | gpl-3.0 | 6,578 | 0.03907 | """
Copyright 2014
This file is part of Phase.
Phase 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.
Phase is distributed in the hope that... | _object("textviewVulnerabilitiesValue").get_buffer().set_text(treeview.get_model().get_value(iter,4))
def add(self,vulnerabilities):
for vulnerability in vulnerabilities:
parent=self.store.contains(None,[(vulnerability.title,0)])
if parent == None:
parent=self.store.append(None,[vulnerability.title,vu... | ndation,""])
self.store.append(parent,[vulnerability.url,vulnerability.risk,vulnerability.description,vulnerability.recommendation,vulnerability.value])
else:
if self.store.contains(parent,[(vulnerability.url,0)]) == None:
self.store.append(parent,[vulnerability.url,vulnerability.risk,vulnerability.desc... |
spseol/DOD-2014 | NXTornadoWServer/NXTornadoWServer/ClientsHandler.py | Python | lgpl-2.1 | 775 | 0.003871 | import logging
from tornado.web import RequestHandler
from NXTornadoWServer.ControlSocketHandler import ControlSocketHandler
class ClientsHandler(Reques | tHandler):
def get(self):
try:
controller_i = ControlSocketHandler.clients.index(ControlSocketHandler.client_controller)
except ValueError:
controller_i = 0
return self.render('../static/clients.html', clients=ControlSocketHandler.clients, controller_i=controller_i)
... | join(v) for k, v in self.request.arguments.iteritems()}
try:
ControlSocketHandler.client_controller = ControlSocketHandler.clients[int(args['i'])]
except IndexError:
pass
ControlSocketHandler.refresh_clients()
|
SalemAmeen/neon | tests/test_linear_layer.py | Python | apache-2.0 | 6,132 | 0 | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems 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.o... | return
# permute mm indicies to change order of computaitons
# to estimate numerical percision
# this is a rough estimate
def est_mm_prec(A, B, ntrials=1):
A64 = np.float64(A)
B64 = np.float64(B)
gt = np.dot(A64, B64)
max_err = -1.0
for trial in | range(ntrials):
inds = np.random.permutation(A.shape[1])
# this method gives better estimate of precision tolerances
# but takes too long to run
# for i in range(A.shape[0]):
# for j in range(B.shape[1]):
# c = np.sum(np.multiply(A[i,inds], B[inds,j]))
#... |
marcos-sb/hacker-rank | artificial-intelligence/statistics-and-machine-learning/battery/Solution.py | Python | apache-2.0 | 639 | 0 |
# import matplotlib.pyp | lot as plt
# import numpy as np
# from scipy import stats
# import sys
#
# c = list()
# b = list()
# for line in sys.stdin:
# linesp = list(map(float, line.strip().split(",")))
# if(linesp[0] < 4):
# c.append(linesp[0])
# | b.append(linesp[1])
#
# carr = np.array(c)
# barr = np.array(b)
#
# slope, intercept, r_value, p_value, std_err = stats.linregress(c,b)
#
# plt.figure()
# plt.plot(carr,barr, 's')
# plt.show()
# print(slope,intercept,r_value,p_value,std_err)
# 2.0 0.0 1.0 0.0 0.0
import sys
for line in sys.stdin:
x = float(... |
zhouhoo/conceptNet_55_client | app/query.py | Python | apache-2.0 | 5,682 | 0.001562 | import os
from hanziconv import HanziConv # 简繁转换
from app.ResultParse import ResultParse
from app.statistics import analysis
from interface.api import LookUp, Search, Association
from tools.parse_and_filter import parse_sentence
from tools.translate import Translate
class Query:
def __init__(self, debug=False)... | es
def concept_search(self, to_traditional=True):
# print('looking for conceptions all related commonsense')
if not self.conceptions:
return
if to_traditional:
translated_conceptions = HanziConv.toTraditional(' '.join(self.conceptions))
conceptions = tr... | ata = Query.base_search(conceptions)
# if not data:
# translated_conceptions = Translate.zh_to_en(self.conceptions)
#
# data = Query.base_search(translated_conceptions, lang='en')
if data:
self.commonsense = self.commonsense.union(set(data))
@staticmeth... |
joergsimon/gesture-analysis | main.py | Python | apache-2.0 | 1,322 | 0.008321 | from dataingestion.initial_input import InitialInput
from const.constants import Constants
from dataingestion.preprocessing import preprocess_basic
from dataingestion.window import get_windows
from dataingestion.cache_control import *
from analysis.preparation import permutate
from analysis.preparation import split_tes... | index trace info / main:")
| print(len(const.feature_indices['flex']['row_1']))
print(len(const.feature_indices['flex']['row_2']))
r1 = []
for i in const.feature_indices['flex']['row_1']:
r1.append(const.feature_headers[i])
print(r1)
# permutate the data
data, labels = permutate(data, labels)
# split train an... |
alexei-matveev/ase-local | ase/gui/calculator.py | Python | gpl-2.0 | 84,895 | 0.003028 | # encoding: utf-8
"""calculator.py - module for choosing a calculator."""
import gtk
from gettext import gettext as _
import os
import numpy as np
from copy import copy
from ase.gui.setupwindow import SetupWindow
from ase.gui.progress import DefaultProgressIndicator, GpawProgressIndicator
from ase.gui.widgets import p... | ef __init__(self, gui):
SetupWindow.__init__(self)
self.set_title(_("Select calculator"))
vbox = gtk.VBox()
# Intoductory text
self.packtext(vbox, introtext)
pack(vbox, [gtk.Label(_("Calculator:"))])
# No calculator (the default)
self.no... | # Lennard-Jones
self.lj_radio = gtk.RadioButton(self.none_radio,
_("Lennard-Jones (ASAP)"))
self.lj_setup = gtk.Button(_("Setup"))
self.lj_info = InfoButton(lj_info_txt)
self.lj_setup.connect("clicked", self.lj_setup_window)
self.pack_line... |
unnikrishnankgs/va | venv/lib/python3.5/site-packages/IPython/utils/daemonize.py | Python | bsd-2-clause | 162 | 0.012346 | from warnings import warn
warn | ("IPython.utils.daemonize has moved to ipyparallel.apps.daemonize", stacklevel=2)
from ipyparallel.apps.daemoni | ze import daemonize
|
bfontaine/RemindMe | remindme/providers/free.py | Python | mit | 841 | 0 | # -*- coding: UTF-8 -*-
from freesms import FreeClient
from base import BaseProvider, MissingConfigParameter, ServerError
class FreeProvider(BaseProvider):
"""
This is a provider class for th | e French telco 'Free'.
>>> f = FreeProvider({'api_id': '12345678', 'api_key':'xyz'})
>>> f.send('Hello, World!')
True
"""
def required_keys(self):
return ['api_id', 'api_key']
def send(self, msg):
params = {
'user': self.params['api_id'],
'passwd': self... | _code == 400:
raise MissingConfigParameter()
if res.status_code == 500:
raise ServerError()
return False
|
ledtvavs/repository.ledtv | script.tvguide.Vader/resources/playwith/playwithchannel.py | Python | gpl-3.0 | 2,435 | 0.009035 | import sys
import xbmc,xbm | caddon,xbmcvfs
import sqlite3
from subprocess import Popen
import datetime,time
channel = sys.argv[1]
start = sys.argv[2]
ADDON = xbmcaddon.Addon(id='script.tvguide.Vader')
def adapt_datetime(ts):
# http://docs.python.org/2/library/sqlite3.html#registering-an-adapter-calla | ble
return time.mktime(ts.timetuple())
def convert_datetime(ts):
try:
return datetime.datetime.fromtimestamp(float(ts))
except ValueError:
return None
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
sqlite3.register_converter('timestamp', convert_datetime)
path = xbmc.translate... |
goldmann/cct | cct/__init__.py | Python | mit | 696 | 0.001437 | """
Copyright (c) 2015 Red Hat, Inc
All rights reserved.
This software may | be modified and distributed under the terms
of the MIT license. See the LICENSE file for details.
"""
import logging
def setup_logging(name="cct", level=logging.DEBUG):
# create logger
logger = logging.getLogger(name)
logger.handlers = []
logger.setLevel(level)
# create console handler and set ... | amHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
|
hhucn/webvulnscan | webvulnscan/__main__.py | Python | mit | 428 | 0 | #!/usr/bin/env python
# Execute with
# $ python webvuln | scan/__main__.py (2.6+)
# $ python -m webvulnscan (2.7+)
import sys
if __package__ is None and not hasattr(sys, "frozen"):
# direct call of __main__.py
import os.path
path = os.path.realpath(os.path.abspath(__file__))
sys.path.append(os.path.dirname(os.path.dirname(path)))
import webvulnscan... | )
|
twilio/twilio-python | tests/integration/preview/sync/service/test_sync_list.py | Python | mit | 8,183 | 0.003666 | # coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class SyncListTestCase(Integrat... | s": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Permissions"
},
"revision": "revision",
"service_sid": "ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
| "sid": "ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"unique_name": "unique_name",
"url": "https://preview.twilio.com/Sync/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Lists/ESaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
}
'''
))
actual = self.client.preview.sync.se... |
valkyriesavage/invenio | modules/bibauthorid/lib/bibauthorid_tables_utils.py | Python | gpl-2.0 | 54,551 | 0.00275 | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2011 CERN.
##
## Invenio is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2 of the
## License, or (at your option) a... | nfig.TABLES_UTILS_DEBUG:
print "authornames_tables_gc: aidAUTHORNAMES deleting " + str(authrow)
else:
bibreflist = ''
for ref in authrow[0][2].split(','):
if ref != junkref:
bibreflist += ... | breflist[0:len(bibreflist) - 1]
run_sql("update aidAUTHORNAMES set bibrefs=%s where id=%s",
(bibreflist, id_to_remove[1]))
if bconfig.TABLES_UTILS_DEBUG:
print "authornames_tables_gc: aidAUTHORNAMES updating " + str(authrow) + '... |
teamllamauk/ScopeDriver | plugins/debris.py | Python | gpl-3.0 | 6,763 | 0.000591 | import random
import time
from dot3k.menu import MenuOption
class Debris(MenuOption):
def __init_ | _(self, backlight=None):
if backlight is None:
import dot3k.backlight
self.backlight = dot3k.backlight
else:
self.backlight = backlight
| self.debug = False
self.star_seed = 'thestarsmydestination'
self.debris_seed = 'piratemonkeyrobotninja'
self.debris = []
self.stars = []
self.running = False
self.max_debris = 10
self.max_stars = 10
self.last_update = 0
self.time_start = 0
... |
hbiyik/tribler | src/tribler-core/tribler_core/restapi/base_api_test.py | Python | lgpl-3.0 | 2,844 | 0.003516 | import json
from aiohttp import ClientSession
from tribler_core.restapi import get_param
from tribler_core.tests.tools.test_as_server import TestAsServer
from tribler_core.utilities.path_util import Path
from tribler_core.version import version_id
def path_to_str(obj):
if isinstance(obj, dict):
return {... | lse)
self.config.set_trustchain_enabled(False)
# Make sure we select a random port for the HTTP API
self.config.set_http_api_port(self.get_port())
async def do_request(self, endpoint, req_type, data, headers, json_response):
url = 'http://localhost:%d/%s' % (self.session.config.get... | Agent': 'Tribler ' + version_id}
async with ClientSession() as session:
async with session.request(req_type, url, data=data, headers=headers) as response:
return response.status, (await response.json(content_type=None)
if json_response else a... |
danfairs/django-dfk | dfk/models.py | Python | bsd-3-clause | 176 | 0 |
class De | ferredForeignKey(object):
def __init__(self, *args, **kwargs):
self.name = kwargs.pop('name', None)
self.args = args
self.kwargs = kwargs | |
gauthiier/mailinglists | www/archives.py | Python | gpl-3.0 | 1,896 | 0.030063 | import logging, os, json
import search.archive
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
logging.info('**** new Singleton instance')
retur... | = os.path.join(self.archives_dir, a)
self.data[a] = self.load_archive(self.archives_dir, a)
logging.info("done.")
self.loaded = True
def load_archive(self, archive_dir, archive_name):
if not os.path.isdir(archive_dir):
logging.error("Archives:: the path - " + archive_dir + " - is not a valid direct... | load(archive_name)
return archive
# # -- shoudl use Archive in searh module here....
# files = [f for f in os.listdir(archive_dir) if f.endswith('.json')]
# arch = {}
# for f in files:
# file_path = os.path.join(archive_dir, f)
# with open(file_path) as fdata:
# arch[f.replace('.json', '')] = jso... |
joakim-hove/ert | test-data/local/snake_oil_structure/snake_oil/jobs/snake_oil_npv.py | Python | gpl-3.0 | 2,757 | 0 | #!/usr/bin/env python
from ecl.summary import EclSum
OIL_PRICES = {
"2010-01-01": 78.33,
"2010-02-01": 76.39,
"2010-03-01": 81.20,
"2010-04-01": 84.29,
"2010-05-01": 73.74,
"2010-06-01": 75.34,
"2010-07-01": 76.32,
| "2010-08-01": 76.60,
"2010-09-01": 75.24,
"2010-10-01": 81.89,
"2010-11-01": 84.25,
"2010-12-01": 89.15,
"2011-01-01": 89.17,
"2011-02-01": 88.58,
"2011-03-01": 102.86,
"2011-04-01": 109.53,
"2011-05-01": 100.90,
"2011-06-01": 96.26,
"2011-07-01": 97.30,
"2011-08-01": ... | 2011-12-01": 98.56,
"2012-01-01": 100.27,
"2012-02-01": 102.20,
"2012-03-01": 106.16,
"2012-04-01": 103.32,
"2012-05-01": 94.65,
"2012-06-01": 82.30,
"2012-07-01": 87.90,
"2012-08-01": 94.13,
"2012-09-01": 94.51,
"2012-10-01": 89.49,
"2012-11-01": 86.53,
"2012-12-01": 87.... |
GafferHQ/gaffer | .github/workflows/main/setBuildVars.py | Python | bsd-3-clause | 6,394 | 0.021896 | #!/usr/bin/env python
##########################################################################
#
# Copyright (c) 2020, Cinesite VFX Ltd. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# ... | VER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
impo... | can be populated at run-time by echoing special
# strings to an env file. The following allows vars to be set:
#
# https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#environment-files
#
# echo var=value >> $GITHUB_ENV
#
# We make use of this mechanism to allow cus... |
vericred/vericred-python | test/test_county_bulk.py | Python | apache-2.0 | 9,989 | 0.002903 | # coding: utf-8
"""
Vericred API
Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and an... | er: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Peri... | re has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Netw... |
BambooHR/rapid | rapid/release/data/models.py | Python | apache-2.0 | 4,322 | 0.003702 | """
Copyright (c) 2015 Michael Bright and Bamboo HR LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | id'), nullable=False, index=True)
sort_order = Column(Integer, default=0)
release = relationship("Release", lazy='subquery', backref="steps")
status = relationship('Status')
integrations = relationship("Integration", secondary="step_integrations")
class StepUser(BaseModel, Base):
step_id = Column... | able=False, default=datetime.datetime.utcnow)
class StepUserComment(BaseModel, Base):
step_user_id = Column(Integer, ForeignKey('step_users.id'), nullable=False)
comment = Column(Text)
class User(BaseModel, Base):
name = Column(String(150), nullable=False)
username = Column(String(150), nullable=Fal... |
Azure/azure-sdk-for-python | sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.1/sample_recognize_business_cards.py | Python | mit | 5,129 | 0.003509 | # 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.
# --------------------------------------------------------------------... | fidence))
other_phones = business_card.fields.get("OtherPhones")
if other_phones:
for other_phone in other_phones.va | lue:
print("Other phone number: {} has confidence: {}".format(other_phone.value, other_phone.confidence))
# [END recognize_business_cards]
if __name__ == '__main__':
sample = RecognizeBusinessCardSample()
sample.recognize_business_card()
|
zeeshanali/blaze | blaze/compute/air/passes/ckernel_impls.py | Python | bsd-3-clause | 1,537 | 0.003904 | """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#---------------------------------------... | overload = op.metadata['overload']
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = monosig.argtypes
if function.matches('ckernel', argtypes):
overload = fun | ction.best_match('ckernel', argtypes)
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata(... |
Robpol86/sphinxcontrib-versioning | sphinxcontrib/versioning/lib.py | Python | mit | 5,599 | 0.0025 | """Common objects used throughout the project."""
import atexit
import functools
import logging
import os
import shutil
import tempfile
import weakref
import click
class Config(object):
"""The global configuration and state of the running program."""
def __init__(self):
"""Constructor."""
s... | ."""
super(HandledError, self).__init__(None)
def show(self, **_):
"""Error messages should be logged before raising this exception."""
logging.critical('Failure.')
class TempDir(object):
"""Similar to TemporaryDirectory in Python 3.x | but with tuned weakref implementation."""
def __init__(self, defer_atexit=False):
"""Constructor.
:param bool defer_atexit: cleanup() to atexit instead of after garbage collection.
"""
self.name = tempfile.mkdtemp('sphinxcontrib_versioning')
if defer_atexit:
at... |
stephanepechard/projy | projy/templates/DjangoProjectTemplate.py | Python | gpl-3.0 | 4,869 | 0.00801 | # -*- coding: utf-8 -*-
""" Projy template for PythonPackage. """
# system
from datetime import date
from os import mkdir, rmdir
from shutil import move
from subprocess import call
# parent class
from projy.templates.ProjyTemplate import ProjyTemplate
# collectors
from projy.collectors.AuthorCollector import AuthorCol... | MakefileTemplate' ],
[ self.project_name + '/conf',
'requirements_base.txt',
'DjangoRequirementsBaseTemplate' ],
[ self.project_name + '/conf',
'requirements_dev.txt',
'DjangoRequirementsDevTemplate' ],
[ self.project_name + '/c... | f',
'nginx.conf',
'DjangoNginxConfTemplate' ],
[ self.project_name + '/conf',
'supervisord.conf',
'DjangoSupervisorConfTemplate' ],
[ self.project_name,
'fabfile.py',
'DjangoFabfileTemplate' ],
[ self... |
tjsavage/rototutor_djangononrel | django/forms/fields.py | Python | bsd-3-clause | 31,759 | 0.026575 | """
Field classes.
"""
import datetime
import os
import re
import time
import urlparse
import warnings
from decimal import Decimal, DecimalException
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.core.exceptions import ValidationError
from django.core import valida... | eld in a form. By default, Django will use a "pretty"
# version of the form field name, if the | Field is part of a
# Form.
# initial -- A value to use in this Field's initial display. This value
# is *not* used as a fallback if data isn't given.
# help_text -- An optional string to use as "help text" for this Field.
# error_messages -- An optional dictionary to override the default
... |
mitsuhiko/django | tests/regressiontests/forms/localflavor/cz.py | Python | bsd-3-clause | 3,835 | 0.001825 | import warnings
from django.contrib.localflavor.cz.forms import (CZPostalCodeField,
CZRegionSelect, CZBirthNumberField, CZICNumberField)
from django.core.exceptions import ValidationError
from utils import LocalFlavorTestCase
class CZLocalFlavorTests(LocalFlavorTestCase):
def setUp(self):
self.save_... | f.clean, '885223/0000', 'f')
def test_CZICNumberField(self):
error_invalid = [u'Enter a valid IC number.']
valid ={
'12345679': '12345679',
'12345601': '12345601',
'12345661': '12345661',
'12345610': '12345610',
}
invalid = ... | self.assertFieldOutput(CZICNumberField, valid, invalid)
|
KhronosGroup/COLLADA-CTS | StandardDataSets/1_5/collada/library_kinematics_model/kinematics_model/asset/unit/unit.py | Python | mit | 3,954 | 0.006829 |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publ... | E WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, T | ORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
# See Core.Logic.FJudgementContext for the information
# of the 'context' parameter.
# This sample judging object does the following:
#
# JudgeBaseline: just verifies that the standard step... |
alshedivat/tensorflow | tensorflow/python/kernel_tests/py_func_test.py | Python | apache-2.0 | 22,732 | 0.012234 | # -*- coding: utf-8 -*-
# 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
#
# Un... | onstant([1.0, 2.0], dtypes.float64)
y = | constant_op.constant([2.0, 3.0], dtypes.float64)
z = self.evaluate(script_ops.py_func(np_func, [x, y], [dtypes.float64]))
self.assertAllEqual(z[0],
np_func([1.0, 2.0], [2.0, 3.0]).astype(np.float64))
def testComplexType(self):
with self.cached_session():
x = constant_... |
luckiestlindy/osproject | booker/migrations/0026_remove_event_expected_guests.py | Python | gpl-3.0 | 403 | 0 | # -*- coding: utf-8 -*-
# Gen | erated by Django 1.10.5 on 2017-03-01 05:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('booker', '0025_event_wedding_options'),
]
operations = [
migrations.RemoveField(
model_name='event',... | me='expected_guests',
),
]
|
A425/django-nadmin | nadmin/plugins/aggregation.py | Python | mit | 2,408 | 0.002076 | from django.db.models import FieldDoesNotExist, Avg, Max, Min, Count, Sum
from django.utils.translation import ugettext as _
from nadmin.sites import site
from nadmin.views import BaseAdminPlugin, ListAdminView
from nadmin.views.list import ResultRow, ResultItem
from nadmin.util import display_for_field
AGGREGATE_ME... | TE_METHODS])
row = ResultRow()
row['is_display_first'] = False
row.cells = [self._get_field_aggregate(field_name, obj, row) for field_name in self.admin_view.list_display]
row.css_class = 'info aggregate'
return row
def results(self, rows):
if rows:
rows... | ia.add_css({'screen': [self.static(
'nadmin/css/nadmin.plugin.aggregation.css'), ]})
return media
site.register_plugin(AggregationPlugin, ListAdminView)
|
edx/edx-platform | common/lib/xmodule/xmodule/contentstore/utils.py | Python | agpl-3.0 | 1,571 | 0.001273 | # lint-amnesty, pylint: disable=missing-module-docstring
from xmodule.contentstore.content import StaticContent
from .django import contentstore
def empty_asset_trashcan(course_locs):
'''
This method will hard delete all assets (optionally within a course_id) from the trashcan
'''
store = contentsto... | rash.find(content.thu | mbnail_location)
store.save(thumbnail_content)
except Exception: # lint-amnesty, pylint: disable=broad-except
pass # OK if this is left dangling
|
yasushiyy/awr2csv | awrtext2csv102.py | Python | mit | 21,131 | 0.007668 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Create CSV from AWR text reports
#
# Tested Versions
# 10.2.0.1 RAC
# 10.2.0.4 RAC
#
# Note
# extracts values specified with "===" sequence.
#
######################################################################################################
t = {... | l_line = line2list(line, m_dbname)
l_base = l_line[:4]
db_ver = l_line[4]
print(' DB Version: ' + db_ver)
section = ''
##### Snap Time
# ===================
... | -13 05:00:50 640 .1
# End Snap: 3727 16-2月 -13 06:00:16 672 .2
# Elapsed: 59.43 (mins)
# DB Time: 25.21 (mins)
#
elif line.startswith('Begin Snap:') or line.startswith(' End Snap:'):
... |
iansprice/wagtail | wagtail/wagtailredirects/tests.py | Python | bsd-3-clause | 23,927 | 0.003679 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase, override_settings
from wagtail.tests.utils import WagtailTestUtils
from wagtail.wagtailcore.models import Page, Site
from wagtail.wagtailredirects import mode... | s.Redirect.objects.create(old_path='/xmas', redirect_page=christmas_page)
response = self.client.get('/xmas/', HTTP_HOST='test.example.com')
self.assertRedirects(response, 'http://test.example.com/events/christmas/', status_code=301, fetch_redirect_response=False)
def | test_redirect_from_any_site(self):
contact_page = Page.objects.get(url_path='/home/contact-us/')
Site.objects.create(hostname='other.example.com', port=80, root_page=contact_page)
christmas_page = Page.objects.get(url_path='/home/events/christmas/')
models.Redirect.objects.create(old_pa... |
talflon/rkivas-python | rkivas/config.py | Python | gpl-3.0 | 3,679 | 0.000272 | # rkivas file backupper
# Copyright (C) 2016 Daniel Getz
#
# 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 later version.
#
# This pro... | E = '/etc/rkivas.conf'
DEFAULTS = """
[sources]
[backup]
filename-format = {source}/{timestamp:%Y-%m}/{source}-{timestamp:%Y%m%d_%H%M%S}-{hash}
hash-algorithm = md5
hash-length = 8
[backup-no-timestamp]
f | ilename-format = {source}/unknown/{source}-{hash}
hash-algorithm = md5
hash-length = 16
[extension-map]
jpeg = jpg
tiff = tif
[extension-handlers]
jpg = exif
tif = exif
"""
class ConfigParser(RawConfigParser):
def optionxform(self, optionstr):
return optionstr
def load_config_files(opts):
cfg = C... |
cloudbase/neutron | neutron/tests/fullstack/test_qos.py | Python | apache-2.0 | 11,734 | 0 | # Copyright 2015 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 agre... | elf):
host_desc = [
environment.HostDescription(
l3_agent=False,
of_interface=self.of_interface,
ovsdb_interface=self.ovsdb_interface,
l2_agent_type=self.l2_agent_type
) for _ in range(2)]
env_desc = environment.Envi... | env = environment.Environment(env_desc, host_desc)
super(BaseQoSRuleTestCase, self).setUp(env)
self.tenant_id = uuidutils.generate_uuid()
self.network = self.safe_client.create_network(self.tenant_id,
'network-test')
self.subnet =... |
kawamon/hue | desktop/core/ext-py/pyasn1-modules-0.2.6/tests/test_rfc5649.py | Python | apache-2.0 | 1,730 | 0.001156 | #
# This file is part of pyasn1-modules software.
#
# Created by Russ Housley
# Copyright (c) 2019, Vigil Security, LLC
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
from pyasn1.codec.der import decoder as der_decoder
from pyasn1.codec.der import encoder as der_encoder
from pyasn1_modules import pe... | lf):
self.asn1Spec = rfc5649.AlgorithmIdentifier()
def testDerCodec(self):
substrate = pem.readBase64fromText(self.kw_pad_alg_id_pem_text)
asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec)
assert not rest
assert asn1Object.prettyPrint()
assert ... | romModule(sys.modules[__name__])
if __name__ == '__main__':
import sys
result = unittest.TextTestRunner(verbosity=2).run(suite)
sys.exit(not result.wasSuccessful())
|
alphagov/notifications-delivery | wsgi.py | Python | mit | 322 | 0.003106 | i | mport os
from notifications_delivery.app import create_app
from credstash import getAllSecrets
# on aws get secrets and export to env
secrets = getAllSecrets(region="eu-west-1")
for key, val in secrets.items():
os.environ[key] = val
application = create_app()
if __name__ == "__main__":
applica | tion.run()
|
Tutakamimearitomomei/Kongcoin | contrib/wallettools/walletunlock.py | Python | mit | 159 | 0 | from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:12644" | )
pwd = raw_input("Enter wallet passphrase: ")
access.walletpassphras | e(pwd, 60)
|
hzlf/openbroadcast | website/_notification/atomformat.py | Python | gpl-3.0 | 22,948 | 0.009936 | #
# django-atompub by James Tauber <http://jtauber.com/>
# http://code.google.com/p/django-atompub/
# An implementation of the Atom format and protocol for Django
#
# For instructions on how to use this module to generate Atom feeds,
# see http://code.google.com/p/django-atompub/wiki/UserGuide
#
#
# Copyright (c) 2... | parts.hostname,
date_part,
parts.path,
parts.fragment,
)
## based on django.contrib.syndication.feeds.Feed
class Feed(object):
VALIDATE = True
def __init__(self, slug, feed_url):
# @@@ slug and feed_url are not used yet
pass
... | callable(attr):
# Check func_code.co_argcount rather than try/excepting the
# function and catching the TypeError, because something inside
# the function may raise the TypeError. This technique is more
# accurate.
if hasattr(attr, 'func_code'):
... |
steveb/heat | heat/tests/openstack/heat/test_resource_group.py | Python | apache-2.0 | 58,016 | 0 | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | urceGroup",
"properties": {
"count": 2,
"resource_def": {
"type": "OverwrittenFnGetRefIdType",
"properties": {
"Foo": "Bar"
}
}
}
}
}
}
template2 = {
... | "properties": {
"Foo": "baz"
}
},
"group1": {
"type": "OS::Heat::ResourceGroup",
"properties": {
"count": 2,
"resource_def": {
"type": "OverwrittenFnGetRefIdType",
"properties": {... |
yuroller/pvaurora | src/config-dist.py | Python | gpl-3.0 | 152 | 0.006579 | #!/usr/bin | /env python
# encoding: utf-8
'''
pvaurora configuration file
'''
LATITUDE = | 42.6
LONGITUDE = 12.9
API_KEY = "api_key_value"
SYSTEM_ID = -1
|
gautelinga/BERNAISE | utilities/mesh_scripts/barbell_capillary.py | Python | mit | 1,501 | 0 | """ barbell_capilar script. """
from common import info
import dolfin as df
import mshr
import os
from generate_mesh import MESHES_DIR, store_mesh_HDF5
import matplotlib.pyplot as plt
def description(**kwargs):
info("Generates mesh for a barbell capillary.")
def method(res=50, diameter=1., length=5., show=False... | iameter/2., length/2+inletlength/2.)
capilar = mshr.Rectangle(a, b)
# Define coners of "leftbell
c = df.Point(-inletdiameter/2., -length/2-inletlength)
d = df.Point(inletdiameter/2., -length/2)
leftbell = mshr.Rectangle(c, d)
# Define coners of "rightbell"
e = df.Point(-inletdiameter/2., len... | lar + leftbell + rightbell
mesh = mshr.generate_mesh(domain, res)
meshpath = os.path.join(MESHES_DIR,
"BarbellCapilarDolfin_d" + str(diameter) + "_l" +
str(length) + "_res" + str(res))
store_mesh_HDF5(mesh, meshpath)
if show:
df.plot(mesh)... |
tomkralidis/geonode | geonode/tasks/tasks.py | Python | gpl-3.0 | 4,983 | 0.000201 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2017 OSGeo
#
# 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 ... | binary=True)
lock_type = "MEMCACHED"
except Exception:
from django.core.cache import cache
from contextlib import contextmanager
lock_type = "MEMCACHED-LOCAL-CONTEXT"
memcache_client = None
"""
ref.
h | ttp://docs.celeryproject.org/en/latest/tutorials/task-cookbook.html#ensuring-a-task-is-only-executed-one-at-a-time
"""
class Lock(object):
def __init__(self, lock_id, *args, **kwargs):
self.lock_id = lock_id
self.client = kwargs.get('client', None)
@contextmanager
... |
octopus-platform/bjoern | python/bjoern-tools/bjoern/plugins/vsa.py | Python | gpl-3.0 | 414 | 0 | from octopus.plugins.plugin import OctopusPlugin
class VSA(OctopusPlugin):
def __init__(self, executor):
super().__i | nit__(executor)
self._pluginname = 'vsa.jar'
self._classname = 'bjoern.plugins.vsa.VSAPlugin'
def __setattr__(self, key, value):
if key == "project":
| self._settings["database"] = value
else:
super().__setattr__(key, value)
|
qsnake/gpaw | doc/exercises/surface/surface.agts.py | Python | gpl-3.0 | 180 | 0.005556 | def agts(queue):
al = que | ue.add( | 'surface.agts.py')
queue.add('work_function.py', ncpus=1, deps=[al])
if __name__ == '__main__':
execfile('Al100.py', {'k': 6, 'N': 5})
|
SlideAtlas/SlideAtlas-Server | slideatlas/models/common/multiple_database_model_document.py | Python | apache-2.0 | 5,469 | 0.002377 | # coding=utf-8
from flask import g
from mongoengine.connection import get_db
from .model_document import ModelDocument, ModelQuerySet
################################################################################
__all__ = ('MultipleDatabaseModelDocument',)
#######################################################... | as = self._get_db_alias()
self._db_alias = cls_db_alias # save the value for use in the 'database' property
self.switch_db(cls_db_alias) # thi | s patches over 'self._get_db'
|
arju88nair/projectCulminate | venv/lib/python3.5/site-packages/pylint/test/functional/wrong_import_position.py | Python | apache-2.0 | 777 | 0.006435 | """Checks im | port order rule"""
# pylint: disable=unused-import,relative-import,ungrouped-imports,wrong-import-order
# pylint: disable=import-error, too-few-public-methods, missing-docstring,using-constant-test
import os.path
if True:
from astroid import are_exclusive
try:
import sys
except ImportError:
class Myclass(o... | """Nothing to see here."""
def some_func(self):
pass
import six # [wrong-import-position]
CONSTANT = True
import datetime # [wrong-import-position]
VAR = 0
for i in range(10):
VAR += i
import scipy # [wrong-import-position]
import astroid # [wrong-import-position]
|
hoechenberger/psychopy | psychopy/experiment/utils.py | Python | gpl-3.0 | 1,018 | 0 | #!/usr/bin/env | python
# -*- coding: utf-8 -*-
# Part of the PsychoPy library
# Copyrigh | t (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).
"""Utility functions to support Experiment classes
"""
import re
# this needs to be accessed from __str__ method of Param
scriptTarget = "PsychoPy"
# predefine some regex's; deepcopy complains if do in NameSpace.__init_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.