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 |
|---|---|---|---|---|---|---|---|---|
armab/st2contrib | packs/servicenow/actions/approve_change.py | Python | apache-2.0 | 317 | 0 | from lib.actions import BaseAction
class ApprovalAction(BaseAction):
def run(self, number):
s = self.client
s.table = 'chang | e_request'
res = s.get({'number': number})
sys_id = res[0]['sys_id']
resp | onse = s.update({'approval': 'approved'}, sys_id)
return response
|
ufal/udpipe | releases/pypi/test/test_udpipe.py | Python | mpl-2.0 | 1,690 | 0.004782 | #!/usr/bin/python
# vim:fileencoding=utf8
from __future__ import unicode_literals
import unittest
class TestUDPipe(unittest.TestCase):
def test_model(self):
import ufal.udpipe
model = ufal.udpipe.Model.load('test/data/test.model')
self.assertTrue(model)
tokenizer = model.newToken... | tokenizer.setText("Znamená to, že realitě nepodléhá. ");
self.assertTrue(tokenizer.nextSentence(sentence, error))
self.assertFalse(error.occurred())
self.assertTrue(model.tag(sentence, model.DEFAULT))
self.assertTrue(model.pars | e(sentence, model.DEFAULT))
self.assertEqual(conlluOutput.writeSentence(sentence), """\
# newdoc
# newpar
# sent_id = 1
# text = Znamená to, že realitě nepodléhá.
1 Znamená znamenat VERB VB-S---3P-AA--- Aspect=Imp|Mood=Ind|Negative=Pos|Number=Sing|Person=3|Tense=Pres|VerbForm=Fin|Voice=Act 0 root _ _
2 to ten ... |
all-of-us/raw-data-repository | rdr_service/lib_fhir/fhirclient_3_0_0/models/graphdefinition_tests.py | Python | bsd-3-clause | 2,760 | 0.005435 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import graphdefinition
from .fhirdate import FHIRDate
class GraphDefinitionTests(unittest.TestCase):
def instantiate_from(self, file... | "Include any list entries")
self.assertEqual(inst.link[0].target[0].link[0].path, "List.entry.item")
self.assertEqual(inst.link[0].target[0].link[0].target[0].compartment[0].code, "Patient")
self.assertEqual(inst.link[0].target[0].link[0].target[0].compartment[0]. | rule, "identical")
self.assertEqual(inst.link[0].target[0].link[0].target[0].type, "Resource")
self.assertEqual(inst.link[0].target[0].type, "List")
self.assertEqual(inst.name, "Document Generation Template")
self.assertEqual(inst.publisher, "FHIR Project")
self.assertEqual(inst.... |
blorgon9000/pyopus | demo/parallel/cooperative/05-asyncloop.py | Python | gpl-3.0 | 2,431 | 0.051008 | # This demo does the same as the dyndispatch demo, except that a
# custom dispatcher loop is used. This is how asynchronous parallel
# optimization algorithms like DE and PSADE are implemented.
# mpirun -n 4 python 05-asyncloop.py
from pyopus.parallel.cooperative import cOS
from pyopus.parallel.mpi import MPI
from ... | ximal number of parallel tasks
# Th | e maximal number of parallel tasks can be infinite (set maxTasks to None)
minTasks=1
maxTasks=1000
if __name__=='__main__':
# Set up MPI
cOS.setVM(MPI())
# Thsi list will hold the jobs (values that are doubled)
jobs=[]
# This list will be filled with results
results=[]
# Stop the loop
stop=False
# Running... |
TheTimmy/spack | var/spack/repos/builtin.mock/packages/dtbuild2/package.py | Python | lgpl-2.1 | 1,542 | 0 | ########## | ####################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# F... | ftware; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# ... |
Ultimaker/Uranium | UM/Math/Plane.py | Python | lgpl-3.0 | 975 | 0.005128 | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the LGPLv3 or higher.
from UM.Math.Vecto | r import Vector
from UM.Math.Float import Float
class Plane:
"""Plane representation using normal and distance."""
def __init__(self, normal = Vector(), distance = 0.0):
super().__init__()
self._normal = normal
self._distance = distance
@property
def normal(self):
re... | ._normal
@property
def distance(self):
return self._distance
def intersectsRay(self, ray):
w = ray.origin - (self._normal * self._distance)
nDotR = self._normal.dot(ray.direction)
nDotW = -self._normal.dot(w)
if Float.fuzzyCompare(nDotR, 0.0):
return F... |
petrvanblokland/Xierpa3 | xierpa3/attributes/frames.py | Python | mit | 1,825 | 0.010411 | # -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
# xierpa server
# Copyright (c) 2014+ [email protected], www.petr.com, www.xierpa.com
#
# X I E R P A 3
# Distribution by the MIT License.
#
# -----------------------------------------------------------... |
self.v1 = v1
self.v2 = v2
self.v3 = v3
def _get_value(self):
return '%s %s %s' % (self.v1, self.v2 or '', self.v3 or | '')
value = property(_get_value)
def _get_raw(self):
return self.id, self.v1, self.v2, self.v3
raw = property(_get_raw)
|
alex/taskmaster | setup.py | Python | apache-2.0 | 977 | 0 | #!/usr/bin/python
from setuptools import setup, find_packages
setup(
name="taskmaster",
license='Apache License 2.0',
version | ="0.5.2",
description="",
author="David Cramer",
author_email="[email protected]",
url="https://github.com/dcramer/taskmaster",
packages=find_packages("src"),
package_dir={'': 'src'},
entry_points={
'console_scripts': [
'tm-master = taskmaster.cli.master:main',
... | ',
'tm-spawn = taskmaster.cli.spawn:main',
],
},
install_requires=[
'progressbar',
'gevent',
'gevent_zeromq',
# 'pyzmq-static',
],
tests_require=[
'unittest2',
'Nose>=1.0',
],
classifiers=[
"Environment :: Console",
... |
antoinecarme/pyaf | tests/model_control/detailed/transf_Difference/model_control_one_enabled_Difference_Lag1Trend_Seasonal_MonthOfYear_NoAR.py | Python | bsd-3-clause | 165 | 0.048485 | import | tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Difference'] , ['Lag1Trend'] , ['Seasonal_MonthOfYear'] , | ['NoAR'] ); |
KaiRo-at/socorro | alembic/versions/21e4e35689f6_bug_993786_update_crash_adu_by_build_.py | Python | mpl-2.0 | 728 | 0.012363 | """bug 993786 - update_crash_adu_by_build_signature-bad-buildids
Revision ID: 21e4e35689f6
Revises: 224f0fda6ecb
Create Date: 2014-04-08 18:46:19.755028
"""
# revision identifiers, used by Alembic.
revision = '21e4e35689f6'
down_revision = '224f0fda6ecb'
from alembic import op
from socorrolib.lib import citexttype,... | y_build_ | signature.sql'])
|
rcarrillocruz/ansible | lib/ansible/modules/network/f5/bigip_iapp_service.py | Python | gpl-3.0 | 14,587 | 0.000686 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2017 F5 Networks Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundat | ion, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.0'
}
DOCUMENTATION... |
migue/voltdb | lib/python/vdm/server/Configuration.py | Python | agpl-3.0 | 59,480 | 0.002808 | # This file is part of VoltDB.
# Copyright (C) 2008-2017 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ver... | er_json = get | _users_from_xml(deployment,
'list')
for deployment_user in user_json:
HTTPListener.Global.DEPLOYMENT_USERS[int(deployment_user['userid'])] = deployment_user
def validate_and_convert_xml_to_json(config_path):
"""
Method to get the json cont... |
devilry/devilry-django | devilry/devilry_markup/views.py | Python | bsd-3-clause | 610 | 0.004918 | from django.http import Ht | tpResponse
from django.http import HttpResponseBadRequest
from django.views.generic import View
from devilry.devilry_markup.parse_markdown import markdown_full
class DevilryFlavouredMarkdownFull(View):
def _parse(self, data):
if 'md' in data:
md = data['md']
return HttpResponse(m... | return self._parse(request.POST)
## For debugging:
#def get(self, request):
#return self._parse(request.GET)
|
co-devs/microsoftBookDownloader | microsoftBookDownloader.py | Python | gpl-3.0 | 3,629 | 0.003031 | #!/usr/bin/env python
# Author: Michael Devens
# Derek Ditch <github:@dcode>
# Github: https://github.com/co-devs
# Simple, poorly written script to download all of the files being shared
# by microsoft instead of downloading by hand. Downloads consecutively,
# will therefore take a while. Could be optimized, b... | print catDir, ' Exists'
except:
# print 'Mkdir: ', catDir
os.mkdir(catDir)
# TODO: Debug print, remove or change to a progress meter
# print 'Category: ', category
title = bookData[1].getText().encode('ascii', 'ignore').translate(None, badChars)
titleDir = os.path.join(catD | ir, title)
try:
os.stat(titleDir)
# print titleDir, 'Exists'
except:
# print 'Mkdir: ', titleDir
os.mkdir(titleDir)
# TODO: Debug print, remove or change to a progress meter
# print 'Title: ', title
links = bookData[2].select('a')
linkNum = 1
for j in links:
... |
paradiseOffice/sandbox_API_v1.0 | paradise_office_site/sandbox_v1.0/cygnet_maker/cy_tests/test_time.py | Python | gpl-2.0 | 1,622 | 0.018496 | #!/usr/bin/python3.3
import unittest
import sys
sys.path.append("/home/hazel/Documents/new_linux_paradise/paradise_office_site/sandbox_v1.0/cygnet_maker/cy_data_validatio | n")
from datetime import time
from time_conv import Time
class TimeTestCase(unittest.TestCase):
''' Tests with numbered degrees of bad or good data, on a scale of 0=baddest to 10=goodest '''
def setUp(self):
self.time = Time.check_time("")
# A string
def test_vbad0(self):
self.time = Time.check_tim... | rtEqual( correct_time, self.time)
# An out of range whole number
def test_bad1(self):
self.time = Time.check_time("52304")
correct_time = time(00, 00, 00)
self.assertEqual( correct_time, self.time)
# Two out of range whole numbers
def test_bad2(self):
self.time = Time.check_time("70 80")
c... |
Toshakins/wagtail | wagtail/wagtailadmin/tests/tests.py | Python | bsd-3-clause | 12,417 | 0.002175 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import json
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.core import mail
from django.core.urlresolvers import reverse, reverse_lazy
from django.test import TestCase... | ks(TestCase, WagtailTestUtils):
def setUp(self):
self.homepage = Page.objects.get(id=2)
self.login()
def test_editor_css_hooks_on_add(self):
response = self.client.get(reverse('wagtailadmin_pages:add', args= | ('tests', 'simplepage', self.homepage.id)))
self.assertEqual(response.status_code, 200)
self.assertContains(response, '<link rel="stylesheet" href="/path/to/my/custom.css">')
def test_editor_js_hooks_on_add(self):
response = self.client.get(reverse('wagtailadmin_pages:add', args=('tests', '... |
AlvaroOdoo/openacademy-project | modulo01/__openerp__.py | Python | apache-2.0 | 881 | 0.001139 | # -*- coding: utf-8 -*-
{
'name': "Módulo de Ejemplo",
'summary': """Manage trainings""",
'description': """
Módulo01 for managing trainings:
- training courses
- training sessions
- attendees registration
""",
'author': "Alvaro Villavicencio Ramírez",
... | r modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# f | or the full list
'category': 'Test',
'version': '0.1',
# any module necessary for this one to work correctly
'depends': ['base'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
# 'templates.xml',
],
# only loaded in demonstration mode
'demo': [
... |
texastribune/armstrong.base | armstrong/base/tests/context_processors.py | Python | bsd-3-clause | 3,000 | 0.004333 | from django.http import HttpRequest
import fudge
import random
from ._utils import TestCase
from .. import context_processors
from ..context_processors import media_url, static_url
class TestOfMediaUrlContextProcessor(TestCase):
def generate_fake_request(self, is_secure=False):
request = fudge.Fake(HttpR... | }
return fake_settings, expected_result
def test_returns_media_url_from_settings(self):
request = self.generate_fake_request()
fake_settings, expected_result = self.generate_fake_media_settings_and_result()
with fudge.patched_context(context_processors, 'settings', fake_settings):
... | expected_result)
def test_returns_secure_media_url_from_settings_on_is_secure(self):
request = self.generate_fake_request(is_secure=True)
fake_settings, expected_result = self.generate_fake_media_settings_and_result(is_secure=True)
with fudge.patched_context(context_processors, 'settings',... |
DanielKeep/rust-numeric-float | update-docs.py | Python | mit | 5,819 | 0.003437 | #!/usr/bin/env python2
import distutils.dir_util
import os
import shutil
import subprocess
import sys
import tempfile
import time
DOC_ARGS = '--no-deps'
DOC_FEATURES = "conv num rustc-serialize serde"
DOC_TARGET_BRANCH = 'gh-pages'
TEMP_CHECKOUT_PREFIX = 'gh-pages-checkout-'
TEMP_OUTPUT_PREFIX = 'gh-pages-generated-'... |
tmp1 = tempfile.mkdtemp(prefix=TEMP_CHECKOUT_PREFIX)
tmp2 = tempfile.mkdtemp(prefix=TEMP_OUTPUT_PREFIX)
msg_trace('tmp1 = %r' % tmp1)
msg_trace('tmp2 = | %r' % tmp2)
try:
msg("Cloning into a temporary directory...")
sh('git clone -qb "%s" "%s" "%s"' % (DOC_TARGET_BRANCH, dir, tmp1))
msg_trace('os.chdir(%r)' % tmp1)
os.chdir(tmp1)
sh('git checkout -q master')
msg("Generating documentation...")
args = '%s --fea... |
torn2537/AnimationJava | LSTM2.py | Python | mit | 3,840 | 0.00026 | from __future__ import print_function
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib import rnn
import time
from datetime import timedelta
# Import MNIST data
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/t... | "{:.4f}".format(loss) + ", Training Accuracy= " +
"{:.3f}".format(acc))
print("Optimization Finished!")
print(loss_group)
print(epoch_group)
plt.plot(epoch_group, loss_group)
plt.show()
end_time = time.time()
time_dif = end_time - start_time
print("Time usage:... | e_dif)))))
# Calculate accuracy for 128 mnist test images
test_len = 128
test_data = mnist.test.images[:test_len].reshape(
(-1, timesteps, num_input))
test_label = mnist.test.labels[:test_len]
print("Testing Accuracy:",
sess.run(accuracy, feed_dict={X: test_data, Y: test_label}))
|
vinzenz/prototype | leapp/snactor/commands/workflow/__init__.py | Python | apache-2.0 | 313 | 0.003195 | from lea | pp.utils.clicmd import command
_LONG_DESCRIPTION = '''
Leapp Workflow related commands.
For more information please consider reading the documentation at:
https://red.ht/leapp-docs
'''
@command('workflow', help='Workflow related commands', description=_LONG_DESCRIPTION)
def workflow(*args | ):
pass
|
acressity/acressity | narratives/models.py | Python | gpl-3.0 | 5,401 | 0.003888 | from django.db import models
from django.core.urlresolvers import reverse
from django import forms
from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.utils import timezone
from django.core.paginator import Paginator
from django.utils.translation import ugettext_lazy as _
fro... | ForeignKey(Experience, related_name='narratives')
author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='narra | tives', null=False)
date_created = models.DateTimeField(default=timezone.now, null=False, blank=True)
date_modified = models.DateTimeField(auto_now=True, help_text='Updated every time object is saved')
category = models.CharField(max_length=50, null=True, blank=True, help_text='Optional information used to ... |
hhorak/rpmquality | setup.py | Python | mit | 1,001 | 0.022977 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except:
from distutils.core import setup, find_packages
setup(
name = 'rpmquality',
version = '0.1',
description = 'Short description',
long_description = 'Long description | ',
keywords = 'some, keywords',
author = 'Honza Horak',
author_email = '[email protected]',
license = 'MIT',
packages = find_packages(),
entry_points={'console_scripts':['rpmquality = rpmquality.bin:main']},
classifiers = ['Development Status :: 3 - Alpha',
'Environment ::... | pproved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Software Development :: Build Tools',
'Topic :: System :: Software Distribution',
]
)
|
otakup0pe/aomi | aomi/seed_action.py | Python | mit | 7,172 | 0 | """ The aomi "seed" loop """
from __future__ import print_function
import os
import difflib
import logging
from shutil import rmtree
import tempfile
from termcolor import colored
import yaml
from future.utils import iteritems # pylint: disable=E0401
from aomi.helpers import dict_unicodeize
from aomi.filez import thaw
... | % (maybe_colored("!", "red", opt), str(thing)))
if changed != OVERWRITE and changed != NOOP:
maybe_details(thing, opt)
def diff(vault_client, opt):
"""Derive a comparison between what is represented in the Secretfile
and what is actually live on a Vault instance"""
if opt.thaw_from:
o... | ')
auto_thaw(vault_client, opt)
ctx = Context.load(get_secretfile(opt), opt) \
.fetch(vault_client)
for backend in ctx.mounts():
diff_a_thing(backend, opt)
for resource in ctx.resources():
diff_a_thing(resource, opt)
if opt.thaw_from:
rmtree(opt.secre... |
semkiv/heppy_fcc | background_Bs2DsDsK_with_Ds2TauNu_analysis_cfg.py | Python | gpl-3.0 | 3,807 | 0.023903 | #!/usr/bin/env python
"""
Configuration script for the analyzer of B0s -> K*0 Ds+ Ds- background events
| | |-> tau- nu
| | |-> pi- pi- pi+ nu
... | momentum_x_resolution = 0.01,
momentum_y_resolution = 0.01,
momentum_z_resolution = 0.01,
smear_pv = True,
# IDL-like res
pv_x_resolution = 0.0025,
pv_y_resolution = 0.0025,... | lution = 0.001,
# pv_z_resolution = 0.001,
# outstanding res
# pv_x_resolution = 0.0005,
# pv_y_resolution = 0.0005,
# pv_z_resolution = 0.0005,
smear_sv = True,
# IDL-like ... |
saks/hb | records/views.py | Python | mit | 1,196 | 0.001672 | from djmoney.money import Money
from rest_framework import permissions, viewsets
from .models import Record
from .serializers import RecordSerializer
class RecordViewSet(viewsets.ModelViewSet):
serializer_class = RecordSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = Record.objec... | cy": { "code":"CAD", "name": "foo" }
}
}
'''
amount = self.request.data.get('amount')
| tags = self.request.data.get('tags')
if amount and 'amount' in amount.keys() and 'currency' in amount.keys():
amount = Money(amount['amount'], amount['currency']['code'])
serializer.save(tags=tags, user=self.request.user, amount=amount)
def perform_create(self, serializer):
se... |
juhojama/sensible-shroom | generator.py | Python | apache-2.0 | 6,684 | 0.005236 | #!/usr/bin/env python
import os
import sys
import collections
from flask import g, Flask, render_template, url_for, abort, redirect, request
from flask_frozen import Freezer
from flask_wtf import Form
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from wtforms import StringField, Password... |
@app.route('/')
def index():
return render_template("index.html",
posts=blog.posts,
title='Blogialusta|Tervetuloa',
user='Testi-User')
@app.route('/blog/<path:path>/')
def post(path):
post = blog.get_post_or_404(path)
return r... | nssin passaus templatelle
### / User management --> ###
@app.route('/register/')
def register():
return render_template("register.html",
title='Rekisteroidy')
@app.route('/login/', methods=["GET", "POST"])
def login():
form = EmailPasswordForm()
if form.validate_on_submit():
... |
pexip/os-kombu | t/unit/transport/test_mongodb.py | Python | bsd-3-clause | 16,952 | 0 | from __future__ import absolute_import, unicode_literals
import datetime
import pytest
from case import MagicMock, call, patch, skip
from kombu import Connection
from kombu.five import Empty
def _create_mock_connection(url='', **kwargs):
from kombu.transport import mongodb # noqa
class _Channel(mongodb.C... | lection
def get_collection(name):
try:
return self.collections[name]
except KeyError:
mock = self.collections[name] = MagicMock(
name='collection:%s' % name)
return mock
mock.__g... | m__.side_effect = get_collection
return mock
def get_now(self):
return self.now
class Transport(mongodb.Transport):
Channel = _Channel
return Connection(url, transport=Transport, **kwargs)
@skip.unless_module('pymongo')
class test_mongodb_uri_parsing:
def test_... |
biswajitsahu/kuma | vendor/packages/git/head.py | Python | mpl-2.0 | 2,739 | 0.00073 | # head.py
# Copyright (C) 2008-2010 Michael Trier ([email protected]) and contributors
#
# This module is part of GitPython and is released under
# the BSD License: http://www.opensource.org/licenses/bsd-license.php
import commit
class Head(object):
"""
A Head is a named reference to a Commit. Every Head insta... | ssmethod
def find_all( | cls, repo, **kwargs):
"""
Find all Heads in the repository
`repo`
is the Repo
`kwargs`
Additional options given as keyword arguments, will be passed
to git-for-each-ref
Returns
git.Head[]
List is sorted by committerd... |
dieb/algorithms.py | tests/sorting/test_bubblesort.py | Python | mit | 283 | 0.003534 | fr | om algorithms.sorting.bubblesort import bubble_sort
def test_bubble_sort_small(array_ints_small, assert_sorted):
assert_sorted(array_ints_small, bubble_sort)
def test_bubble_sort_large(array_ints_large, assert_sorted):
assert_sorted(array_ints_large[:800], bubble_s | ort)
|
arxanas/caenbrew | caenbrew/packages/ffmpeg.py | Python | gpl-3.0 | 1,345 | 0 | from .x264 import X264Package
from .yasm import YasmPackage
from ..packaging import AutotoolsPackage, package
@package
class FfmpegPackage(AutotoolsPackage):
"""Ffmpeg: record, convert and stream audio and video."""
name = "ffmpeg"
homepage = "https://www.ffmpeg.org/"
version = "3.0"
dependencie... | tproc",
"--enable-version3",
"--enable-x11grab",
"--enable-shared",
"--ena | ble-pic"]
def __init__(self, *args, **kwargs):
"""Help `ffmpg` detect `libx264` in `configure`."""
super(FfmpegPackage, self).__init__(*args, **kwargs)
prefix_dir = self._config["prefix_dir"]
self.configure_options += ["--extra-ldflags=-L{}/lib"
.f... |
khchine5/lino-welfare | lino_welfare/projects/eupen/tests/test_watchtim.py | Python | agpl-3.0 | 36,147 | 0.004096 | # -*- coding: UTF-8 -*-
# Copyright 2013-2017 Luc Saffre
# This file is part of Lino Welfare.
#
# Lino Welfare is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at y... | esByMaster.request(georges)
self.assertEqual(ar.get_ | total_count(), 0)
# Company becomes Client
# ValidationError([u'A Partner cannot be parent for a Client']) (201302-22 12:42:07)
# A Partner in TIM has both `PAR->NoTva` nonempty and
# `PARATTR_N` set. It currently exists in Lino as a Company but
# not as a Client. `w... |
davebshow/projx | projx/__init__.py | Python | mit | 434 | 0 | from .api import Projection, execute_etl
from .grammar import parse_query
from .nxprojx import (reset_index, match, traverse, project, transfer,
| combine, build_subgraph, NXProjector)
from .utils import (test_graph, project_etl, transfer_etl, combine_etl,
multi_transform_etl, draw_simple_graph, remove_edges,
proj_density, neo4j2nx_etl, edgelist2neo4j_etl)
import mo | dules
|
JoaoFelipe/data-mining-algorithms | examples/custom_association_rules.py | Python | mit | 560 | 0.007143 |
import sys
sys.path.append("..")
from data_mining.association_rule.base import rules, lift, support
from data_mining.association_rule.apriori import apriori
from data_mining.association_rule.liftmin import apriorilift
from pat_data_association_rules import compare
LE = | "leite"
PA = "pao"
SU = "suco"
OV = "ovos"
CA = "cafe"
BI = "biscoito"
AR = "arroz"
FE = "feijao"
CE = "cerveja"
MA = "manteiga"
data = [ | [CA, PA, MA], [LE, CE, PA, MA], [CA, PA, MA], [LE, CA, PA, MA],
[CE], [MA], [PA], [FE], [AR, FE], [AR]]
compare(data, 0.0000000001, 5.0, 0)
|
rjshade/grpc | tools/run_tests/run_microbenchmark.py | Python | bsd-3-clause | 10,997 | 0.008457 | #!/usr/bin/env python2.7
# Copyright 2017, 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 lis... | ['make', bm_name,
'CONFIG=%s' % cfg, '-j', '%d' % multiprocessing.cpu_count()])
cmd | = ['bins/%s/%s' % (cfg, bm_name),
'--benchmark_out=%s.%s.json' % (base_json_name, cfg),
'--benchmark_out_format=json']
if args.summary_time is not None:
cmd += ['--benchmark_min_time=%d' % args.summary_time]
return subprocess.check_output(cmd)
def collect_summary(bm_name, args):
heading('S... |
cjordog/NRLWebsite | demo/uw1.py | Python | mit | 14,884 | 0.019887 | #!/usr/bin/python
import json, math, sys, string, random, subprocess, serial
from time import localtime, strftime, clock, time # for timestamping packets
import time
import hashlib #for checksum purposes
import mysql.connector # mysql database
import getpass
import urllib2
import requests
sys.path.append('/usr/lib/pyt... | #############################################################################
### 1. Port configuration
################################################################################
### Setup the port to be read from ( /dev/ttyUSB0 ) with timeout to enable
### recov | ery from packet loss.
port_ttyUSB0 = serial.Serial(port='/dev/ttyUSB0', baudrate=115200)
port_ttyUSB1 = serial.Serial(port='/dev/ttyUSB1', baudrate=115200, timeout= 25)
### For each port, enter command mode (+++A) and enable checksum ($HHCRW,MMCHK,1),
### then check for success.
port_ttyUSB0.write("+++A\r\n")
if... |
kaiix/depot_tools | apply_issue.py | Python | bsd-3-clause | 10,737 | 0.009686 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Applies an issue from Rietveld.
"""
import getpass
import json
import logging
import optparse
import os
import subprocess
impor... | rn 0
logging.basicConfig(
format='%(levelname)5s %(module)11s(%(lineno)4d): %(message)s',
level=[logging.WARNING, logging.INFO, logging.DEBUG][
min(2, options.verbose)])
if args:
parser.error('Extra argument(s) "%s" not understood' % ' '.join(args))
if not options.issue:
pars | er.error('Require --issue')
options.server = options.server.rstrip('/')
if not options.server:
parser.error('Require a valid server')
options.revision_mapping = json.loads(options.revision_mapping)
# read email if needed
if options.email_file:
if not os.path.exists(options.email_file):
parser.... |
daxm/fmcapi | unit_tests/failoverinterfacemacaddressconfigs.py | Python | bsd-3-clause | 958 | 0 | import logging
import fmcapi
def test__failoverinterfacemacaddressconfigs(fmc):
logging. | info( |
"Test FailoverInterfaceMACAddressConfigs. get, post, put, "
"delete FailoverInterfaceMACAddressConfigs Objects"
)
obj1 = fmcapi.DeviceHAFailoverMAC(fmc=fmc, ha_name="HaName")
obj1.p_interface(name="GigabitEthernet0/0", device_name="device_name")
obj1.failoverActiveMac = "0050.5686.718f... |
cfossace/crits | crits/events/api.py | Python | mit | 3,519 | 0.000853 | from django.core.urlresolvers import reverse
from tastypie import authorization
from tastypie.authentication import MultiAuthentication
from crits.events.event import Event
from crits.events.handlers import add_new_event
from crits.core.api import CRITsApiKeyAuthentication, CRITsSessionAuthentication
from crits.core.a... | self.crits_response(content)
if event_type not in EventTypes.values():
content['message'] = 'Not a valid Event Type.'
self.crits_response(content)
result = add_new_event(title,
description,
event_type,
... | ,
analyst,
bucket_list,
ticket)
if result.get('message'):
content['message'] = result.get('message')
content['id'] = result.get('id', '')
if result.get('id'):
url = reverse('api_... |
sumaxime/LIFAP1 | TD/TD7/Code/Python/7.py | Python | mit | 539 | 0 | #!/usr/bin/python
# Remplir un tableau avec les coefficients du triangle de Pascal
from math import factor | ial as fact
def combin(n, p):
res = int(fact(n) / (fact(p) * fact(n - p)))
return res
def triangle_ | pascal(tab):
for i in range(len(tab)):
for j in range(i + 1):
tab[i][j] = combin(i, j)
tab = [[[] for i in range(6)] for j in range(6)]
triangle_pascal(tab)
# Affichage de tableau
for k in range(len(tab)):
for m in range(k + 1):
print(tab[k][m], '', sep='\t', end='')
print(''... |
odoousers2014/odoo | addons/account/account.py | Python | agpl-3.0 | 190,066 | 0.00694 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# |
##############################################################################
import logging
from datetime import datetime
from dateutil.relativedelta import relativedelta
from operator import itemgetter
import time
import openerp
from openerp import SUPERUSER_ID, api
from openerp import tools
from openerp.osv impo... |
fracpete/python-weka-wrapper-examples | src/wekaexamples/classifiers/incremental_classifier.py | Python | gpl-3.0 | 1,881 | 0.001595 | # 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 program is distributed in the hope that it will be useful,
# b... | ifier incrementally on a dataset. The dataset can be supplied as parameter.
:param args: the commandline arguments
:type args: list
"""
# load a dataset
if len(args) <= 1:
data_file = helper.get_data_dir() + os.sep + "vote.arff"
else:
data_file = args[1]
helper.print_info("L... |
data = loader.load_file(data_file, incremental=True)
data.class_is_last()
# classifier
nb = Classifier(classname="weka.classifiers.bayes.NaiveBayesUpdateable")
nb.build_classifier(data)
# train incrementally
for inst in loader:
nb.update_classifier(inst)
print(nb)
if __name... |
quantumlib/ReCirq | recirq/readout_scan/tasks.py | Python | apache-2.0 | 4,314 | 0.001854 | # Copyright 2020 Google
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, soft... | solution_factor: int
@property
def fn(self):
n_shots = _abbrev_n_shots(n_shots=self.n_shots)
qubit = _abbrev_grid_qubit(self.qubit)
return (f'{self.dataset_id}/'
f'{self.device_name}/'
f'q-{qubit}/'
f'ry_scan_{self.resolution_factor}_{n_sh... | """Shorter n_shots component of a filename"""
if n_shots % 1000 == 0:
return f'{n_shots // 1000}k'
return str(n_shots)
def _abbrev_grid_qubit(qubit: cirq.GridQubit) -> str:
"""Formatted grid_qubit component of a filename"""
return f'{qubit.row}_{qubit.col}'
EXPERIMENT_NAME = 'readout-sca... |
nagyistoce/devide | modules/filters/resources/python/resampleImageViewFrame.py | Python | bsd-3-clause | 2,908 | 0.005158 | #!/usr/bin/env python
# -*- coding: ansi_x3.4-1968 -*-
# generated by wxGlade 0.6.3 on Sat Feb 09 13:36:33 2008
import wx
# begin wxGlade: extracode
# end wxGlade
class resampleImageViewFrame(wx.Frame):
def | __init__(self, *args, **kwds):
# begin wxGlade: resampleImageViewFrame.__init__
kwds["style"] = w | x.DEFAULT_FRAME_STYLE
wx.Frame.__init__(self, *args, **kwds)
self.viewFramePanel = wx.Panel(self, -1)
self.label_1 = wx.StaticText(self.viewFramePanel, -1, "Interpolation type:")
self.interpolationTypeChoice = wx.Choice(self.viewFramePanel, -1, choices=["Nearest Neighbour", "Linear", "Cu... |
GoogleCloudPlatform/explainable_ai_sdk | explainable_ai_sdk/metadata/tf/v1/utils_test.py | Python | apache-2.0 | 2,629 | 0.004184 | # Copyright 2021 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 agreed to in writing, ... | verning permissions and
# limitations under the License.
"""Tests for metadata utils."""
import os
import tensorflow.compat.v1 as tf
from explainable_ai_sdk.metadata.tf.v1 import utils
class UtilsTest(tf.test.TestCase):
def test_save_graph_model_explicit_session(self):
sess = tf.Session(g | raph=tf.Graph())
with sess.graph.as_default():
x = tf.placeholder(shape=[None, 10], dtype=tf.float32, name='inp')
weights = tf.constant(1., shape=(10, 2), name='weights')
model_path = os.path.join(tf.test.get_temp_dir(), 'explicit')
utils.save_graph_model(sess, model_path, {'x': x}, {'w': weight... |
dem4ply/sebastian | manage.py | Python | gpl-2.0 | 252 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sebastian.settings")
from django.core.m | anagement import execute_from_command_line
execute_from_c | ommand_line(sys.argv)
|
EmreAtes/spack | var/spack/repos/builtin/packages/nekbone/package.py | Python | lgpl-2.1 | 3,143 | 0.000318 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | structure and user interface of the extensive Nek5000 software.
Nek5000 is a high order, incompressible Navier-Stokes solver based on
the spectral element method."""
homepage = "https | ://github.com/Nek5000/Nekbone"
url = "https://github.com/Nek5000/Nekbone/tarball/v17.0"
tags = ['proxy-app', 'ecp-proxy-app']
version('17.0', 'cc339684547614a0725959e41839fec1', git='https://github.com/Nek5000/Nekbone.git')
version('develop', git='https://github.com/Nek5000/Nekbone.git')
# Varian... |
dphiffer/dna-codec | lib/dnacloud/source/decode.py | Python | mit | 19,780 | 0.039383 | """
Author: Shalin Shah
Project: DNA Cloud
Graduate Mentor: Dixita Limbachya
Mentor: Prof. Manish K Gupta
Date: 5 November 2013
Website: www.guptalab.org/dnacloud
This module contains method to decode the given dnac file.
"""
from cStringIO import StringIO
import sqlite3
import sqlite3 as lite
import unicodedata
impo... | K_SIZE) == 0:
noOfFileChunks = 1
else:
noOfFileChunks = | (fileSize/CHUNK_SIZE)
else:
noOfFileChunks = (fileSize/CHUNK_SIZE) + 1
#print "No of Chunks" , noOfFileChunks
if noOfFileChunks > 1:
#print "Chunk No : 1"
dnaList = fileOpened.read(CHUNK_SIZE)
prependString = ""
j = -1
while True:
if dnaList[j] == ',':
break
prependString = dnaL... |
sharifyounes/wapi | wapi/tests/test_fields_required.py | Python | gpl-3.0 | 6,170 | 0.003404 |
from flask import jsonify
from unittest import TestCase
from wapi.tests import TestMixin
from wapi import fields_required
import json
class TestFieldsRequired(TestMixin, TestCase):
def setUp(self):
super(TestFieldsRequired, self).setUp()
@self.app.route("/")
@fields_required(... | test_no_data(self):
r = json.loads(self.c.get("/").response.next())
self.assertEqual(r["Error"], "Missing field.")
try:
try:
self.assertEqual(r["Missing field"], "Missing field.")
except AssertionError:
self.assertEqual(r... |
def test_missing_all_data_single(self):
payload = {}
r = json.loads(self.c.get("/", data=json.dumps(payload)).response.next())
self.assertEqual(r["Error"], "Missing field.")
try:
try:
self.assertEqual(r["Missing field"], "taxonomy.brand")
ex... |
oculusstorystudio/kraken | unittests/core/objects/test_transform.py | Python | bsd-3-clause | 365 | 0 |
import unittest
from kraken.core.objects.transform import Transform
class Te | stTransform(unittest.TestCase):
def testInstance(self):
transform = Transform('test')
self.assertIsNotNone(transform)
def suite():
return unittest.TestLoader().loadTestsFromTestCase(TestTransform)
if __name__ == '__main__':
unittest.main(verbosity= | 2)
|
disqus/nose-unittest | setup.py | Python | apache-2.0 | 569 | 0 | #!/usr/bin/env python
from setuptools import setup, find_package | s
setup(
name='nose-unittest',
version='0.1.1',
author='DISQUS',
author_email='[email protected]',
url='http://github.com/disqus/nose-unittest',
package_dir={'': 'src'},
packages=find_packages('src'),
zip_safe=False,
install_requires=[
'nose>=0.9',
],
entry_point... | Apache License 2.0',
include_package_data=True,
)
|
Findspire/workflow | workflow/apps/workflow/urls.py | Python | mit | 2,979 | 0.007385 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2015 Findspire
from django.conf.urls import patterns, url
from workflow.apps.workflow import views
urlpatterns = patterns('workflow.apps.workflow',
url(r'^$', 'views.index', name='index'),
url(r'^project/new/$', views.proj... | , name='project_new'),
url(r'^project/edit/(?P<project_pk>\d+)/$', views.project_edit, name='project_edit'),
url(r'^project/list/$', views.proj | ect_list, name='project_list'),
url(r'^workflow/reset/(?P<workflow_pk>\d+)/$', views.reset_item_validation,
name='workflow_reset'),
url(r'^workflow/new/$', views.workflow_create, name='workflow_new'),
url(r'^workflow/new/(?P<project_pk>\d+)/$', views.workflow_create, name='workflow_new'),
url(r'^wor... |
mosajjal/mitmproxy | test/pathod/test_log.py | Python | mit | 480 | 0.002083 | import io
from pathod import log
from mitmproxy import exceptions
class DummyIO(io.StringIO):
def start_log(self, *args, **kwargs):
pass
def get_log(self, *args, **kwargs):
return ""
def test_disconnect():
outf = DummyIO()
rw | = DummyIO()
l = log.ConnectionLogger(outf, False, True, rw, rw)
| try:
with l.ctx() as lg:
lg("Test")
except exceptions.TcpDisconnect:
pass
assert "Test" in outf.getvalue()
|
cwtaylor/viper | viper/modules/jar.py | Python | bsd-3-clause | 1,994 | 0.001003 | # This file is part of Viper - https://github.com/viper-framework/viper
# See the file 'LICENSE' for copying permission.
import hashlib
import zipfile
from viper.common.abstracts import Module
from viper.core.session import __sessions__
class Jar(Module):
cmd = 'jar'
description = 'Parse Java JAR archives'
... | ws.append([item, value])
self.log('info', "Manifest File:")
self.log('table', dict(header=['Item', 'Value'], rows=rows))
super(Jar, self).run()
if self.args is None:
return
arg_dump = self.args.dump
if not __sessions__.is_set():
self.lo... | file.is_zipfile(__sessions__.current.file.path):
self.log('error', "Doesn't Appear to be a valid jar archive")
return
with zipfile.ZipFile(__sessions__.current.file.path, 'r') as archive:
jar_tree = []
for name in archive.namelist():
item_data = ... |
oVirt/vdsm | tests/hostdev_test.py | Python | gpl-2.0 | 10,768 | 0 | #
# Copyright 2014-2020 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | ations, expandPermutations
from monkeypatch import MonkeyClass, MonkeyPatchScope
from testValidation import skipif
from vdsm.common import hooks
from vdsm.common import hostdev
from vdsm.common import libvirtconnection
import hostdevlib
@expandPermutations
@MonkeyClass(libvirtconnection, 'get', hostdevlib.Connectio... | son: json)
@MonkeyClass(hostdev, '_get_udev_block_mapping',
lambda: hostdevlib.UDEV_BLOCK_MAP)
class HostdevTests(TestCaseBase):
def testProcessDeviceParams(self):
deviceXML = hostdev._process_device_params(
libvirtconnection.get().nodeDeviceLookupByName(
hostdevlib... |
expertanalytics/fagkveld | worldmap/src/worldmap/__init__.py | Python | bsd-2-clause | 52 | 0.019231 |
__all__ = [
'DTM',
]
from | .mode | l import DTM
|
Tanoshinderuyo/Python | Calendar/A2Jahreskalender/calendar.py | Python | gpl-2.0 | 9,023 | 0.066533 | import calfunctions
from tkinter import *
#Main-File
#verwendet: schaltjahr(jahr), monatslaenge(jahr,monat), wochentag(jahr,monat,tag)
def kalender(jahr):
#Listen für schnellen Zugriff auf Monatsname und Wochentag
monatsname = ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','No... | h=15, relief=GROOVE, bg='green', fg='white').grid(row=reihe,column=0) ###beginnt bei 0, siehe Tage
reihe+=1 ###hat null einfluss
for tag in range(1,8,1):
Label(fenster2, text=tagname[tag%7],width=15, relief=GROOVE).grid(row=reihe, column=tag-1)
reihe+=1 ###wochdentagsüberschriften
monatlang=calfunctions.mona... | ===============================
w = calfunctions.wochentag(jahr,monat,1)
#fügt Leerzeichen ein vor erstem Eintrag in Monat
###BEACHTE COLUMN BEGINNEN BEI 0
if (w!=1):
if(w!=0):
###print('\t'*(w-1)+'1',end='')
#hier noch einmal die empty-labels durchgucken, es müssen mehr gedruckt werden
fo... |
JulienPalard/wicd | wicd/monitor.py | Python | gpl-2.0 | 14,528 | 0.001996 | #!/usr/bin/env python3
""" monitor -- connection monitoring process
This process is spawned as a child of the daemon, and is responsible
for monitoring connection status and initiating autoreconnection
when appropriate.
"""
#
# Copyright (C) 2007 - 2009 Adam Blackburn
# Copyright (C) 2007 - 2009 Dan O'Reilly
#
#... | and/or modify
# it under the terms of the GNU General Public License Version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PUR... | ved a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import gobject
import time
from dbus import DBusException
from wicd import wpath
from wicd import misc
from wicd import dbusmanager
misc.RenameProcess("wicd-monitor")
if __name__ == '__main__':
... |
eduNEXT/edx-platform | lms/djangoapps/lti_provider/models.py | Python | agpl-3.0 | 6,044 | 0.002151 | """
Database models for the LTI provider feature.
This app uses migrations. If you make changes to this model, be sure to create
an appropriate migration file and check it in at the same time as your model
changes. To do that,
1. Go to the edx-platform dir
2. ./manage.py lms schemamigration lti_provider --auto "descr... | arch by consumer key instead of instance_guid. If there is no
# consumer with a matching key, the LTI launch does not have permission
# to access the content.
if not consum | er:
consumer = LtiConsumer.objects.get(
consumer_key=consumer_key,
)
# Add the instance_guid field to the model if it's not there already.
if instance_guid and not consumer.instance_guid:
consumer.instance_guid = instance_guid
consumer.sav... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractSunkenfleetWordpressCom.py | Python | bsd-3-clause | 742 | 0.028302 | def extractSunkenfleetWordpressCom(item):
'''
Parser for 'sunkenfleet.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('noble wife', 'Noble Wife Wants No Love', ... |
('dflb', 'Don\'t Fall In Love With The Boss', | 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return Fals... |
hustodemon/spacewalk | backend/satellite_tools/__init__.py | Python | gpl-2.0 | 49 | 0 | # Copyright (c) 2005, Red Hat Inc.
|
__all__ | = []
|
beagles/neutron_hacking | neutron/agent/rpc.py | Python | apache-2.0 | 3,789 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation.
# 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.... | ent_id, host=None):
return self.client.call(context, 'update_device_down',
device=device,
agent_id=agent_id,
host=host)
def update_dev | ice_up(self, context, device, agent_id, host=None):
return self.client.call(context, 'update_device_up',
device=device,
agent_id=agent_id,
host=host)
def tunnel_sync(self, context, tunnel_ip, tunnel_type=None):
... |
Juniper/tempest | tempest/api/compute/admin/test_flavors.py | Python | apache-2.0 | 10,059 | 0 | # Copyright 2012 OpenStack Foundation
# 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 requ... | .assertEqual(flavor['ram'], self.ram)
self.assertEqual(flavor['vcpus'], self.vcpus)
self.assertEqual(flavor['disk'], self.disk)
self.assertEqual(int(flavor['id']), new_flavor_id)
verify_flavor_response_extension(flavor)
# Verify flavor is retrieved
flavor = se | lf.admin_flavors_client.show_flavor(new_flavor_id)['flavor']
self.assertEqual(flavor['name'], flavor_name)
verify_flavor_response_extension(flavor)
# Check if flavor is present in list
flavors_list = [
f for f in self.flavors_client.list_flavors(detail=True)['flavors']
... |
ubik2/PEGAS-kRPC | kRPC/Main.py | Python | mit | 10,069 | 0.002781 | import numpy as np
import time
import krpc
import init_simulation
import unified_powered_flight_guidance as upfg
from launch_targeting import launch_targeting, LaunchSite
from flight_manager import flight_manager
from flight_sim_3d import GravityTurnControl, cart2sph
g0 = init_simulation.g0
mu = init_simulat... | ble
"""
for engine in vessel.parts.engines:
if engine.active and engine.available_thrust > 0:
return True
return False
def stage_if_needed(vessel):
"""
Check to see if we need to stage, and if so, activate the next stage
:param vessel: Vessel object from kRPC
... | we activated a new stage
"""
if check_engine(vessel):
return False
print('There is no active engine, checking Propellant condition')
for engine in vessel.parts.engines:
if engine.has_fuel:
for engine_module in engine.part.modules:
if engine_module.h... |
deviantintegral/feedback | src/listener.py | Python | mit | 622 | 0.009646 | from flask import Flask, request, send_from_directory
from time import sleep
app = Flask(__name__, static_url_path='/public')
@app.route('/')
def root():
return send_from_directory('./', 'index.html')
@app.route('/feedback.js')
def script():
return send_from_directory('./', 'feedback.js')
@app.route('/feedb... | return send_from_directory('./', 'feedback.css')
@app.route('/icons.png')
def icons():
return send_from_directory('./', 'icons.png')
@app.route('/listener', methods=['GET', 'POST'])
def listener():
sleep(30)
re | turn '1'
if __name__ == '__main__':
app.run()
|
deepmind/distrax | distrax/_src/distributions/mvn_from_bijector_test.py | Python | apache-2.0 | 12,417 | 0.004429 | # Copyright 2021 DeepMind Technologies Limited. 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 ... | ros((4,))),
('loc is 0d', 1, 1, True, np.zeros(shape=())),
| ('loc has more dims than batch_shape', 1, 1, True,
np.zeros(shape=(2, 4))),
)
def test_raises_on_wrong_inputs(
self, event_ndims_in, event_ndims_out, is_constant_jacobian, loc):
bij = DummyBijector(event_ndims_in, event_ndims_out, is_constant_jacobian)
with self.assertRaises(ValueError):
... |
morpheby/levelup-by | cms/envs/aws.py | Python | agpl-3.0 | 6,436 | 0.002175 | """
This is the default template for our main set of AWS servers.
"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
import json
from .common import *
from logsettings import get_logger_config
import os
# speci... | = ENV_TOKENS.get("COURSES_WITH_UNSAFE_CODE", [])
#Timezone overrides
TIME_ZON | E = ENV_TOKENS.get('TIME_ZONE', TIME_ZONE)
for feature, value in ENV_TOKENS.get('MITX_FEATURES', {}).items():
MITX_FEATURES[feature] = value
LOGGING = get_logger_config(LOG_DIR,
logging_env=ENV_TOKENS['LOGGING_ENV'],
syslog_addr=(ENV_TOKENS['SYSLOG_SERVER']... |
Rbeaty88/ginga | ginga/qtw/ipg.py | Python | bsd-3-clause | 12,780 | 0.002817 | #! /usr/bin/env python
#
# ipg.py -- Example of Ginga widget interaction with IPython.
#
# Eric Jeschke ([email protected])
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
# CREDIT:
# Contains code from IP... | b.use('Agg')
import matplotlib.pyplot as plt
from IPython.display import Image
import StringIO
STD_FORMAT = '%(asctime)s | | %(levelname)1.1s | %(filename)s:%(lineno)d (%(funcName)s) | %(message)s'
# global ref to keep an object from being collected
app_ref = None
# workaround for suppressing logging to stdout in ipython notebook
# on Macs
use_null_logger = True
class IPyNbImageView(ImageViewCanvas):
def show(self):
return ... |
isc-projects/forge | tests/config.py | Python | isc | 3,628 | 0.001378 | # Copyright (C) 2013-2020 Internet Systems Consortium.
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET ... | o wait for, and fail
Fails if the message is not found after 10 seconds.
| """
strings = [message]
if not_message is not None:
strings.append(not_message)
(found, line) = world.processes.wait_for_stderr_str(process_name, strings, new)
if not_message is not None:
assert found != not_message, line
@step(r'wait for (new )?(\w+) stdout message (\w+)(?: not (\w+))... |
lem9/weblate | weblate/trans/tests/test_angularjs_checks.py | Python | gpl-3.0 | 3,835 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2017 Michal Čihař <[email protected]>
# Copyright © 2015 Philipp Wolfer <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lice... | e | currency }}',
u'Value: {{ something.value }}',
MockUnit('angularjs_format', flags='angularjs-format')
))
def test_check_highlight(self):
highlights = self.check.check_highlight(
u'{{name}} {{ something.value | currency }} string',
MockUnit('angula... | )
self.assertEqual(2, len(highlights))
self.assertEqual(0, highlights[0][0])
self.assertEqual(8, highlights[0][1])
self.assertEqual(9, highlights[1][0])
self.assertEqual(41, highlights[1][1])
def test_check_highlight_ignored(self):
highlights = self.check.check_highl... |
DuGuille/urban-data | client/urbandata.py | Python | apache-2.0 | 1,412 | 0.021955 | import requests
import json
import datetime
import logging
Config = {
'url' : 'http://198.199.98.147:5000/data_point',
'agent' : 'Default',
'user': 'urbanuser',
'password' : 'urbankey'
}
# send (latitud, longitud, extra)
# Sends a bundle of data to the server as a geojson point
# usage :
#send( 1... | ests.post(Config['url'], data=json.dumps(payload), headers=headers, auth=(Config['user'], Config['password']))
logger = logging.getLogger('urban-data')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
|
#TODO: add SQL or TXT file logging policies
#fh = logging.FileHandler('spam.log')
# https://docs.python.org/2/howto/logging-cookbook.html
if r.ok:
logger.debug("Succesful request")
logger.info("Sent data with values: {0}".format(json.dumps(payload)))
|
SavinaRoja/npyscreen2 | npyscreen2/widgets/textfield.py | Python | gpl-3.0 | 9,852 | 0.003959 | # -*- coding: utf-8 -*-
import curses
from . import Widget
import logging
log = logging.getLogger('npyscreen2.widgets.textfield')
class TextField(Widget):
"""
The TextField class will most likely serve as the general basis for most
widgets that display text to the screen. The value attribute should alw... | int, self.h_addch),
# (self.t_is_ck, self.h_erase_right),
# (self.t_is_cu, self.h_erase_left),
))
def _ | pre_edit(self):
super(TextField, self)._pre_edit()
#self.bold = True
#Explicitly setting the behavior for an unset cursor_position
if self.cursor_position is None and self.start_cursor_at_end:
self.cursor_position = len(self.value)
else:
self.cursor_positi... |
lagopus/lagopus | test/datastore/long_run/lib/async_datastore_cmd.py | Python | apache-2.0 | 3,080 | 0.000649 | #!/usr/bin/env python
import sys
import socket
import ssl
import os
import select
import json
import logging
import asyncore
import threading
import six
from six.moves import _thread
from six.moves import queue
from contextlib import contextmanager
from const import *
class AsyncDataStoreCmd(asyncore.dispatcher):
... | self.close()
def writable(self):
return ((len(self.wbuf) > 0) or (not self.queue.empty()))
def handle_write(self):
try:
if len(self.wbuf) == 0:
self.wbuf = self.queue.get_nowait()
if self.wbuf is None:
_thread.exit()
... | sentlen = self.send(w)
self.wbuf = self.wbuf[sentlen:]
except queue.Empty:
pass
def readable(self):
return True
def handle_read(self):
# ignore
data = self.recv(BUFSIZE)
if not data:
raise RuntimeError("connection broken!")
... |
ksmit799/Toontown-Source | toontown/coghq/DistributedMintBattleAI.py | Python | mit | 2,940 | 0.006803 | from toontown.toonbase import ToontownGlobals
from toontown.coghq import DistributedLevelBattleAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import State
from direct.fsm import ClassicFSM, State
from toontown.battle.BattleBase import *
import CogDisguiseGlobals
from toontown.toonbase.ToontownBat... | 0,
0,
| 0]
amount = ToontownGlobals.MintCogBuckRewards[self.level.mintId]
index = ToontownGlobals.cogHQZoneId2deptIndex(self.level.mintId)
extraMerits[index] = amount
for toon in toons:
recovered, notRecovered = self.air.questManager.recoverItems(toon, self.suitsKilled, self... |
MAPC/myschoolcommute | survey/views.py | Python | gpl-3.0 | 12,688 | 0.001813 | from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils import simplejson, dateparse
from django.db.models import Count, Q
from django.forms.models... | t least one crossing street
"""
school = School.objects.get(pk | =school_id)
intersections = school.get_intersections()
intersections = intersections.filter(st_name_1__iexact=street1)
if street2 is not None and street2.strip() != "":
intersections = intersections.filter(st_name_2__iexact=street2)
features = []
for f in list(intersections.distinct()):
... |
openatv/enigma2 | lib/python/Screens/Recording.py | Python | gpl-2.0 | 4,584 | 0.022469 | from os import stat
from os.path import isdir, join as pathjoin
from Components.config import config
from Components.UsageConfig import preferredPath
from Screens.LocationBox import defaultInhibitDirs, MovieLocationBox
from Screens.MessageBox import MessageBox
from Screens.Setup import Setup
from Tools.Directories imp... | lf.pathSelect, MovieLocationBox, self.getCurrentEntry(), preferredPath(item.value))
else:
Setup.keySelect(self)
def keySave(self):
if self.errorItem == -1:
Setup.keySave( | self)
else:
self.session.open(MessageBox, "%s\n\n%s" % (self.getFootnote(), _("Please select an acceptable directory.")), type=MessageBox.TYPE_ERROR)
def buildChoices(self, item, configEntry, path):
configList = config.movielist.videodirs.value[:]
styleList = [] if item == "DefaultPath" else self.styleKeys
... |
MrAlone/mzbench | lib/bdl_utils_test.py | Python | bsd-3-clause | 3,059 | 0.006211 | #!/usr/bin/env nosetests
# This is nose based tests for benc | hDL translator, run "pip install nose" if you don't have "nosetests"
import bdl_utils
from nose.tools import eq_
def test_indents():
eq_(bdl_utils.add_indents('#!benchDL\nmake_instal | l(git = "[email protected]:foo/bar", branch = "b")'),
'#!benchDL\nmake_install(git = "[email protected]:foo/bar", branch = "b")')
def test_indents_2():
eq_(bdl_utils.add_indents('#!benchDL\npool(size = 1):\n do_stuff(1,2)'),
'#!benchDL\npool(size = 1):\n_INDENT_ do_stuff(1,2)\n_DEDENT_ ')
def test_inden... |
linuxdeepin/dde-daemon | network/examples/python/dbus_gen/com_deepin_daemon_Network.py | Python | gpl-3.0 | 20,639 | 0.005281 | '''
Created with dbus2any
https://github.com/hugosenari/dbus2any
This code require python-dbus
Parameters:
* pydbusclient.tpl
* ./dbus_gen/dbus_dde_daemon_network.xml
See also:
http://dbus.freedesktop.org/doc/dbus-specification.html
http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html
'''
import... | //dbus.freedesktop.org/doc/dbus-specification.html#idp94392448
'''
return self._dbus_interf | ace.GetProxyMethod(*arg, **kw)
def GetSupportedConnectionTypes(self, *arg, **kw):
'''
Method (call me)
return:
: as
See also:
http://dbus.freedesktop.org/doc/dbus-specification.html#idp94392448
'''
return self._dbus_interface.GetS... |
xiaohan2012/temporal-topic-mining | test_util.py | Python | mit | 748 | 0.00134 | # coding: utf8
from util import load_line_corpus
from nose.tools import assert_equal
def test_load_line_corpus():
corpus = load_line_corpus("test_data/line_corpus.dat")
corpus = list(corpus)
assert_equal(len(corpus), 3)
assert_equal(corpus[0], u"We introduce the Randomized Dependence Coefficient (RDC... | pendence between random variables of arbitrary dimension based on the Hirschfeld-Gebelein-Rényi Maximum Correla | tion Coefficient. RDC is defined in terms of correlation of random non-linear copula projections; it is invariant with respect to marginal distribution transformations, has low computational cost and is easy to implement: just five lines of R code, included at the end of the paper.")
|
foobarbazblarg/stayclean | stayclean-2016-august/update-google-chart.py | Python | mit | 5,485 | 0.003282 | #!/usr/bin/python
import json
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import datetime
from participantCollection import ParticipantCollection
# Edit Me!
par | ticipantFileNames = ['../stayclean-2014-november/participants.txt',
'../stayclean-2014-december/participants.t | xt',
'../stayclean-2015-january/participants.txt',
'../stayclean-2015-february/participants.txt',
'../stayclean-2015-march/participants.txt',
'../stayclean-2015-april/participants.txt',
'../stayclean-... |
stephrdev/loetwerk | journeyman/projects/forms.py | Python | mit | 1,763 | 0.010777 | from django import forms
from journeyman.projects.models import Project
class Reposi | toryForm(forms.Form):
name = forms.CharField(
help_text='What\'s the name of your awesome project?')
repository = forms.CharField(
help_text='Please enter a valid repository url \
(e.g. git+git://github.com/stephrdev/loetwerk.git)')
class BuildProcessForm(forms.Form):
build_steps = ... | the commands needed to install your package')
test_steps = forms.CharField(initial='python setup.py test',
widget=forms.Textarea(attrs={'rows':3, 'cols':40}),
help_text='Now tell us how to run your tests. If you should have \
many different test suites, just add another line.')
d... |
infant-cognition-tampere/drop | drop/Experiment.py | Python | mit | 3,168 | 0 | """Experiment-class."""
import glib
from Section import Section
class Experiment:
"""
Experiment class.
Takes care of the experiment presentation
(window, ... control) will work one experiment file and control the
flow of sections. "Experiment"-level stuff.
"""
def __init__(self, views,... | ."""
# end experiment?
if nextsection >= len(self.data):
glib.idle_add(self.on_experiment_done)
return False
self.section_num = nextsection
sectioninfo = self.data[self.section_num]
if "collect_data" in sectioninfo["options"]:
# check if the... | ser wanted to start data collection on all devices
# or just one?
self.ctrl.start_collecting_data(sectioninfo["name"])
glib.idle_add(self.section_start)
def section_start(self):
"""Create new section instance and start it."""
sectioninfo = self.data[self.section_nu... |
openstack/networking-odl | networking_odl/ml2/port_status_update.py | Python | apache-2.0 | 5,546 | 0 | # Copyright (c) 2017 OpenStack Foundation
# 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 ... | ports:
port_id = port["id"]
response = client.get(port_id)
if response.status_code != 200:
LOG.warning("Non-200 response code %s", str(response))
continue
odl_status = response.json()['port'][0]['status']
if odl_status == n_cons... | support transition from DOWN->ACTIVE
# See https://bugs.launchpad.net/networking-odl/+bug/1686023
provisioning_blocks.provisioning_complete(
context.get_admin_context(),
port_id, resources.PORT,
provisioning_blocks.L2_AGENT_ENT... |
trondhindenes/Flauthority | flauthority/api_task_status.py | Python | mit | 1,886 | 0.008484 | from flask_restful import Resource, Api
from flask_restful_swagger import swagger
from flauthority import app
from flauthority import api, app, celery, auth
from ModelClasses import AnsibleCommandModel, AnsiblePlaybookModel, AnsibleExt | raArgsModel
import celery_runner
class TaskStatus(Re | source):
@swagger.operation(
notes='Get the status of an certificate generation task/job',
nickname='taskstatus',
parameters=[
{
"name": "task_id",
"description": "The ID of the task/job to get status for",
"required": True,
"allowMultiple": False,
... |
plotly/python-api | packages/python/plotly/plotly/validators/densitymapbox/colorbar/tickformatstop/_enabled.py | Python | mit | 515 | 0 | import _plotly_utils.basevalidators
class EnabledValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self,
plotly_name="enabled",
pare | nt_name="densitymapbox.colorbar.tickformatstop",
| **kwargs
):
super(EnabledValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
rbitia/aci-demos | vk-burst-demo/aci-worker/app/dbAzureBlob.py | Python | mit | 2,832 | 0.006356 | #By Sam Kreter
#For use by Microsoft and other parties to demo
#Azure Container Service, Azure Container Instances
#and the experimental ACI-connector
import os
from azure.storage.blob import BlockBlobService
import sqlite3
COPY_PICS_NUM = 1
class DbAzureBlob:
def __init__(self):
AZURE_BLOB_ACCOUNT ... |
);
''')
| conn.execute('INSERT INTO time values(1,"2017-09-23 18:28:24","2017-09-23 18:28:24",0,0);')
generator = self.block_blob_service.list_blobs('pictures')
for blob in generator:
if(blob.name[:2] == "._"):
blob.name = blob.name[2:]
for i in range(COPY_PICS_NUM):
... |
w1r0x/ansible-modules-core | cloud/docker/docker.py | Python | gpl-3.0 | 71,287 | 0.004335 | #!/usr/bin/python
# (c) 2013, Cove Schneider
# (c) 2014, Joshua Conner <[email protected]>
# (c) 2014, Pavel Antonov <[email protected]>
#
# This file is part of Ansible,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the... | - Publish all exposed ports to the host interfaces.
default: false
version_added: "1.5"
volumes:
description:
- List of volumes to mount within the container
- 'Use docker CLI-style syntax: C(/host:/container[:mode])'
- You can specify a read mode for the mount with either C(ro) or C(rw)... | the volume.
default: null
volumes_from:
description:
- List of names of containers to mount volumes from.
default: null
links:
description:
- List of other containers to link within this container with an optional
- 'alias. Use docker CLI-style syntax: C(redis:myredis).'
defau... |
scith/htpc-manager_ynh | sources/libs/ndg/__init__.py | Python | gpl-3.0 | 653 | 0.003063 | """ndg_httpsclient - PyOpenSSL utility to make a httplib-like interface suitable
for use with urllib2
This is a setuptools namespace_packa | ge. DO NOT place any other
code in this file! There is no guarantee that it will be i | nstalled
with easy_install. See:
http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
... for details.
"""
__author__ = "P J Kershaw"
__date__ = "06/01/12"
__copyright__ = "(C) 2012 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ =... |
pixlra/HARP-fork | PythonLib/Regex.py | Python | gpl-3.0 | 961 | 0.012487 | #!/usr/bin/env python
# coding: utf8
# (c) 2014 Dominic Springer
# File licensed under GNU GPL (see HARP_License.txt)
import re
import numpy as np
#look for: import re, re.search
# HOW TO ==================================
# 1) Paste line to https://pythex.org/
# 2) Create function to wrap
#==================== | ======================
#==========================================
def get_DimX_DimY_from_Filename(FN):
#==========================================
res = re.search(r"(\d*)x(\d*)", FN)
return (np.int32(res.group(1)), np.int32(res.group(2)))
#==========================================
def fromStartToBracket(Str... | e = FH.readline()
# DimX = int( re.search(r"DimX=([-|\d]*)", line).group(1))
# DimY = int( re.search(r"DimY=([-|\d]*)", line).group(1))
|
antoinecarme/pyaf | tests/artificial/transf_BoxCox/trend_PolyTrend/cycle_0/ar_12/test_artificial_128_BoxCox_PolyTrend_0_12_100.py | Python | bsd-3-clause | 263 | 0.087452 | import pyaf.Bench.TS_d | atasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 0, transform = "BoxCox", | sigma = 0.0, exog_count = 100, ar_order = 12); |
miyataken999/weblate | weblate/requirements.py | Python | gpl-3.0 | 5,638 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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, eith... | return result
def get_versions():
'''
Returns list of used versions.
'''
result = []
result.append((
'Python',
'http://www.python.org/',
sys.version.split()[0],
'2.7',
))
name = 'Django'
url = 'https://www.djangoproject.com/'
mod = get_version_m... | me = 'python-social-auth'
url = 'http://psa.matiasaguirre.net/'
mod = get_version_module('social', name, url)
result.append((
name,
url,
mod.__version__,
'0.2.0',
))
name = 'Translate Toolkit'
url = 'http://toolkit.translatehouse.org/'
mod = get_version_modul... |
dashng/netseen | manage.py | Python | apache-2.0 | 1,064 | 0 | #!/usr/bin/env python
from __future__ import print_function
import os
import sys
import unittest
from flask_script import | Manager
from netseen import create_app
from netseen.database import DataBase
sys.path.insert(0, os.getcwd())
manager = Manager(create_app)
@manager.command
def createdb(drop_first=False):
"""Creates the datab | ase."""
try:
if drop_first:
DataBase().drop_all()
DataBase().create_all()
except Exception as e:
print(e)
@manager.command
def test():
"""Runs the unit tests without coverage."""
tests = unittest.TestLoader().discover('netseen.tests', pattern='test*.py')
result ... |
axiome-oss/dive-into-django-i18n | your_project/your_package/models.py | Python | mit | 199 | 0.005025 | from django.db import | models
from django.contrib.auth.mode | ls import User
class Profile(models.Model):
user = models.OneToOneField(User)
description = models.TextField(blank=True, null=True)
|
Spirotot/py3status | py3status/modules/gpmdp.py | Python | bsd-3-clause | 2,411 | 0.001662 | # -*- coding: utf-8 -*-
"""
Display currently playing song from Google Play Music Desktop Player.
Configuration parameters:
cache_timeout: how often we refresh this module in seconds (default 5)
format: specify the items and ordering of the data in the status bar.
These area 1:1 ma... | staticmethod
def _run_cmd(cmd):
return check_output(['gpmdp-remote', cmd]).decode('utf-8').strip()
def gpmdp(self, i3s_output_list, i3s_config):
if self._run_cmd('status') == 'Paused':
result = ''
else:
cmds = ['info', 'title', 'artist', 'album', 'status', 'curre... | md in cmds:
if '{%s}' % cmd in self.format:
data[cmd] = self._run_cmd(cmd)
result = self.format.format(**data)
response = {
'cached_until': time() + self.cache_timeout,
'full_text': result
}
return response
if __name__ =... |
Harmon758/discord.py | examples/basic_bot.py | Python | mit | 1,925 | 0.004675 | # This example requires the 'members' privileged intents
import discord
from discord.ext import commands
import random
description = '''An example bot to showcase the discord.ext.commands extension
module.
There are a number of utility commands being showcased here.'''
intents = discord.Intents.default()
intents.me... | :
"""Repeats a message multiple times."""
for i in range(times):
await ctx.send(content) |
@bot.command()
async def joined(ctx, member: discord.Member):
"""Says when a member joined."""
await ctx.send(f'{member.name} joined in {member.joined_at}')
@bot.group()
async def cool(ctx):
"""Says if a user is cool.
In reality this just checks if a subcommand is being invoked.
"""
if ctx.i... |
bloomberg/phabricator-tools | py/phl/phlsys_signal__t.py | Python | apache-2.0 | 7,979 | 0 | """Test suite for phlsys_signal."""
# =============================================================================
# TEST PLAN
# -----------------------------------------------------------------------------
# Here we detail the things we are concerned to test and specify which tests
#... | re the original signal handler when we're done testing
# or nose will hang indefinitely when we run the tests.
handler = signal.getsig | nal(signal.SIGTERM)
# CONCERN: can run phlsys_signal.set_exit_on_sigterm
phlsys_signal.set_exit_on_sigterm()
# CONCERN: exit_level is 0 before exit contexts are active
self.assertEqual(
phlsys_signal._SIGNAL_FLAGS.delay_sigterm_exit_level,
0)
with phlsys... |
wolfe-pack/moro | public/javascripts/brat/testserver.py | Python | bsd-2-clause | 2,109 | 0.002371 | #!/usr/bin/env python
'''
Run brat using the built-in Python CGI server for testing purposes.
Author: Pontus Stenetorp <pontus stenetorp se>
Version: 2012-07-01
'''
from BaseHTTPServer import HTTPServer, test as simple_http_server_test
from CGIHTTPServer import CGIHTTPRequestHandler
# Note: It is a terribl... | return -1
except IndexError:
port = 8000
print >> stderr, 'WARNING: This server is for testing purposes only!'
print >> stderr, (' You can also use it for trying out brat before '
'deploying on | a "real" web server such as Apache.')
print >> stderr, (' Using this web server to run brat on an open '
'network is a security risk!')
print >> stderr
print >> stderr, 'You can access the test server on:'
print >> stderr
print >> stderr, ' http://localhost:%s/' % port
print >>... |
nkantar/Parsenvy | tests/test_list.py | Python | bsd-3-clause | 648 | 0 | import parsenvy
def test_list_several(monkeypatch):
monkeypatch.setenv("foo", "bar,baz,barf")
assert parsenvy.list("foo") == ["bar", "baz", "barf"]
def test_list_one(monkeypatch):
monkeypatch.setenv("foo", "bar")
assert parsenvy.list("foo") == ["bar"]
def test_list_one_comma(monkeypatch):
monk... | "foo") == ["", ""]
def test_list_multiple_commas(monkeypatch):
monkeypatch.setenv("foo", ",,,")
assert parsenvy.list("foo") == ["", "", "", ""]
def test_list_empty(monkey | patch):
monkeypatch.setenv("foo", "")
assert parsenvy.list("foo", ["bar"]) == ["bar"]
|
xobb1t/django-loginza-auth | test_project/urls.py | Python | isc | 353 | 0 | from django.conf.urls.defaults import include, patterns, url
from django.views.ge | neric import TemplateView
urlpatterns = patterns(
'',
url(r'^$', TemplateView.as_view(template_name='index.html'),
name='login'),
url(r'^logout/$', 'django. | contrib.auth.views.logout', name='logout'),
url(r'^loginza/', include('loginza.urls')),
)
|
mingkaic/rocnnet | app/pydemo/gym_demo.py | Python | mit | 1,420 | 0.016901 | #!/usr/bin/env python
import _init_paths
import gym
from tf_rl.controller import DiscreteDeepQ, NL
specname = 'CartPole-v0'
serializedname = 'dqntest_'+specname+'.pbx'
spec = gym.spec(specname)
env = spec.make()
episode_count = 250
max_steps = 10000
action_space = env.ac | tion_space
maxaction = action_space.n
observation_space = env.observation_space
maxobservation = observation_space.shape[0]
batchsize = 32 # store at least 12 times before training, each looking at 12 action-observation
controller = DiscreteDeepQ(maxobservation, [128, 128, maxaction],
[NL.TANH, NL.TANH, NL.IDENTITY]... | , discount_rate=0.99,
exploration_period=5000, max_experience=10000, )
controller.initialize(serializedname)
# training step
for ep in xrange(episode_count):
observation = env.reset()
reward = done = None
total_reward = 0
nsteps = 0
for step_it in range(max_steps):
action = controller.action(observation)
new... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.