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
UMD-SEAM/bugbox
framework/Exploits/Bugtraq_54330.py
Python
bsd-3-clause
1,719
0.009889
# Copyright 2013 University of Maryland. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE.TXT file. import sys import os import time import selenium.common.exceptions from selenium.common.exceptions import NoAlertPresentException import framework...
lert.
text self.verified = True break except NoAlertPresentException: tries -= 1 time.sleep(1) if self.visible: time.sleep(10) driver.cleanup() return def verify(self): return self.verified
rtilder/shavar-list-creation
lists2safebrowsing.py
Python
mpl-2.0
13,448
0.019557
#!/usr/bin/env python import ConfigParser import hashlib import json import os import re import sys import tempfile import time import urllib2 import urlparse import boto.s3.connection import boto.s3.key # bring a URL to canonical form as described at # https://developers.google.com/safe-browsing/developers_guide_v2...
est()); publishing += 1 domain_dict[canon_d] = 1; hashdata_bytes += 32; output.append(hashlib.sha256(canon_d).digest());
# Write safebrowsing-list format header if output_file: output_file.write("a:%u:32:%s\n" % (chunk, hashdata_bytes)); output_string = "a:%u:32:%s\n" % (chunk, hashdata_bytes); for o in output: if output_file: output_file.write(o); output_string = output_string + o print "Tracking protection(...
tomka/CATMAID
django/applications/catmaid/fields.py
Python
gpl-3.0
15,358
0.002409
# -*- coding: utf-8 -*- import psycopg2 from psycopg2.extensions import register_adapter, adapt, AsIs from psycopg2.extras import CompositeCaster, register_composite import re from typing import Any, ClassVar, Dict from django import forms from django.contrib.postgres.fields import ArrayField from django.contrib.post...
connection.cursor().cursor, globally=True, factory=klass.factory_class() ).type except psycopg2.ProgrammingError: _missing_types[db_type] = cls else: def adapt_composite(composite): ...
# that those can be escaped rather than relying on # `__str__`. return AsIs("(%s)::%s" % ( ", ".join([ adapt(getattr(composite, field)).getquoted().decode('utf-8') for field in cls.python_type._fields ...
AlpacaDB/chainer
chainer/testing/helper.py
Python
mit
829
0
import pkg_resources import unittest def with_requires(*requirements): """Run a test case only when given requirements are satisfied. .. admonition:: Example This test case runs only when `numpy>=1.10` is
installed. >>> from chainer import testing ... class Test(unittest.TestCase): ... @testing.with_requires('numpy>=1.10') ... def test_for_numpy_1_10(self): ... pass Args: requirements: A list of string representing requirement condition to run...
t() try: ws.require(*requirements) skip = False except pkg_resources.VersionConflict: skip = True msg = 'requires: {}'.format(','.join(requirements)) return unittest.skipIf(skip, msg)
elakamarcus/python
class-inheritance_02.py
Python
gpl-3.0
3,445
0.004354
#!/bin/python3 class SpaceShip: def __init__(self, id, health, x, y): self.id = id self.health = int(health) self.x = x self.y = y def __del__(self): print("{} was destroyed.".format(self.id)) del self def takeDMG(self, hit): self.health -= hit ...
print("| Ship location: {}, {}".format(self.x, self.y)) print("|------------------") class Destroyer(SpaceShip): def __init__(self, id, health, x, y, weapon, ammo): super().__init__(id, health, x, y) self.weapon = weapon self.ammo = ammo self.shipclass = "Destroyer" ...
"| Ship type :", self.shipclass) print("| Ship location: ({}, {})".format(self.x, self.y)) print("| Ship armament:", self.weapon) print("| Ship ammo : {}%".format(self.ammo)) print("| Ship health : {}%".format(self.health)) print("|----------------------------") d...
jduan/jenkinsapi
jenkinsapi_tests/unittests/test_nodes.py
Python
mit
8,323
0.000481
import mock # To run unittests on python 2.6 please use unittest2 library try: import unittest2 as unittest except ImportError: import unittest from jenkinsapi.jenkins import Jenkins from jenkinsapi.nodes import Nodes from jenkinsapi.node import Node class TestNode(unittest.TestCase): DATA0 = { ...
//halob:8080/'}, 'quietingDown': False, 'slaveAgentPort': 0, 'unlabeledLoad': {}, 'useCrumbs': False, 'useSecurity': False, 'views': [ {'name': 'All', 'url': 'http://halob:8080/'}, {'name': 'FodFanFo', 'url': 'http://halob:8080/view/FodFanFo/'} ...
', 'executors': [{}, {}], 'icon': 'computer.png', 'idle': True, 'jnlpAgent': False, 'launchSupported': True, 'loadStatistics': {}, 'manualLaunchAllowed': True, 'monitorData': { ...
OpenSight/StreamSwitch
controller/python/streamswitch/wsgiapp/models.py
Python
agpl-3.0
6,163
0.003894
""" streamswitch.wsgiapp.models ~~~~~~~~~~~~~~~~~~~~~~~ This module implements the domain models for the WSGI application, based on the SQLAlchemy's ORM :copyright: (c) 2015 by OpenSight (www.opensight.cn). :license: AGPLv3, see LICENSE for more details. """ from __future__ import unicode_literals, division from sql...
extra_option
s_json) self.other_kwargs = json.loads(self.other_kwargs_json) # print("init_on_load") def __repr__(self): return "SenderConf Object(sender_name:%s, sender_type:%s, " \ "dest_url:%s, stream_name:%s, stream_host:%s, stream_port:%d)" % ( self.sender_name, self.send...
andrewzwicky/puzzles
CodeEval/test_challenge_7.py
Python
mit
289
0.00346
from unittest import TestCase from CodeEval.challenge_7 import chal
lenge class Chall
enge7Test(TestCase): def test_input_1(self): self.assertEqual(5, challenge("- * / 15 - 7 + 1 1 3 + 2 + 1 1")) def test_input_2(self): self.assertEqual(20, challenge("* + 2 3 4"))
web2py/pydal
pydal/contrib/mockimaplib.py
Python
bsd-3-clause
10,686
0.001684
# -*- encoding: utf-8 -*- from imaplib import ParseFlags # mockimaplib: A very simple mock server module for imap client APIs # Copyright (C) 2014 Alan Etkin <spametki@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public Li...
if query.strip().isdigit(): return [ self.spam[self._mailbox][int(query.strip()) - 1], ] elif query[1
:-1].strip().isdigit(): return [ self.spam[self._mailbox][int(query[1:-1].strip()) - 1], ] elif query[1:-1].replace("UID", "").strip().isdigit(): for item in self.spam[self._mailbox]: if item["uid"] == query[1:-1].replace("UID", "").strip(): ...
finder/mako_base
urls.py
Python
mit
770
0.018182
from django.conf.urls.defaults import * from django.conf import settings import base # Uncomment the next two lines to
enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^quotes/', include('quotes.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', ...
# Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^$', base.views.home), ) if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.MEDIA_ROOT}) )
olysonek/tuned
tuned/plugins/__init__.py
Python
gpl-2.0
49
0
from
.repository import * from . import instance
allcaps/wagtail-robot-nao
wagtailrobot/home/models.py
Python
bsd-3-clause
1,051
0.000951
from __future__ import absolute_import, unicode_literals from django import forms from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.wagtailcore.blocks import ( FieldBlock,
RichTextBlock, StreamBlock, StructBlock, ) from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore.models import Page as BasePage from wagtail.wagtailimages.blocks import ImageChooserBlock from wagtail.wagtailsearch import index class ImageBlock(StructBlock): image = ImageChooserBlock(...
ocks/image_block.html' class webappStreamBlock(StreamBlock): intro = RichTextBlock(icon="pilcrow") paragraph = RichTextBlock(icon="pilcrow") image = ImageBlock(label="Image", icon="image") class Page(BasePage): body = StreamField(webappStreamBlock()) search_fields = BasePage.search_fields + [ ...
matrix-org/pymacaroons
pymacaroons/field_encryptors/secret_box_encryptor.py
Python
mit
1,205
0
from base64 import standard_b64encode, standard_b64decode import nacl.bindings import nacl.utils from nacl.secret import SecretBox from pymacaroons.field_encryptors.base_field_encryptor import ( BaseFieldEncryptor ) from pymacaroons.utils import ( truncate_or_pad, convert_to_bytes, convert_to_string ) class...
nonce=None): super(SecretBoxEncryptor, self).__init__( signifier=signifier or 'sbe::' ) self.nonce = nonce or nacl.utils.random( nacl.bindings.crypto_secretbox_NONCEBYTES ) def encrypt(self, signature, field_data): encrypt_key = truncate_or_pad(signat...
fier + standard_b64encode(encrypted) def decrypt(self, signature, field_data): key = truncate_or_pad(signature) box = SecretBox(key=key) encoded = convert_to_bytes(field_data[len(self.signifier):]) decrypted = box.decrypt(standard_b64decode(encoded)) return convert_to_string...
printedheart/h2o-3
h2o-docs/src/booklets/v2_2015/source/deeplearning/deeplearning_inspect_model.py
Python
apache-2.0
369
0.00271
# View
the specified parameters of your deep learning model model.params # Examine the performance of the trained model model # display all performance metrics model.model_performance(train=True) # training set metrics model.model_performance(valid=True) # val
idation set metrics # Get MSE only model.mse(valid=True) # Cross-validated MSE model_cv.mse(xval=True)
QuantCrimAtLeeds/PredictCode
tests/gui/tk/date_picker_test.py
Python
artistic-2.0
2,322
0.004737
import pytest import unittest.mock as mock import datetime import open_cp.gui.tk.date_picker as date_picker @pytest.fixture def dp(): with mock.patch("open_cp.gui.tk.date_picker._DatePickerView") as clazzmock: yield date_picker.DatePicker() def test_days_to_text(dp): import locale if locale.getde...
and = cmd d = datetime.date(year=2011, month=5, day
=23) dp.selected_date = d cmd.assert_called_once_with(d) def test_set_colour(dp): dp.selected_colour = "#aa66ff" assert dp.selected_colour == "#aa66ff" dp._view.make_date_grid.assert_called_once_with()
icoxfog417/pykintone
tests/test_comment.py
Python
apache-2.0
1,667
0.000612
# -*- coding: utf-8 -*- import unittest import pykintone from pykintone.model import kintoneModel import tests.envs as envs class TestAppModelSimple(kintoneModel): def __init__(self): super(TestAppModelSimple, self).__init__() self.my_key = "" self.stringField = "" class TestComment(uni...
rator", "USER")]) self.assertTrue(r_created_m.ok) # select comment r_selected = app.comment(_record_id).select(True, 0, 10) self.assertTrue(r_selected.ok) self.assertTrue(2, len(r_selected.raw_comments)) comments = r_selected.comments() self.assertTru
e(1, len(comments[-1].mentions)) # delete comment for c in comments: r_deleted = app.comment(_record_id).delete(c.comment_id) self.assertTrue(r_deleted.ok) r_selected = app.comment(_record_id).select() self.assertEqual(0, len(r_selected.raw_comments)) # ...
gwpy/gwsumm
gwsumm/html/tests/test_static.py
Python
gpl-3.0
1,947
0
# -*- coding: utf-8 -*- # Copyright (C) Alex Urban (2019) # # This file is part of GWSumm. # # GWSumm 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 ...
tance(css, OrderedDict) # test dict keys assert list(
css.keys()) == [ 'font-awesome', 'font-awesome-solid', 'gwbootstrap', ] # test list of files css_files = list(x.split('/')[-1] for x in css.values()) assert css_files == [ 'fontawesome.min.css', 'solid.min.css', 'gwbootstrap.min.css', ] def test_get_...
bishalkc/portal-andino-theme
ckanext/gobar_theme/controller.py
Python
agpl-3.0
3,532
0.001699
from ckan.controllers.home import HomeController from ckan.controll
ers.api import ApiController from ckan.common import c import ckan.logic as logic import ckan.model as model import ckan.lib.base as base import json import ckan.plugins as p from ckanext.googleanalytics.controller import GAApiController class GobArHomeController(HomeController): def _list_groups(self): c...
el': model, 'session': model.Session, 'user': c.user or c.author } data_dict_page_results = { 'all_fields': True, 'type': 'group', 'limit': None, 'offset': 0, } return logic.get_action('group_list')(context, data_dic...
kusm/dnschecker
config.py
Python
mit
750
0
#! /usr/bin/env python # coding:utf-8 # レコードファイルがあるディレクトリ # デフォルトではこのスクリプトファイルが存在する # ディレクトリにある zones/ 以下に配置する zone_dir = "testzones" # 生成した
HTML をおくディレクトリ html_dir = "build" # レコードに関する情報をおいているディレクトリ record_info_dir = "testzones" # A レコードのゾーンファイル名 a_record_filenames = [ "example.jp.zone", ] # PTR レコードのゾーンファイル名そのネットワーク ptr_record_filename_networks = [ ('19
2.168.0.rev', '192.168.0.0/24'), ] # レコード情報を納めたファイル record_info_filenames = [ '192.168.0.info', ]
aserebryakov/godville-monitor-console
monitor/status_processing/__init__.py
Python
gpl-2.0
23
0
from .r
ule import Rule
googleapis/python-bigquery
samples/magics/conftest.py
Python
apache-2.0
1,166
0
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
er the License. import pytest interactiveshell = pytest.importorskip("IPython.terminal.interactiveshell") tools = pytest.importorskip("IPython.testing.tools") @pytest.fixture(scope="session") def
ipython(): config = tools.default_config() config.TerminalInteractiveShell.simple_prompt = True shell = interactiveshell.TerminalInteractiveShell.instance(config=config) return shell @pytest.fixture(autouse=True) def ipython_interactive(ipython): """Activate IPython's builtin hooks for the du...
kf5grd/push2clip
setup.py
Python
gpl-3.0
357
0.014006
from setuptools import setup setup( name='push2clip', version='0.1', py_modules= ['push2
clip'], install_requires=[ 'Click', 'requests', ], entry_points=''' [console_scripts] push2clip=push2clip:cli ''', )
mahabs/nitro
nssrc/com/citrix/netscaler/nitro/resource/stat/pq/pq_stats.py
Python
apache-2.0
5,276
0.039803
# # Copyright (c) 2008-2015 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
s: basic = "basic" full = "full" class pq_response(base_response) : def __init__(self, length=1) : self.pq = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.pq = [pq_stats() for _
in range(length)]
rumblesan/diddy-vm
puff/tokens.py
Python
mit
598
0
#!/usr/bin/env python def NUMBER(value): return ("NUMBER", value) def NAME(value): return ("NAME", value) def SYMBOL(value): return ("SYMBOL", value) def SEMICOLON(): return ("SEMICOLON", ) def OPENPAREN(): return ("OPENPAREN",
) def CLOSEPAREN(): return ("CLOSEPAREN
", ) def OPENBRACKET(): return ("OPENBRACKET", ) def CLOSEBRACKET(): return ("CLOSEBRACKET", ) def ASSIGNMENT(): return ("ASSIGNMENT", ) def EOF(): return ("EOF", ) def FUNCTIONDEF(): return ("FUNCTIONDEF", ) def FUNCTIONRETURN(): return ("FUNCTIONRETURN", )
beeryardtech/scripts
python/dk_test/libs/nodes.py
Python
apache-2.0
3,032
0.033971
#------------------------------------------------------------------------------- # Name: nodes #------------------------------------------------------------------------------- from __future__ import with_statement __author__ = "Travis Goldie" __email__ = "test_automation@us.sios.com" __date__ = ...
propName.lower(), cleanValue(prop)) for propName, prop in self.properties ) #If any of these props are in self.properties, #create key and set to a default value (or to blank) self.props["hostname"] = self.props.get("hostname", self.nodeName) #List of possible names or IDs to id the node s...
self.props.get("privateip")] self.volsformirror = self._loadVolsForMirror() #self.sharedformirror = self._loadSharedForMirror() self.allVols = self.volsformirror pass #--------------------------------------------------------------------------- # Local get functi...
bozzzzo/quark
quarkc/test/emit/expected/py/int-methods/setup.py
Python
apache-2.0
242
0
# Setup file for package int_methods from setuptools
import setup setup(name="int_methods", version="0.0.1", install_requires=["quark==0.0.1"], py_modules=['int_met
hods'], packages=['int_methods', 'int_methods_md'])
CiscoSystems/tempest
tempest/scenario/test_minimum_basic.py
Python
apache-2.0
5,548
0
# Copyright 2013 NEC Corporation # 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 ...
p['ip']) self.nova_reboot() self.linux_client = self.get_remote_client(self.floating_i
p['ip']) self.check_partitions()
tvwenger/galfacts
find_sources.py
Python
mit
6,373
0.01067
""" find_sources.py Find sources in GALFACTS transient search 03 June 2014 - Trey Wenger - creation 12 June 2014 - Trey Wenger - fixed smoothing convolution normalization bug in beam.py """ vers = "v1.0.1" import sys import os import argparse import numpy as np import beam def main(**opti...
e=float,nargs=7, help='RA beam location correction', metavar=("BEAM0","BEAM1","BEAM2","BEAM3", "BEAM4","BEAM5","BEAM6"), default=[0.,2.7417,5.4833,2.7417,-2.7417, -5.4833,-...
='number of channels in observation', default=2048) semi_opt.add_argument('--bin_width',type=float, help='width of analysis bins in MHz', default=5.) semi_opt.add_argument('--band_width',type=float, help='wid...
goru47/INF1L-PRJ-2
INF1L-PRJ-2/BattlePortDatabase.py
Python
mit
2,314
0.013829
#import modules import psycopg2 # Connect to database connection = psycopg2.connect(database="BattlePort", user="postgres", password="ivo123", host="127.0.0.1", port="5433") print ("Opened database successfully") cursor = connection.cursor() # Tabel aanmaken def create_table(): cursor.execute("CREATE ...
1]) print("Score = ", row[2], "\n") print("----------------------------------") # database lezen def read_database(zoekopdracht): cursor.execute(zoekopdracht)#selecteren #rows = cursor.fetchall()# kopieeren for row in cursor.fetchal
l(): print(row) #create_table() #data_entry(730, 'jan', 304) #data_entry(675, 'guus', 5677) #kweerie("SELECT * FROM scores WHERE score > 9000") #kweerie("SELECT * FROM scores WHERE score > 5000 AND score < 9000") #kweerie("SELECT * FROM scores WHERE score < 5000") #kweerie("SELECT * FROM sco...
buchuki/prickle
prickle/controllers/projects.py
Python
agpl-3.0
2,138
0.000935
# Copyright 2010-2011 Dusty Phillips # This file is part of Prickle. # Prickle is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version....
create(name=id) return render('/project/project_form.html')
@validate(schema=RateForm, form='view') def edit(self, id): project, created = Project.objects.get_or_create(name=id) project.rate = self.form_result['rate'] project.save() return redirect(url(controller="timesheet", action="index")) @validate(schema=RateForm, form='view') ...
Insanityandme/dotfiles
vim/bundle/ultisnips/pythonx/UltiSnips/snippet/definition/_base.py
Python
unlicense
14,330
0.000349
#!/usr/bin/env python # encoding: utf-8 """Snippet representation after parsing.""" import re import vim import textwrap from UltiSnips import _vim from UltiSnips.compatibility import as_unicode from UltiSnips.indent_util import IndentUtil from UltiSnips.text import escape from UltiSnips.text_objects import Snippet...
s,%s)' % ( self._priority, self._trigger, self._description, self._opts) def _re_matc
h(self, trigger): """Test if a the current regex trigger matches `trigger`. If so, set _last_re and _matched. """ for match in re.finditer(self._trigger, trigger): if match.end() != len(trigger): continue else: self._matched = tri...
tmerrick1/spack
var/spack/repos/builtin/packages/fyba/package.py
Python
lgpl-2.1
2,243
0.000446
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
t find install-sh or install.sh force_autoreconf = True depends_on('autoconf', type='bu
ild') depends_on('automake', type='build') depends_on('libtool', type='build') depends_on('m4', type='build') # error: macro "min" passed 3 arguments, but takes just 2 # https://github.com/kartverket/fyba/issues/21 patch('gcc-6.patch') # fatal error: 'sys/vfs.h' file not found #...
kamyu104/LeetCode
Python/range-addition-ii.py
Python
mit
1,282
0.00156
# Time: O(p), p is the number of ops # Space: O(1) # Given an m * n matrix M initialized with all 0's and several update operations. # # Operations are represented by a 2D array, # and each operation is represented by an array with two positive integers a and b, # which means M[i][j] should be added by one for all 0 ...
# You need to count and return the number of maximum integers # in the mat
rix after performing all the operations. # # Example 1: # Input: # m = 3, n = 3 # operations = [[2,2],[3,3]] # Output: 4 # Explanation: # Initially, M = # [[0, 0, 0], # [0, 0, 0], # [0, 0, 0]] # # After performing [2,2], M = # [[1, 1, 0], # [1, 1, 0], # [0, 0, 0]] # # After performing [3,3], M = # [[2, 2, 1], # [2...
janezhango/BigDataMachineLearning
py/testdir_multi_jvm_fvec/test_KMeans_covtype20x_fvec.py
Python
apache-2.0
2,882
0.007634
import unittest, time, sys, random sys.path.extend(['.','..','py']) import h2o, h2o_cmd, h2o_glm, h2o_hosts, h2o_kmeans import h2o_browse as h2b, h2o_import as h2i class Basic(unittest.TestCase): def tearDown(self): h2o.check_sandbox_for_errors() @classmethod def setUpClass(cls): global lo...
for csvFilename, timeoutSecs, hex_key in csvFilenameList: csvPathname = importFolderPath + "/" + csvFilename # creates csvFilename.hex from file in importFolder dir start = time.time() parseResult = h2i.import_parse(bucket='home-0xdiag-datasets', path=csvPathname, ...
o.check_sandbox_for_errors() inspect = h2o_cmd.runInspect(None, parseResult['destination_key']) print "\n" + csvPathname, \ " numRows:", "{:,}".format(inspect['numRows']), \ " numCols:", "{:,}".format(inspect['numCols']) k = 2 kwarg...
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/test/test_generators.py
Python
gpl-2.0
54,447
0.000404
import gc import sys import unittest import weakref from test import support class FinalizationTest(unittest.TestCase): def test_frame_resurrect(self): # A generator frame can be resurrected by a generator's finalization. def gen(): nonlocal frame try: yie...
del g support.gc_collect() self
.assertIs(wr(), None) self.assertTrue(frame) del frame support.gc_collect() def test_refcycle(self): # A generator caught in a refcycle gets finalized anyway. old_garbage = gc.garbage[:] finalized = False def gen(): nonlocal finalized ...
landscape-test/all-messages
messages/pylint/E0202.py
Python
unlicense
47
0
""" E0202 An att
ribute is hiding
a method """
simbuerg/benchbuild
benchbuild/tests/test_run.py
Python
mit
2,638
0.000758
""" This Test will run through benchbuild's execution pipeline. """ import os import unittest from contextlib import contextmanager from benchbuild.utils import cmd def shadow_commands(command): def shadow_command_fun(func): def shadow_command_wrapped_fun(self, *args, **kwargs): cmd.__override...
(after)") self.assertEqual(mkdir.formulate(), outside.formulate(), msg="mkdir (before) is not the same as mkdir (after)") class TestRun(unittest.TestCase): @shadow_commands("true") def test_run(self): from benchbuild import experimen
t from benchbuild.utils.actions import Experiment class MockExp(experiment.Experiment): NAME = "mock-exp" def actions_for_project(self, project): from benchbuild.utils.actions import ( Prepare, Download, Configure, Build, Run, Clean) ...
ScottyLabs/directory-api
input_parser.py
Python
mit
2,729
0.004764
import dir_search from bs4.element import Tag class Parser : data : Tag or None single : bool error : bool results : list[dict] or dict def __init__(self, data : Tag): self.data = data if data is not None: self.error = bool(data.findPrevious('p', class_="error")) ...
("b"): if entry.text == "Display Name:": self.results['name'] = entry.next_sibling[1:] if entry.text == "Email:": se
lf.results['email'] = entry.next_sibling[1:] if entry.text == "Andrew UserID:": self.results['andrew_id'] = entry.next_sibling[1:] if entry.text == "Advisor:": self.results['advisor'] = entry.findNext().text if entry.text == "Phone:": s...
pando85/django-registration
test_app/settings_test.py
Python
bsd-3-clause
1,575
0
# coding: utf-8 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '
:memory:', }, } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'registration', 'test_app', ) DEBUG = True ALLOWED_HOSTS = ['*'] SECRET_KEY = '_' SITE_ID = 1 ROOT_URLCONF = 'test_app.url...
[ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', ...
v-legoff/pa-poc3
src/controller/controller.py
Python
bsd-3-clause
3,681
0.000543
# Copyright (c) 2012 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and th...
in self.server.allowed_formats: return "Unknown format {}.".format(format) return formats[format].render(view, **representations) def get_cookie(self, name, value=None): """Return, if found, the cookie. Otherwise, return value. """ return self.server.get_coo...
n=1): """Set a cookie.""" self.server.set_cookie(name, value, max_age, path, version)
canfar/cadcstats
svc_plots/tomcat_old.py
Python
mit
24,867
0.08461
from elasticsearch import Elasticsearch, TransportError from elasticsearch.helpers import scan import requests import pandas as pd import numpy as np import re from ipaddress import IPv4Address as ipv4, AddressValueError import time from bokeh.plotting import figure, output_file, show, save from bokeh.models import Fun...
## # fig1 would not work on my ES index, since i did not do reverse DNS at the time of ingestion # nor do i have th
e "clientdomain" field # def fig1(conn, idx): method = ["PUT","GET"] service = ["transfer_ws", "data_ws", "vospace_ws"] p = 1 plots = [] for j, s in enumerate(service): for i, m in enumerate(method): query = { "query" : { "bool" : { "filter" : [ { "term" : { "se...
reaperhulk/paramiko
tests/test_sftp_big.py
Python
lgpl-2.1
14,044
0.001994
# Copyright (C) 2003-2009 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko 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 (a...
ER, 'rb') as f: file_size = f.stat().st_size f.prefetch(file_size) # read on odd boundaries to make sure the bytes aren't getting scrambled n = 0 k2blob = kblob + kblob
chunk = 629 size = 1024 * 1024 while n < size: if n + chunk > size: chunk = size - n data = f.read(chunk) offset = n % 1024 self.assertEqual(data, k2blob[offset:offset +...
ganesh-95/python-programs
thoughtworks/ascii.py
Python
mit
197
0.015228
#sum of ascii values of characters in a string str = raw_input('enter th
e string:') ascii_numbers = [ord(c) for c in str] print ascii_numbers print sum(ascii_numbers)
onlytiancai/warning-collector
src/db.py
Python
mit
4,385
0.001382
# -*- coding: utf-8 -*- import sqlalchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session from datetime import datetime from sqlalchemy.exc import DisconnectionError import web import config engine = sqlalchemy.create_engine(config.dbconn, echo=False, co...
dbapi_con.ping() except dbapi_con.OperationalError as exc: if exc.args[0] in (2006, 2013, 2014, 2045, 2055): raise DisconnectionError() else: raise sqlalchemy.event.listen(engine, 'checkout', checkout_listener) class WebSession(Base): __tablename__ = 'sessions' ...
session_id = sqlalchemy.Column(sqlalchemy.String(128), nullable=False, unique=True, primary_key=True) atime = sqlalchemy.Column(sqlalchemy.TIMESTAMP, nullable=False, default=sqlalchemy.func.current_timestamp) data = sqlalchemy.Column(sqlalchemy.TEXT) class User(Base): __tablename__ = 'users' __table...
JoseALermaIII/python-tutorials
pythontutorials/Udacity/CS101/Lesson 23 - Problem Set/Q3-Spreading Udaciousness.py
Python
mit
1,742
0.000574
# Spreading Udaciousness # One of our modest goals is to teach everyone in the world to program and # understand computer science. To estimate how long this will take we have # developed a (very flawed!) model: # Everyone answering this question will convince a number, spread, (input to # the model) of their friends ...
2, 150000)) # >>> 1 # need to match or exceed the target print(hexes_to_udaciousness(50000, 2, 150001)) # >>> 2 # only 12 hexamesters (2 years) to world domination! print(hexes_to_udaciousness(20000, 2, 7 * 10 ** 9)) # >
>> 12 # more friends means faster world domination! print(hexes_to_udaciousness(15000, 3, 7 * 10 ** 9)) # >>> 10
usi-systems/p4paxos
bmv2/scripts/httpServer.py
Python
apache-2.0
2,016
0.009425
#!/usr/bin/env python import os, json, argparse, ConfigParser from twisted.internet import reactor, defer from twist
ed.internet.task import deferLater from twisted.web.resour
ce import Resource from twisted.web.server import Site, NOT_DONE_YET from twisted.web import static THIS_DIR=os.path.dirname(os.path.realpath(__file__)) from paxoscore.proposer import Proposer class MainPage(Resource): def getChild(self, name, request): if name == '': return self else: print nam...
att-comdev/drydock
drydock_provisioner/statemgmt/design/resolver.py
Python
apache-2.0
4,304
0.001394
# Copyright 2017 AT&T Intellectual Property. All other 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...
design_uri.scheme) url = urllib.parse.urlunparse( (new_scheme, design_uri.netloc, design_uri.path, design_uri.params, design_uri.query, design_uri.fragment)) logger = logging.getLogger(__name__) logger.debug("Calling Keystone session for url %s" % str(url)) resp ...
nvalidDesignReference( "Received error code for reference %s: %s - %s" % (url, str(resp.status_code), resp.text)) return resp.content scheme_handlers = { 'http': resolve_reference_http, 'file': resolve_reference_file, 'https': resolve_reference_http, ...
diegoguimaraes/django
tests/reverse_lookup/models.py
Python
bsd-3-clause
823
0
""" 25. Reverse lookups This demonstrates the reverse lookup features of the database API. """ from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class User(models.Model): name = models.CharField(max_length=200) def __str__(self): ...
retur
n self.name
mircealungu/Zeeguu-Core
setup.py
Python
mit
923
0.002167
#!/usr/bin/env python # -*- coding: utf8 -*- import setuptools from setuptools.command.develop import develop from setuptools.command.install import install class DevelopScript(develop): def run(self): develop.run(self) ntlk_install_packages() class InstallScript(install): def run(self): ...
ata=True, zip_safe=False, author="Zeeguu Team", author_email="me@mir.lu", description="Core for Zeeguu",
keywords="second language acquisition api", cmdclass={ 'develop': DevelopScript, 'install': InstallScript, }, )
plumdog/datasheet
alembic/versions/13a57b7f084_add_user.py
Python
mit
741
0.013495
"""Add
user Revision ID: 13a57b7f084 Revises: None Create Date: 2014-05-11 17:12:17.244013 """ # revision identifiers, used by Alembic. revision = '13a57b7f084' down_revision = None from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create...
mn('password_hash', sa.String(length=1000), nullable=True), sa.PrimaryKeyConstraint('id') ) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('user') ### end Alembic commands ###
leliel12/scikit-criteria
doc/source/conf.py
Python
bsd-3-clause
6,770
0.002068
# -*- coding: utf-8 -*- # # Scikit-Criteria documentation build configuration file, created by # sphinx-quickstart on Thu Aug 3 02:18:36 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fil...
_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output -------------------------------------
--------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} if on_rtd:...
vicnet/weboob
modules/presseurop/test.py
Python
lgpl-3.0
1,158
0
# -*- coding: utf-8 -*- # Copyright(C) 2012 Florent Fourcot # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the Lice...
with this weboob module
. If not, see <http://www.gnu.org/licenses/>. from weboob.tools.test import BackendTest from weboob.tools.value import Value class PresseuropTest(BackendTest): MODULE = 'presseurop' def setUp(self): if not self.is_backend_configured(): self.backend.config['lang'] = Value(value='fr') ...
Esri/ops-server-config
Publish/Portal/PrepItemsForExtract.py
Python
apache-2.0
5,238
0.007064
#!/usr/bin/env python #------------------------------------------------------------------------------ # Copyright 2015 Esri # 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.apac...
sword = results total_success = True title_break_count = 100 section_break_count = 75 search_query = None print '=' * title_break_count print 'Prepare Items for Extract' print '=' * title_break_count try: portal = Portal(portal_address, adminuser, ...
rtal.search(q=search_query, sort_field='owner') # --------------------------------------------------------------------- # Prepare hosted service items # --------------------------------------------------------------------- # Add new tag to hosted service so we can identify the o...
trolldbois/python-haystack
test/haystack/test_utils.py
Python
gpl-3.0
12,507
0.000959
# -*- coding: utf-8 -*- """Tests haystack.utils .""" import haystack.model # init ctypes with a controlled type size import ctypes import logging import unittest import os from haystack import model from haystack import utils from haystack import types from haystack import target from haystack.mappings.process impor...
_local() my_ctypes = my_target.get_target_ctype
s() my_utils = my_target.get_target_ctypes_utils() ctypes5_gen64 = haystack.model.import_module_for_target_ctypes("test.src.ctypes5_gen64", my_ctypes) # kinda chicken and egg here... # one call mappings = make_local_memory_handler() m = mappings.get_mappings()[0] ...
jreback/pandas
pandas/tests/arrays/test_timedeltas.py
Python
bsd-3-clause
12,380
0.000889
import numpy as np import pytest import pandas as pd from pandas import Timedelta import pandas._testing as tm from pandas.core import nanops from pandas.core.arrays import TimedeltaArray class TestTimedeltaArrayConstructor: def test_only_1dim_accepted(self): # GH#25282 arr = np.array([0, 1, 2, 3...
se]) def test_sum_empty(self, skipna): tdi = pd.TimedeltaIndex([]) arr = tdi.array result = tdi.sum(skipna=skipna) assert isinstance(result, Timedelta) assert result == Timedelta(0) result = arr.sum(skipna=skipna) assert isinstance(result, Timedelta) ...
TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"]) result = arr.min() expected = Timedelta("2H") assert result == expected result = arr.max() expected = Timedelta("5H") assert result == expected result = arr.min(skipna=False) assert r...
D4wN/brickv
src/build_data/windows/OpenGL/GL/ARB/fragment_program.py
Python
gpl-2.0
3,247
0.028334
'''OpenGL extension ARB.fragment_program This module customises the behaviour of the OpenGL.raw.GL.ARB.fragment_program to provide a more Python-friendly API Overview (from the spec) Unextended OpenGL mandates a certain set of configurable per- fragment computations defining texture application, texture envir...
on adds a small set of relatively inflexible per- fragment computations. This inflexibility is in contrast to the typical flexibility provided by the underlying programmable floating point engines (whether micro-coded fragment engines, DSPs, or CPUs) that are traditionally used to implement OpenGL's texturing...
ent parameters. For the purposes of discussing this extension, a fragment program is a sequence of floating-point 4-component vector operations that determines how a set of program parameters (not specific to an individual fragment) and an input set of per-fragment parameters are transformed to a set of per-f...
xiawei0000/Kinectforactiondetect
ChalearnLAPSample.py
Python
mit
41,779
0.017329
# coding=gbk #------------------------------------------------------------------------------- # Name: Chalearn LAP sample # Purpose: Provide easy access to Chalearn LAP challenge data samples # # Author: Xavier Baro # # Created: 21/01/2014 # Copyright: (c) Xavier Baro 2014 # Licence: <your lic...
os+9])) pos=pos+9 self.joins['ElbowLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['WristLeft']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['Hand...
+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['ElbowRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) pos=pos+9 self.joins['WristRight']=(map(float,data[pos:pos+3]),map(float,data[pos+3:pos+7]),map(int,data[pos+7:pos+9])) p...
Code4SA/pmg-cms-2
tests/views/test_admin_view.py
Python
apache-2.0
894
0
from tests import PMGLiveServerTestCase from pmg.models import db from tests.fixtures import dbfixture, UserData, RoleData class TestAdminView(PMGLiveServerTestCase): def setUp(self): super(TestAdminView, self).setUp() self.fx = dbfixture.data(RoleData, UserData,) self.fx
.setup() def tearDown(self): self.fx.teardown() super(TestAdminView, self).tearDown() def test_admin_page_unauthorised(self):
""" Test admin page (/admin) unauthorised """ self.make_request("/admin", follow_redirects=True) self.assertIn("Login now", self.html) def test_admin_page_authorised(self): """ Test admin page (/admin) authorised """ user = self.fx.UserData.admin ...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/duplicity/robust.py
Python
gpl-3.0
46
0.021739
../../..
/../share/pyshared/dupl
icity/robust.py
kizniche/Mycodo
mycodo/scripts/generate_manual_inputs_by_measure.py
Python
gpl-3.0
4,380
0.006164
# -*- coding: utf-8 -*- """Generate markdown file of Input information to be inserted into the manual.""" import os import sys sys.path.append(os.path.abspath(os.path.join(__file__, "../../.."))) from collections import OrderedDict from mycodo.utils.system_pi import add_custom_measurements from mycodo.utils.system_pi...
): name_str = "" if 'input_manufacturer' in each_data and each_data['input_manufacturer']: name_str += "{}".format(each_data['input_manufacturer']) if 'input_name' in each_data and each_data['input_name']: name_str += ": {}".format(...
"-").replace(":", "-").replace(",", "-").replace("/", "-") link_str = link_str.replace("--", "-").replace("--", "-").strip("-") out_file.write("### [{}](/Mycodo/Supported-Inputs/#{})\n".format(name_str, link_str)) out_file.write("\n")
dasseclab/dasseclab
clones/routersploit/tests/creds/cameras/arecont/test_ssh_default_creds.py
Python
gpl-2.0
594
0.001684
from routersploit.modules.creds.cameras.arecont.ssh_default_creds import Exploit def test_check_success(target): """ Test scenario - testing against SSH server """
exploit = Exploit() assert exploit.target == "" assert exploit.port == 22 assert exploit.threads == 1 as
sert exploit.defaults == ["admin:", ":"] assert exploit.stop_on_success is True assert exploit.verbosity is True exploit.target = target.host exploit.port = target.port assert exploit.check() is False assert exploit.check_default() is None assert exploit.run() is None
Mausy5043/bonediagd
DHT22/bonediagd_DHT/platform_detect.py
Python
mit
1,586
0.002522
# Copyright (c) 2014 Adafruit Industries # Au
thor: Tony DiCola # Modified by Mauy5043 (2016) # 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 # to use, copy, modify, merge, pu...
Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission 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 T...
citrix-openstack-build/ironic
ironic/openstack/common/service.py
Python
apache-2.0
10,246
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may #...
self, service): """Load and start the given service. :param service: The service you would like to start. :returns: None """ service.backdoor_port = self.backdoor_port self._services.add_thread(self.run_service, service) def stop(self): """Stop all services...
re currently running. :returns: None """ self._services.stop() def wait(self): """Waits until all services have been stopped, and then returns. :returns: None """ self._services.wait() class SignalExit(SystemExit): def __init__(self, signo, exccode=...
PawarPawan/h2o-v3
h2o-py/tests/testdir_algos/kmeans/pyunit_ozoneKmeans.py
Python
apache-2.0
589
0.03056
imp
ort sys sys.path.insert(1, "
../../../") import h2o def ozoneKM(ip, port): # Connect to a pre-existing cluster # connect to localhost:54321 train = h2o.import_file(path=h2o.locate("smalldata/glm_test/ozone.csv")) # See that the data is ready print train.describe() # Run KMeans my_km = h2o.kmeans(x=train, k=...
antong/ldaptor
ldaptor/test/util.py
Python
lgpl-2.1
4,431
0.003611
from twisted.python import failure from twisted.internet import reactor, protocol, address, error from twisted.test import testutils from twisted.trial import unittest from StringIO import StringIO class FakeTransport(protocol.FileWrapper): disconnecting = False disconnect_done = False def __init__(self, ...
0) cData = self.clientIO.read() sD
ata = self.serverIO.read() self.clientIO.seek(0) self.serverIO.seek(0) self.clientIO.truncate() self.serverIO.truncate() self.server.dataReceived(cData) self.client.dataReceived(sData) if cData or sData: return 1 else: return 0 cla...
tomachalek/kontext
lib/plugins/abstract/issue_reporting.py
Python
gpl-2.0
1,501
0.000666
# Copyright (c) 2017 Charles University, Faculty
of Arts, # Institute of the Czech National Corpus # Copyright (c) 2017 Tomas Machalek <tomas.machalek@gmail.com> # # 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; version 2 #...
1991. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License ...
kaze/paasmaker
paasmaker/common/api/application.py
Python
mpl-2.0
4,363
0.028879
# # Paasmaker - Platform as a Service # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # import loggin
g import paasmaker from apirequest import APIRequest, APIResponse logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) class ApplicationGetAPIRequest(APIRequest): """ Get the details for a single application. """ def __init__(self, *args, **kwargs): super(ApplicationGetAPIRequest, sel...
**kwargs) self.application_id = None self.method = 'GET' def set_application(self, application_id): """ Set the application ID for the request. """ self.application_id = application_id def get_endpoint(self): return '/application/%d' % self.application_id class ApplicationListAPIRequest(APIRequest):...
ktok07b6/polyphony
tests/error/loop_var01.py
Python
mit
222
0.004505
#Using the variable 'i' is restricted by polyphony's name scope rule from polyphony im
port testbench def loop_var01(): for i in range(10):
pass return i @testbench def test(): loop_var01() test()
jirikuncar/kwalitee
kwalitee/wsgi.py
Python
gpl-2.0
1,154
0
# -*- coding: utf-8 -*- # # This file is part of kwalitee # Copyright (C) 2014, 2015 CERN. # # kwalitee 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) an...
SE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with kwalitee; if not, write to the Free Software Foundation, # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # # In applying this lic
ence, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or submit itself to any jurisdiction. """WSGI application with debug middleware if in debug mode.""" from __future__ import absolute_import from kwalitee import create_app applicat...
lneuhaus/pyrpl
pyrpl/hardware_modules/ams.py
Python
gpl-3.0
859
0.002328
from ..modules import HardwareModule from ..attributes import PWMRegister class AMS(HardwareModule): """mostly deprecated module (redpitaya has removed adc support). only here for dac2 and dac3""" addr_base = 0x40400000 # attention: writing to dac0 and dac1 has no effect # only write to dac2 and ...
MRegister(0x20, doc="PWM output 0 [V]") dac1 = PWMRegister(0x24, doc="PWM output 1 [V]") dac2 = PWMRegister(0x28, doc="PWM output 2 [V]") dac3 = PWMRegister(0x2C, doc="PWM output 3 [V]") def _setup(self): # the function is here for its docstring to be used by the metaclass. """ sets up ...
Algomorph/nyc-data-exploration
scraping/irs_tables/irs_table_scraper.py
Python
apache-2.0
6,902
0.012315
#!/usr/bin/env python # encoding: utf-8 ''' irs_table_scraper -- scrapes IRS data from www.melissadata.com for given zips irs_table_scraper is a python script that reads in a list of zips and scrapes the IRS data for those scrips from www.melissadata.com @author: Gregory Kramida @copyright: 2013 Gregor...
#also skip last row - footer rows = table.findAll('tr') if(len(rows) != 24): if verbose > 0: print "Missing data for zip %s" % szip continue rows = rows[2:19] #prep the first 10 rows out_arr[i...
i_out_col = 2 for row in rows: #skip first cell (row header) cells = row.findAll(tcell_regex)[1:] i_year = 0 for cell in cells: #strip tags, $, %, and remove commas str_cell = cell...
lixiangning888/whole_project
modules/signatures_orignal/disables_wer.py
Python
lgpl-3.0
645
0.003101
# Copyright (C) 2015 Kevin Ross # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org # See the file 'docs/LICENSE' for copying permission. from lib.cuckoo.common.abstracts import Signature class DisablesWER(Signature): name = "disables_wer" description = "Attempts to disable Windows Error Repo...
"] authors = ["Kevin Ross"] minimum = "1.2" def run(self):
if self.check_write_key(pattern=".*\\\\SOFTWARE\\\\(Wow6432Node\\\\)?Microsoft\\\\Windows\\\\Windows\\ Error\\ Reporting\\\\Disabled$", regex=True): return True return False
jsha/letsencrypt
certbot-apache/setup.py
Python
apache-2.0
2,131
0
import sys from setuptools import setup from setuptools import find_packages version = '0.20.0.dev0' # Please update tox.ini when modifying dependency version requirements install_requires = [ 'acme=={0}'.format(version), 'certbot=={0}'.format(version), 'mock', 'python-augeas', # For pkg_resourc...
, 'Topic :: Security', 'Topic :: System :: Installation/Setup', 'Topic :: System :: Networking', 'Topic :: System
:: Systems Administration', 'Topic :: Utilities', ], packages=find_packages(), include_package_data=True, install_requires=install_requires, extras_require={ 'docs': docs_extras, }, entry_points={ 'certbot.plugins': [ 'apache = certbot_apache.configurator...
davy39/eric
Helpviewer/UserAgent/__init__.py
Python
gpl-3.0
169
0
# -*- coding: utf-8 -*- # Copyright (c) 20
10 - 2014 Detlev Offenbach <detlev@die-offenbachs.de> # """ Package implementing a menu to select the user agent string. """
gromitsun/sim-xrf-py
others/scatt_bg/scatt_bg_c.py
Python
mit
1,042
0.03071
import ctypes import numpy as np import os libpath = os.path.dirname(os.path.realpath(__file__)) lib = ctypes.cdll.LoadLibr
ary(libpath+'\libscatt_bg.so') scatt_bg_c = lib.scatt_bg scatt_bg_c.restype = ctypes.c_void_p # reset return types. default is c_int scatt_bg_c.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_double), ctypes.c_int, ctypes.c_int] subtend_c = lib.subtend subtend_c.restype = ctypes.c_double # reset return types. ...
Z_max = 98, theta_max = 90): # kev = np.asarray(kev) out = np.zeros(Z_max*theta_max) # Z_max = np.asarray(Z_max) # theta_max = np.asarray(theta_max) scatt_bg_c(ctypes.c_double(kev),out.ctypes.data_as(ctypes.POINTER(ctypes.c_double)),ctypes.c_int(Z_max),ctypes.c_int(theta_max)) return out def subtend(theta0,thet...
dpgaspar/Flask-AppBuilder
flask_appbuilder/security/sqla/models.py
Python
bsd-3-clause
5,212
0.001343
import datetime from flask import g from sqlalchemy import ( Boolean, Column, DateTime, ForeignKey, Integer, Sequence, String, Table, UniqueConstraint, ) from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.orm import backref, relat
ionship from ... import Model from ..._compat import as_unicode _dont_audit = False class Permission(Model): __tablename__ = "ab_permission" id = Column(Integer, Sequence("ab_permission_id_seq"), primary_key=True) name = Column(String(100), unique=True, nullable=False) def __repr__(self): r...
ue) name = Column(String(250), unique=True, nullable=False) def __eq__(self, other): return (isinstance(other, self.__class__)) and (self.name == other.name) def __neq__(self, other): return self.name != other.name def __repr__(self): return self.name assoc_permissionview_ro...
EdDev/vdsm
tests/storage_volume_metadata_test.py
Python
gpl-2.0
6,516
0
# Copyright 2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the ...
aDataKeyNotFoundError, volume.VolumeMetadata.from_lines, lines) @permutations([[None], ['pool']]) def test_deprecated_pool(self, val): lines = make_lines(**{sc.POOL: val}) md = volume.VolumeMetadata.from_lines(lines) self.assertEqual("", md.legacy_info()[sc.POO...
lines = make_lines(INVALID_KEY='foo') self.assertNotIn("INVALID_KEY", volume.VolumeMetadata.from_lines(lines).legacy_info()) @permutations([[sc.SIZE], [sc.CTIME], [sc.MTIME]]) def test_from_lines_int_parse_error(self, key): lines = make_lines(**{key: 'not_an_int...
twilio/twilio-python
twilio/rest/fax/v1/fax/__init__.py
Python
mit
17,574
0.002105
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import serialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import...
.v1.fax.fax_media import FaxMediaList class FaxList(ListResource): """ PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. """
def __init__(self, version): """ Initialize the FaxList :param Version version: Version that contains the resource :returns: twilio.rest.fax.v1.fax.FaxList :rtype: twilio.rest.fax.v1.fax.FaxList """ super(FaxList, self).__init__(version) # Path Soluti...
andreas-schmidt/tapetool
spiegel.py
Python
mit
3,188
0.002823
#!/usr/bin/env python from __future__ import print_function import numpy as np from scipy.io import wavfile def lmbinv(i, speed, fs, f1): f0 = 10. t1 = 20. freq = f0 + (f1 - f0) * i / fs / t1 return freq / speed def f_log(fs, i): t = float(i) / fs t1 = 10. f0 = 20. f1 = 20000. re...
open('logfreq-' + out, 'w'), reflog) r(s1, 2000., .1905, prefix + '-1905.dat') r(s2, 1000., .0953, prefix + '-0953.dat') r(s3, 500., .0476, prefix + '-0476.dat') template = open('template.plt').read() plt_l = template.format(title='L ' + title, prefix=prefix, col=3) plt_r = te...
itle='R ' + title, prefix=prefix, col=4) open(prefix + '-l.plt', 'w').write(plt_l) open(prefix + '-r.plt', 'w').write(plt_r) template = open('template-freq.plt').read() plt_l = template.format(title='L ' + title, prefix=prefix, col=3) plt_r = template.format(title='R ' + title, prefix=prefix, col=4...
kactus2/kactus2dev
PythonAPI/ipmm_core_pkg/component.py
Python
gpl-2.0
2,871
0.009056
from ipmm_core_pkg.primitive import Primitive from ipmm_core_pkg.addressBlock import AddressBlock from ipmm_core_pkg.register import Register from ipmm_core_pkg.field import Field from ipmm_core_pkg.port import Port from ipmm_core_pkg.parameter import Parameter class Component(Primitive): def __ini...
f.parameters.append(parameter) def add_port(self, port): self.ports.append(port) def add_constant(self, constant): self.constants.append(constant) def add_memoryMap(self, memoryMap): self.memoryMaps.append(memoryMap) def add_renderer(self,...
self.renderers.append(renderer) ## render can manipulate (remove, add, modify) parameters, ports, memorymaps def render(self): for r in self.renderers: r() def printer(self): Primitive.printer(self) for p in self.ports: ...
e2crawfo/dps
motmetrics/__init__.py
Python
apache-2.0
201
0.004975
from .mot import MOTAccumulato
r import motmetrics.lap import motmetrics.metrics import motmetrics.distances import motmetrics.io import motmet
rics.utils # Needs to be last line __version__ = '1.1.3'
ossobv/asterisklint
asterisklint/app/vall/app_softhangup.py
Python
gpl-3.0
870
0
# AsteriskLint -- an Asterisk PBX config syntax checker # Copyright (C) 2019 Walter Doekes, OSSO B.V. # # This program is free software: you ca
n 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 you
r option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU ...
jimyx17/jimh
lib/simplejson/tool.py
Python
gpl-3.0
1,025
0.000976
r"""Command-line tool to validate and pretty-print JSON Usage:: $ echo '{"json":"obj"}' | python -m simplejson.tool { "json": "obj" } $ echo '{ 1.2:3.4}' | python -m simplejson.tool Expec
ting property name: line 1 column 2 (char 2) """ import sys import lib.simplejson as json def main(): if len(sys.argv) == 1: infile = sys.stdin outfile = sys.stdout elif len(sys.argv) == 2: infile = open(sys.argv[1], 'rb') outfile = sys.stdout elif len(sys.argv) == 3: ...
else: raise SystemExit(sys.argv[0] + " [infile [outfile]]") try: obj = json.load(infile, object_pairs_hook=json.OrderedDict, use_decimal=True) except ValueError, e: raise SystemExit(e) json.dump(obj, outfile, sort_keys=True, indent=' ...
flaviovdf/pyksc
src/scripts/col_to_cluster.py
Python
bsd-3-clause
7,933
0.012227
# -*- coding: utf8 from __future__ import division, print_function from collections import defaultdict from matplotlib import pyplot as plt from radar import radar_factory from scipy import stats from scripts import initialize_matplotlib import numpy as np import plac import sys REFERRER_ABBRV = { 'EXTERNAL':...
if present: labels.add(ref_abbrv) to_plot[class_num][ref_abbrv] += val curr_line += 1 return to_plot, sum_classes, sorted(labels) def generate_data_plot(to_plot, sum_classes, labels, classes): num_classes = len(set(classes)) ...
um in xrange(num_classes): color = colors[class_num] data_plot = [] for label in labels: total += to_plot[class_num][label] data_plot.append(to_plot[class_num][label] / sum_classes[class_num]) yield data_plot, color, class_num def radar_...
anybox/anybox.buildbot.odoo
anybox/buildbot/openerp/build_utils/analyze_oerp_tests.py
Python
agpl-3.0
1,459
0
"""Analyse the tests log file given as argument. Print a report and return status code 1 if failures are detected """ import sys import re FAILURE_REGEXPS = { 'Failure in Python block': re.compile(r'WARNING:tests[.].*AssertionError'), 'Errors during x/yml tests': re.compile(r'ERROR:tests[.]'), 'Errors or...
s = {} # label -> extracted line for line in test_log.readlines(): for label, regexp in FAILURE_REGEXPS.items():
if regexp.search(line): failures.setdefault(label, []).append(line) if not failures: print "No failure detected" sys.exit(0) total = 0 print 'FAILURES DETECTED' print for label, failed_lines in failures.items(): print label + ':' for line in failed_lines: print ' ' + line...
ericmjl/bokeh
examples/plotting/file/markers.py
Python
bsd-3-clause
768
0.001302
from numpy.random import random from bokeh.models.markers import marker_types from bokeh.plotting import figure, output_file, show p = figure(title="Bokeh Markers", toolbar_location=None, output_backend="webgl") p.grid.grid_line_
color = None p.background_fill_color = "#eeeeee" p.axis.visible = False p.y_range.flipped = True N = 10 y = 1 for i, marker in enumera
te(marker_types): x = i % 4 if x == 0: y += 4 p.scatter(random(N)+2*x, random(N)+y, marker=marker, size=14, line_color="navy", fill_color="orange", alpha=0.5) p.text(2*x+0.5, y+2.5, text=[marker], text_color="firebrick", text_align="center", text_font_size="13px") out...
Ichag/openerp-server
openerp/osv/fields.py
Python
agpl-3.0
69,883
0.005023
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
ain = domai
n self._context = context self.write = False self.read = False self.select = select self.manual = manual self.selectable = True self.group_operator = args.get('group_operator', False) self.groups = False # CSV list of ext IDs of groups that can access thi...
McDermott-Group/LabRAD
LabRAD/TestScripts/fpgaTest/pyle/pyle/dataking/squid.py
Python
gpl-2.0
19,393
0.009075
from Queue import Empty from multiprocessing import Process, Queue import numpy as np import matplotlib.pyplot as plt from matplotlib import widget
s from scipy import interpolate from labrad.units import Unit V, mV, us, GHz, rad = [Unit(s) for s in ('V', 'mV', 'us', 'GHz', 'rad')] from pyle.dataking import utilMultilevels as ml from pyle.fitting import fitting def adjust_s_scanning(qubit, data, qnd=False): f, phase = data.T traces = [{'x':f, 'y': phase...
GHz], 'range': (min(f),max(f)), 'axis': 'x', 'color': 'b'}] else: params = [{'name': 'readout frequency', 'val': qubit['readout frequency'][GHz], 'range': (min(f),max(f)), 'axis': 'x', 'color': 'b'}] result = adjust(params, traces) if result is not None: if qnd: qubit['qnd_readou...
DataSploit/datasploit
emails/__init__.py
Python
gpl-3.0
380
0.005263
from os.path import dirname,
basename, isfile, abspath import glob, importlib, sys modules = glob.glob(dirn
ame(__file__) + "/email_*.py") __all__ = [basename(f)[:-3] for f in modules if isfile(f)] sys.path.append(dirname(abspath(__file__))) for m in __all__: __import__(m, locals(), globals()) del m, f, dirname, basename, isfile, abspath, glob, importlib, sys, modules
googleapis/python-domains
docs/conf.py
Python
apache-2.0
12,378
0.000566
# -*- coding: utf-8 -*- # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
value of this option must be the # base URL from which the finished HTML is served. # html_use_o
pensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'...
h4ck3rm1k3/MapNickAutotools
demo/test/textspacing.py
Python
lgpl-2.1
2,565
0.008577
# $Id: rundemo.py 577 2008-01-03 11:39:10Z artem $ # # This file is part of Mapnik (c++ mapping toolkit) # Copyright (C) 2005 Jean-Francois Doyon # # Mapnik is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; eith...
uccessfully before running this script.\n\n' raise m = Map(690,690,"+proj=latlong +ellps=WGS84") m.background = Color(255,100,100,255) road_style = Style() #Road road_rule = Rule() road_stroke = Stroke(Color('white'), 12) road_stroke.line_cap = line_cap.ROUND_CAP road_
stroke.line_join = line_join.ROUND_JOIN #road_rule.filter = Filter("[CLASS] = 'STRAIGHT'") road_rule.symbols.append(LineSymbolizer(road_stroke)) road_style.rules.append(road_rule); #Road text text_symbolizer = TextSymbolizer('NAME', 'DejaVu Sans Book', 10, Color('black')) text_symbolizer.label_placement=label_placemen...
datagrok/python-misc
datagrok/django/middleware/__init__.py
Python
agpl-3.0
29
0
"""Middleware for Django.""
"
Radagast-red/golem
tests/apps/core/task/test_core_verificator.py
Python
gpl-3.0
3,320
0.003614
from mock import Mock from golem.testutils import TempDirFixture from golem.tools.assertlogs import LogTestCase from apps.core.task.verificator import CoreVerificator, SubtaskVerificationState, logger class TestCoreVerificator(TempDirFixture, LogTestCase): def _fill_with_states(self, cv): cv.ver_states...
assert cv.get_verification_state("SUBTASK UNKNOWN") == \ SubtaskVerificationState.UNKNOWN assert cv.get_verification_state("SUBTASK PARTIALLY VERIFIED") == \ SubtaskVerificationState.PARTIALLY_VERIFIED assert cv.get_verification_s...
) == \ SubtaskVerificationState.WRONG_ANSWER assert cv.get_verification_state("another_verified") == \ SubtaskVerificationState.VERIFIED assert cv.get_verification_state("SUBTASK VERIFIED") == \ ...
crutchcorn/WMIControl
machineclasses/WMIMachineClass.py
Python
mpl-2.0
6,411
0.004212
# Core imports from lib.setSettings import djangopath djangopath(up=1, settings='settings') from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # DB models and exceptions from data import models from machineclasses.MachineClass import Machine class WMIMachine(Machine): def lo...
, partnum=PartNumber, speed=ram.Speed, formFactor=formNam
e.name, memoryType=memTypeName.name, serial=SerialNumber, location=ram.DeviceLocator ) def lookupWMIGPU(self, gpu): vidArchName, createdVidArch = models.WMICodes.objects.get_or_create(code=gpu.VideoArchitecture, ...
qedsoftware/commcare-hq
corehq/util/spreadsheets/excel_importer.py
Python
bsd-3-clause
1,783
0.001683
from corehq.util.spreadsheets.excel import WorkbookJSONReader from soil import DownloadBase class UnknownFileRefException(Exception): pass class ExcelImporter(object): """ Base class for `SingleExcelImporter` and `MultiExcelImporter`. This is not meant to be used directly. """ def __init__(...
task, file_ref_id): super(SingleExcelImporter, self).__init__(task, file_ref_id) self.worksheet = self.workbook.worksheets[0] self.total_rows = self.worksheet.worksheet.get_highest_row() class MultiExcelImporter(ExcelImporter): """ Manage importing from an excel file with multiple ...
ref_id): super(MultiExcelImporter, self).__init__(task, file_ref_id) self.worksheets = self.workbook.worksheets self.total_rows = sum(ws.worksheet.get_highest_row() for ws in self.worksheets)
ltowarek/budget-supervisor
third_party/saltedge/test/test_income_report_streams_regular.py
Python
mit
1,008
0
# coding: utf-8 """ Salt Edge Account Information API API Reference for
services # noqa: E501 OpenAPI spec version: 5.0.0 Contact: support@saltedge.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_clien
t from swagger_client.models.income_report_streams_regular import IncomeReportStreamsRegular # noqa: E501 from swagger_client.rest import ApiException class TestIncomeReportStreamsRegular(unittest.TestCase): """IncomeReportStreamsRegular unit test stubs""" def setUp(self): pass def tearDown(sel...
nkgeorgiev/psilyp
setup.py
Python
gpl-2.0
286
0.003497
from distutils.core import setup setup(name
='psilyp', version='1.0', description='A Basic lisp interpreter', author='Nikolay Georgiev', author_email='nikolaykgeorgiev@gmail.com',
url='https://github.com/HuKCaHa/psilyp', packages=['psilyp'], )
philipkershaw/ndg_security_server
ndg/security/server/test/integration/openidrelyingparty/authenticationservicesapp.py
Python
bsd-3-clause
2,769
0.006862
#!/usr/bin/env python """NDG Security test harness for authorisation middleware NERC DataGrid Project """ __author__ = "P J Kershaw" __date__ = "20/11/08" __copyright__ = "(C) 2009 Science a
nd Technology Facilities Council" __contact__ = "Philip.Kershaw@stfc.ac.uk" _
_revision__ = "$Id$" from os import path import optparse from OpenSSL import SSL from ndg.security.server.utils.paste_utils import PasteDeployAppServer from ndg.security.test.unit.base import BaseTestCase INI_FILEPATH = path.join(path.dirname(path.abspath(__file__)), 'authenticatio...
aktorion/bpython
bpython/curtsiesfrontend/interpreter.py
Python
mit
4,702
0
import code import traceback import sys from codeop import CommandCompiler from six import iteritems from pygments.token import Generic, Token, Keyword, Name, Comment, String from pygments.token import Error, Literal, Number, Operator, Punctuation from pygments.token import Whitespace from pygments.formatter import Fo...
tokensource and outfile params passed to it from the Pygments highlight() method a
nd slops them into the appropriate format string as defined above, then writes to the outfile object the final formatted string. This does not write real strings. It writes format string (FmtStr) objects. See the Pygments source for more info; it's pretty straightforward.""" def __init__(self,...
hickford/datrie
setup.py
Python
lgpl-2.1
2,391
0.000418
#! /usr/bin/env python """Super-fast, efficiently stored Trie for Python.""" import os import sys from setuptools import setup, Extension from setuptools.command.test import test as TestCommand LIBDATRIE_DIR = 'libdatrie/datrie' LIBDATRIE_FILE_NAMES = [ 'alpha-map.c', 'darray.c', 'fileutils.c', 'tail.c', 'trie.c...
build-in ``test`` command to run :mod:`pytest`. """ def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest s
ys.exit(pytest.main(self.test_args + ["./tests"])) setup( name="datrie", version="0.7", description=DESCRIPTION, long_description=LONG_DESCRIPTION, author='Mikhail Korobov', author_email='kmike84@gmail.com', license=LICENSE, url='https://github.com/kmike/datrie', classifiers=CLASSI...