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 |
|---|---|---|---|---|---|---|---|---|
Alexey95/physpy | physpy/__init__.py | Python | mit | 1,808 | 0.001111 | #!/usr/bin/python2
#-*- coding: utf-8 -*-
#
# This file is released under the MIT License.
#
# (C) Copyright 2012 Alessio Colucci
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the “Software”), to deal in the Software without
# res... | ILITY,
# 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 SOFTWARE.
#
import os
import sys
__author__ = "Alessio Colucci"
__version__ | = "0.1a1"
try:
pkg = __import__("physpy")
except ImportError:
pkg_path = os.path.abspath(os.path.dirname(__file__))
if not pkg_path in sys.path:
sys.path.append(pkg_path)
else:
if pkg.__version__ == __version__:
pkg_path = os.path.abspath(os.path.dirname(pkg.__file__))
else:
... |
VerifiableRobotics/LTLMoP | src/lib/handlers/share/Pose/NullPoseHandler.py | Python | gpl-3.0 | 1,041 | 0.008646 | #!/usr/bin/env python
"""
==========================================================
NullPose.py - Pose Handler for single region without Vicon
==========================================================
"""
import sys, time
from numpy import *
from lib.regions import *
import lib.handlers.handlerTemplates as handlerT... | tor.proj.rfiold.indexOfRegionWithName(initial_region)
center = executor.proj.rfiold.reg | ions[r].getCenter()
self.x = center[0]
self.y = center[1]
self.theta = 0
def getPose(self, cached=False):
x=self.x
y=self.y
o=self.theta
return array([x, y, o])
def setPose(self, x, y, theta):
self.x=x
self.y=y
self.theta=theta
... |
mapzen/vector-datasource | integration-test/1062-road-shield-cleanup.py | Python | mit | 1,209 | 0 | from . import FixtureTest
class RoadShieldCleanup(FixtureTest):
def _check_network_relation(
self, way_id, rel_id, tile, expected_shield_text):
self.load_fixtures([
'https://www.openstreetmap.org/way/%d' % (wa | y_id,),
'https://www.openstreetmap.org/relation/%d' % (rel_id,),
], clip=self.tile_bbox(*tile))
z, x, y = tile
self.assert_has_feature(
z, x, y, 'roads',
{ | 'id': way_id, 'shield_text': expected_shield_text})
def test_A151(self):
self._check_network_relation(
way_id=208288552, rel_id=1159812, tile=(16, 32949, 22362),
expected_shield_text='A151')
def test_E402(self):
self._check_network_relation(
way_id=121496753... |
lino-framework/welfare | lino_welfare/projects/gerd/tests/dumps/18.8.0/gfks_helptext.py | Python | agpl-3.0 | 794 | 0.025189 | # -*- coding: UTF-8 -*-
logger.info("Loading 5 objects to table gfks_helptext...")
# fields: id, content_type, field, help_text
loader.save(create_gfks_helptext(1,contacts_Partner,u'language',u'Die Sprache, in der Dokumente ausgestellt werden sollen.'))
loader.save(create_gfks_helptext(2,gfks_HelpText,u'field',u'The na... | rom TIM.'))
loader.save(create_gfks_helptext(5,contacts_Partner,u'language',u'Die Sprache, in der Dokumente a | usgestellt werden sollen.'))
loader.flush_deferred_objects()
|
SerialShadow/SickRage | sickbeard/sab.py | Python | gpl-3.0 | 8,550 | 0.002924 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: https://sickrage.tv
# Git: https://github.com/SiCKRAGETV/SickRage
#
# This file is part of SickRage.
#
# SickRage 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, ei... | PASSWORD != None:
params['ma_password'] = sickbeard.SAB_PASSWORD |
if sickbeard.SAB_APIKEY != None:
params['apikey'] = sickbeard.SAB_APIKEY
category = sickbeard.SAB_CATEGORY
if nzb.show.is_anime:
category = sickbeard.SAB_CATEGORY_ANIME
if category != None:
params['cat'] = category
# use high priority if specified (recently aired episode)
... |
vigojug/reto | 201705/alexhermida/reto.py | Python | bsd-3-clause | 247 | 0 | from itertools import combinations
def check_adding_e | lements(integers_list):
if [item for i in range(len(integers_list), 0, -1) for item in
combinations(integers_list, i) if sum(item) == 0]:
return True
ret | urn False
|
orbitfp7/nova | nova/tests/unit/test_fixtures.py | Python | apache-2.0 | 6,695 | 0 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 t... | timeout = fixtures.Timeout("10")
self.assertEqual(timeout.test_timeout, 10)
timeout = fixtures.Timeout("10", 2)
self.assertEqual(timeout.test_timeout, 20)
class TestDatabaseFixture(testtools.TestCase):
def test_fixture_reset(self):
# because this sets up reasonable db connection s... | ct()
result = conn.execute("select * from instance_types")
rows = result.fetchall()
self.assertEqual(len(rows), 5, "Rows %s" % rows)
# insert a 6th instance type, column 5 below is an int id
# which has a constraint on it, so if new standard instance
# types are added yo... |
fastmonkeys/pontus | tests/test_file_size_validator.py | Python | mit | 2,007 | 0 | # -*- coding: utf-8 -*-
import os
import pytest
import boto3
from pontus.exceptions import ValidationError
from pontus.validators import FileSize
class TestFileSizeValidator(object):
@pytest.fixture
def jpeg_key(self, bucket):
with open(os.path.join(
os.path.dirname(__file__),
... | _key)
assert e.value.error == (
u'File is smaller than 27670 bytes.'
)
def test_does_not_raise_validation_error_if_file_is_of_valid_size(
self,
jpeg_key
):
validator = FileSize(min=27660, max=27662)
validator(jpeg_key)
def test_raises_value_error... | or) as e:
FileSize()
assert str(e.value) == (
'At least one of `min` or `max` must be defined.'
)
def test_raises_value_error_if_min_is_more_than_max(self):
with pytest.raises(ValueError) as e:
FileSize(min=2, max=1)
assert str(e.value) == (
... |
jcshen007/cloudstack | scripts/util/migrate-dynamicroles.py | Python | apache-2.0 | 5,812 | 0.005678 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Ve... | , "--properties-file", action="store", type="string", dest="commandsfile", default="/etc/cloudstack/management/commands.properties",
| help="The commands.properties file")
parser.add_option("-d", "--dryrun", action="store_true", dest="dryrun", default=False,
help="Dry run and debug operations this tool will perform")
(options, args) = parser.parse_args()
print("Apache CloudStack Role Permission Mig... |
vollov/python-test | services/account_service.py | Python | mit | 437 | 0.002288 | #!/usr/bin/python
import logging
logger = logging.getLog | ger('pytest')
class AccountService:
'''
account service template
'''
def place_order(self):
'''authentication'''
print 'account service - authentication'
logger.info('account service - authentication')
@staticmethod
def get_service_name():
'''get service name'''... | me')
|
Slack06/yadg | descgen/tasks.py | Python | mit | 1,273 | 0.001571 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2015 Slack
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
... | ermission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ... | AMAGES 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
# SOFTWARE.
from celery import shared_task
@shared_task
def get_result(scraper, additional_data):
return scraper.get_result(), additional_... |
derekzhang79/livestreamer | src/livestreamer/stream/akamaihd.py | Python | bsd-2-clause | 6,596 | 0.001819 | #!/usr/bin/env python
from . import Stream, StreamError
from ..compat import str, bytes, urlparse
from ..utils import RingBuffer, swfdecompress, swfverify, urlget, urlopen
from ..packages.flashmedia import FLV, FLVError
from ..packages.flashmedia.tag import ScriptData
import base64
import hashlib
import hmac
import ... | fc07a19f717b9": Auth3TokenGenerator
}
StatusComplete = 3
StatusError = 4
Errors = {
1: "Stream not found",
2: "Track not found",
| 3: "Seek out of bounds",
4: "Authentication failed",
5: "DVR disabled",
6: "Invalid bitrate test"
}
def __init__(self, session, url, swf=None, seek=None):
Stream.__init__(self, session)
parsed = urlparse(url)
self.logger = self.session.logger.new_module("s... |
tedye/leetcode | Python/leetcode.125.valid-palindrome.py | Python | mit | 594 | 0.005051 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
: | rtype: bool
"""
if not s:
return True
start = 0
end = len(s)-1
s = s.lower()
while start < end:
while start < end and not s[start].isalnum():
start += 1
while start < end and not s[end].isalnum():
... | 1
end -= 1
else:
return False
return True |
xebialabs-community/xlr-xldeploy-plugin | src/main/resources/xlr_xldeploy/XLDVersionsTile.py | Python | mit | 1,585 | 0.003785 | #
# Copyright 2019 XEBIALABS
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati | on files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The... | the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 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 LIABILI... |
pvagner/orca | test/keystrokes/gtk-demo/role_text_multiline.py | Python | lgpl-2.1 | 10,142 | 0.003155 | #!/usr/bin/python
"""Test of multiline editable text."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("<Control>f"))
sequence.append(TypeAction("Application main window"))
sequence.append(KeyComboAction("Return"))
sequence.append(KeyComboAction("Tab"))
sequ... | tion Application Window frame T $l'",
" VISIBLE: 'T $l', cursor=2",
"BRAILLE LINE: 'gtk-demo application Application Window frame T $l'",
" VISIBLE: 'T $l', cursor=2",
"BRAILLE LINE: 'gtk-demo application Application Window frame Th $l'",
" VISIBLE: 'Th $l', cursor=3",
"BR... | SIBLE: 'Th $l', cursor=3",
"BRAILLE LINE: 'gtk-demo application Application Window frame Thi $l'",
" VISIBLE: 'Thi $l', cursor=4",
"BRAILLE LINE: 'gtk-demo application Application Window frame Thi $l'",
" VISIBLE: 'Thi $l', cursor=4",
"BRAILLE LINE: 'gtk-demo application Applicati... |
leifos/tango_with_django | made_with_twd_project/made_with_twd_project/wsgi.py | Python | mit | 1,464 | 0.001366 | """
WSGI config for made_with_twd_project project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_... | ght make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the env... | multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "made_with_twd_project.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "made_with_twd_project.settings")
# This application object is... |
ikn/o | game/__init__.py | Python | gpl-3.0 | 125 | 0 | from | .engine import conf as engine_conf
from .conf import Conf
from | .level import Level as EntryWorld
engine_conf.add(Conf)
|
JamesRamm/longclaw | longclaw/core/jinja2tags.py | Python | mit | 1,022 | 0 | import jinja2
import jinja2.nodes
from jinja2.ext import Extension
from django.template.loader import get_template
# to keep namespaces from colliding
from .templatetags import longclawcore_tags as lc_tags
def longclaw_vendors_bundle():
template = get_template('core/longclaw_script.html')
context = lc_tags... | claw_client_bundle,
'longclaw_vendors_bundle': longclaw_vendors_bundle,
})
| # Nicer import names
core = LongClawCoreExtension
|
SickGear/SickGear | lib/diskcache_py3/recipes.py | Python | gpl-3.0 | 13,534 | 0 | """Disk Cache Recipes
"""
import functools
import math
import os
import random
import threading
import time
from .core import ENOVAL, args_to_key, full_name
class Averager(object):
"""Recipe for calculating a running average.
Sometimes known as "online statistics," the running average maintains the
to... | f):
"Acquire semaphore by decrementing value using spin-lock algorithm."
while True:
with self._cache.transact(retry=True):
value = self._cache.get(self._key, default=self._value)
if value > 0:
self._cache.set(
self.... | expire=self._expire, tag=self._tag,
)
return
time.sleep(0.001)
def release(self):
"Release semaphore by incrementing value."
with self._cache.transact(retry=True):
value = self._cache.get(self._key, default=self._value)
... |
tobi-weber/levitas | src/levitas/middleware/redirectMiddleware.py | Python | apache-2.0 | 1,326 | 0.002262 | # -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Tobias Weber <tobi-weber@gmx.de>
#
# 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 ... | ting, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from . import Middleware
log = logging.g... | (Middleware):
"""
Redirects the client to the given URL for all GET requests.
Example settings entry:
urls = [(r"/oldpath", RedirectMiddleware,
{"url": "/newpath", "permanent": True})]
"""
LOG = True
def __init__(self, url, permanent=True):
"""
@param ur... |
gusyussh/learntosolveit | languages/python/algorithm_spelling.py | Python | bsd-3-clause | 1,031 | 0.020369 | import re, collections
def words(text): return re.findall('[a-z]+', text.lower())
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
NWORDS = train(words(file('big.txt').read()))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):... |
transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1]
replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b]
inserts | = [a + c + b for a, b in splits for c in alphabet]
return set(deletes + transposes + replaces + inserts)
def known_edits2(word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = kno... |
OniOniOn-/MCEdit-Unified | albow/controls.py | Python | isc | 9,986 | 0.001302 | #
# Albow - Controls
#
#-# Modified by D.C.-G. for translation purpose
from pygame import Rect, draw
from widget import Widget, overridable_property
from theme import ThemeProperty
import resource
from translate import _, getLang
class Control(object):
highlighted = overridable_property('highlighted')
enabl... | kwds['enable | '] = enable
if rightClickAction:
kwds['rightClickAction'] = rightClickAction
Label.__init__(self, text, **kwds)
class Image(Widget):
# image Image to display
highlight_color = ThemeProperty('highlight_color')
image = overridable_property('image')
highlighted = False
... |
CodigoSur/cyclope | cyclope/apps/staticpages/admin.py | Python | gpl-3.0 | 4,331 | 0.003233 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010-2013 Código Sur Sociedad Civil.
# All rights reserved.
#
# This file is part of Cyclope.
#
# Cyclope 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... | ce(selected_items)
new_items = selected_items.difference(old_items)
for menu_item in discarded_items:
menu_item.content_type = None
menu_item.object_id = None
menu_item.content_view = None
menu_item. | save()
for menu_item in new_items:
menu_item.content_type = object_type
menu_item.content_view = frontend.site.get_default_view_name(StaticPage)
menu_item.object_id = obj.id
menu_item.save()
admin.site.register(StaticPage, StaticPageAdmin)
class HTMLBlockAdminF... |
tridesclous/tridesclous | tridesclous/gui/__init__.py | Python | mit | 2,001 | 0.005997 | import PyQt5 # this force pyqtgraph to deal with Qt5
# For matplotlib to Qt5 :
# * this avoid tinker problem when not installed
# * work better with GUI
# * trigger a warning on notebook
import matplotlib
import warnings
with warnings.catch_warnings():
try: ... |
except:
# on serve | r without screen this is not possible.
pass
from .myqt import QT,mkQApp
#for catalogue window
from .cataloguecontroller import CatalogueController
from .traceviewer import CatalogueTraceViewer
from .peaklists import PeakList, ClusterPeakList
from .ndscatter import NDScatter
from .waveformviewer import Wavefor... |
Derikulous/zillow_hackathon | data/clean_zillow_nbr_old.py | Python | mit | 605 | 0.004959 | import os
import sys
from scrapy.selector import Selector
from parsers import xfi | rst
#
# Unfinished
#
with open('./output/sf_nbr_zillow_raw.tsv') as f:
for line in f:
parts = line.split('\t')
xml = parts[1]
sel = Selector(text = xml)
for page in sel.xpath('//pages/page'):
for table in page.xpath('.//table'):
tab_name = xfirst(table,... | s' % (tab_name, name)
break
|
lukaszpiotr/pylama_with_gjslint | pylama/checkers/pylint/astroid/mixins.py | Python | lgpl-3.0 | 4,313 | 0.001159 | # copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of astroid.
#
# astroid is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
#... | renceError(modname)
except SyntaxError, ex:
raise InferenceError(str(ex))
def real_name(self, asname):
"""get n | ame from 'as' name"""
for name, _asname in self.names:
if name == '*':
return asname
if not _asname:
name = name.split('.', 1)[0]
_asname = name
if asname == _asname:
return name
raise NotFoundError(asnam... |
yakky/django-cms | cms/utils/conf.py | Python | bsd-3-clause | 10,383 | 0.002023 | # -*- coding: utf-8 -*-
from functools import update_wrapper
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import ugettext_lazy as _
from urllib.parse import urljoin
from cms import constants
from cms import __version__
__all__ = ['... | te IDs) and 'default'"
" for default values. %s is not a valid key." % site)
for language_object in language_list:
for required_key in required_language_keys:
if required_key not in language_object:
raise ImproperlyConfigured("CMS_LANGUAGES has a ... | for key in language_object:
if key not in valid_language_keys:
raise ImproperlyConfigured(
"CMS_LANGUAGES has invalid key %r in language %r in site %r" % (key, language_code, site)
)
if 'fallbacks' not in language_object:
... |
ocr-doacao/ocr | ocrDoacao/testes/teste_ong.py | Python | apache-2.0 | 297 | 0.010101 | from django.test import TestCase
from ocrDoacao.models import Ong
class OngTest(T | estCase):
def test_get_path(self):
nome_modulo = __name__.split(".")[0]
ong = Ong()
ong.nome = 'teste_ong'
self.assertEqual(ong.get_path(), nome_modulo + '/static/o | ngs/teste_ong') |
fos/fos | examples/microcircuit_multi.py | Python | bsd-3-clause | 2,857 | 0.044802 | import h5py
import sys
import os.path as op
from fos import *
import numpy as np
a=np.loadtxt(op.join(op.dirname(__file__), "data", "rat-basal-forebrain.swc") )
pos = a[:,2:5].astype( np.float32 )
radius = a[:,5].astype( np.float32 ) * 4
# extract parent connectivity and create full connectivity
parents = a[1:,6] - ... | ata" : {
"semantics" : [
{ "name" : "skeleton", "value" : "1" },
| { "name" : "presynaptic", "value" : "2" },
{ "name" : "postsynaptic", "value" : "3" }
]
}
},
"id" : { "data" : con_ids, "metadata" : { } }
}
act = Microcircuit(
name = "Simple microcircuitry",
vertices = vertbig,
connectivity ... |
cntnboys/410Lab5 | todolist.py | Python | apache-2.0 | 1,157 | 0.021608 | import sqlite3
from flask import Flask, render_template, g
database = "test.db"
app = Flask(__name__)
@app.route("/")
def welcome():
return "<h1> Welcome to CMPUT 410 - Jinja lab </h1>"
@app.route('/task', methods = ['GET', 'POST'])
def task():
return render_template('show_entries.html', tasks = query_db... | ):
db = getattr(g, "_database", None)
if db is None:
db = g._database = sqlite3.connect(database)
#return object connect
#name and value
db.row_factory = sqlite3.Row
return db
#Query the db
def query_db(query, args=(), one=False):
cur = get_conn().curs | or()
cur.execute(query, args)
result = cur.fetchall()
cur.close()
return result
@app.teardown_appcontext
#close connection
def close_conn(exeption):
db = getattr(g, '_database', None)
if db != None:
db.close()
db = None\
if __name__ =='__main__':
app.debug = True
app.... |
gaberger/sdncli | sdncli/__init__.py | Python | bsd-3-clause | 202 | 0 | __title__ = 'sdncli' |
__author__ = 'Gary Berger'
__license__ = 'BSD'
__copyright__ = 'Brocade Communications'
from ._version import get_versions
__version__ = get_versions()['version']
del get_ | versions
|
pyroscope/pimp-my-box | tasks.py | Python | gpl-2.0 | 2,150 | 0.001395 | # -*- coding: utf-8 -*-
#
# Project Tasks
#
from __future__ import print_function, unicode_literals
import os
import time
import shutil
import webbrowser
from invoke import task
SPHINX_AUTOBUILD_PORT = int(os.environ.get('SPHINX_AUTOBUILD_PORT', '8340'))
def watchdog_pid(ctx):
"""Get watchdog PID via ``netstat... | utobuild.log 2>&1 &'
.format(port=SPHINX_AUTOBUILD_PORT, pwd=os.getcwd()), pty=False)
for i in range(25):
time.sleep(2.5)
pid = watchdog_pid(ctx)
if pid:
ctx.run("touch docs/index.rst")
ctx.run('ps {}'.format(pid) | , pty=False)
url = 'http://localhost:{port:d}/'.format(port=SPHINX_AUTOBUILD_PORT)
if open_tab:
webbrowser.open_new_tab(url)
else:
print("\n*** Open '{}' in your browser...".format(url))
break
@task
def stop(ctx):
"Stop Sphinx watchdo... |
TNT-Samuel/Coding-Projects | Kulka - Sphero/ex_move_rand.py | Python | gpl-3.0 | 5,169 | 0.008512 | from kulka import Kulka
from random import randint
import time
class HSV:
def __init__(self,hue,saturation,value):
import colorsys
self.h = hue
self.s = saturation
self.v = value
rgb = colorsys.hsv_to_rgb(self.h/255, self.s/255, self.v/255)
self.r = round(rgb[0] * 25... | import threading
self.t = threading.Thread(target=control_surface,args=(mac_address,1))
self.threading = threading
self.reset_init()
def set_back_led(self,level):
globals()["Sphero_blackled"] = level
def set_rgb(self,red,green,blue):
globals()["Sphero_red"] = red
... | a2"] = a2
globals()["Sphero_state"] = state
def sleep(self):
globals()["Sphero_sleep"] = True
self.t.join()
def start(self):
self.t.start()
import time
while (not globals()["Sphero_conn"]) and self.t.is_alive():
time.sleep(0.1)
return globals()... |
dl1ksv/gnuradio | gr-filter/python/filter/__init__.py | Python | gpl-3.0 | 624 | 0 | #
# Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#
'''
Filter blocks and related functions.
'''
import os
from gnuradio.fft import window
try:
from .filter_python import *
except ImportError:
dirname, filename = os.path. | split(os.path.abspath(__file__))
__ | path__.append(os.path.join(dirname, "bindings"))
from .filter_python import *
from .filterbank import *
from .freq_xlating_fft_filter import *
from . import pfb
from . import optfir
# Pull this into the filter module
from .file_taps_loader import file_taps_loader
|
x64dbg/x64dbgpy | swig/x64dbgpy/pluginsdk/_scriptapi/debug.py | Python | mit | 744 | 0.016129 | from .. import x64dbg
class HardwareType:
HardwareAccess = x64dbg.HardwareAccess
HardwareWrite = x64dbg.HardwareWrite
Hardwar | eExe | cute = x64dbg.HardwareExecute
def Wait():
x64dbg.Wait()
def Run():
x64dbg.Run()
def Stop():
x64dbg.Stop()
def StepIn():
x64dbg.StepIn()
def StepOver():
x64dbg.StepOver()
def StepOut():
x64dbg.StepOut()
def SetBreakpoint(address):
return x64dbg.SetBreakpoint(address)
def DeleteBreakp... |
vlukes/sfepy | tests/test_base.py | Python | bsd-3-clause | 4,617 | 0.033788 | from __future__ import absolute_import
from sfepy.base.base import assert_
from sfepy.base.testing import TestCommon
##
# 28.08.2007, c
class Test( TestCommon ):
##
# 28.08.2007, c
def from_conf( conf, options ):
return Test( conf = conf, options = options )
from_conf = staticmethod( from_conf... | options['verbose'] = 1
output('test3')
_ok1 = bool(goptions['verbose'])
_ok2 = fd.getvalue() == 'test test1\ntest test3\n'
fd.close()
ok = _ok1 and _ok2
return ok
def test_resolve_deps(self):
from sfepy.base.resolve_deps import resolve
deps = {
... |
'f' : ['e', 'f', 'g'],
'g' : ['g'],
}
order = resolve(deps)
ok1 = order == [['g'], ['a', 'b'], ['c', 'd', 'e'], ['f']]
deps = {
'a' : ['b'],
'b' : ['c'],
'c' : ['a'],
}
order = resolve(deps)
ok2 = order... |
FederatedAI/FATE | examples/pipeline/homo_sbt/pipeline-homo-sbt-binary-with-memory-backend.py | Python | apache-2.0 | 4,517 | 0.004649 | #
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | t{namespace}"}
host_train_data = {"name": "breast_homo_host", "namespace": f"experiment{namespace}"}
host_validate_data = {"name": "breast_homo_test", "namespace": f"experiment{namespace}"}
pipeline = PipeLine().set_initiator(role='guest', party_id=guest).set_roles(guest=guest, host=host, arbiter=arbiter)... | r_1 = Reader(name="reader_0"), Reader(name='reader_1')
reader_0.get_party_instance(role='guest', party_id=guest).component_param(table=guest_train_data)
reader_0.get_party_instance(role='host', party_id=host).component_param(table=host_train_data)
data_transform_0.get_party_instance(role='guest', party_id=... |
austinhartzheim/rigidity | rigidity/__init__.py | Python | gpl-3.0 | 8,662 | 0.000231 | '''
Rigidity is a simple wrapper to the built-in csv module that allows for
validation and correction of data being read/written from/to CSV files.
This module allows you to easily construct validation and correction
rulesets to be applied automatically while preserving the csv interface.
This allows you to easily upg... | t that an exception occurs.
'''
for row in rows:
self.writerow(row)
# New methods, not part of the `csv` interface
def validate(self, row):
'''
.. warning::
This method is d | eprecated and will be removed in a future
release; it is included only to support old code. It will
not produce consistent results with bi-directional rules.
You should use :meth:`validate_read` or
:meth:`validate_write` instead.
Validate that the row conforms with t... |
CyanogenMod/android_external_mockito | releasing/release.undo.py | Python | mit | 676 | 0.014793 | #This script is not really portable. It's just to automate some manual steps I usually do when releasing.
#It might evolve into someting more robust but for now it's ok for me.
import os
import shutil
def run(cmd):
print("\nRunning command: " + cmd)
if os.system(cmd) == 0: print("\nWarning, command failed... | "Specify the version to try to delete, e.g. 1.9:")
branch = 'http | s://mockito.googlecode.com/svn/branches/' + ver
tag = 'https://mockito.googlecode.com/svn/tags/' + ver
run('svn delete -m "removed botched branch" ' + branch)
run('svn delete -m "removed botched tag" ' + tag)
shutil.rmtree("../../mockito-1.8.5", 1) |
almarklein/flexx | examples/ui/box_performance.py | Python | bsd-2-clause | 4,634 | 0.004748 | """ An example that defines two apps, one with a single hbox and
one with hboxes in vboxes in hboxes. For performance testing
"""
import time
import flexx
from flexx import ui
class MyApp1(ui.App):
def init(self):
with ui.VBox() as self.l1:
ui.Button(text='Box A', flex=0)
... | with ui.HBox(flex=2):
ui.Button(text='Box A', flex=1)
ui.Button(text='Box B', flex=2)
ui.Button(text='Box C is a bit longer', flex=3)
with ui.VBox():
with ui.HBox(flex=1):
| ui.Button(text='Box A', flex=0)
ui.Button(text='Box B', flex=0)
ui.Button(text='Box C is a bit longer', flex=0)
with ui.HBox(flex=0):
ui.Button(text='Box A', flex=1)
ui.Button(text='Box B', flex=1)
... |
jamesfolberth/NGC_STEM_camp_AWS | notebooks/data8_notebooks/lab04/tests/q2_5.py | Python | bsd-3-clause | 400 | 0 | test = {
| 'name': '',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> print_kth_top_movie_year(4)
Year number 4 for total gross movie sales was: 2009
""",
'hidden': False,
'locked': False
},
],
'scored': True,
'... | wn': '',
'type': 'doctest'
}
]
}
|
yarikoptic/NiPy-OLD | nipy/io/files.py | Python | bsd-3-clause | 8,110 | 0.001603 | """The image module provides basic functions for working with images in nipy.
Functions are provided to load, save and create image objects, along with
iterators to easily slice through volumes.
load : load an image from a file
save : save an image to a file
fromarray : create an image from a numpy array... | st.img.gz')
'analyze'
>>> _type_from_filename('test.mnc')
'minc'
'''
if filename.endswith('.gz'):
filename = filename[:-3]
elif filename.endswith('.bz2'):
filename = filename[:-4]
_, ext = os.path.splitext(filename)
if ext in ('', '.nii'):
return 'nifti1single'
... | aise ValueError('Strange file extension "%s"' % ext)
def as_image(image_input):
''' Load image from filename or pass through image instance
Parameters
----------
image_input : str or Image instance
image or string filename of image. If a string, load image and
return. If an image, pas... |
madedotcom/photon-pump | test/conversations/test_catchup.py | Python | mit | 25,039 | 0.000679 | import asyncio
import json
import uuid
import pytest
from photonpump import exceptions as exn
from photonpump import messages as msg
from photonpump import messages_pb2 as proto
from photonpump.conversations import CatchupSubscription
from ..fakes import TeeQueue
async def anext(it, count=1):
if count == 1:
... | onse.reason = reason
await convo.respond_to(
msg.InboundMessage(
uuid.uuid4(),
msg.TcpCommand.SubscriptionDropped,
response.SerializeToString(),
),
output,
)
async def confirm_subscription(convo, output_queue=None, event_number=1, commit_pos=1):
... | ponse.last_commit_position = commit_pos
await convo.respond_to(
msg.InboundMessage(
uuid.uuid4(),
msg.TcpCommand.SubscriptionConfirmation,
response.SerializeToString(),
),
output_queue,
)
return await convo.result
def event_appeared(
commit... |
morgenst/PyAnalysisTools | run_scripts/convert_root2numpy.py | Python | mit | 4,105 | 0.003898 | #!/usr/bin/env python
import collections
import itertools
import os
import sys
from functools import partial
import six
from pathos.multiprocessing import Pool
import pandas as pd
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder
from PyAnalysisTools.base import get_default_argparser, default_ini... | stance(branches, collections.Mapping):
branches = list(itertools.chain(*branches.values()))
if regions is None:
Pool().map(partial(convert_and_dump, output_path=args.output_path, tree_name=args.tree_name, branc | hes=branches,
output_fmt=args.format, mining=args.mining_fraction),
file_handles)
else:
for region in regions.regions:
Pool().map(partial(convert_and_dump, output_path=args.output_path, tree_name=args.tree_name,
region=... |
spacy-io/thinc | thinc/tests/mypy/modules/success_no_plugin.py | Python | mit | 428 | 0 | from thinc.api import chain, Relu, reduce_max, Softmax, add
good_model = chain(Relu(10), Relu | (10), Softmax())
re | veal_type(good_model)
good_model2 = add(Relu(10), Relu(10), Softmax())
reveal_type(good_model2)
bad_model_undetected = chain(Relu(10), Relu(10), reduce_max(), Softmax())
reveal_type(bad_model_undetected)
bad_model_undetected2 = add(Relu(10), Relu(10), reduce_max(), Softmax())
reveal_type(bad_model_undetected2)
|
chrxr/wagtail | wagtail/wagtailadmin/views/page_privacy.py | Python | bsd-3-clause | 2,828 | 0.001414 | from __future__ import absolute_import, unicode_literals
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from wagtail.wagtailadmin.forms import PageViewRestrictionForm
from wagtail.wagtailadmin.modal_workflow import render_modal_workflow
from wagtail.wagtailcore.mode... | stance=restriction)
else:
# no current view restrictions on this page
form = PageViewRestrictionForm(initial={
'restriction_type': 'none'
})
if restriction_exists_on_ancestor:
# display a message indicating that there is a rest... | , 'wagtailadmin/page_privacy/ancestor_privacy.html', None,
{
'page_with_restriction': restriction.page,
}
)
else:
# no restriction set at ancestor level - can set restrictions here
return render_modal_workflow(
request,
'wagtail... |
sysadminmatmoz/odoo-clearcorp | veterinary/veterinary.py | Python | agpl-3.0 | 7,094 | 0.013251 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute... | = not self.active_view
@api.multi
def patient_healthy (self):
self.write({'state':'healthy'})
@api.multi
def patient_sick (self):
self.write({'state':'sick'})
@api.onchange('pure_breed')
def onchange_pure_breed(self):
self.pedrigree=''
@api... | if self.breed_id not in self.specie_id.breed_ids:
raise Warning('Breed does not belong to Specie')
return True
@api.constrains('medical_history')
def check_medical_history(self): # function for verify the field medical history is not empty
if not self.medical_history:
... |
ros2/demos | demo_nodes_py/demo_nodes_py/topics/talker_qos.py | Python | apache-2.0 | 2,757 | 0.000363 | # Copyright 2016 Open Source Robotics Foundation, 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... | self.create_timer(timer_period, self.timer_callback)
def timer_callback(self):
msg = String()
msg.data = 'Hello World: {0}'.format(self.i)
self.i += 1
self.get_logger().info('Publishing: "{0}"'.format(msg.data))
self.pub.publish(msg)
def main(argv=sys.arg | v[1:]):
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'--reliable', dest='reliable', action='store_true',
help='set qos profile to reliable')
parser.set_defaults(reliable=False)
parser.add_argument(
'-n', '--number_o... |
tensorflow/tpu | models/official/detection/projects/vild/preprocessing/dataset_util.py | Python | apache-2.0 | 1,426 | 0.004208 | # Lint as: python2, python3
# Copyright 2021 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
#
... | cense for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Dataset preprocessing utils, for creating tf reco | rds etc.."""
import tensorflow.compat.v1 as tf
def int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def int64_list_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def bytes_feature(value):
return tf.train.Feature(bytes_list=tf.t... |
mkrupcale/ansible | lib/ansible/modules/cloud/amazon/ec2_vol.py | Python | gpl-3.0 | 19,393 | 0.004383 | #!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed... | se
default: null
aliases: ['aws_zone', 'ec2_zone']
snapshot:
description:
- snapshot ID on which to base the volume
required: false
default: null
version_added: "1.5"
validate_certs:
description:
- When set to "no", SSL certificates will not be validated for boto versions >= ... | dded: "1.5"
state:
description:
- whether to ensure the volume is present or absent, or to list existing volumes (The C(list) option was added in version 1.8).
required: false
default: present
choices: ['absent', 'present', 'list']
version_added: "1.6"
author: "Lester Wade (@lwade)"
extends_... |
schleichdi2/OPENNFR-6.3-CORE | opennfr-openembedded-core/meta/lib/oeqa/utils/package_manager.py | Python | gpl-2.0 | 6,234 | 0.002406 | #
# SPDX-License-Identifier: MIT
#
import os
import json
import shutil
from oeqa.core.utils.test import getCaseFile, getCaseMethod
def get_package_manager(d, root_path):
"""
Returns an OE package manager that can install packages in root_path.
"""
from oe.package_manager import RpmPM, OpkgPM, DpkgPM
... | ectory where the package was
extracted without dependencies.
"""
from oeqa.utils.package_manager import get_package_manager
pkg_path = os.path.join(d.getVar('TEST_INSTALL_TMP_DIR'), pkg)
pm = get_package_manager(d, pkg_path)
extract_dir = pm.extract(pkg)
shutil.rmtree(pkg_path)
return... | t_package_manager
pkg_path = os.path.join(d.getVar('TEST_INSTALL_TMP_DIR'), pkg)
dst_dir = d.getVar('TEST_PACKAGED_DIR')
pm = get_package_manager(d, pkg_path)
pkg_info = pm.package_info(pkg)
file_path = pkg_info[pkg]['filepath']
shutil.copy2(file_path, dst_dir)
shutil.rmtree(pkg_path)
def ... |
axbaretto/beam | sdks/python/.tox/lint/lib/python2.7/site-packages/pylint/test/input/func_noerror_crash_127416.py | Python | apache-2.0 | 546 | 0.001832 | # | pylint: disable=C0111,R0201
"""
FUNCTIONALITY
"""
class Example(object):
"""
@summary: Demonstrates pylint error caused by method expecting tuple
but called method does not return tuple
"""
def method_expects_tuple(self, obj):
meth, args = self.method_doesnot_return_tuple(obj)
... | # in the future
return {'success': obj}
|
askyourgovt/nammamla2 | src/misc/models.py | Python | gpl-3.0 | 6,418 | 0.040044 | from django.db import models
GENDER=(
('Male','Male'),
('Female','Female'),
('Transgender','Transgender'),
('Unknown','Unknown'),
)
QUALIFICATION =(
('SSLC','SSLC'),
('Unknown','Unknown'),
)
ATTENDANCE =(
('Present','Present'),
('Absent','Absent'),
('N.A','N.A'),
)... | ll=True,default = None)
question | = models.CharField(max_length=2000) |
JackDanger/sentry | tests/sentry/api/endpoints/test_user_avatar.py | Python | bsd-3-clause | 2,972 | 0.001346 | from __future__ import absolute_import
import six
from base64 import b64encode
from django.core.urlresolvers import reverse
from sentry.models import UserAvatar
from sentry.testutils import APITestCase
class UserAvatarTest(APITestCase):
def test_get(self):
user = self.create_user(email='a@example.com')... | = UserAvatar.objects.get(user=user)
| assert response.status_code == 400
assert avatar.get_avatar_type_display() == 'letter_avatar'
response = self.client.put(url, data={'avatar_type': 'foo'}, format='json')
assert response.status_code == 400
assert avatar.get_avatar_type_display() == 'letter_avatar'
def test_put_for... |
wagtail/wagtail | wagtail/core/migrations/0016_change_page_url_path_to_text_field.py | Python | bsd-3-clause | 442 | 0.002262 | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [ |
("wagtailcore", "0015_ | add_more_verbose_names"),
]
operations = [
migrations.AlterField(
model_name="page",
name="url_path",
field=models.TextField(verbose_name="URL path", editable=False, blank=True),
preserve_default=True,
),
]
|
sadaf2605/django | django/db/models/fields/related_descriptors.py | Python | bsd-3-clause | 49,686 | 0.001771 | """
Accessors for related objects.
When a field defines a relation between two models, each model class provides
an attribute to access related instances of the other model class (unless the
reverse accessor has been disabled with related_name='+').
Accessors are implemented as descriptors in order to customize acces... | won't fail.
return qs.get(self.field.get_reverse_related_filter(instance))
def __get__(self, instance, cls=None):
"""
Get the related instance through the forward relation.
With the example above, when getting ``child.parent``:
- ``self`` is the descriptor managing the ``... | ce is None:
return self
# The related instance is loaded from the database and then cached in
# the attribute defined in self.cache_name. It can also be pre-cached
# by the reverse accessor (ReverseOneToOneDescriptor).
try:
rel_obj = getattr(instance, self.cache_... |
eandersson/amqpstorm | examples/publish_message_with_expiration.py | Python | mit | 624 | 0 | import logging
from | amqpstorm import Connection
from amqpstorm import Message
logging.basicConfig(level=logging.INFO)
with Connection('localhost', 'guest', 'guest') as connection:
with connection.channel() as channel:
# Declare a queue called, 'simple_queue'.
channel.queue.declare('simple_queue')
# Create t... | ies={"expiration": '6000'}
)
# Publish the message to the queue, 'simple_queue'.
message.publish('simple_queue')
|
ajrichards/notebook | visualization/mpl-simple-pick-event.py | Python | bsd-3-clause | 6,330 | 0.000632 | """
You can enable picking by setting the "picker" property of an artist
(for example, a matplotlib Line2D, Text, Patch, Polygon, AxesImage,
etc...)
There are a variety of meanings of the picker property
None - picking is disabled for this artist (default)
boolean - if True then picking will be enabled and... | lot as plt
from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text
from matplotlib.image import AxesImage
import numpy as np
from numpy.random import rand
if 1: # simple picking, lines, rectangles and text
fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.set_title... | nce
# pick the rectangle
bars = ax2.bar(range(10), rand(10), picker=True)
for label in ax2.get_xticklabels(): # make the xtick labels pickable
label.set_picker(True)
def onpick1(event):
if isinstance(event.artist, Line2D):
thisline = event.artist
xdata = thisli... |
nvelaborja/CptS-483_Robotics | Lab 4/draw_a_square.py | Python | gpl-3.0 | 3,425 | 0.017518 | #!/usr/bin/env python
'''
Copyright (c) 2015, Mark Silliman
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of condit... | entation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBU... | SE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ... |
trnewman/VT-USRP-daughterboard-drivers_python | gr-usrp/src/db_wbx.py | Python | gpl-3.0 | 20,483 | 0.010643 | #
# Copyright 2007 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#... | = (1 << 0) # an | tenna switch between RX2 and TX/RX port
RXENABLE = (1 << 1) # enables mixer
PLL_LOCK_DETECT = (1 << 2) # Muxout pin from PLL -- MUST BE INPUT
MReset = (1 << 3) # NB6L239 Master Reset, asserted low
SELA0 = (1 << 4) # NB6L239 SelA0
SELA1 = (1 << 5) # NB6L239 SelA1
SELB0 = (1 << 6)... |
infilect/ml-course1 | week4/attention_ocr/python/datasets/unittest_utils.py | Python | mit | 2,107 | 0.006645 | # Copyright 2017 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.or | g/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitation... | ========================================================================
"""Functions to make unit testing easier."""
import StringIO
import numpy as np
from PIL import Image as PILImage
import tensorflow as tf
def create_random_image(image_format, shape):
"""Creates an image with random values.
Args:
imag... |
Kazade/NeHe-Website | google_appengine/google/appengine/tools/devappserver2/endpoints/api_config_manager_test.py | Python | bsd-3-clause | 14,958 | 0.003008 | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | = method
sorted_methods = self.config_manager._get_sorted_methods(methods)
# Single-part paths should be sorted by path name, http_method.
expected_data = [
('name1', 'abcdefghi', 'GET'),
('name4', 'bar', 'POST'),
('name7', 'baz', 'DELETE'),
('name5', 'baz', 'GET'),
... | for name, path, http_method in expected_data]
self.assertEqual(expected_methods, sorted_methods)
def test_parse_api_config_invalid_api_config(self):
fake_method = {'httpMethod': 'GET',
'path': 'greetings/{gid}',
'rosyMethod': 'baz.bim'}
config = json.dumps... |
daishichao/elephas | examples/ml_mlp.py | Python | mit | 2,318 | 0.002588 | from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
from elephas.ml... | sEstimator(sc,model, nb_epoch=nb_epoch, batch_size=batch_size,
verbose=0, validation_split=0.1, num_workers=8, categorical=True, nb_classes=nb_classes)
# Fitting a model returns a Transformer
fitted_model = estimator.fit(df)
# Evaluate Spark model by evaluating the underlying model
prediction = fitt | ed_model.transform(df)
pnl = prediction.select("label", "prediction")
pnl.show(100)
prediction_and_label= pnl.map(lambda row: (row.label, row.prediction))
metrics = MulticlassMetrics(prediction_and_label)
print(metrics.precision())
print(metrics.recall())
|
samuelcolvin/django-db-viewer | DbInspect/pipe.py | Python | gpl-2.0 | 3,166 | 0.012318 | import DbInspect
import subprocess
import DbInspect._utils as utils
def simple_printer(line):
print line
def SQL_to_MongoDB_all_complete(source_comms, dest_comms, printer = simple_printer):
tables = []
for table, _ in source_comms.get_tables()[0]:
tables.append(table)
S... | self._dest.db[coll_name].drop()
df = self._source.get_pandas(query)
items = self._dest.insert_pandas(coll_name, df)
self._printer('Added %d items' % items)
def run_query_external(self, query, coll_name):
self._printer('Collection: %s' % coll_name)
if... | able exists and cancel_if_table_exists is True, not adding')
if self.delete_existing_tables:
self._printer('Deleting existing collection')
self._dest.db[coll_name].drop()
command = self._get_command(self._dest.dbsets, coll_name)
self._printer('Import Call: ' +... |
catsop/CATMAID | scripts/export/export_all_graphml.py | Python | gpl-3.0 | 3,992 | 0.003758 | # Albert Cardona 2014-11-20
# This file is meant to be run from within ./manage.py shell in the environment, like:
# [1] load export_all_graphml.py
# [2] project_id = 12
# [2] export(project_id, "all.graphml")
#
# Will generate a gzip'ed file like "all.graphml.gz"
#
# Includes all skeletons with more than 1 treenode;
#... | nector tc1,
treenode_connector tc2
where tc1.project_id=%s
and tc1.relation_id = %s
and tc2.relation_id = %s
and tc1.connector_id = tc2.connector_id
and | tc1.skeleton_id IN (select skeleton_id from treenode where project_id=%s group by skeleton_id having count(*) > 1)
''' % (project_id, relations['presynaptic_to'], relations['postsynaptic_to'], project_id))
#
print("Writing synapses")
for row in cursor.fetchall():
file.write(... |
exTerEX/PrimeOnScientificProgramming | Chapter 1/hello_world.py | Python | mit | 255 | 0.023529 | #Exercise 1.2: Write a Hello World program
#Author: Andreas Solberg Sagen - University of Oslo
print("Hello World")
#Or we could do the more "classic one":
hello = "Hello"
wor | ld = "World"
print(hello | + " " + world)
#samplerun
#Hello World
#Hello World
|
kain88-de/mdanalysis | testsuite/MDAnalysisTests/coordinates/test_pqr.py | Python | gpl-2.0 | 7,667 | 0.000261 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysis --- http://www.mdanalysis.org
# Copyright (c) 2006-2016 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
... | mm_ProNcharges, 3,
"Charges for N atoms in Pro residues do not match.")
class TestPQRWriter(RefAdKSmall):
def setUp(self):
self.universe = mda.Universe(PQR)
self.prec = 3
ext = ".pqr"
self.tmpdir = tempdir.TempDir()
self.outfile = self.tmpdi | r.name + '/pqr-writer-test' + ext
def tearDown(self):
try:
os.unlink(self.outfile)
except OSError:
pass
del self.universe
del self.tmpdir
def test_writer_noChainID(self):
assert_equal(self.universe.segments.segids[0], 'SYSTEM')
self.unive... |
kaarolch/ansible | lib/ansible/cli/doc.py | Python | gpl-3.0 | 13,556 | 0.003467 | # (c) 2014, James Tanner <tanner.jc@gmail.com>
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed i... | # this typically means we couldn't even parse the docstring, not just that the YAML is busted,
# probably a quoting issue.
raise AnsibleError("Parsing produced an empty object.")
except Exception as e:
display.vvv(traceback.format_exc())
... | str(e)))
if text:
self.pager(text)
return 0
def find_modules(self, path):
for module in os.listdir(path):
full_path = '/'.join([path, module])
if module.startswith('.'):
continue
elif os.path.isdir(full_path):
... |
JackieLan/django-polls | polls/migrations/0001_initial.py | Python | apache-2.0 | 1,229 | 0.003255 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-12 09:50
fro | m __future__ import unicode_literals
from django.db import migrations, models
import django. | db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')... |
YoQuieroSaber/votainteligente-portal-electoral | elections/urls.py | Python | gpl-3.0 | 4,564 | 0.007011 | from django.conf import settings
from django.conf.urls import patterns, url
from haystack.views import SearchView
from elections.forms import ElectionForm
from elections.views import ElectionsSearchByTagView, HomeView, ElectionDetailView,\
CandidateDetailView, SoulMateDetailView, FaceToFaceView, AreaDetailView, \
... | w_answer/%s/?$" % (settings.NEW_ANSWER_ENDPOINT)
sitemaps = {
'elections': ElectionsSitemap,
'candidates': CandidatesSitemap,
}
urlpatterns = patterns('',
url(new_answer_endpoint,AnswerWebHook.as_view(), name='new_answer_endpoint' ),
url(r'^/?$', cache_page(60 * settings.CACHE_MINUTES)(HomeView.as_vie... | earch'),
url(r'^busqueda_tags/?$', ElectionsSearchByTagView.as_view(), name='tags_search'),
url(r'^election/(?P<slug>[-\w]+)/?$',
cache_page(60 * settings.CACHE_MINUTES)(ElectionDetailView.as_view(template_name='elections/election_detail.html')),
name='election_view'),
url(r'^election/(?P<sl... |
bouk/redshift_sqlalchemy | tests/test_copy_command.py | Python | mit | 2,969 | 0.000337 | import pytest
import re
import sqlalchemy as sa
from redshift_sqlalchemy.dialect import CopyCommand, RedshiftDialect
def clean(query):
return re.sub(r'\s+', ' ', query).strip()
def quote(s):
return "'%s'" % s
def compile_query(q):
return str(q.compile(dialect=RedshiftDialect(),
... | = 'IO1IWSZL5YRFM3BEW256'
secret_access_key = 'A1Crw8=nJwEq+9SCgnwpYbqVSCnfB0cakn=lx4M1'
creds = (
'aws_access_key_id={access_key_id};aws_secret_access_key={secret_access_key}'.format(
access_key_id=access_key | _id,
secret_access_key=secret_access_key
)
)
tbl = sa.Table('t1', sa.MetaData(), schema='schema1')
tbl2 = sa.Table('t1', sa.MetaData())
def test_basic_copy_case():
expected_result = """
COPY schema1.t1 FROM 's3://mybucket/data/listing/'
CREDENTIALS '%s'
CSV TRUNCATECOLUMNS DELIMITER ',' ... |
codermoji-contrib/python | start/Intro to variables/002/setvar2.py | Python | mit | 24 | 0 | y | ear = 201 | 5
print(year)
|
Dentosal/python-sc2 | test/travis_test_script.py | Python | mit | 2,800 | 0.004643 | import sys, subprocess, time
"""
This script is made as a wrapper for sc2 bots to set a timeout to the bots (in case they cant find the last enemy structure or the game is ending in a draw)
Usage:
cd into python-sc2/ directory
docker build -t test_image -f test/Dockerfile .
docker run test_image -c "python test/travi... | != 0:
print("Exiting with exit code 5, error: Attempted to launch script {} timed out after {} seconds. Retries completed: {}".format(sys.argv[1], timeout_time, retries) | )
exit(5)
# process.returncode will always return 0 if the game was run successfully or if there was a python error (in this case it returns as defeat)
print("Returncode: {}".format(process.returncode))
print("Game took {} real time seconds".format(round(time.time() - t0, 1)))
if process is ... |
cwyark/micropython | tests/float/builtin_float_minmax.py | Python | mit | 553 | 0.079566 | # test | builtin min and max functions with float args
try:
min
max
except:
import sys
print("SKIP")
sys.exit()
print(min(0,1.0))
print(min(1.0,0))
print(min(0,-1.0))
print(min(-1.0,0))
print(max(0,1.0))
p | rint(max(1.0,0))
print(max(0,-1.0))
print(max(-1.0,0))
print(min(1.5,-1.5))
print(min(-1.5,1.5))
print(max(1.5,-1.5))
print(max(-1.5,1.5))
print(min([1,2.9,4,0,-1,2]))
print(max([1,2.9,4,0,-1,2]))
print(min([1,2.9,4,6.5,-1,2]))
print(max([1,2.9,4,6.5,-1,2]))
print(min([1,2.9,4,-6.5,-1,2]))
print(max([1,2.9,4,-6.5,-... |
bazad/ida_kernelcache | ida_kernelcache/offset.py | Python | mit | 4,124 | 0.005092 | #
# ida_kernelcache/offset.py
# Brandon Azad
#
# Functions for converting and symbolicating offsets.
#
import re
import idc
import idautils
import ida_utilities as idau
import internal
import kernel
import stub
_log = idau.make_log(1, __name__)
def initialize_data_offsets():
"""Convert offsets in data segments... | convert each offset
into an offset type in IDA, and rename each offset according to its target.
This function does nothing in the newer 12-merged format kernelcache.
"""
next_offset = internal.make_name_generator(kernelcache_offset_suffix)
for ea in idautils.Segme | nts():
segname = idc.SegName(ea)
if not segname.endswith('__got'):
continue
_log(2, 'Processing segment {}', segname)
_process_offsets_section(ea, next_offset)
|
wkentaro/chainer | setup.py | Python | mit | 6,122 | 0 | #!/usr/bin/env python
import os
import pkg_resources
import sys
from setuptools import setup
import chainerx_build_helper
if sys.version_info[:3] == (3, 5, 0):
if not int(os.getenv('CHAINER_PYTHON_350_FORCE', '0')):
msg = """
Chainer does not work with Python 3.5.0.
We strongly recommend to use anothe... | return pkg_resources.get_distribution(pkg)
except pkg_resources.DistributionNotFound:
pass
return None
mn_pkg = find_any_distribution(['chainermn'])
if mn_pkg is not None:
msg = """
We detected that ChainerMN is installed in your environment.
ChainerMN has been integrated to Chainer... | path.abspath(os.path.dirname(__file__))
# Get __version__ variable
exec(open(os.path.join(here, 'chainer', '_version.py')).read())
setup_kwargs = dict(
name='chainer',
version=__version__, # NOQA
description='A flexible framework of neural networks',
long_description=open('README.md').read(),
lon... |
WhiskeyMedia/ella | ella/photos/management/commands/check_photo_files_consistence.py | Python | bsd-3-clause | 5,635 | 0.004969 | import re
import os
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from ella.photos.conf import photos_settings
class Command(BaseCommand):
help = 'Check consistence between database records and coresponding image files'
VERBOSITY_ERROR = 0
VERBOSITY_WARN... | plit(',')
self.extensions_ic = options['extensions_ic']
def print_message(self, message, level, fd=None):
if level <= self.verbosity:
if fd:
try:
print | >> fd, message
except IOError:
pass
else:
print message
def print_error(self, message):
self.print_message(message, self.VERBOSITY_ERROR, sys.stderr)
def print_warning(self, message):
self.print_message(message, self.VERBOSITY_WAR... |
linzhonghong/dnspod_desktop | dnspod_desktop.py | Python | gpl-2.0 | 20,963 | 0.00844 | # -*- coding: utf-8 -*-
__author__ = 'linzhonghong'
__version__ = '2013.11.001'
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
import os
from signal import SIGTERM
import wx
import wx.lib.buttons as buttons
from gui import MyStatusBar,MyListCtrl,WarnDialog,LogoutDialog,LoginDialog,WarnDialog2
... | close_image1 = image_c.GetSubImage((0, 0, image_c.GetWidth()/3, image_c.GetHeight())).ConvertToBitmap()
close_image2 = image_c.GetSubImage((image_c.GetWidth()/3, 0, image_c.GetWidth()/3, image_c.GetHeight())).ConvertToBitmap()
image_m = wx.Image(self.basedir + os.sep + 'm | insize.png',wx.BITMAP_TYPE_PNG)
min_image1 = image_m.GetSubImage((0, 0, image_m.GetWidth()/4, image_m.GetHeight())).ConvertToBitmap()
min_image2 = image_m.GetSubImage((image_m.GetWidth()/4, 0, image_m.GetWidth()/4, image_m.GetHeight())).ConvertToBitmap()
self.btn_min = wx.BitmapButton(p1, -... |
sergiocorreia/panflute | tests/test_convert_text.py | Python | bsd-3-clause | 4,653 | 0.004943 | import io
import panflute as pf
def test_all():
md = 'Some *markdown* **text** ~xyz~'
c_md = pf.convert_text(md)
b_md = [pf.Para(pf.Str("Some"), pf.Space,
pf.Emph(pf.Str("markdown")), pf.Space,
pf.Strong(pf.Str("text")), pf.Space,
pf.Subscript(pf.... | e,
pf.Math(r"x_n = \sqrt{a + b}", format='InlineMath'),
pf.Space, pf.RawInline(r"\textit{a}", format='tex'))]
print("Benchmark TEX:")
print(b_tex)
print("Converted TEX:")
print(c_tex)
assert repr(c_tex) == repr(b_tex)
with io.StringIO() as f:
d... | doc = pf.Doc(*b_tex)
pf.dump(doc, f)
b_tex_dump = f.getvalue()
assert c_tex_dump == b_tex_dump
print("\nBack and forth conversions... md->json->md")
md = 'Some *markdown* **text** ~xyz~'
print("[MD]", md)
md2json = pf.convert_text(md, input_format='markdown', output_format='json'... |
WeLikeAlpacas/python-pubsub | tests/test_influxdb.py | Python | mit | 1,306 | 0 | import socket
import datetime
import mock
from qpaca.monitoring.influx import InfluxDB
class TestInfluxDB(object):
@mock.patch('qpaca.monitoring.influx.InfluxDBClient')
def test_init(self, mocked_class):
client = InfluxDB(name='something', config={'client': {}})
assert mocked_class.called
... | ef test_write_influx(self, mocked_function):
client = InfluxDB(name='something', config={'client': {}})
date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f'")
client.write(point=(date, 1))
mocked_function.assert_called_with(
[{
"measurement": 'someth... | gethostname(),
},
"time": date,
"fields": {
"value": 1}}])
|
qxf2/qxf2-page-object-model | tests/test_successive_form_creation.py | Python | mit | 6,309 | 0.014265 | """
This is an example automated test to help you learn Qxf2's framework
Our automated test will do the following action repeatedly to fill number of forms:
#Open Qxf2 selenium-tutorial-main page.
#Fill the example form
#Click on Click me! button and check if its working fine
"""
#The import statements impo... | result_counter
actual_pass = test_obj.pass_counter
except Exception as e:
print("Exception when trying to run test :%s"%__file__)
print("Python says:%s"%str(e))
assert expected_pass == actual_pass ,"Test failed: %s"%__file__
#---START OF SCRIPT
if __name__=='__main__':
print("St... | tion_Parser()
options=options_obj.get_options()
#Run the test only if the options provided are valid
if options_obj.check_options(options):
test_obj = PageFactory.get_page_object("Zero",base_url=options.url)
#Setup and register a driver
test_obj.register_driver(options.remote_flag,... |
chbrun/behavui | behavui/campaigns/menus.py | Python | gpl-2.0 | 223 | 0 | from | menu import Menu, MenuItem
from django.core.urlresolvers import reverse
Menu.add_item(
"main",
MenuItem(
"Campaign",
reverse("campaigns_ | list"),
weight=10,
icon="tools",
)
)
|
BBN-Q/pyqgl2 | src/python/pyqgl2/test_cl.py | Python | apache-2.0 | 7,256 | 0.006202 | #!/usr/bin/env python3
#
# Copyright 2019 by Raytheon BBN Technologies Corp. All Rights Reserved.
"""
Create a test ChannelLibrary. 3 qubits, with a bidirectional edge between q1 and q2.
If we're assigning to HW (default not), do something APS2ish spreading across APS1-10.
Stores in an in-memory ChannelLibrary.
"""
d... | 1',
'cr-gate': 'APS5-m1',
'M-q1q2': 'APS6-1',
'M-q1q2-gate': 'APS6-m1',
'q3' : 'APS7-1',
'q3-gate' : 'APS7-m1',
'M-q3' : 'APS8-1',
'M-q3-gate' : 'APS8-m1',
'cr2' ... | 2-gate' : 'APS9-m1',
'M-q2q1' : 'APS10-1',
'M-q2q1-gate' : 'APS10-m1'}
for name, value in mapping.items():
channels[name].phys_chan = channels[value]
return channels
def save_in_library(channels, new=False, libName=":memory:"):
"""Store this construc... |
jemandez/creaturas-magicas | Configuraciones básicas/scripts/addons/blendertools-1.0.0/makewalk/action.py | Python | gpl-3.0 | 6,035 | 0.003645 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; eimcp.r version 2
# of the License, or (at your option) any later version.
#
# This program is distri... | om .utils import *
#
# Global variables
#
_actions = []
#
# Select or delete action
# Delete button really deletes action. Handle with care.
#
# listAllActions(context):
# findActionNumber(name):
# class VIEW3D_O | T_McpUpdateActionListButton(bpy.types.Operator):
#
def listAllActions(context):
global _actions
scn = context.scene
try:
doFilter = scn.McpFilterActions
filter = context.object.name
if len(filter) > 4:
filter = filter[0:4]
flen = 4
else:
... |
steveandroulakis/mytardis | tardis/tardis_portal/migrations/0005_auto__add_field_schema_immutable.py | Python | bsd-3-clause | 16,169 | 0.00872 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Schema.immutable'
db.add_column('tardis_portal_schema', 'immutable', self.gf('django.db.mo... | l': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ord | ering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
... |
genixpro/universal_schema | universal_schema/formats/emberdataformat.py | Python | lgpl-3.0 | 2,018 | 0.009911 | # This file is part of the Universal Schema.
#
# The Universal Schema 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.
#... | ot, see <http://www.gnu.org/licenses/>.
#
#
from universal_schema.format import Format
from mako.template imp | ort Template
from universal_schema.fields import *
from universal_schema import data_file
from pprint import pprint
class EmberDataFormat(Format):
""" EmberDataFormat allows you to plug in Universal Schema into the Ember.Data libary: http://emberjs.com/guides/models/"""
def __init__(self):
self.templat... |
Tehsmash/networking-cisco | networking_cisco/apps/saf/common/config.py | Python | apache-2.0 | 6,222 | 0 | # Copyright 2015 Cisco Systems, Inc.
# All R | ights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | OUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import sys
from oslo_config import cfg
from networking_cisco._i18n import _LE
from networking_cisco.apps.saf.agent.vdp import (
... |
WarwickAnimeSoc/aniMango | showings/views.py | Python | mit | 1,605 | 0.001869 | from datetime import date
from django.core.paginator import Paginator, InvalidPage
from django.db.models import Q
from django.shortcuts import render
from .models import Showing, Show
# All your search and not search needs in one place (as long as template is not missing any var assignments in links
# and etc.) - S... | r(get_showings(year, query), 10)
try:
showing_page = paginator.page(request.GET.get('page'))
except InvalidPage:
showing_page = paginator.page(1)
if request.GET.get('cd_search'):
context['cd_search'] = True
context['showing_page'] = showing_page
context['date_range'] = get_d... | s = Showing.objects
if year and isint(year):
start_date = date(int(year), 8, 1)
end_date = date(int(year) + 1, 8, 1)
showings = showings.filter(date__gte=start_date, date__lt=end_date)
if query:
showings = showings.filter(
Q(show__lib_series__title__icontains=query) |... |
zakharvoit/discrete-math-labs | Season2/BinaryTrees/Tree23/gen.py | Python | gpl-3.0 | 449 | 0.028953 | from ra | ndom import randrange
MAX = 100000
args = [randrange(MAX) for x in range(2 * MAX)]
args1 = [randrange(MAX) for x in range(MAX)]
args2 = [randrange(MAX) + MAX for x in range(MAX)]
def mkdel(s):
return "delete " + str(s)
def mkins(s):
return "insert " + str(s)
def mknext(s):
ret | urn "next " + str(s)
print ("\n".join(map(mkins, args1)) \
+ "\n" + "\n".join(map(mkins, args2)) \
+ "\n" + "\n".join(map(mknext, args)))
|
ghchinoy/tensorflow | tensorflow/contrib/sparsemax/python/ops/sparsemax.py | Python | apache-2.0 | 3,656 | 0.000547 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | _tensor(logits, name="logits")
obs = array_ops.shape(logits)[0]
dims = array_ops.shape(logits)[1]
# In the paper, they call the logits z.
# The mean(logits) can be substracted from logits to make the algorithm
# more numerically stable. the instability in this algorithm c | omes mostly
# from the z_cumsum. Substacting the mean will cause z_cumsum to be close
# to zero. However, in practise the numerical instability issues are very
# minor and substacting the mean causes extra issues with inf and nan
# input.
z = logits
# sort z
z_sorted, _ = nn.top_k(z, k=dims... |
jeroanan/Aquarius | aquarius/persistence/sqlitepersistence/GetBookByTitleAndAuthor.py | Python | gpl-3.0 | 634 | 0.001577 | from aquarius.objects.Book import Book
class GetBookByTitleAndAuthor(object):
def __init__(self, connection):
self.__connection = connection
def execute(self, book):
b = Book()
| sql = "SELECT Id, Title, Author FROM Book WHERE Title=? AND Author=?"
r = list(self.__connection.execute_sql_fetch_all_with_params(sql, (book.title, book.author)))
if len(r) > 0:
| self.map_resultset_to_book(b, r)
return b
def map_resultset_to_book(self, book, resultset):
book.id = resultset[0][0]
book.title = resultset[0][1]
book.author = resultset[0][2]
|
t3dev/odoo | odoo/addons/test_testing_utilities/tests/test_form_impl.py | Python | gpl-3.0 | 16,663 | 0.00102 | # -*- coding: utf-8 -*-
"""
Test for the pseudo-form implementation (odoo.tests.common.Form), which should
basically be a server-side implementation of form views (though probably not
complete) intended for properly validating business "view" flows (onchanges,
readonly, required, ...) and make it easier to generate sen... | t_get
self.assertEqual(f.m2m[:], a | b)
f.m2o = c |
self.assertEqual(f.m2m[:], a | b | c)
f.m2o = d
self.assertEqual(f.m2m[:], a | b | c | d)
def test_m2m_readonly(self):
Sub = self.env['test_testing_utilities.sub3']
a = Sub.create({'name': 'a'})
b = Sub.create({'name': 'b'})
r = self.env['test_testing_utili... |
AndrewReynen/Lazylyst | lazylyst/UI/ComboBox.py | Python | mit | 2,055 | 0.003406 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ComboBox.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_comboBoxDialog(object):
def setupUi(self, comboBoxDialog):
co... | sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(comboBoxDialog.sizePolicy().hasHeightForWidth())
comboBoxDialog.setSizePolicy(sizePolicy)
comboBoxDialog.setMinimumSize(QtCore.QSize(0, 84))
comboBoxDialog.setMaximumSize(QtCore.QSize(16777215, 84))
self.verticalL... | self.verticalLayout.setObjectName("verticalLayout")
self.comboBox = QtWidgets.QComboBox(comboBoxDialog)
self.comboBox.setObjectName("comboBox")
self.verticalLayout.addWidget(self.comboBox)
self.buttonBox = QtWidgets.QDialogButtonBox(comboBoxDialog)
self.buttonBox.setOrientatio... |
fiee/fiee-temporale | demo/views.py | Python | bsd-3-clause | 121 | 0.008264 | from django.views.generic i | mport ListView, TemplateView
class IndexView(TemplateVi | ew):
template_name = 'index.html'
|
plinecom/pydpx_meta | sample2_ex.py | Python | mit | 176 | 0.005682 | i | mport pydpx_meta
# High level class DpxHeaderEx sample
#dpx = pydpx_meta.DpxHeaderEx("/root/V14_37_26_01_v001.0186.dpx")
dpx = pydpx_meta.DpxHeaderEx()
print(dpx.describe() | )
|
frappe/frappe | frappe/core/doctype/prepared_report/test_prepared_report.py | Python | mit | 862 | 0.024362 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies and Contributors
# License: MIT. See LICENSE
import frappe
import unittest
import json
class TestPreparedReport(unittest.TestCase):
def setUp(self):
self.report = frappe.get_doc({
"doctype": "Report",
"name": "Permitted Documents For User"
}... | name
}).insert()
def tearDown(self):
frappe.set_user("Administrator")
self.prepared_report_doc.delete()
def test_for_creation(self):
self.assertTrue('QUEUED' == self.prepared_report_doc.status.upper())
self.assertTrue | (self.prepared_report_doc.report_start_time)
|
jronald01/behave-teamcity | setup.py | Python | mit | 861 | 0.001161 | from setuptools import setup
setup(
name='behave-teamcity',
version="0.1.23",
packages=['behave_teamcity', ],
url='https://github.com/iljabauer/behave-teamcity',
download_url='https://github.com/iljabauer/behave-teamcity/releases/tag/0.1.23',
license='MIT',
author='Ilja Bauer',
author_e... | y test report formatter for behave',
install_requires=["behave>=1.2.5,<=1.3", "teamcity-messages"],
keywords=['testing', 'behave', 'teamcity', 'formatter', 'report'],
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Appro... | ild Tools",
"Topic :: Utilities"
],
)
|
CARPEM/GalaxyDocker | data-manager-hegp/analysisManager/analysismanager/sequencer/apps.py | Python | mit | 134 | 0 | f | rom __future__ import unicode_literals
from django.apps import AppConfig
class SequencerConfig(AppConfig):
name = 'sequencer | '
|
MSMBA/msmba-workflow | msmba-workflow/srclib/wax/examples/statusbar-1.py | Python | gpl-2.0 | 728 | 0.002747 | # statusbar-1.py
from wax import *
import time
class MainFrame(Vert | icalFrame):
def Body(self):
statusbar = StatusBar(self, numpanels=3, add=1 | )
# "add=1" adds the statusbar to its parent automagically; if you omit
# this, you'll have to do self.SetStatusBar(statusbar) explicitly
# add some buttons so the window isn't so empty
for i in range(5):
b = Button(self, str(i+1))
self.AddComponent(b, expand='h'... |
co-ment/comt | src/cm/migrations/0003_update_keys_to_textversion.py | Python | agpl-3.0 | 15,210 | 0.008153 |
from south.db import db
from django.db import models
from cm.models import *
class Migration:
def forwards(self, orm):
"Write your forwards migration here"
for tv in orm.TextVersion.objects.all():
tv.key = orm.TextVersion.objects._gen_key()
tv.adminkey = orm.T... | max_length': '1000'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'}),
'text_version': ('django.db.models.fields.related.ForeignKey', [], {'to': "or... | django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'}),
'content': ('django.db.models.fields.TextField', [], {}),
'content_html': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'aut... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.