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
Gagaro/PimpMyBot
pimpmybot/utils/commands.py
Python
mit
1,789
0.001118
from __future__ import absolute_import, unicode_literals from copy import copy import json from peewee import Model, CharField, ForeignKeyField, IntegerField from utils.modules import BaseModule, modules from utils.modules.api import api as pmb_api from utils import db class Action(Model): class Meta: ...
tabase = db command = CharField(unique=True) def get_actions(self): return ( Action .select() .join(CommandAction) .join(Command) .where(Command.id == self.id) .order_by(CommandAction.order) ) def ...
action in ( CommandAction.select() .join(Command) .where(Command.id == self.id) ): commandaction.delete_instance() class CommandAction(Model): class Meta: database = db command = ForeignKeyField(Command) action = ...
abyrd/OTPProfiler
resultsdb.py
Python
gpl-3.0
2,067
0.024673
#!/usr/bin/python import sqlite3, os, random class ResultsDatabase : def __init__(self): filename = 'results.sqlite' init = False if not os.path.exists(filename): init = True self.conn = sqlite3.connect(filename) if init : self.setup() ...
FLOAT)" ) self.conn.commit() c.close() def generate_endpoints(): #random endpoints N = 500 c = self.conn.cursor() for i in range(N) : olat = random.gauss(CENTER[0], STDEV[0]) olon = random.gauss(CENTER[1], STDEV[1]) c.execute("...
populate_endpoints(): #defined endpoints for line in open('endpoints'): fields = line.strip().split(',') if len(fields) != 3: print 'line does not have 3 fields' else: name, lat, lon = fields endpoints. endpoi...
haakenlid/django-extensions
django_extensions/management/commands/generate_secret_key.py
Python
mit
787
0.002541
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand from django_extensions.management.utils import signalcommand try: from django.core.management.utils import get_random_secret_key except ImportError: from django.utils.crypto import get_random_string def get_random_secret_key(): ...
s, **options): return get_random_secret
_key()
austinharris/gem5-riscv
src/dev/x86/I8042.py
Python
bsd-3-clause
2,210
0.001357
# Copyright (c) 2008 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list ...
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SU...
Black from m5.params import * from m5.proxy import * from Device import BasicPioDevice from X86IntPin import X86IntSourcePin class I8042(BasicPioDevice): type = 'I8042' cxx_class = 'X86ISA::I8042' cxx_header = "dev/x86/i8042.hh" # This isn't actually used for anything here. pio_addr = 0x0 data...
mezz64/home-assistant
homeassistant/components/ecoal_boiler/__init__.py
Python
apache-2.0
3,573
0.001399
"""Support to control ecoal/esterownik.pl coal/wood boiler controller.""" import logging from ecoaliface.simple import ECoalController import voluptuous as vol from homeassistant.const import ( CONF_HOST, CONF_MONITORED_CONDITIONS, CONF_PASSWORD, CONF_SENSORS, CONF_SWITCHES, CONF_USERNAME, ) f...
={}): SENSOR_SCHEMA, vol.Optional(CONF_SWITCHES, default={}): SWITCH_SCHEMA, vol.Optional(CONF_USERNAME, default=DEFAULT_USERNAME): cv.string, } ) }, extra=vol.ALLOW_EXTRA, ) def setup(hass: HomeAssistant, hass_config: ConfigType) -> bool: """Set up glob...
NF_PASSWORD] # Creating ECoalController instance makes HTTP request to controller. ecoal_contr = ECoalController(host, username, passwd) if ecoal_contr.version is None: # Wrong credentials nor network config _LOGGER.error( "Unable to read controller status from %s@%s (wrong host/...
miing/mci_migo
acceptance/tests/emails/_token_reuse.py
Python
agpl-3.0
1,231
0.004874
from sst.actions import ( assert_title, fails, ) from u1testutils import mail from u1testutils.sst import config from acceptance import helpers config.set_base_
url_from_env() primary_email_id = mail.make_unique_test_email_address
() secondary_email_id = mail.make_unique_test_email_address() print 'primary: %s\nsecondary: %s' % (primary_email_id, secondary_email_id) helpers.register_account(primary_email_id) #add email vcode = helpers.add_email(secondary_email_id) print 'vcode:', vcode #delete it helpers.delete_email() #try to validate it he...
JustinWingChungHui/okKindred
emailer/migrations/0008_auto_20151224_1528.py
Python
gpl-2.0
467
0
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-24 15:28 from __futu
re__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('emailer', '0007_auto_20150509_1922'), ] operations = [ migrations.AlterField( model_name='email', name='recipient',
field=models.EmailField(db_index=True, max_length=254), ), ]
eliostvs/tomate-gtk
tests/pomodoro/test_plugin.py
Python
gpl-3.0
2,983
0.001676
import os from distutils.version import StrictVersion import pytest from wiring.scanning import scan_to_graph from tomate.pomodoro import Events, PluginEngine, suppress_errors @pytest.fixture def plugin_engine(bus, graph, config) -> PluginEngine: return PluginEngine(bus, config, graph) def test_module(bus, co...
_errors def raise
_exception(): raise Exception() assert not raise_exception() def test_raises_exception_when_debug_enable(self): os.environ.setdefault("TOMATE_DEBUG", "1") @suppress_errors def raise_exception(): raise Exception() with pytest.raises(Exception): ...
gg7/gentoostats
pym/gentoostats/argument_parser_wrapper.py
Python
gpl-2.0
6,535
0.031064
#!/usr/bin/env python # # Copyright 2011 Vikraman Choudhury <vikraman.choudhury@gmail.com> # Copyright 2012 G. Gaydarov <ggaydarov@gmail.com> # # Distributed under the terms of the GNU General Public License v2 or later from __future__ import print_function import sys import argparse import gentoolkit from .app_util...
) >>> _replace_if_found('abcd', 'x', '1') (False, 'abcd') """ new_s = s.replace(what_to_replace, replacement) return (new_s != s, new_s) def _translate_message(message): """ Translates argparse message
s to gentoolkit messages (kinda). """ found, message = \ _replace_if_found( message, 'the following arguments are required: ', '' ) if found: return "Missing argument(s): " + message found, message = \ _replace_if_found(message, 'unrecognized arguments: ', '') if found: return ...
eyaler/tensorpack
examples/FasterRCNN/utils/generate_anchors.py
Python
apache-2.0
3,442
0.004648
# https://github.com/rbgirshick/py-faster-rcnn/blob/master/lib/rpn/generate_anchors.py # -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------...
""" Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = _whctrs(anchor) ws = w * scales hs = h * scales anchors = _mkanchors(ws, hs, x_ctr, y_ctr) return anchors if __name__ == '__main__': #import time #t = time.time() #a = generate_anchors() #...
les=np.asarray((2, 4, 8, 16, 32), 'float32'), ratios=[0.5,1,2]) print(anchors) import IPython as IP; IP.embed()
Shao-Feng/testkit-lite
testkitlite/util/session.py
Python
gpl-2.0
86,792
0.003249
#!/usr/bin/python # # Copyright (C) 2012 Intel Corporation # # 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 pr...
f set_global_parameters(self, options): "get all options " # apply dryrun if options.bdryrun: self.bdryrun = options.bdryrun # Disable set the result of core manual cases from the console if options.non_active: self.non_active = options.non_active ...
ile: self.resultfile = options.resultfile # set the external test if options.exttest: self.external_test = options.exttest if options.debug: self.debug = options.debug if options.rerun: self.rerun = options.rerun if options.test_pre...
ZeitOnline/zeit.calendar
src/zeit/calendar/tests/test_doctest.py
Python
bsd-3-clause
581
0
import docte
st import unittest import zeit.calendar.calendar import zeit.calendar.testing import zeit.cms.testing def test_suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite( zeit.calendar.calendar, optionflags=zeit.cms.testing.optionflags)) suite.addTest(doctest.DocFileSuite( ...
.testing.optionflags)) suite.addTest(zeit.calendar.testing.FunctionalDocFileSuite( 'calendar.txt', package='zeit.calendar', )) return suite
etsiiull/medicalpybrain
Datasets y Scripts/Pybrain_Melanoma_for_test_Hidden.py
Python
gpl-3.0
3,861
0.02513
#Imports from __future__ import division from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer from pybrain.tools.shortcuts import buildNetwork from pybrain.utilities import percentError import numpy as np import pylab as pl import math as ma import csv #Leer las bases ...
t[i], patternValidTarget[i]) testDS = SupervisedDataSet(numColsTest-1, 1) for i in range(numPatTest): patternTestTarget[i] = patternTest[i, 0] testDS.addSample(patternTestInput[i], patternTestTarget[i]) resultados = np
.zeros((100,7)) numHiddenNodes = 5 while(numHiddenNodes < 101): counter = 0 while(counter < 5): #Crear red con una capa oculta #numHiddenNodes = 25 myLearningRate = 0.0001 myMomentum = 0.1 net = buildNetwork(numColsTrain-1, numHiddenNodes, 1, bias=True) #Crear el trainer y hacer enternar el DS trainer...
thought-machine/please
test/python_rules/python_coverage.py
Python
apache-2.0
265
0.003774
"""This exists only as a test harness for examining slightly non-trivial coverage output.""" import sys from coll
ections import defaultdict def calculate_answer(a, b): return a * b def the_answer(): return calculate_answe
r( 6, 7, )
Tinkerforge/brickv
src/brickv/plugin_system/plugins/red/program_wizard.py
Python
gpl-2.0
1,802
0.00333
# -*- coding: utf-8 -*- """ RED Plugin Copyright (C) 2014-2015, 2017 Matthias Bolte <matthias@tinkerforge.com> program_wizard.py: Program Wizard 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; eithe...
Wizard ProgramWizardContext = namedtuple('ProgramWizardContext'
, 'session identifiers script_manager image_version executable_versions') class ProgramWizard(QWizard): def __init__(self, parent, context): super().__init__(parent) self.setModal(True) self.session = context.session self.identifiers = context.identifiers ...
nealchenzhang/Py4Invst
Backtest_Futures/__init__.py
Python
mit
1,101
0.000908
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### # # Created on Tue Dec 26 08:58:19 2017 # @author: NealChenZhang # This program is personal trading platform designed when employed in # Aihui Asset Management as a quantitative analyst. # # ...
.backtest import * from .data import * from .event import * from .execution import * from .performance import * from .portfolio import * from .strat
egy import * __author__ = 'Neal Chen Zhang'
Pybonacci/cffi_test
examples/example_numba.py
Python
bsd-3-clause
197
0
# coding: utf-8 from hyper import hyper from numba import ji
t @jit(nopython=True) def hyp_battin(x): return hyper.hyp2f1(3, 1, 5/2, x)
if __name__ == '__main__': print(hyp_battin(0.5))
CCI-MOC/GUI-Backend
api/v2/views/ssh_key.py
Python
apache-2.0
465
0
from api.v2.views.base import AuthViewSet from api.v2.serializers.details import SSHKeySerializer from core.models import SSHKey class SSHKeyViewSet(AuthViewSet): """ API
endpoint that allows providers to be viewed or edited. """ serializer_class = SSHKeySerializer def get_queryset(self): """ Filter projects by current user """ user = self.request.user
return SSHKey.objects.filter(atmo_user=user)
jerkern/pyParticleEst
pyparticleest/paramest/interfaces.py
Python
lgpl-3.0
10,506
0.002094
''' Interfaces required for using the parameter estimation methods @author: Jerker Nordh ''' import abc import numpy import scipy.optimize class ParamEst(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def maximize(self, straj): pass class ParamEstIntFullTraj(object): __metaclass__ ...
if (yt[i] is not None): val = self.eval_logp_y(sest[i], yt[i], tt[i]) logp_y += numpy.sum(val) return logp_y / M def eval_logp_xnext(self, particles, particles_next, u, t): """ Calculate gradient of a term of the I2 integral approximation as sp...
particles (array-like): Model specific representation of all particles, with first dimension = N (number of particles) - x_next (array-like): future states - t (float): time stamp Returns: (array-like) or (float) """ # Here we can just reuse the method used in the ...
Aalto-LeTech/a-plus
lib/viewbase.py
Python
gpl-3.0
3,001
0.001333
""" Defines base views for extending and mixing to higher level views. The structure was created for handling nested models. """ from django.http.response import HttpResponseRedirect from django.utils.http import is_safe_url from django.views.generic.base import TemplateResponseMixin, TemplateView, View from django.vie...
def get_permissions(self): perms = super().get_permissions() perms.extend((Perm() for Perm in self.base_permission_classes)) return perms def get_access_mode(self): return self.access_mode def _get_kwarg(self, kw, **kwargs): arg = self.kwargs.get(kw) if not arg:...
raise AttributeError( "Missing argument from URL pattern: {}".format(kw)) return arg class BaseViewMixin(AuthorizedResourceMixin): permission_classes = [] # common come from BaseMixin and this drops NoPermission default pass class BaseView(BaseViewMixin, View): pass cl...
qisanstudio/qsapp-microsite
src/microsite/migration/env.py
Python
mit
2,298
0.003916
# -*- coding: utf-8 -*- from __future__ import with_statement import os import sys sys.path.insert(0, os.getcwd()) from alembic import context from sqlalchemy import engine_from_config, pool from logging.config import fileConfig from studio.core.engines import db from microsite import app # this is the Alembic Con...
a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to co
ntext.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure(url=url, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in ...
3Geo/mipp
mipp/xsar/CSK.py
Python
lgpl-3.0
4,457
0.004936
# # WORK IN PROGRESS for CosmoSkyMed # import os import copy import numpy as np from datetime import datetime, timedelta from lxml import etree import logging logger = logging.getLogger('mipp') import mipp.xsar import mipp.geotiff class _Calibrator(object): def __init__(self, mda): self.error = "Unknown ...
alibrated = 'NOTCALIBRATED' return mda def read_image(mda, filename=None, mask=True, calibrate=1): mda = copy.copy(mda) mda.calibrate = _Calibrator(mda) mda.calibration_unit = 'counts' mda.is_calibrated = False del mda.calibrated mda.product_name = (mda.time_start.strftime("%Y%m%d_%H%M%S")...
mda.product_type + '_' + mda.polarisation) logger.info('Product name: %s'% mda.product_name) if not filename: filename = mda.image_filename params, data = mipp.geotiff.read_geotiff(filename) area_def = mipp.geotiff.tiff2areadef(params['projection'], ...
cgstudiomap/cgstudiomap
main/parts/server-tools/auth_from_http_remote_user/res_users.py
Python
agpl-3.0
2,630
0
# -*- coding: utf-8 -*- ############################################################################## # # Author: Laurent Mignon # Copyright 2014 'ACSONE SA/NV' # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # pub...
o_key', '=', password)]) if not res: raise openerp.exceptions.AccessDenied() def check(self, db, uid, passwd): try: return super(res_users, self).check(db, uid, passwd)
except openerp.exceptions.AccessDenied: if not passwd: raise with RegistryManager.get(db).cursor() as cr: cr.execute('''SELECT COUNT(1) FROM res_users WHERE id=%s AND s...
AntonioJBT/CGATPipeline_core
CGATPipelines/PipelineEnrichmentGSEA.py
Python
mit
13,384
0.006276
''' PipelineEnrichmentGSEA.py ============================================= :Tags: Python Usage ----- This pipeline is a wrapper of script runGSEA.py (enrichment analysis by using GSEA. Further description is provided ...
information on leading edge analysis genesets (i.e. participating genes in each gene set). 3- Leading edge (gct,cluster format) files for unclustered and clustered gene set. It is a boolean matrix. tha
t can be used as an input into other resources for additional analysis as this is ideal format for cluster representation (in GSEA) For details on the algorithm please refer to Subramanian, Tamayo, et al. (2005, PNAS 102, 15545-15550) and Mootha, Lindgren, et al. (2003, Nat Genet 34, ...
Vysybyl/motuus
motuus/visualize/tests.py
Python
gpl-3.0
9,175
0.002943
import unittest from time import sleep from math import pi, sin, cos from panda3d.core import Quat as Panda3dQuat from random import random as rnd from motuus.visualize.graph2D import Graph2D from motuus.visualize.graph3D import Graph3D from motuus.movement.constants import * from motuus.movement.utils import build_q,...
TATION_VECTOR, EAST_ORIENTATION_VECTOR, SOUTH_ORIENTATION_VECTOR, WEST_ORIENTATION_VECTOR, UP_FRONT_ORIENTATION_VECTOR, U
P_LEFT_ORIENTATION_VECTOR, UP_REAR_ORIENTATION_VECTOR, UP_RIGHT_ORIENTATION_VECTOR , DOWN_FRONT_ORIENTATION_VECTOR, DOWN_LEFT_ORIENTATION_VECTOR, DOWN_REAR_ORIENTATION_VECTOR, DOWN_RIGHT_ORIENTATION_VECTOR ...
edx/edx-platform
common/djangoapps/third_party_auth/management/commands/saml.py
Python
agpl-3.0
1,687
0.002371
""" Management commands for third_party_auth """ import logging from django.core.management.base import BaseCommand, CommandError from common.djangoapps.third_party_auth.tasks import fetch_saml_metadata class Command(BaseCommand): """ manage.py commands to manage SAML/Shibboleth SSO """ help = '''Configur...
total=total, skipped=skipped, attempted=attempted, updated=updated, failed=failed, ) )
if failed > 0: raise CommandError( "Command finished with the following exceptions:\n\n{failures}".format( failures="\n\n".join(failure_messages) ) )
atirage/aGreenHouse
clients/piOLED.py
Python
mit
4,728
0.007403
#from gpiozero import MotionSensor #import subprocess from PIL import Image from PIL import ImageDraw from PIL import ImageFont import time import datetime import syslog import requests import json import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 URL = "http://localhost:8888/properties" STOP...
FF h = 0.1 # needs to be < 1 h_1 = int(1/h) def GetImgOffset(t): global T if t <= T/2: return (64 * 2 * t) / T else: return (2 * 64 * (T - t)) / T def CheckTimeIn(h0, m0, h1, m1): start = datetime.time(h0, m0) end = datetime.time(h1, m1)
timenow = datetime.datetime.now().time() if (start <= timenow <= end): return True else: return False def GetLivingData(ambT, atm, light, mask = 0x07): try: r = requests.get(URL) rv = r.status_code if rv == 200: response = r.json() ...
drvinceknight/Axelrod
axelrod/strategies/rand.py
Python
mit
235
0.008511
from axelrod import Player import random class Random(Player): """A player who randomly chooses between cooper
ating and defecting.""" name = 'Random' def strategy(self, opponent): retur
n random.choice(['C','D'])
Jumpscale/jumpscale6_core
lib/JumpScale/baselib/git/__init__.py
Python
bsd-2-clause
131
0.007634
from JumpScale import j from Gi
tFactory import GitFactory j.base.loader.makeAvaila
ble(j, 'clients') j.clients.git = GitFactory()
imvu/bluesteel
app/logic/gitrepo/controllers/__init__.py
Python
mit
94
0
""" Automatic file """ from app.logic.gitrepo.controllers
.GitController import GitControlle
r
greggyNapalm/lunaport_server
lunaport_server/dao/path.py
Python
apache-2.0
4,535
0.001103
# -*- encoding: utf-8 -*- """ lunaport.dao.line ~~~~~~~~~~~~~~~~~ Storage interaction logic for line resource. """ import pprint pp = pprint.PrettyPrinter(indent=4).pprint from sqlalchemy import text, exc from ..wsgi import app, db from .. domain.line import LineBuilder, LineAdaptor from exceptions impo...
part, q_params_up = f.cmpl_query() query_params.update(q_params_up) rv = cls.rdbms_call( ''.join([cls.select_join_part, filter_part, pagination_part]), query_params) rows = rv.fetchall() if len(rows) == 0: return None, None, None, None
elif len(rows) < per_page: # last chunk of data next_page = None def create_dc(row): t_kw = dict(zip(rv.keys(), row)) return LineBuilder.from_row(**t_kw) return map(create_dc, rows), per_page, next_page, prev_page
timtadh/tst
tst/t_suffix.py
Python
bsd-3-clause
11,460
0.009162
''' SuffixTree - A Ternary Search Trie Author: Tim Henderson Contact: tim.tadh@hackthology.com or timothy.henderson@case.edu This File: Tests for the SuffixTree. Copyright (c) 2010, Tim Henderson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provi...
, 1), ('d', 4), ('daf', 5), ('db', 6), ('dac', 3)), list()) def test_random(self): for j in xrange(100): s = set() l1 = list() for x in xrange(100)
: k = base64.b64encode(os.urandom(x%10 + 1)).rstrip('=') if k in s: continue l1.append((k, x)) s.add(k) l2 = [(s,i+15) for s,i in l1] t = SuffixTree() if not self.insert_tester3(t, l1, l2): break def test_complete(s...
shawnlawson/The_Force
pythonBridge/simple-https-server.py
Python
mit
581
0.008606
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/ # generate server.xml with the following command: # openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes # run as follows: # python simple-https-server.py # t
hen in your browser, visit: # https://localhost:4443 import BaseHTTPServer, SimpleHTTPServer import ssl httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./server.pem', server_side=T
rue) httpd.serve_forever()
sanguinariojoe/FreeCAD
src/Mod/TechDraw/TDTest/DVAnnoSymImageTest.py
Python
lgpl-2.1
1,959
0.008167
#!/usr/bin/env python # -*- coding: utf-8 -*- # annotation & symbol test script for TechDraw module # creates a page, 1 annotation and import 1 symbol from __future__ import print_function import FreeCAD import Part import Measure import TechDraw import os def DVAnnoSymImageTest(): path = os.path.dirname(os.path...
th) templateFileSpec = path + '/TestTemplate.svg' symbolFileSpec = path + '/TestSymbol.svg' imageFileSpec = path + '/TestImage.png' FreeCAD.newDocument("TDAnno") FreeCAD.setActiveDocument("TDAnno") FreeCAD.ActiveDocument=FreeCAD.getDocument("TDAnno") page = FreeCAD.ActiveDocument.addObject...
aw::DrawSVGTemplate','Template') FreeCAD.ActiveDocument.Template.Template = templateFileSpec FreeCAD.ActiveDocument.Page.Template = FreeCAD.ActiveDocument.Template # page.ViewObject.show() # unit tests run in console mode #annotation anno = FreeCAD.ActiveDocument.addObject('TechDraw::DrawViewAnno...
kalicodextu/djangoblog
blog/urls.py
Python
mit
186
0
from django.conf.urls import url from blog import views urlpatterns = [ url(r'^view$', views.a
rchive), url(r'^$', views.welcome), url(r'^create', views.create
_blogpost), ]
foone/7gen
bin/rgb2vxp.py
Python
gpl-2.0
6,990
0.045207
#!/usr/env python # Change this stuff: name='Light Blue Fun Timexxxx' author='Travis Wells' shortname='litebluebg' # out file will be shortname with a 'vxp' extension color=(155,204,224) # Set to the Red,Green,Blue of the color you want. uniqueid=0 # Set to 0 if you don't have one. #Don't change this stuff: #RGB2VXP...
eference(gokd,0) gokd.addReference(mbmp,65536) vxp3th=lib3dmm.c3dmmFileOut() vxp3th.addQuad(bkth) vxp3th.addQuad(cath) vxp3
th.addQuad(gokd) vxp3th.addQuad(mbmp) progress() outzip.writestr(shortname+'.3th',vxp3th.getData()) progress() pygame.init() palette_surf=pygame.image.load('code/palette.bmp') if uniqueid is None or uniqueid==0: uniqueid=GenerateID() if uniqueid==0: raise SaveError("Could...
ramusus/django-instagram-api
instagram_api/tests.py
Python
bsd-3-clause
14,673
0.000617
# -*- coding: utf-8 -*- from datetime import datetime from django.test import TestCase from django.conf import settings from django.utils import timezone from .factories import UserFactory, LocationFactory from .models import Media, User, Tag, Location from .api import InstagramError USER_ID = 237074561 # tnt_onli...
rtEqual(int(u2.id), 237074561) self.assertEqual(u1.username, 'tnt_online') self.assertEqual(u2.username, 'bmwru') u1 = User.remote.fetch(8910216) u2 = User.remote.fetch(237074561) self.assertEqual(User.objects.count(), 2) self.assertEqual(int(u1.id), 8910216) se...
test_fetch_real_duplicates_user(self): UserFactory(id=2116301016) User.remote.fetch(2116301016) with self.assertRaises(InstagramError): User.remote.get(1206219929) try: User.remote.get(1206219929) except InstagramError as e: self.assertEqua...
mahak/neutron
neutron/extensions/securitygroup.py
Python
apache-2.0
14,709
0
# 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.apache.org/licenses/LICENSE-2.0 # # Unless...
ss SecurityGroupNotFound(exceptions.NotFound): message = _("Security group %(id)s does not exist") class SecurityGroupRuleNotFound(exceptions.NotFound): message = _("Security group rul
e %(id)s does not exist") class DuplicateSecurityGroupRuleInPost(exceptions.InUse): message = _("Duplicate Security Group Rule in POST.") class SecurityGroupRuleExists(exceptions.InUse): message = _("Security group rule already exists. Rule id is %(rule_id)s.") class SecurityGroupRuleInUse(exceptions.InUs...
YuhangSong2017/test_4
train.py
Python
gpl-3.0
6,963
0.004596
import argparse import os import sys import gym import config import copy import time import numpy as np import subprocess import config parser = argparse.ArgumentParser(description="Run commands") def new_tmux_cmd(session, name, cmd): if isinstance(cmd, (list, tuple)): cmd =
" ".join(str(v) for v in cmd) return name, "tmux send-keys -t {}:{} '{} && {}' Enter".format(session, name, 'source activate dhp_env', cmd) def create_tmux_commands(session, logdir): if config.mode in ['on_line']: '''genrate game done dic for first run, so that latter is auto started by t
he programe''' done_sinal_dic = [] worker_running = 0 for game_i in range(0,len(config.game_dic)): for subjects_i in range(0,config.num_subjects): done_sinal_dic += [[game_i,subjects_i]] worker_running += 1 if worker_running >= config.n...
vortex-ape/scikit-learn
sklearn/manifold/tests/test_isomap.py
Python
bsd-3-clause
4,726
0
from itertools import product import numpy as np from numpy.testing import (assert_almost_equal, assert_array_almost_equal, assert_equal) from sklearn import datasets from sklearn import manifold from sklearn import neighbors from sklearn import pipeline from sklearn import preprocessing fro...
N_per_side ** 2 n_neighbors = Npts - 1 # grid of equidistant points in 2D, n_components = n_dim X = np.array(list(product(range(N_per_side), repeat=2))) # add noise in a third dimension rng = np.random.RandomState(0) noise = 0.1 * rng.randn(Npts, 1) X = np.concatenate((X, noise), 1) #...
.KernelCenterer() K = centerer.fit_transform(-0.5 * G ** 2) for eigen_solver in eigen_solvers: for path_method in path_methods: clf = manifold.Isomap(n_neighbors=n_neighbors, n_components=2, eigen_solver=eigen_solver, path_...
disasterisk/itc110
guess.py
Python
mit
1,117
0.0188
import random number = random.randint(1,100) def guessAgain(): i = input("Again? y/n ") i = i.lower() if i == "y": return True elif i == "
n": return False else: print("I don't understand? Try y or n.")
return None print("I'm thinking of a number between 1 and 100.") play = True count = 0 while play == True: try: guess=int(input("Guess what it is? ")) except ValueError: print("I said I was thinking of a *number*") continue count+=1 ...
samdroid-apps/aslo
web/main.py
Python
agpl-3.0
3,514
0.001138
import os import json import thread import requests from datetime import datetime from flask.ext.babel import Babel from flask import Flask, render_template, send_from_directory, \ request, redirect, abort, Response import backend from pykafka import KafkaClient from i18n import get_localized_text a...
.add_extension('jinja2.ext.i18n') app.jinja_env.install_null_translations(newstyle=True) app.jinja_env.globals.update(reversed=rever
sed) # IDK app.jinja_env.globals.update(datetime=datetime) app.jinja_env.globals.update(l=get_localized_text) app.jinja_env.globals.update(embed_icon=backend.embed_icon) @app.route('/') @app.route('/page/<int:page>') def index(page=1, size=18): total = len(backend.ALL_BUNDLE_IDS) if total < size*(page-1): ...
Neurosim-lab/netpyne
examples/batchCellMapping/batch.py
Python
mit
1,998
0.019019
""" batch.py Batch simulation for M1 model using NetPyNE """ from netpyne.batch import Batch import numpy as np def runBatch(b, label, setup='mpi_bulletin'): b.batchLabel = label b.saveFolder = 'data/'+b.batchLabel b.method = 'grid' if setup == 'mpi_bulletin': b.runCfg = {'type': 'mpi_bulle...
': 15} b = Batch(params=params, initCfg=initCfg) runBatch(b, 'batchNa', setup='mpi_bulletin') def batchNMDA(): params = {'tau1NMDA': [10, 15, 20, 25], ('NetStim1', 'weight'): list(np.arange(1.0, 10.0, 1.0)/1e4
)} initCfg = {'duration': 1.1} b = Batch(params=params, initCfg=initCfg) runBatch(b, 'batchNMDA', setup='mpi_bulletin') def batchNMDAMapping(): params = {'tau1NMDA': [10, 15, 20, 25]} initCfg = {'duration': 1100} from cfg import cfg from netParams import netParams b = Batch(params=params, initCfg=initCfg, c...
Diyago/Machine-Learning-scripts
DEEP LEARNING/NLP/LSTM RNN/Next Chars pytorch/project-tv-script-generation/helper.py
Python
apache-2.0
1,431
0.001398
import os import pickle import torch SPECIAL_WORDS = {"PADDING": "<PAD>"} def load_data(path): """ Load Dataset from File """ input_file = os.path.join(path) with open(input_file, "r") as f: data = f.read() return data def preprocess_and_save_data(dataset_path, token_lookup, creat...
oken)) text = text.lower() text = text.split() vocab_to_int, int_to_vocab = create_lookup_tables( text + list(SPECIAL_WORDS.values()) ) int_text = [vocab_to_int[word] for word in text] pickle.dump( (int_text, vocab_to_int,
int_to_vocab, token_dict), open("preprocess.p", "wb") ) def load_preprocess(): """ Load the Preprocessed Training data and return them in batches of <batch_size> or less """ return pickle.load(open("preprocess.p", mode="rb")) def save_model(filename, decoder): save_filename = os.path.splite...
foursquare/commons-old
src/python/twitter/common/dirutil/lock.py
Python
apache-2.0
2,508
0.008772
# ================================================================================================== # Copyright 2012 Twitter, Inc. # -------------------------------------------------------------------------------------------------- # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
pid = int(fd.read().strip()) if onwait: blocking = onwait(pid) if not blocking: return None lock_fd = lock_file(path, blocking=blocking) lock_fd.truncate(0) lock_fd.write('%d\n' % os.getpid()) lock_fd.flush() ret
urn Lock(lock_fd) def __init__(self, lock_fd): self._lock_fd = lock_fd def release(self): """Releases this lock if held and returns True; otherwise, returns False to indicate the lock was already released. """ if self._lock_fd: unlock_file(self._lock_fd, close=True) self._lock_fd ...
coherence-project/Coherence
coherence/upnp/core/test/test_msearch.py
Python
mit
3,566
0.000561
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2014, Hartmut Goebel <h.goebel@goebel-consult.de> """ Test cases for L{upnp.core.msearch} """ import time from twisted.trial import unittest from twisted.internet import protocol from twisted.test ...
'\r\n'.join(MSEARCH_RESPONSE_1) + '\r\n\r\n' self.proto.datagramReceived(data, ('10.20.30.40', 1234)) service1 = self.ssdp_server._known[USN_1] last_seen1 = service1['last-seen'] time.sleep(0.5) self.proto.datagramReceived(data, ('10.20.30.40', 1234)) service2 = self.ssdp...
self.assertLess(last_seen1, last_seen2+0.5) def test_discover(self): self.assertEqual(self.tr.written, []) self.proto.discover() expected = [(l + '\r\n') for l in [ 'M-SEARCH * HTTP/1.1', 'HOST: 239.255.255.250:1900', 'MAN: "ssdp:discover"', ...
rosscdh/django-crocodoc
dj_crocodoc/tests/signals.py
Python
gpl-2.0
8,364
0.006098
# -*- coding: utf-8 -*- """ Webhook signals """ # # Required for reading files # import sys; reload(sys); sys.setdefaultencoding("utf8") from django.core.files import File from django.core.cache import cache from django.dispatch import receiver from django.test import TestCase, Client from django.core.urlresolvers impo...
return self.client.post(self.endpoint, {"payload": json.dumps(data)}) def test_comment_create(self):
resp = self.send(data=crocodoc_data.CROCODOC_COMMENT_CREATE) self.assertItemsEqual(cache.get('test_crocodoc_webhook_event_recieved'), self.EXPECTED_KEYS) self.assertEqual(json.loads(resp.content), {"details": [True, True]}) def test_annotation_highlight(self): resp = self.send(data=cro...
mvendra/mvtools
tests/backup_preparation_test.py
Python
mit
84,237
0.005401
#!/usr/bin/env python3 import sys import os import stat import shutil import unittest from unittest import mock from unittest.mock import patch import getpass import fsquery import create_and_write_file import mvtools_test_fixture import backup_preparation import git_test_fixture import git_wrapper import path_utils ...
ts6) file_cnav2_contents = "" file_cnav2_contents += "#!/usr/bin/env python3" + os.linesep
file_cnav2_contents += "def invalid_interface(path):" + os.linesep file_cnav2_contents += " return []" + os.linesep self.test_cnav2_file = path_utils.concat_path(self.test_dir, "test_cnav2_file.py") create_and_write_file.create_file_contents(self.test_cnav2_file, file_cnav2_contents) ...
rnicoll/dogecoin
test/functional/interface_rpc.py
Python
mit
2,837
0.00141
#!/usr/bin/env python3 # Copyright (c) 2018-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Tests some generic aspects of the RPC interface.""" import os from test_framework.authproxy import JSO...
d'], 'getrpcinfo') assert_greater_than_or_equal(command['duration'], 0) assert_equal(info['logpath'], os.path.join(self.nodes[0].datadir, self.chain, 'debug.log')) def test_batch_request(self): self.log.info("Te
sting basic JSON-RPC batch request...") results = self.nodes[0].batch([ # A basic request that will work fine. {"method": "getblockcount", "id": 1}, # Request that will fail. The whole batch request should still # work fine. {"method": "invalidmethod...
jmoiron/daneel
daneel/plugins/weblib.py
Python
mit
2,749
0.004729
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convenience functions for doing web things.""" import re import requests import urlparse import traceback import json from lxml.cssselect import CSSSelector as cs from lxml.html import document_fromstring from daneel import utils ua = "Mozilla/5.0 (Macintosh; Intel M...
ary for a url.""" if "yelp.com" in url: return "Yelp is not supported because they IP blocked the server daneel runs on." page = requests.get(url, headers={'User-Agent': ua}) try: content = page.text except: content = page.content content = utils.utf8_damnit(content) ...
f a URL is passed, it may be treated specially to give better results, eg. twitter will return the tweet.""" html = document_fromstring(content) if url: parsed = urlparse.urlparse(url) if parsed.netloc.endswith("twitter.com") and "status" in url: tweet = text(".permalink-tweet .t...
pollitosabroson/retoglobal
retoglobal/wsgi.py
Python
apache-2.0
398
0
""" WSGI config for retoglobal project. It exposes the WSGI callable
as a module-level variable named ``application``. For more inf
ormation on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "retoglobal.settings") application = get_wsgi_application()
h3biomed/ansible
lib/ansible/modules/crypto/openssl_certificate.py
Python
gpl-3.0
79,027
0.002961
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016-2017, Yanis Guenane <yanis+ansible@guenane.org> # Copyright: (c) 2017, Markus Teufelberger <mteufelberger+ansible@mgit.at> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import...
ecified in this module are for
validation of an existing or newly generated certificate. The proper place to specify them, if you want to receive a certificate with these properties is a CSR (Certificate Signing Request). - "Please note that the module regenerates existing certificate if it doesn't match the module's options, ...
sergey-dryabzhinsky/dedupsqlfs
lib-dynload/brotli/setup.py
Python
mit
10,320
0.000581
# Copyright 2015 The Brotli Authors. All rights reserved. # # Distributed under MIT license. # See file LICENSE for detail or copy at https://opensource.org/licenses/MIT import os import sys import platform import re import unittest try: from setuptools import Extension from setuptools import setup except: ...
output format functions EXTRA_O
PT=1 sys.argv.remove("--extra-optimization") CURR_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) def get_version(): """ Return BROTLI_VERSION string as defined in 'common/version.h' file. """ version_file_path = os.path.join(CURR_DIR, 'c', 'common', 'version.h') version = 0 wi...
neopenx/Dragon
Dragon/python/dragon/vm/tensorflow/training/__init__.py
Python
bsd-2-clause
193
0.005181
# ---------------
----------------------------------------- # TensorFlow for Dragon # Copyright(c) 2017 SeetaTech # Written by Ting Pan # ----------------------------------------------
----------
emesika/RaananaTiraProject
rose/client/main.py
Python
gpl-2.0
3,395
0
import argparse import imp import logging import os.path import sys from twisted.internet import reactor, protocol from twisted.protocols import basic from rose.common import config, message from . import game log = logging.getLogger('main') class Client(basic.LineReceiver): def connectionMade(self): ...
icitly. if fp: fp.close() def main(): logging.basicConfig(level=logging.INFO, format=config.logger_format) parser = argparse.ArgumentParser(description="ROSE Client") parser.add_argument("--server-address", "-s", dest="server_address", default="localhost", ...
e: '10.20.30.44' or 'my-server.com'." " If not specified, localhost will be used.") parser.add_argument("driver_file", help="The path to the driver python module") args = parser.parse_args() try: driver_mod = load_driver_module(args.driver_file)...
Orav/kbengine
kbe/src/lib/python/Lib/test/test_call.py
Python
lgpl-3.0
3,290
0.000304
import unittest from test import support # The test cases here cover several paths through the function calling # code. They depend on the METH_XXX flag that is used to define a C # function, which can't be verified from Python. If the METH_XXX decl # for a C function changes, these tests may not cover the rig...
self.assertRaises(TypeError, [].count) def test_oldargs1_1(self): [].count(1) def test_oldargs1_2(self
): self.assertRaises(TypeError, [].count, 1, 2) def test_oldargs1_0_ext(self): try: [].count(*()) except TypeError: pass else: raise RuntimeError def test_oldargs1_1_ext(self): [].count(*(1,)) def test_oldargs1_2_ex...
forslund/mycroft-core
test/unittests/util/test_format.py
Python
apache-2.0
30,604
0
# -*- coding: iso-8859-15 -*- # # Copyright 2017 Mycroft AI 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 appli...
""" self.assertEqual(nice_number(5.5, lang='as-fd'), '5.5', 'should format 5.5 as 5.5 not {}'.format(
nice_number(5.5, lang='as-df'))) class TestPronounceNumber(unittest.TestCase): def test_convert_int(self): self.assertEqual(pronounce_number(0), "zero") self.assertEqual(pronounce_number(1), "one") self.assertEqual(pronounce_number(10), "ten") self.assertE...
mirjalil/ml-visual-recognition
codes/logisticRegression.py
Python
apache-2.0
3,262
0.021153
import numpy as np import pandas import scipy, scipy.spatial import sklearn import sys from sklearn import linear_model from sklearn.metrics import precision_score, recall_score, f1_score import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('train', help='Training Data') p...
e[0], dtype=int) ic = args.pl
ab y[np.where(y_all[0] != ic)[0]] = -1 y[np.where(y_all[0] == ic)[0]] = 1 print('Training set: %d Pos: %d Neg: %d'%(y.shape[0], np.sum(y==1), np.sum(y==-1))) chunks=500000 for i in range(1): sys.stdout.write('%d '%(i)) n = 0 for df in pandas.read_table(args.train, sep=' '...
Azure/azure-sdk-for-python
sdk/dataprotection/azure-mgmt-dataprotection/azure/mgmt/dataprotection/operations/_operation_status_operations.py
Python
mit
4,607
0.003907
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
"""Gets the operation status for a resource. Gets the operation status for a resource. :param location: :type location: str :param operation_id: :type operation_id: str :keyword callable cls: A custom type or function that will be passed the direct response ...
~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.OperationResource"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) ...
cmjatai/cmj
sapl/parlamentares/migrations/0005_auto_20170814_1615.py
Python
gpl-3.0
480
0.002083
# -*- cod
ing: utf-8 -*- # Generated by Django 1.9.11 on 2017-08-14 16:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parlamentares', '0004_auto_20170711_1305'), ] operations = [ migrations.AlterModelOptions( ...
mentar', 'verbose_name_plural': 'Frentes Parlamentares'}, ), ]
JCH222/matriochkas
matriochkas/tests/ParsingEntities.py
Python
mit
69,308
0.006161
# coding: utf8 from matriochkas.core import ParsingEntities from collections import Counter from threading import Thread from time import sleep import copy ######################################################################################################################## class InstanceParsingEntity(ParsingEnt...
r__(self)
: return '' def __repr__(self): return self.__str__() def __copy__(self): return InstanceParsingEntity(self.name, self.checkReturn) def __deepcopy__(self, memodict={}): return InstanceParsingEntity(self.name, self.checkReturn) def check(self, element, ref_position): ...
tudinfse/fex
core/draw.py
Python
mit
13,949
0.001219
""" Drawing plots """ import logging from abc import ABCMeta, abstractmethod, abstractproperty import matplotlib.pyplot as plt import matplotlib.ticker as plticker import numpy as np from scipy.stats.mstats import gmean from core import prepare from core import styles from config import Config class FexPlot: __...
for key, grp in self.df.groupby(['compilertype']): if not grp.empty: plot = grp.plot( ax=plot, x="tput", y="lat", kind="line", # linestyle=styles.LINE_STYLES[idx], ...
markersize=8, color=style.colors[idx], title="", figsize=figsize, linewidth=3, **kwargs ) labels.append(self.conf.build_names[build_names][key]) idx += 1 # get lin...
wolfram2012/nimo
perception/ros_track_ssd/scripts/detect/detector.py
Python
gpl-3.0
6,261
0.001278
from __future__ import print_function import mxnet as mx import numpy as np from timeit import default_timer as timer from dataset.testdb import TestDB from dataset.iterator import DetIter class Detector(object): """ SSD detector which hold a detection network and wraps detection API Parameters: -----...
Returns: ---------- """ import cv2 dets = self.im_detect(im_list, root_dir, extension, show_timer=show_timer) if not isin
stance(im_list, list): im_list = [im_list] assert len(dets) == len(im_list) for k, det in enumerate(dets): img = cv2.imread(im_list[k]) img[:, :, (0, 1, 2)] = img[:, :, (2, 1, 0)] self.visualize_detection(img, det, classes, thresh)
psiinon/addons-server
src/olympia/amo/tests/test_cron.py
Python
bsd-3-clause
1,830
0
from unittest import mock from olympia.amo.cron import gc from olympia.amo.tests import TestCase from olympia.files.models import FileUpload @mock.patch('olympia.amo.cron.storage') class TestGC(TestCase): def test_file_uploads_deletion(self, storage_mock): fu_new = FileUpload.objects.create(path='/tmp/ne...
FileUpload.objects.create(path='/tmp/older', name='older') fu_older.update(created=self.days_ago(300)) fu_old = FileUpload.objects.create(path='/tmp/old', name='old') fu_old.update(created=self.days_ago(8)) storage_mock.delete.side_effect = OSError gc() # Even though d...
ch corresponding path on # the filesystem. assert FileUpload.objects.count() == 0 assert storage_mock.delete.call_count == 2 assert storage_mock.delete.call_args_list[0][0][0] == fu_older.path assert storage_mock.delete.call_args_list[1][0][0] == fu_old.path
podiobooks/podiobooks
podiobooks/ratings/templatetags/ratings_tags.py
Python
gpl-3.0
778
0
""" Tags used for working with Titles """ from django import template register = template.Library() @register.inclusion_tag('ratings/calculation.html') def show_overall_rating(title): """Calculate the overall rating for a title""" if title.promoter_count < 0: title.promoter_count = 0 title....
ractor_count = 0 title.save() total = title.promoter_count + title.detractor_count if total < 5: return {"rating": None} rating = float(title.promoter_count) / total rating_
range = round(rating, 1) rating = int(rating * 100) rating_range *= 100 if rating > 100: rating = 100 return {"rating": rating, "rating_range": int(rating_range)}
bird-house/emu
tests/common.py
Python
apache-2.0
1,541
0
import os from pywps import get_ElementMakerForVersion from pywps.app.basic import get_xpath_ns from pywps.tests import WpsClient, WpsTestResponse TESTS_HOME = os.path.abspath(os.path.dirname(__file__)) CFG_FILE = os.path.join(TESTS_HOME, 'test.cfg') VERSION = "1.0.0" WPS, OWS = get_ElementMakerForVersion(VERSION) xp...
h_ns = get_xpath_ns(VERSION) def resource_file(filepath): return os.path.join(TESTS_HOME, 'testdata', filepath) class WpsTestClient(WpsClient): def get(self, *args, **kwargs): query = "?" for key, value in kwargs.items(): query += u"{0}={1}&".format(key, value) return su...
client_for(service): return WpsTestClient(service, WpsTestResponse) def get_output(doc): """Copied from pywps/tests/test_execute.py. TODO: make this helper method public in pywps.""" output = {} for output_el in xpath_ns(doc, '/wps:ExecuteResponse' '/wps:Process...
sk2/ank_le
AutoNetkit/plotting/tests/test.py
Python
bsd-3-clause
592
0.008446
import os import AutoNetkit import AutoNetkit.config as config from pkg_resources im
port resource_filename import logging LOG = logging.getLogger("ANK") def test_plot(): inet = AutoNetkit.internet
.Internet("multias") inet.compile() inet.plot() assert(os.path.exists(os.path.join(config.plot_dir, "summary.html"))) js_plot_files = ["arbor.js", "dns_auth.js", "dns.js", "ebgp.js", "ibgp.js", "igp.js", "ip.js", "main.js"] for js_file in js_plot_files: assert(os.path.exists(os.path.join(co...
oslab-fr/lesspass
cli/lesspass/version.py
Python
mit
22
0
__version__ = "
9.1.4"
justayak/fast_guided_filters
test/sample.py
Python
mit
88
0.022727
import sys sys.path.insert(0,'../') from fast_guided_filter import blur print("hel
lo")
bruderstein/PythonScript
PythonLib/full/asyncio/proactor_events.py
Python
gpl-2.0
32,256
0.000155
"""Event loop using a proactor and related classes. A proactor is a "notify-on-completion" multiplexer. Currently a proactor is only implemented on Windows with IOCP. """ __all__ = 'BaseProactorEventLoop', import io import os import socket import warnings import signal import threading import collections from . im...
({ 'message': message, 'exception': exc, 'transport': self, 'proto
col': self._protocol, }) finally: self._force_close(exc) def _force_close(self, exc): if self._empty_waiter is not None and not self._empty_waiter.done(): if exc is None: self._empty_waiter.set_result(None) else: se...
gustavla/autocolorize
autocolorize/config.py
Python
bsd-3-clause
284
0.003521
import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) RES_DIR = os.path.join(SCRIPT_DIR, 'res') WEIGHTS_DIR =
os.path.expanduser('~/.autocoloriz
e') WEIGHTS_URL = 'http://people.cs.uchicago.edu/~larsson/colorization/res/autocolorize.caffemodel.h5' TOTAL_SIZE = 588203256
vied12/superdesk
server/apps/archive/archive_media.py
Python
agpl-3.0
3,616
0.001936
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import loggi...
t in doc or doc['media'] is None: abort(400, description="No media found") file, content_type, metadata = self.get_file_from_document(doc) inserted = [doc['media']] file_type = content_type.s
plit('/')[0] try: update_dates_for(doc) generate_unique_id_and_name(doc) doc['guid'] = generate_guid(type=GUID_TAG) doc.setdefault('_id', doc['guid']) doc['type'] = self.type_av.get(file_type) doc[config.VERSIO...
e-dub/DesOptPy
examples/TestProblemsUnconstrained/Michalewicz.py
Python
gpl-3.0
889
0
# -*- coding: utf-8 -*- """ Michalewicz test function for design optimization xOpt = 0 fOpt = 0.0 """ from DesOptPy import OptimizationProblem import numpy as np class Michalewicz: x = np.zeros( [ 2
, ] ) def SysEq(self): michalewicz_m = 2 n = len(self.x) j = np.arange(1.0, n + 1) self.f = -np.sum( np.sin(self.x) * np.sin(j * self.x ** 2 / np.pi) ** (2.0 * michalewicz_m) ) OptMichalewicz = OptimizationProblem(Michalewicz) OptMichale...
x' OptMichalewicz.x0 = ( np.ones( 2, ) * +0 ) OptMichalewicz.xL = ( np.ones( 2, ) * -5 ) OptMichalewicz.xU = ( np.ones( 2, ) * +5 ) OptMichalewicz.f = 'f' OptMichalewicz.Alg = 'PSQP' OptMichalewicz.optimize() OptMichalewicz.plotConvergence()
sunlightlabs/bulgogi
manage.py
Python
mit
250
0
#!/us
r/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "foreign.settings") from django.core.management import execute_from_command_line execute_from_
command_line(sys.argv)
narurien/ganeti-ceph
lib/cmdlib/test.py
Python
gpl-2.0
12,412
0.006687
# # # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google 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...
RTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Test logical units.""" im...
compat from ganeti import constants from ganeti import errors from ganeti import locking from ganeti import utils from ganeti.masterd import iallocator from ganeti.cmdlib.base import NoHooksLU from ganeti.cmdlib.common import ExpandInstanceUuidAndName, GetWantedNodes, \ GetWantedInstances class LUTestDelay(NoHooksL...
DarthVeder/daFre
split.py
Python
gpl-3.0
12,276
0.011567
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import re import writeXml import io import logging import collections import os from mutagen.mp3 import MP3 dictionary = { 'eng': [u'and', u'of', u'the', u'to', u'and' , u'from'], 'fra': [u'et']} def maxSplit(language, p): ...
, p) if len(cks) > n_split: n_split = len(cks) k_n = k split_command = r' \b(?=\b' + k_n + r')+' return re.split(split_command, p) def split(language, unit, page, dialogue_title, file_name, flag, use_dictionary): """ This function split...
e syntacti rules and following a dictionary. It also calls the synchornization library aeneas """ # Storing the ordered name of the characters character_name = collections.OrderedDict() # text spoken by each character (character_name, line_number) speech_text_lines = [] to...
vijayendrabvs/ssl-python-neutronclient
neutronclient/neutron/v2_0/quota.py
Python
apache-2.0
8,697
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...
id(parsed_args.tenant_id, neutron_client) data = obj_updator(tenant_id, body) if self.res
ource in data: for k, v in data[self.resource].iteritems(): if isinstance(v, list): value = ""
DVSBA/ajenti
plugins/network/nctp_bsd.py
Python
lgpl-3.0
2,275
0.008352
import time from ajenti.com import * from ajenti.ui import * from ajenti.utils import shell, str_fsize class BSDIfconfig(Plugin): platform = ['FreeBSD'] def get_info(self, iface): ui = UI.Container( UI.Formline( UI.HContainer( UI.Image(...
UI.Label(tex
t='Up %s, down %s' % ( str_fsize(self.get_tx(iface)), str_fsize(self.get_rx(iface)), )), text='Traffic', ), ) return ui def get_tx(self, iface): s = shell('netstat -bI...
Kongsea/tensorflow
tensorflow/python/keras/_impl/keras/engine/training.py
Python
apache-2.0
98,431
0.005821
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
check_batch_axis=True, exception_prefix=''): """Normalizes inputs and targets provided by users. Users may pass data as a list of arrays, dictionar
y of arrays, or as a single array. We normalize this to an ordered list of arrays (same order as `names`), while checking that the provided arrays have shapes that match the network's expectations. Arguments: data: User-provided input data (polymorphic). names: List of expected array names. s...
tjcsl/ion
intranet/apps/eighth/tests/admin/test_admin_activities.py
Python
gpl-2.0
13,432
0.003797
from django.contrib.auth import get_user_model from django.urls import reverse from django.utils import timezone from intranet.apps.groups.models import Group from ...models import EighthActivity, EighthBlock, EighthRoom, EighthScheduledActivity, EighthSponsor from ..eighth_test import EighthAbstractTest class Eigh...
ep room history" page self.assertTemplateUsed(response, "eighth/admin/keep_room_history.html") # Say "yes" - i.e. have the extra room only apply for new activities response = self.client.post( reverse("eighth_admin_edit_activity", kwargs={"activity_id": activity.id}), da...
"default_capacity": 7, "sticky": "sticky", "wed_a": "on", "fri_b": "on", "restricted": "on", "sponsors": [sponsor.id], "rooms": [room1.id, room2.id], "change_room_history": "yes", }, ...
JaniszM/easylife
easylife/photo_organizer/run_photo_organizer.py
Python
mit
6,785
0.002948
import os import re import logging import exifread import shutil import platform from datetime import datetime from shutil import copy2 from easylife import get_logger from easylife.photo_organizer import PHOTO_EXTENSIONS, VIDEO_EXTENSIONS, METADATA_EXTENSIONS, PATTERN, \ DEFAULT_COPY_DIR, FILE_DATE_FORMAT, LOG_FI...
ield and convert to datetime try: exif_info = str(exif_info['EXIF DateTimeOriginal']) exif_info = datetime.strptime(exif_info, FILE_DATE_FORMAT) return template_to_path(template, destination, os.path.basename(s
rc), exif_info) except KeyError: LOG.info('Missing exif DateTimeOriginal tag for %s. Reading date from system file property...', src) return build_new_file_destination(template, src, destination) def build_new_file_destination(template, src, destination): """ Builds new path and filename f...
fbradyirl/home-assistant
homeassistant/components/axis/__init__.py
Python
apache-2.0
2,370
0
"""Support for Axis devices.""" import voluptuous as vol from homeassistant import config_entries from homeassistant.const import ( CONF_DEVICE, CONF_MAC, CONF_NAME, CONF_TRIGGER_TIME, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.helpers import config_validation as cv from .config_flow import D...
for Axis devices.""" if not hass.config_entries.async_entries(DOMAIN) and DOMAIN in config: for device_name, device_config in config[DOMAIN].items(): if CONF_NAME not in device_config: device_config[CONF_N
AME] = device_name hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT}, data=device_config, ) ) return True async def async_setup_...
SahSih/ARStreaming360Display
RealTimeVideoStitch/realtime-panorama-stitching/hello.py
Python
mit
188
0.047872
from fl
ask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == '__main__': app.debug = True app.run(host = '0.0.0.0', port = 5000)
DeveloperMal/wger
wger/manager/migrations/0006_auto_20160303_2138.py
Python
agpl-3.0
986
0.002028
# -*- coding: utf-8 -*- from __future__ import
unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0009_auto_20160303_2340'), ('manager', '0005_auto_20160303_2008'), ] operations = [ migrations.RenameField( model_name='setting', o...
t', ), migrations.RenameField( model_name='workoutlog', old_name='unit', new_name='repetition_unit', ), migrations.AddField( model_name='setting', name='weight_unit', field=models.ForeignKey(verbose_name='Unit', to='...
tedlaz/pyted
tests/mvc/view_form.py
Python
gpl-3.0
2,609
0
# -*- coding: utf-8 -*- """viewform module""" import PyQt5.QtWidgets as Qw class ViewForm(Qw.QDialog): def __init__(self, idx, parent=None): # Qw.QDialog.__init__(self, parent) super().__init__(parent) self.setWindowTitle('ViewForm') self._dataMapper = Qw.QDataWidgetMapper() ...
self.accept() def close
Event(self, event): # self.saveit() pass
mozilla/firefox-flicks
vendor-local/lib/python/billiard/reduction.py
Python
bsd-3-clause
5,061
0.00079
# # Module to allow connection and socket objects to be transferred # between processes # # multiprocessing/reduction.py # # Copyright (c) 2006-2008, R Oudkerk # Licensed to PSF under a Contributor Agreement. # from __future__ import absolute_import __all__ = [] import os import sys import socket import threading f...
(conn): rh = reduce_handle(conn.fileno()) return rebuild_connection, (rh, conn.readable, conn.writable) def rebuild_connection(reduced_handle, readable, writable): handle = rebuild_handle(reduced_ha
ndle) return _billiard.Connection( handle, readable=readable, writable=writable ) ForkingPickler.register(_billiard.Connection, reduce_connection) # # Register `socket.socket` with `ForkingPickler` # def fromfd(fd, family, type_, proto=0): s = socket.fromfd(fd, family, type_, proto) if s...
devdelay/home-assistant
homeassistant/components/sensor/speedtest.py
Python
mit
4,705
0
""" Support for Speedtest.net based on speedtest-cli. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.speedtest/ """ import logging import re import sys from subprocess import check_output, CalledProcessError import homeassistant.util.dt as dt_uti...
day=config.get(CONF_DAY, None)) def update(self, now): """Get the latest data from speedtest.net.""" import speedtest_cli _LOGGER.info('Executing speedtest') try: re_output = _SP
EEDTEST_REGEX.split( check_output([sys.executable, speedtest_cli.__file__, '--simple']).decode("utf-8")) except CalledProcessError as process_error: _LOGGER.error('Error executing speedtest: %s', process_error) return self.data = {'pi...
masschallenge/django-accelerator
accelerator_abstract/models/base_application_answer.py
Python
mit
985
0
from __future__ import unic
ode_literals import swapper from django.db import models from accelerator_abstract.models.accelerator_model import AcceleratorModel class BaseApplicationAnswer(AcceleratorModel): application = models.ForeignKey(to=swapper.get_model_name( AcceleratorModel.Meta.app_label, "Application"), on_delete...
ame( AcceleratorModel.Meta.app_label, 'ApplicationQuestion'), on_delete=models.CASCADE) answer_text = models.TextField(blank=True) class Meta(AcceleratorModel.Meta): verbose_name_plural = 'Application Answers' db_table = 'accelerator_applicationanswer' abstract = True ...
GNOME/conduit
conduit/modules/ShutterflyModule/ShutterflyModule.py
Python
gpl-2.0
3,019
0.049685
""" Shutterfly Data Sink """ import logging log = logging.getLogger("modules.Shutterfly") import conduit import conduit.utils as Utils from conduit.datatypes import Rid import conduit.dataproviders.Image as Image import conduit.Exceptions as Exceptions import conduit.datatypes.Photo as Photo Utils.dataprovider_add_di...
k.get(self, LUID) sphoto = self.sphotos[LUID] f = Photo.Photo(URI=sphoto.url) f.set_open_URI(sphoto.url) f.set_UID(LUID) return f def delete(self, LUID): """ Delete a photo by ID Deleting a photo invalidates album length and photo index values. We must reload the photos (or do something else...) ...
t self.sphotos.has_key(LUID): log.warn("Photo does not exist") return try: self.salbum.deletePhoto(self.sphotos[LUID]) except Exception, e: raise Exceptions.SyncronizeError("Shutterfly Delete Error - Try Again.") self.sphotos = self.salbum.getPhotos() def _upload_photo(self, uploadInfo): """ ...
flamholz/equilibrator
matching/matcher.py
Python
mit
7,321
0.007376
import itertools, logging from gibbs.models import CommonName, Compound, Enzyme from haystack.query import SearchQuerySet class Error(Exception): pass class IllegalQueryError(Error): pass class Match(object): """An object containing a string match and it's score.""" def __init__(self, key, va...
return self.value.kegg_id elif self.IsEnzyme(): return self.value.ec return None class Matcher(object): """A class that matches a string against the database. The base implementation does exact matching. "
"" def __init__(self, max_results=10, min_score=0.0, match_enzymes=True): """Initializes the Matcher. Args: scorer: a MatchScorer object for scoring. max_results: the maximum number of matches to return. min_score: the minimum match score to return. ...
auag92/n2dm
Asap-3.8.4/Test/RawRDF.py
Python
mit
2,771
0.009383
"Test the RawRadialDistributionFunction function." from numpy import * from asap3 import * from asap3 import _asap from ase.lattice.cubic import FaceCenteredCubic from asap3.testtools import * from asap3.Internal.ListOfElements import ListOfElements print_version(1) # testtypes: latticeconst, maxRDF, bins, useEMT te...
of atoms", natoms, 4000, 0) if withemt: atoms.set_calculator(EMT()) print atoms.get_potential_energy() result = _asap.RawRDF(atoms, maxrdf, nbins, zeros(len(atoms), i
nt32), 1, ListOfElements(atoms)) z = atoms.get_atomic_numbers()[0] globalrdf, rdfdict, countdict = result print globalrdf ReportTest("Local and global RDF are identical", min( globalrdf == rdfdict[0][(z,z)]), 1, 0) ReportTest("Atoms are counted correctly",...
janverschelde/PHCpack
src/Python/PHCpy2/phcpy/series.py
Python
gpl-3.0
26,702
0.002884
""" The module series exports functions to compute power series solutions with Newton's method in double, double double, or quad double precision. """ def replace_symbol(pol, idx): """ In the polynomial pol, replaces the first symbol by the symbol at place idx. """ from phcpy.phcpy2c2 import py2c_...
if size == -1: print "An error occurred in the execution of Newton's method." else: print "Computed %d series solutions." % size result = [] for k in range(1, size+1): py2c_syspool_copy_to_dobldobl_container(k) sersol = load_dobldobl_system() result.append...
ersol, idx)) py2c_syspool_dobldobl_clear() return result def quaddobl_newton_series(pols, sols, idx=1, maxdeg=4, nbr=4, verbose=True): r""" Computes series in quad double precision for the polynomials in *pols*, where the leading coefficients are the solutions in *sols*. On entry are the follow...
Onager/plaso
plaso/multi_processing/task_manager.py
Python
apache-2.0
20,352
0.007174
# -*- coding: utf-8 -*- """The task manager.""" import collections import heapq import threading import time from dfvfs.lib import definitions as dfvfs_definitions from plaso.containers import tasks from plaso.lib import definitions from plaso.engine import processing_status from plaso.engine import profilers from p...
le_size: raise ValueError('Task storage file size not set.') if task.file_entry_type == dfvfs_definitions.FIL
E_ENTRY_TYPE_DIRECTORY: weight = 1 else: weight = storage_file_size task.merge_priority = weight heap_values = (weight, task) heapq.heappush(self._heap, heap_values) self._task_identifiers.add(task.identifier) class TaskManager(object): """Manages tasks and tracks their completion ...
viccro/diarc
fabrik/flowlabel.py
Python
apache-2.0
1,392
0.005029
# Copyright 2014 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 ...
(_)(\d+$)", flowlabel) if len(result) == 0: raise Exception("Inva
lid flowlabel %s"%flowlabel) return (int(result[0][0]), int(result[0][2])) def gen_flowlabel(origin_index, destination_index): """ generate a flowlabel """ return "%d_%d"%(origin_index, destination_index)
luispedro/imread
imread/ijrois.py
Python
mit
3,061
0.0049
# Copyright: Luis Pedro Coelho <luis@luispedro.org>, 2012-2018 # License: MIT import numpy as np def read_roi(fileobj): ''' points = read_roi(fileobj) Read ImageJ's ROI format Parameters ---------- fileobj: should be a file-like object Returns ------- points: a list of points ...
nts[:,1] += left points[:,0] += top points -= 1 return points def read_roi_zip(fname): ''' Reads all ROIs in a ZIP file Parameters ---------- fname : str Input filename Returns ------- rois: list of ROIs Each ROI is a vec
tor of 2D points See Also -------- read_roi: function, reads a single ROI ''' import zipfile with zipfile.ZipFile(fname) as zf: return [read_roi(zf.open(n)) for n in zf.namelist()]
flavour/helios
modules/ClimateDataPortal/DSL/Check.py
Python
mit
6,119
0.005556
import datetime from . import * check = Method("check") # checks arguments are correct type and in range only. def month_number_from_arg(month, error): try: month_number = Months.options[month] except KeyError: error( "Months should be e.g. Jan/January or numbers " "in...
number): if
positive_number.units._positive and positive_number.value < 0: positive_number.errors = ["Affine Numbers must be positive"] else: positive_number.errors = [] return positive_number.errors check_analysis = Method("check_analysis") @check_analysis.implementation(Number) def Number_check_analysi...
FedoraScientific/salome-yacs
src/pyqt/gui/graph.py
Python
gpl-2.0
12,360
0.042799
# Copyright (C) 2006-2014 CEA/DEN, EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library ...
.citems[item.node.ptr()]=node node.show() self.canvas.update() def selectItem(self,item): #print "graph.selectItem",item self.editor.selectItem(item) def layout(self,rankdir): """Compute graph layout with graphviz package""" G=pygraphviz.AGraph(strict=False,directed=True) G.graph_attr[...
2. aspect=dpi/72 for k,n in self.citems.items(): #k is node address (YACS) #n is item in canvas G.add_node(k) for pout,pin in self.node.getSetOfInternalLinks(): if pout.getNode().ptr() not in self.citems : continue if pin.getNode().ptr() not in self.citems: con...
MengGuo/Jackal_Velodyne_Duke
xbee_communication/XBee-2.2.3/xbee/tests/test_base.py
Python
gpl-2.0
5,670
0.002116
#! /usr/bin/python """ test_xbee.py By Paul Malmsten, 2010 pmalmsten@gmail.com Tests the XBeeBase superclass module for XBee API conformance. """ import unittest from xbee.base import XBeeBase from xbee.tests.Fake import FakeDevice, FakeReadDevice class TestWriteToDevice(unittest.TestCase): """ XBeeBase clas...
f.fail("Shorthand call on XBeeBase base class should raise NotImplementedError
") class TestAsyncCallback(unittest.TestCase): """ XBeeBase constructor should accept an optional callback function argument. When provided, this will put the module into a threaded mode, in which it will call the provided function with any API frame data received. As it would be very difficul...
vijaysm/mmodel-software-analysis
contrib/metrixplusplus-1.3.168/tests/common.py
Python
mit
11,187
0.009833
# # Metrix++, Copyright 2009-2013, Metrix++ Project # Link: http://metrixplusplus.sourceforge.net # # This file is a part of Metrix++ Tool. # # Metrix++ is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
d tool_name == 'collect')) and os.path.exists(db_file): os.unlink(db_file) db_file_prev = os.path.join(os.environ['METRIXPLUSPLUS_INSTALL_DIR'], self.su
ite_location, test_name + ".prev.db") self.dbfile_prev = db_file_prev if (remove_exiting_dbfile_prev == True or (remove_exiting_dbfile_prev == None and tool_name == 'collect')) and os.path.exists(db_file_prev): os.unlink(db_file_prev) self.cwd = cwd db_opts = ['--db-...
chair6/bandit
examples/ssl-insecure-version.py
Python
apache-2.0
892
0.004484
import ssl from pyOpenSSL import SSL ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv2) SSL.Context(method=SSL.SSLv2_METHOD) SSL.Context(method=SSL.SSLv23_METHOD) herp_derp(ssl_version=ssl.PROTOCOL_SSLv2) herp_derp(method=SSL.SSLv2_METHOD) herp_derp(
method=SSL.SSLv23_METHOD) # strict tests ssl.wrap_socket(ssl_version=ssl.PROTOCOL_SSLv3) ssl.wrap_socket(ssl_version=ssl.PROTOCOL_TLSv1) SSL.Context(method=SSL.SSLv3_METHOD) SSL.Context(method=SSL.TLSv1_METHOD) herp_derp(ssl_version=ssl.PROTOCOL_SSLv3) herp_derp(ssl_version=ssl.PROTOCOL_TLSv1) herp_derp(method=SSL.SS...
.SSLv2_METHOD): pass def open_ssl_socket(version=SSL.SSLv23_METHOD): pass # this one will pass ok def open_ssl_socket(version=SSL.TLSv1_1_METHOD): pass