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
Som-Energia/somenergia-tomatic
tomatic/pbx/asteriskfake_test.py
Python
gpl-3.0
6,875
0.008145
# -*- coding: utf-8 -*- import unittest from pathlib import Path from .. import persons from .asteriskfake import AsteriskFake class AsteriskFake_Test(unittest.TestCase): from yamlns.testutils import assertNsEqual def setUp(self): self.persons = Path('p.yaml') self.persons.write_text(u"""\ ...
('alice', False), ('carol', False), ('bob', Fals
e), ]) def test_resume(self): a = self.fixture() a.setQueue('aqueue',['alice', 'carol', 'bob' ]) a.pause('aqueue','carol') a.resume('aqueue','carol') self.assertPaused(a.queue('aqueue'), [ ('alice', False), ('carol', False), ('bob'...
RamezIssac/django-sitetree
sitetree/settings.py
Python
bsd-3-clause
1,085
0.003687
from django.conf import settings MODEL_TREE = getattr(settings, 'SITETREE_MODEL_TREE', 'sitetree.Tree') MODEL_TREE_ITEM = getattr(settings, 'SITETREE_MODEL_TREE_ITEM', 'sitetree.TreeItem') APP_MODULE_NAME = getattr(settings, 'SITETREE_APP_MODULE_NAME', 'sitetrees') UNRESOLVED_ITEM_MARKER = getattr(settings, 'SITETR...
d in Django cache for a year (60 * 60 * 24 * 365 = 31536000 sec). # Cache is only invalidated on sitetree or sitetree item change. CACHE_TIMEOUT = getattr(settings, 'SITETREE_CACHE_TIMEOUT', 31536000) # Reserved tree items aliases. ALIAS_TRUNK = 'trunk' ALIAS_THIS_CHILDREN = 'this-children' ALIAS_THIS_SIBLINGS = 'this...
ITEMS_ALIASES = [ ALIAS_TRUNK, ALIAS_THIS_CHILDREN, ALIAS_THIS_SIBLINGS, ALIAS_THIS_ANCESTOR_CHILDREN, ALIAS_THIS_PARENT_SIBLINGS ]
GregoryShen/Flaskk
app/__init__.py
Python
mit
1,305
0
from flask import Flask, request from flask_bootstrap import Bootstrap from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager, current_user from flask_pagedown import PageDown from os import path from flask_gravatar import Gravatar from config import config from flask_babel import Babel b...
db.init_app(app) Bootstrap(app) login_manager.init_app(app) pagedown.init_app(app) Gravatar(app, size=64) babel.init_app(app) from .main import main as main_bl
ueprint from .auth import auth as auth_blueprint app.register_blueprint(main_blueprint) app.register_blueprint(auth_blueprint, url_prefix='/auth') @app.template_test('current_link') def is_current_link(link): return link == request.path # @babel.localeselector # def get_locale(): ...
Nachtfeuer/pipeline
scripts/coverage_check.py
Python
mit
775
0.00129
#!/usr/bin/env python import sys def percentage(total, missing): return (total - missing) * 100.0 / total statements_total = int(sys.argv[1]) statements_missing = int(
sys.argv[2]) statements_percentage = percentage(statements_total, statements_missing) branches_total = int(sys.argv[3]) branches_missing = int(sys.argv[4]) branches_percentage = percentage(branches_total, branches_missing) print("statement coverage: total: %4d, missing: %4d, percentage: %5.2f%%" % (statements_...
ing, statements_percentage)) print("branch coverage: total: %4d, missing: %4d, percentage: %5.2f%%" % (branches_total, branches_missing, branches_percentage)) print("total coverage: %5.3f%%" % ((statements_percentage + branches_percentage) / 2.0))
gusyussh/learntosolveit
languages/python/algorithm_is_sorted.py
Python
bsd-3-clause
116
0.043103
>>> import
random
>>> random.sample(range(10), 5) [7, 6, 3, 5, 1] >>> all(a < b for a, b in zip(_,_[1:])) False >>>
little-dude/simple-ostinato
simple_ostinato/protocols/__init__.py
Python
gpl-3.0
181
0
from .baseclass impo
rt Protocol from .overrides import Mac, Ethernet, IPv4, Payload, Tcp, Udp __all__ = [ 'Protocol',
'Mac', 'Ethernet', 'IPv4', 'Payload', 'Tcp', 'Udp', ]
queid7/hma
modules/resource/vrml_loader.py
Python
mit
14,317
0.000698
import numpy, math import pickle import sys if '..' not in sys.path: sys.path.append('..') import resource.ys_motion_loader as yml class Wrl: child_types = ['JOINT', 'SEGMENT', 'TRANSFORM', 'SHAPE'] class Child: def __init__(self): self.child_type = None def get_type(self)...
self.children: if child.get_type() == 'SEGMENT': if child_segment is None: child_segment = child else: print("two childse
gment exist") if child_segment is None: print("no childsegment exists") return child_segment class Segment(Child): def __init__(self): self.child_type = 'SEGMENT' self.center_of_mass = None self.mass = None self.momen...
aavrug/askbot-devel
askbot/context.py
Python
gpl-3.0
1,070
0.000935
"""Askbot template context processor that makes some parameters
from the django settings, all parameters from the askbot livesettings and the application available for the templates """ from django.conf import settings import askbot from askbot import api from askbot.conf import settings as askbot_settings from askbot.skins.loaders import get_skin from askbot.utils import url_utils...
_CODE my_settings['ASKBOT_URL'] = settings.ASKBOT_URL my_settings['DEBUG'] = settings.DEBUG my_settings['ASKBOT_VERSION'] = askbot.get_version() my_settings['LOGIN_URL'] = url_utils.get_login_url() my_settings['LOGOUT_URL'] = url_utils.get_logout_url() my_settings['LOGOUT_REDIRECT_URL'] = url_ut...
arju88nair/projectCulminate
venv/lib/python3.5/site-packages/pylint/test/conftest.py
Python
apache-2.0
1,039
0
# pylint: disable=redefined-outer-name import os import pytest from pylint import checkers from pylint.lint import PyLinter # pylint: disable=no-name-in-module from pylint.testutils import MinimalTestReporter @pytest.fixture def linter(checker, register, enable, disable, reporter): _linter = PyLinter() _lint...
for msg in enable: _linter.enable(msg) os.environ.pop('PYLINTRC', None) return _linter @pytest.fi
xture(scope='module') def checker(): return None @pytest.fixture(scope='module') def register(): return None @pytest.fixture(scope='module') def enable(): return None @pytest.fixture(scope='module') def disable(): return None @pytest.fixture(scope='module') def reporter(): return MinimalTest...
PaddlePaddle/Paddle
python/paddle/fluid/tests/unittests/ir/inference/test_trt_convert_group_norm.py
Python
apache-2.0
6,063
0.001155
# Copyright (c) 2021 PaddlePaddle 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 ap...
else:
return 0, 3 else: return 0, 3 attrs = [ program_config.ops[i].attrs for i in range(len(program_config.ops)) ] # for static_shape clear_dynamic_shape() self.trt_param.precision = paddle_infer.PrecisionType.Fl...
Kent1/ncclient
examples/nc04.py
Python
apache-2.0
3,827
0.002874
#! /usr/bin/env python # # Copyright 2012 Vaibhav Bajpai <contact@vaibhavbajpai.com> # Copyright 2009 Shikhar Bhushan <shikhar@schmizz.net> # # Create a new user to the running configuration using edit-config # and the test-option provided by the :validate capability. # # $ ./nc04.py cook bob 42 42 import sys, os, war...
[default: critical]''' ) parser.add_argument( '--username', action='store', dest='username', default=os.getenv('USER'), help='username [default...
) parser.add_argument( '--password', action='store', dest='password', help='password' ) results = parser.parse_args() return results if __name__ == '__main__': def setl...
asterix135/infonex_crm
marketing/constants.py
Python
mit
4,640
0
F1_SPLIT = {'': ('NA', 'NA'), 'aboriginal': ('Aboriginal', 'NA'), 'aboriginal/gov': ('Aboriginal', 'Gov'), 'aboriginal/industry': ('Aboriginal', 'Industry'), 'aboriginal/industry/gov': ('Aboriginal', 'Industry'), 'aboriginal/recruiting': ('Aboriginal', 'HR'), ...
ecruiting': ('HR', 'NA'), 'recruiting/hr': ('HR', 'NA'), 'recruiting/gov': ('HR', 'Gov'), 'recruitment': ('HR', 'NA'), 'recuriting': ('HR', 'NA'), 'reruiting': ('HR', 'NA'), 'uk': ('NA', 'NA'), 'usa': ('USA', 'NA'), 'usa/abo...
'usa/gov': ('USA', 'Gov'), 'usa/hr': ('USA', 'HR'), 'usa/industry': ('USA', 'Industry'), 'usa/industry/fin': ('Industry', 'Fin'), 'yyy': ('NA', 'NA'), } SPLIT_OPTIONS = ['1', '2', '3', '4', '5', '6', 'A1', 'A2', 'A3', 'Aboriginal', 'FED 1',...
alxgu/ansible
lib/ansible/module_utils/ec2.py
Python
gpl-3.0
28,571
0.002835
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
owing conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following
disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ...
RyanDJLee/pyta
tests/test_type_inference/test_ifexpr.py
Python
gpl-3.0
598
0.001672
import astroid import nose from hypothesis import given, settings, HealthCheck from typing import Any import tests.custom_hypothesis_support as cs settings.load_profile("pyta") @given(cs.ifexp_node()) @settings(suppress_health_check=[HealthCheck.too_slow]) def test_ifexp(node): """Test the type settin
g of an IfExp node representing an if statement.""" modul
e, type_inferer = cs._parse_text(node) for ifexp_node in module.nodes_of_class(astroid.IfExp): assert ifexp_node.inf_type.getValue() == ifexp_node.body.inf_type.getValue() if __name__ == '__main__': nose.main()
VulcanoAhab/waybackeess
response.py
Python
mit
1,236
0.014563
from datetime import datetime import hashlib from extractor import
Ways from date import way_date class Helpers: ''' ''' @staticmethod def make_id(website, timestamp): ''' ''' m=hashlib.md5() m.update(''.joi
n([website, timestamp]).encode()) return m.hexdigest() class WayDefault: ''' ''' @classmethod def set_parser(cls, ParserObj): ''' ''' cls.parser=ParserObj def __init__(self, snap_dict): ''' ''' self._raw=snap_dict self.timestamp=s...
infphilo/centrifuge
evaluation/test/centrifuge_evaluate_mason.py
Python
gpl-3.0
13,637
0.003153
#!/usr/bin/env python import sys, os, subprocess, inspect import platform, multiprocessing import string, re from datetime import datetime, date, time import copy from argparse import ArgumentParser, FileType """ """ def read_taxonomy_tree(tax_file): taxonomy_tree = {} for line in tax_file: fields = ...
["%s/%s.%d.cf" % (index_path, index_base, i+1) for i in range(3)] assert check_files(index_fnames) # Read taxonomic IDs centrifuge_inspect = os.path.join(path_base, "../centrifuge-inspect") tax_ids = set() tax_cmd = [centrifuge_inspect, "--conversion-t
able", "%s/%s" % (index_path, "b+h+v")] tax_proc = subprocess.Popen(tax_cmd, stdout=subprocess.PIPE) for line in tax_proc.stdout: _, tax_id = line.strip().split() tax_ids.add(tax_id) tax_ids = list(tax_ids) # Read taxonomic tree tax_tree_cmd = [centrifuge_inspect, ...
anhstudios/swganh
data/scripts/templates/object/tangible/loot/dungeon/corellian_corvette/shared_imperial_rescue_intel.py
Python
mit
485
0.045361
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/loot/dungeon/corellian_corvette/shared_imperial_rescue_intel.iff" r...
tem_n","imperial_rescue_intel") ####
BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
ambyte/Vertaler
src/controllers/taskbarcontroller.py
Python
gpl-2.0
2,396
0.015025
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------------- # Copyright (c) 2011 Sergey Gulyaev <astraway@gmail.com> # # This file is part of Vertaler. # # Vertaler is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License ...
------------------ """ Controller for TaskBar """ import wx from src.controllers import settingcontroller, aboutcontroller from src.modules.settings import config from src.gui.mainframe import MainTaskBarIcon class MainTaskBarIconController: def __init__(self): self.tbicon = MainTaskBarIcon(self) ...
event_about, self.tbicon.menuAbout ) self.tbicon.Bind( wx.EVT_MENU,self.event_settings, self.tbicon.menuSetting ) self.tbicon.Bind( wx.EVT_MENU,self.event_setting_ctrl, self.tbicon.menuItemCtrl ) self.tbicon.Bind( wx.EVT_MENU,self.event_setting_nothing, self.tbicon.menuItemNothing ) ...
fos/fos-legacy
setup.py
Python
bsd-3-clause
971
0.013388
#!/usr/bin/env python ''' Installation script for the fos package ''' from os.path import join as pjoin from glob import glob from distutils.core import setup from distutils.extension import Extension import numpy as np from build_helpers import make_cython_ext # we use cython to compile the module if we have it tr...
_cython = True col_ext, cmdclass = make_cython_ext( 'fos.core.collision', has_cython, include_dirs = [np.get_include()
]) cgl_ext, cmdclass = make_cython_ext( 'fos.core.cython_gl', has_cython, include_dirs = [np.get_include()]) setup(name='fos', version='0.2', description='Scientific 3d Engine', author='Fos Team', author_email='garyfallidis@gmail.com', url='http://github.com/Garyfallidis/Fos'...
blankclemens/tools-iuc
data_managers/data_manager_qiime_database_downloader/data_manager/data_manager_qiime_download.py
Python
mit
11,147
0.000449
#!/usr/bin/env python # Data manager for reference data for the QIIME Galaxy tools import argparse import ftplib import json import os import tarfile import zipfile import requests protocol = { "unite": "http", "greengenes": "ftp", "silva": "http", "img": "ftp" } baseUrl = { "unite": "http://uni...
ra_files_path' is the path to a directory where output files must be put for the receiving data manager to pick them up. NB the directory pointed to by 'extra_files_path' doesn't exist initially, it is the job of the script to create it if necessary. """ params = json.loads(open(jsonfile)....
am_dict'], params['output_data'][0]['extra_files_path']) # Utility functions for creating data table dictionaries # # Example usage: # >>> d = create_data_tables_dict() # >>> add_data_table(d,'my_data') # >>> add_data_table_entry(dict(dbkey='hg19',value='human')) # >>> add_data_table_entry(dict(dbkey='mm9...
toddsifleet/staticpy
test/site_test.py
Python
mit
1,243
0
import os from pytest import fixture from doubles import expect, allow import staticpy.site from staticpy.utils import load_settings def get_settings(): path = os.path.realpath(__file__) parts = path.split(os.sep)[:-2] parts.append('template') path = os.path.join(*parts) # '/' is a temporary ha...
= get_settings() assert site.input_path == settings.input_path assert site.output_path == settings.output_path assert site.base_url == settings
.base_url def test_client_js_code(self, site): assert site.client_js_code == '' def test_incldue_drafts(self, site): assert not site.include_drafts class TestSave(object): def test_calls_write_on_each_page(self, site): for page in site.pages: expect(page).write ...
statsbiblioteket/newspaper-jpylizer-deprecated
src/main/extras/jpylyzer-1.10.1/boxvalidator.py
Python
apache-2.0
81,418
0.034612
# # This program 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 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be use...
noBytes else: # Obviously something going wrong here ... compressionRatio
= -9999 return(compressionRatio) def _getBitValue(self, n, p): # Get the bit value of denary (base 10) number n at the equivalent binary # position p (binary count starts at position 1 from the left) # Only works if n can be expressed as 8 bits !!! # Word length in bits wordLength=8 # Shift = ...
carlos-ferras/Sequence-ToolKit
model/singlenton.py
Python
gpl-3.0
563
0.001776
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals class _Singleton(type): """A metaclass that creates a Singleton base class when called.""" _instances = {}
def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._insta
nces[cls] = super( _Singleton, cls ).__call__( *args, **kwargs ) return cls._instances[cls] class Singleton(_Singleton('SingletonMeta', (object,), {})): pass
teeple/pns_server
work/install/Python-2.7.4/Lib/multiprocessing/forking.py
Python
gpl-2.0
16,314
0.00141
# # Module for starting a process object using os.fork() or CreateProcess() # # multiprocessing/forking.py # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: ...
lar to the one from subprocess, but # whose constructor takes a process object as its argument. # class Popen(object): def __init__(self, process_obj): sys.stdout.flush() sys.stderr.flush() self.returncode = None self.pid = os.fork() if ...
in sys.modules: import random random.seed() code = process_obj._bootstrap() sys.stdout.flush() sys.stderr.flush() os._exit(code) def poll(self, flag=os.WNOHANG): if self.returncode is None: ...
dopplershift/Scattering
test/test_scatterer.py
Python
bsd-2-clause
434
0.006912
from scattering import scatterer import numpy as np from numpy.testing import assert_array_almost_equal, run_module_suite def test_ones(): scat = scatterer(.1, 0.0, 'water', diameters=np.array([0.04, 0.05])) scat.set_scattering_mode
l('rayleigh') assert_array_almost_equal(scat.sigma_b, np.array( [0.01170936, 0.04
466766], np.float32 )) if __name__ == "__main__": run_module_suite()
tachijuan/python
myscripts/foldgame.py
Python
mit
3,016
0.028846
#JOHN CONWAY'S GAME OF LIFE import RPi.GPIO as GPIO import time import random import serial import string from plotter import mybuffer MAXGENERATIONS = 4000 DISPLAY = True gamecount = 0 maxgenfold = '' def toggledisplay(pin): global DISPLAY p.turnondisplay() p.loadcustomchars(fullblock=False) DISPLAY = not DI...
g(universe, a, b): count = 0 surrounding = ((a - 1, b - 1), (a - 1, b ), (a - 1, b + 1), (a , b - 1), (a , b + 1), (a + 1, b - 1), (a + 1, b ), (a + 1, b + 1)) for...
universe) or b >= len(universe[a])) and universe[a][b]: count += 1 return count def printUniverse(universe): p.clearbuf() for a in range(0,len(universe)): for b in range(0,len(universe[a])): if universe[a][b]: p.setxy(b,a) def fold(arr): b = '' for a in arr: b=b+''.join(map(l...
dominikkarall/pychromecast
pychromecast/config.py
Python
mit
1,167
0.001714
""" Data and methods to retrieve app specific configuration """ import json import requests APP_BACKDROP = "E8C28D3C" APP_YOUTUBE = "233637DE" APP_MEDIA_RECEIVER = "CC1AD845" APP_PLEX = "06ee44ee-e7e3-4249-83b6-f5d0b6f07f34_1" APP_DASHCAST = "84912283" APP_SPOTIFY = "CC32E753" APP_HOME_ASSISTANT = "B12CE3CA" A
PP_SUPLA = "A41B766D" APP_YLEAREENA = "A9BCCB7C" def get_possib
le_app_ids(): """ Returns all possible app ids. """ try: req = requests.get( "https://clients3.google.com/cast/chromecast/device/baseconfig" ) data = json.loads(req.text[4:]) return [app["app_id"] for app in data["applications"]] + data["enabled_app_ids"] excep...
bikalabs/bika.wine
bika/wine/browser/analysisrequest/getarinfo.py
Python
agpl-3.0
3,221
0.000621
from bika.wine.permissions
import * from bika.lims.browser import BrowserView from bika.lims.permissions import * from bika.lims.utils import to_utf8 as _c from Prod
ucts.CMFCore.utils import getToolByName import json import plone.protect class getARInfo(BrowserView): def __init__(self, context, request): super(getARInfo, self).__init__(context, request) def __call__(self): plone.protect.CheckAuthenticator(self.request) uc = getToolByName(self.c...
Amber-Creative/amber-frappe
setup.py
Python
mit
532
0.018797
from setuptools import set
up, find_packages from pip.req import parse_requirements version = "6.27.20" requirements = parse_requirements("requirements.txt", session="") setup( name='frappe', version=version, description='Metadata driven, full-stack web framework', author='Frappe Technologies', author_email='info@frappe.io', packages=fin...
rements if ir._link] )
volf52/black_hat_python
pic_carver.py
Python
mit
2,905
0.003787
#!/usr/bin/env python """ @author : 'Muhammad Arslan <rslnrkmt2552@gmail.com>' """ import re import zlib import cv2 from scapy.all import * pics = "pictues" faces_dir = "faces" pcap_file = "bhp.pcap" def get_http_headers(http_payload): try: headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2...
image(headers, http_payload) if image is not None and image_type is not None: file_name = "%s-pic_carver_%d.%s" % (pcap_file, carved_images, image_type) with open("%s/%s" % (pics, file_name), "wb") as fd: fd.write(image) carved_images += 1 try: ...
file_name), file_name) if result is True: faces_detected += 1 except: pass return carved_images, faces_detected carved_images, faces_detected = http_assembler(pcap_file) print "Extracted: %d images" % carved_images print "Detected: %d faces" % face...
Dreae/PyFurStream
pyfurstream/__init__.py
Python
mit
1,719
0.004654
from pyfurstream.core import APIConnection, api, configure from pyfurstream.users import User from pyfurstream.streams import Stream import time __version__ = "1.0.0" d
ef get_user_
summaries(users): ''' Returns the list of user objects for the given list of usernames Note: The list of objects is not guaranteed (nor likely) to be in the same order in which the usernames are given ''' _users = api().call('IUsers', 'GetUserSummaries', users=users) ...
gaapt/deepdive
ddlib/without_ddlib.py
Python
apache-2.0
1,813
0.027579
#! /usr/bin/env python # File: udf/ext_has_spouse_features.py import sys, json # For each input tuple # TODO: Sample Data and the input schema. # sample json for row in sys.stdin: obj = json.loads(row) # Library/DSL??? This is a span, it
should be an object. p1_start = obj["p1.start_po
sition"] p1_length = obj["p1.length"] p1_end = p1_start + p1_length p2_start = obj["p2.start_position"] p2_length = obj["p2.length"] p2_end = p2_start + p2_length p1_text = obj["words"][p1_start:p1_length] p2_text = obj["words"][p2_start:p2_length] left_idx = min(p1_end, p2_end) ...
GNOME/orca
test/keystrokes/gtk3-demo/role_push_button.py
Python
lgpl-2.1
2,278
0.001756
#!/usr/bin/python """Test of push button output.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(KeyComboAction("<Control>f")) sequence.append(TypeAction("Button Boxes")) sequence.append(KeyComboAction("Return")) sequence.append(PauseAction(3000)) sequence.append(utils.St...
Button Boxes panel Spread panel OK push button'", " VISIBLE: 'OK push button', cursor=1", "SPEECH OUTPUT: 'OK push b
utton"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Tab")) sequence.append(utils.AssertPresentationAction( "3. Cancel push button", ["BRAILLE LINE: 'gtk3-demo application Button Boxes frame Horizontal Button Boxes panel Spread panel Cancel push button'", " VISIBLE:...
Tinkerforge/brickv
src/brickv/plugin_system/plugins/industrial_counter/__init__.py
Python
gpl-2.0
953
0.00105
# -*- coding: utf-8 -*- """ brickv (Brick Viewer) Copyright (C) 2018 Olaf Lüke <olaf@tinkerforge.com> __init__.py: package initialization 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 versi...
icense, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the...
e Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. """ from brickv.plugin_system.plugins.industrial_counter.industrial_counter import IndustrialCounter device_class = IndustrialCounter
sredmond/menlo-mathsci-help
app/tests.py
Python
mit
306
0.009804
from app import models from app import db u = models.User(first_name="Sam", last_name="Redmond") s = models.
Subject(name="math") db.session.add(u) db.session.commit() db.ses
sion.add(u.teachSubject(s)) db.session.commit() print "Got here" for t in s.tutors: print t for sub in u.subjectsITutor: print sub
rdmorganiser/rdmo
rdmo/questions/tests/test_viewset_widgettype.py
Python
apache-2.0
669
0.00299
import pytest from django.urls import reverse users = ( ('editor', 'editor'), ('reviewer', 'reviewer'), ('user', 'user'), ('api', 'api'), ('anonymous', Non
e), ) status_map = { 'list': { 'editor': 200, 'reviewer': 200, 'api': 200, 'user': 200, 'anonymous': 401 }, } urlnames = { 'list': 'v1-questions:widgettype-list', } @pytest.mark.parametrize('username,password', users) def test_list(db, client, username, password): client.login(username=usern...
rd) url = reverse(urlnames['list']) response = client.get(url) assert response.status_code == status_map['list'][username], response.json()
hpcuantwerpen/easybuild-easyblocks
easybuild/easyblocks/s/scipy.py
Python
gpl-2.0
3,046
0.00394
## # Copyright 2009-2021 Ghent University # # This file is part of EasyBuild, # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), # with support of Ghent University (http://ugent.be/hpc), # the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), # Flemish Research Foundation (F...
__(*args, **kwargs) self.testinstall = True self.testcmd = "cd .. && %(python)s -c 'import numpy; import scipy; scipy.test(verbose=2)'" def configure_step(self): """Custom configure s
tep for scipy: set extra installation options when needed.""" super(EB_scipy, self).configure_step() if LooseVersion(self.version) >= LooseVersion('0.13'): # in recent scipy versions, additional compilation is done in the install step, # which requires unsetting $LDFLAGS ...
shubham0d/smc
salvus/admin.py
Python
gpl-3.0
66,944
0.008933
#!/usr/bin/env python ############################################################################### # # SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal. # # Copyright (C) 2014, William Stein # # This program is free software: you can redistribute it and/or modify # ...
ss, obtained using the ps command. The run option is used to run the command (so it could run on a remote machine). The result is a dictionary; it is empty if the given process is not running. """ fields = ['%cpu', '%mem', 'etime', 'pid', 'start', 'cputime', 'rss', 'vsize'] v = run(['ps', '-p',...
'-o', ' '.join(fields)], verbose=False).splitlines() if len(v) <= 1: return {} return dict(zip(fields, v[-1].split())) def dns(host, timeout=10): """ Return list of ip addresses of a given host. Errors out after timeout seconds. """ a = os.popen3("host -t A -W %s %s | awk '{print $4}'"%(time...
mccarrion/python-practice
crash_course/chapter14/bullet.py
Python
mit
1,133
0.001765
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship""" def __init__(self, ai_settings, screen
, ship): """Create a bullet object at the ship's current position.""" super(Bullet, self).__init__() self.screen = screen # Create a bullet rect at (0, 0) and then set correct position. self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_hei
ght) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top # Store the bullet's position as a decimal value. self.y = float(self.rect.y) self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): ...
FowlerLab/Enrich2
enrich2/gui/dialog_elements.py
Python
bsd-3-clause
10,805
0.000648
from __future__ import print_function import Tkinter as tk import ttk import tkMessageBox import tkFileDialog import os.path DEFAULT_COLUMNS = 3 class SectionLabel(object): def __init__(self, text): self.text = text def body(self, master, row, columns=DEFAULT_COLUMNS, **kwargs): label = ttk....
label = ttk.Label(master, text=self.text) label.grid(row=row, column=0, columnspan=1, sticky="e") self.entry = ttk.Entry(master, textvariable=self.value) self.entry.grid(row=row, column=1, columnspan=columns - 1, sticky="ew") return 1 class IntegerEntry(MyEntry): """ Creates...
def __init__(self, text, cfg, key, optional=False, minvalue=0): MyEntry.__init__(self, text, cfg, key, optional) self.minvalue = minvalue def body(self, master, row, columns=DEFAULT_COLUMNS, width=4, left=False, *
felipehfj/Arduino
libraries/Adafruit_VC0706_Serial_Camera_Library/raspi_camera.py
Python
gpl-3.0
3,977
0.044254
#!/usr/bin/python # python code for interfacing to VC0706 cameras and grabbing a photo # pretty basic stuff # written by ladyada. MIT license # revisions for Raspberrry Pi by Gordon Rush import serial BAUD = 38400 # this is the port on the Raspberry Pi; it will be different for serial ports on other systems. PORT = ...
NTFRAME, 0x0a] def readbuffer(bytes): addr = 0 # the initial offset into the frame buffer photo = [] # bytes to read each time (must be a mutiple of 4) inc = 8192 while( addr < bytes ): # on the last read,
we may need to read fewer bytes. chunk = min( bytes-addr, inc ); # append 4 bytes that specify the offset into the frame buffer command = readphotocommand + [(addr >> 24) & 0xff, (addr>>16) & 0xff, (addr>>8 ) & 0xff, addr & 0xff] # append 4 bytes that specify the data length to re...
RevansChen/online-judge
Codewars/8kyu/watermelon/Python/test.py
Python
mit
390
0
# Python - 3.6.0 test.assert_equals(divide(4),
True) test.assert_equals(divide(2), False) test.assert_equals(divide(5), False) test.assert_equals(divide(88), True) test.assert_equals(divide(100), True) test.a
ssert_equals(divide(67), False) test.assert_equals(divide(90), True) test.assert_equals(divide(10), True) test.assert_equals(divide(99), False) test.assert_equals(divide(32), True)
hoehnp/navit_test
lib/python2.7/site-packages/_pytest/pytester.py
Python
gpl-2.0
40,423
0.000297
""" (disabled by default) support for testing pytest and pytest plugins. """ from __future__ import absolute_import, division, print_function import codecs import gc import os import platform import re import subprocess import sys import time import traceback from fnmatch import fnmatch from weakref import WeakKeyDic...
arsedCall(hook_name, kwargs)) def after(outcome, hook_name, hook_impls, kwargs): pass self._undo_wr
apping = pluginmanager.add_hookcall_monitoring(before, after) def finish_recording(self): self._undo_wrapping() def getcalls(self, names): if isinstance(names, str): names = names.split() return [call for call in self.calls if call._name in names] def assert_contains(s...
hkff/AccMon
accmon/plugins/system.py
Python
gpl-3.0
920
0.001087
""" System plugin Copyright (C) 2016 Walid Ben
ghabrit This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WI...
R A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from accmon.plugins.plugin import * class System(Plugin): def __init__(self): super()....
antoinecarme/pyaf
tests/artificial/transf_None/trend_Lag1Trend/cycle_7/ar_/test_artificial_128_None_Lag1Trend_7__20.py
Python
bsd-3-clause
259
0.088803
import pyaf.Bench.T
S_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 7, transform = "None", sigma = 0.0, exog_count = 20, ar_order
= 0);
flyapen/UgFlu
flumotion/admin/gtk/dialogs.py
Python
gpl-2.0
7,734
0.000905
# -*- Mode: Python; test-case-name: flumotion.test.test_dialogs -*- # -*- coding: UTF-8 -*- # vi:si:et:sw=4:sts=4:ts=4 # # Flumotion - a streaming media server # Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com). # All rights reserved. # This file may be distributed and/or modified under the terms...
k.Dialog.__init__(self, _('About Flumotion'), parent, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, (gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)) self.set_has_separator(False) self.set_resizable(False) self.set_border_width(12) self.v...
ng')) image.show() version = gtk.Label( '<span size="xx-large"><b>Flumotion %s</b></span>' % configure.version) version.set_selectable(True) self.vbox.pack_start(version) version.set_use_markup(True) version.show() text = _('Flumotion...
ListFranz/torngas
torngas/__init__.py
Python
bsd-3-clause
495
0.012121
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'mqingyn' __version_
_ = '1.7.4' version = tuple(map(int, __version__.split('.'))
) from settings_manager import settings from webserver import Server, run from exception import ConfigError, ArgumentError from urlhelper import Url, route, include from utils import is_future, RWLock, cached_property, lazyimport, Null, \ safestr, safeunicode, strips, iterbetter, sleep from storage import storage,...
cmshobe/landlab
tests/graph/test_graph.py
Python
mit
4,049
0.001729
import pytest from numpy.testing import assert_array_almost_equal, assert_array_equal from landlab.graph import Graph r""" For these tests the nodes are given column-by-column:: (1) -- (3) --- (4) | | / (0) | / \ | / (2) Once sorted, the node numbering becomes:: ...
assert_array_equal( graph.nodes_at_link, [[0, 1], [1, 2], [0, 3], [1, 4], [2, 5], [3, 4], [4, 5]] ) with pytest.raises(Va
lueError): graph.nodes_at_link[0] = [1, 0] def test_graph_can_thaw(): graph = Graph((NODE_Y, NODE_X), links=NODES_AT_LINK, sort=True) assert_array_equal( graph.nodes_at_link, [[0, 1], [1, 2], [0, 3], [1, 4], [2, 5], [3, 4], [4, 5]] ) with graph.thawed(): graph.nodes_at_link[0...
csparkresearch/ExpEYES17-Qt
SPARK17/experiments/acgen.py
Python
mit
1,163
0.035254
# -*- coding: utf-8; mode: python; indent-tabs-mode: t; tab-width:4 -*- from ..Qt import QtGui, QtCore from ..templates import ui_plotTemplate as plotTemplate from ..utilities.expeyesWidgetsNew import expeyesWidgets import sys,time,functools,os _translate = QtCore.QCoreApplication.translate class AppWindow(QtGui.QWi...
tc were used to initialize. Uses default va
lues wherever possible
jonathanslenders/ptpython
ptpython/utils.py
Python
bsd-3-clause
5,634
0.00142
""" For internal use only. """ import re from typing import Callable, Iterable, Type, TypeVar, cast from prompt_toolkit.formatted_text import to_formatted_text from prompt_toolkit.formatted_text.utils import fragment_list_to_text from prompt_toolkit.mouse_events import MouseEvent, MouseEventType __all__ = [ "has_...
"""
# Ignore empty lines and lines that have whitespace only. strings = [s for s in strings if not s.isspace() and not len(s) == 0] if not strings: return "" else: s1 = min(strings) s2 = max(strings) for i, c in enumerate(s1): if c != s2[i] or c not in " \t": ...
artemistomaras/django-ethereum-events
django_ethereum_events/forms.py
Python
mit
3,011
0.002325
import inspect import json from django import forms from django.forms import widgets from django.utils.module_loading import import_string from django.utils.translation import ugettext_lazy as _ from eth_utils import add_0x_prefix, event_abi_to_log_topic, is_hex_address from web3 import Web3 from .chainevents impor...
ng(event_receiver) if not inspect.isclass(event_handler_cls) or not issubclass(event_handler_c
ls, AbstractEventReceiver): raise forms.ValidationError( _('%(receiver)s is not a valid subclass of AbstractEventReceiver') % {'receiver': event_receiver}) except ImportError: raise forms.ValidationError(_('Cannot import module %(module)s') % {'module': event_rece...
dvogel/drewlib
drewlib/ansi_colors.py
Python
lgpl-3.0
275
0.003636
# -*- coding: utf-8 -*- from __future__ import print_function from itertools import chain __all__ = ['AnsiColors'
] AnsiColors = "\n".join(["\x1b[{0}m{0}\x1b[0m \x1b[{1}m{1}\
x1b[0m".format(cc, cc+60) for cc in chain(range(30, 38), range(40, 48))])
alexgorban/models
research/slim/train_image_classifier.py
Python
apache-2.0
21,268
0.004373
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
'Use CPUs to deploy clones.') tf.app.flags.DEFINE_integer('worker_replicas', 1, 'Number of worker replicas.') tf.app.flags.DEFINE_integer( 'num_ps_tasks', 0, 'The number of parameter servers. If the value is 0, then the parameters ' 'are handled locally by the worker.') tf.app...
E_integer( 'num_readers', 4, 'The number of parallel readers that read data from the dataset.') tf.app.flags.DEFINE_integer( 'num_preprocessing_threads', 4, 'The number of threads used to create the batches.') tf.app.flags.DEFINE_integer( 'log_every_n_steps', 10, 'The frequency with which logs...
trustedanalytics/spark-tk
integration-tests/tests/test_arima.py
Python
apache-2.0
2,540
0.002843
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # 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 require...
predict(0)) def test_arima_predict(tc): ts = [12.88969427, 13.54964408, 13.8432745, 12.13843611, 12.81156092, 14.2499628, 15.12102595] model = tc.models.timeseries.arima.train(ts, 1, 0
, 1) # predict using the same values that were used with training predicted_vals = model.predict(0) # optionally, provide a list of ts values to use as the gold standard predicted_with_ts = model.predict(0, ts) # the predicted values should be the same, since the same ts was used for both trainin...
plotly/plotly.py
packages/python/plotly/plotly/validators/waterfall/hoverlabel/font/_family.py
Python
mit
574
0.001742
import _plotly_utils.basevalidators class FamilyValidator(_plotly_utils.basevalidators.StringValidator): def __init__( self, plotly_name="family
", parent_name="waterfall.hoverlabel.font", **kwargs ): super(FamilyValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, array_ok=kwargs.pop("array_ok", True), edit_type=kwargs.pop("edit_type", "none"), no_blank=kwargs.pop("...
ct", True), **kwargs )
niksoc/srmconnect
app/rest_retrieve_views.py
Python
gpl-3.0
9,955
0.000904
from django.http import (HttpResponse, Http404, JsonResponse) from django.views.generic import (ListView, DetailView) from django.core import serializers from django.apps import apps from django.shortcuts import get_object_or_404 from hitcount.views import HitCountMixin from django.contrib.auth.models import User from ...
'pk': obj.pk, 'model': str(obj.__class__)[8:-2]} return JsonResponse(response) def latest_comment(request): for_model_name = request.GET['for'] for_id = request.GET['id'] model = apps.get_model('app.Commen
t_' + for_model_name) for_item = apps.get_model( 'app.' + for_model_name).objects.get(pk=for_id) created = modified = datetime.datetime(1996, 11, 28) qs = model.objects.filter(for_item=for_item) if qs.exists(): modified = qs.latest("modified").modified qs = qs.filter(is_active=True) ...
catapult-project/catapult
systrace/systrace/tracing_controller.py
Python
bsd-3-clause
11,838
0.005575
#!/usr/bin/env python # Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Tracing controller class. This class manages multiple
tracing agents and collects data from all of them. It also manages the clock sync process. ''' from __future__ import print_function import ast import json import sys import tempfile import uuid import py_utils from systrace import trace_result from systrace import tracing_agents from py_trace_event import trace_ev...
oller' def ControllerAgentClockSync(issue_ts, name): """Record the clock sync marker for controller tracing agent. Unlike with the other tracing agents, the tracing controller should not call this directly. Rather, it is called via callback from the other tracing agents when they write a trace. """ trace...
ratnania/pyccel
pyccel/stdlib/parallel/openmp.py
Python
mit
2,492
0.013644
# coding: utf-8 # TODO raise StopIteration() instead of 'StopIteration' #$ header class StopIteration(public, hide) #$ header method __init__(StopIteration) #$ header method __del__(StopIterat
ion) class StopIteration(object): def __init__(self): pass def __del__(self): pass #$ header class Parallel(public, with, openmp) #$ header method __init__(Parallel, str, str, str [:], str [:], str [:], str [:], str, str [:], str) #$ header method __del__(Parallel) #$ header method __enter__(...
, str, str) class Parallel(object): def __init__(self, num_threads=None, if_test=None, private=None, firstprivate=None, shared=None, reduction=None, default=None, copyin=None, proc_bind=None): self._num_threads = num_threads self._if_test = ...
Arkapravo/morse-0.6
src/morse/middleware/moos_mw.py
Python
bsd-3-clause
5,831
0.014749
import logging; logger = logging.getLogger("morse." + __name__) import pymoos.MOOSCommClient import morse.core.middleware import bge class MOOSClass(morse.core.middleware.MorseMiddlewareClass): """ Handle communication between Blender and MOOS.""" def __init__(self): """ Initialize the MOOS app"...
unction) #func = getattr(self, "callback") #self._topics.append(rospy.Subscriber(parent_name + "/" + component_name, String, func, component_instance)) else: #Add external module #self._add_method(mw_data, component_instanc
e) pass else: # If there is no such function in this module, # try importing from another one try: # Insert the method in this class function = self._add_method(mw_data, component_instance) except IndexError as deta...
yadt/yadt-config-rpm-maker
test/integrationtests/configrpmmaker_integration_test.py
Python
gpl-3.0
15,116
0.003175
# yadt-config-rpm-maker # Copyright (C) 2011-2013 Immobilien Scout GmbH # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any l...
r}" """ class ConfigRpmMakerIntegrationTestWithNonConfigCommitAndNoConfig(IntegrationTestWithNonConfigCommitAndNoConfigDir): def test_no_build_fail_on_non_config_commit_with_same_prefix_length(self): # "/XXXXXX" has the same length as the configpath prefix "/config". if subprocess.call('svn mkdir ...
n('Could not import test data.') config_rpm_maker = self._given_config_rpm_maker(revision='1') rpms = config_rpm_maker.build() self.assertEqual(rpms, None) def test_no_build_fail_on_non_config_commit_with_path_shorter_than_prefix(self): # The commit path "/X/Y" is shorter than the c...
krips89/robocomp
tools/rcmonitor/examples/moveDrawBase.py
Python
gpl-3.0
4,562
0.029373
# -*- coding: utf-8 -*- # Copyright (C) 2010 by RoboLab - University of Extremadura # # This file is part of RoboComp # # RoboComp 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...
on.move(5,55) self.resetButton.show() self.
connect(self.resetButton, SIGNAL('clicked()'), self.reset) self.show() self.cmdSteer = 0. self.cmdSpeed = 0. self.posList = [] def reset(self): self.proxy.resetOdometer() def job(self): sendCommand = False if self.cmdSteer != float(self.steer.value()): self.cmdSteer = float(self.steer.value()) ...
The6P4C/adventofcode
2015/day3/part2.py
Python
gpl-3.0
716
0.036313
MOVEMENT = { '^': (0, 1), 'v': (0, -1), '<': (-1, 0), '>': (1, 0) } def add_points(p1, p2): return (p1[0] + p2[0], p1[1] + p2[1]) def main(): file_data = '' w
ith open('input.txt', 'r') as f: file_data = f.read().strip() positions = [(0, 0), (0, 0)] visiteds = [[(0, 0)], [(0, 0)]] who = 0 for instruction in file_data: positions[who] = add_points(positions[who], MOVEMENT[instruction]) if positions[who] not in visiteds[who]: visiteds[who].append(positions[who]) ...
in visiteds: for position in visited: if position not in true_visited: true_visited.append(position) print(len(true_visited)) if __name__ == '__main__': main()
benoitc/mt-compono
setup.py
Python
apache-2.0
2,399
0.016674
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of compono released under the Apache 2 license. # See the NOTICE for more information. from distutils.command.install_data import install_data import os import sys if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'): rai...
g System :: OS Independent', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development', 'Topic :: Software Development :: Libraries :: Application Frameworks', ], zip_safe = False, packages = find_pac
kages(), include_package_data = True, datafiles = data_files, cmdclass=cmdclass, install_requires = [ 'setuptools>=0.6b1' ], requires = [ 'django (>1.1.0)', 'couchdbkit (>=0.4.2)', 'simplejson (>=2.0.9)', ], test_suite = 'nose.collector', )
particl/particl-core
test/functional/wallet_importmulti.py
Python
mit
44,970
0.003002
#!/usr/bin/env python3 # Copyright (c) 2014-2021 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the importmulti RPC. Test importmulti by generating keys on node0, importing the scriptPubKeys an...
"Should import an address") key = get_key(self.nodes[0]) self.test_importmulti({"scriptPubKey": {"address": key.p2pkh_addr}, "timestamp": "now"}, success=True) test_address(self.nodes[1], key.p2pkh_addr, ...
True, ismine=False, timestamp=timestamp, ischange=False) watchonly_address = key.p2pkh_addr watchonly_timestamp = timestamp self.log.info("Should not import an invalid address") self.test_importmulti({"scriptPubKey": {"addre...
amilendra/Udacity_FullStack_P1_MovieTracker
media.py
Python
gpl-2.0
338
0.005917
class movie: """Stores movie metadata""" # The constructor takes # - The Title # - The youtube trailer #
- The poster image URL def __init__(self, title, youtube_trailer, poster_url): self.title = title self.trailer_youtube_url = youtube_trailer self.poster_image_url = po
ster_url
cstein/neb
neb/neb.py
Python
mit
7,489
0.001736
import math import numpy class NEB(object): """ A Nudged Elastic Band implementation This NEB implementation is based on http://dx.doi.org/10.1063/1.1323224 by Henkelman et al. """ def __init__(self, path, k): """ Initialize the NEB with a predefined path and force con...
th: (n, k) = numpy.sha
pe(bead.getCoordinates()) self._tangents.append(numpy.zeros((n,k))) self._springforces.append(numpy.zeros((n,k))) self._beadgradients.append(numpy.zeros((n,k))) self._forces.append(numpy.zeros((n,k))) self._energies.append(0.0) self._grms.append(-1...
campadrenalin/EJTP-lib-python
ejtp/tests/test_jacks.py
Python
lgpl-3.0
3,123
0.001601
from ejtp.util.compat import unittest import threading from persei import String, RawData from ejtp import router, client from ejtp.jacks.stream import Connection class TestJacks(unittest.TestCase): def setUp(self): self.routerA = router.Router() self.routerB = router.Router() def test_udp...
transfer_condition.release() self.assertEqual((ifaceB, ifaceA, messageAB), received[0]) self.assertEqual((ifaceA, ifaceB, messageBA), received[1]) def tearDown(self): self.routerA.stop_all() self.routerB.stop_all() class TestJackStream(unittest.TestCase): def setUp(se...
self.plaintext = "The pursuit of \x00 happiness" self.wrapped = self.connection.wrap(self.plaintext) def test_receive(self): self.connection.inject(self.wrapped) self.assertEqual(RawData(self.plaintext), self.connection.recv()) def test_receive_partial(self): self.connecti...
nevercast/home-assistant
homeassistant/components/sensor/vera.py
Python
mit
5,869
0
""" homeassistant.components.sensor.vera ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Support for Vera sensors. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.vera/ """ import logging from requests.exceptions import RequestException import homeassistant.u...
ll this entity. """ return False def update(self): if self.vera_device.category == "Temperature Sensor": current_te
mp = self.vera_device.temperature vera_temp_units = ( self.vera_device.vera_controller.temperature_units) if vera_temp_units == 'F': self._temperature_units = TEMP_FAHRENHEIT else: self._temperature_units = TEMP_CELCIUS if...
hermaa02/cs330-final
db.py
Python
apache-2.0
5,927
0.00928
from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask import os app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://jkrbnkekcosnxb:jOrPwurv94mnMu7acVpIX0W2sA@ec2-54-197-230-161.compute-1.amazonaws.com:5432/da79ahfav90021' db = SQLAlchemy(app) class Item(db.Model): __tablenam...
bstract square canvas with blue trees, line
s', img = 'ht_5.jpg', blue =True, red =True, orange =True, yellow =True, purple =False, green =True) history5 = History(sold=0,available=1) item6 = Item(name = 'square canvas',price = 150,size_w = 24,size_h=24) descrip6 = Description(description ='square canvas with valley and pine trees', img = 'ht_6.jpg', blue = Tru...
plotly/plotly.py
packages/python/plotly/plotly/validators/layout/xaxis/rangeselector/_bordercolor.py
Python
mit
464
0
import _plotly_utils.basevalidators class BordercolorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__( self, plotly_name
="bordercolor", parent_name="layout.xaxis.rangeselector", **kwargs ): super(B
ordercolorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "plot"), **kwargs )
twitter/pants
src/python/pants/backend/jvm/ivy_utils.py
Python
apache-2.0
51,293
0.010313
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import os import pkgutil import threading import xml.etree.Ele...
.join(self.ivy_workdir, self.hash_name) @property def hardlink_classpath_filename(self): return os.path.join(self.workdir, 'classpath') @property def ivy_cache_classpath_filename(self): return '{}.raw'.format(self.hardlink_classpath_filename) @property def frozen_resolve_file(self): return os...
ir, 'jars') @abstractmethod def ivy_xml_path(self): """Ivy xml location.""" @abstractmethod def resolve_report_path(self, conf): """Location of the resolve report in the workdir.""" def _construct_and_load_hardlink_map(self): artifact_paths, hardlink_map = IvyUtils.construct_and_load_hardlink_m...
FALCONN-LIB/FALCONN
src/python/package/setup.py
Python
mit
1,325
0.003774
import os import sys try: import pypandoc long_description = pypandoc.convert('README.md', 'rst', format='md') except (IOError, ImportError): long_description = open('README.md').read() try: from setuptools import setup, find_packages, Extension except ImportError: sys.stderr.write('Setuptools not...
= '-mmacosx-version-min=10.9' module = Extension( '_falconn', sources=['internal/python_wrapper.cc'], extra_compile_args=e
xtra_args, include_dirs=['include', 'external/eigen', 'external/pybind11/include', 'external/simple-serializer']) setup( name='FALCONN', version='1.4.0', author='Ilya Razenshteyn, Ludwig Schmidt', author_email='falconn.lib@gmail.com', url='http://falconn-lib.org/', description= 'A libra...
xch89820/Heartbleed-Tester
heartBleed.py
Python
mit
10,504
0.00714
################################################################################# # File Name : heartBleed.py # Created By : Jone Casper(xu.chenhui@live.com) # Creation Date : [2014-04-14 12:57] # Last Modified : [2014-04-20 12:57] # Description ...
###################################################################### #!/usr/bin/env python import sys, socket, time, select, logging import struct def h2bin(x): return x.replace(' ', '').replace('\n', '').decode('hex') def bin2h(x): return " ".join("{:02x}".format(ord(c)) for c in x) #Thanks...
0c bc 2b 92 a8 48 97 cf bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c...
snapcore/snapcraft
snapcraft/internal/sources/_base.py
Python
gpl-3.0
5,858
0.000683
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015-2017 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in ...
oad(self, filepath: str = None) -> st
r: if filepath is None: self.file = os.path.join(self.source_dir, os.path.basename(self.source)) else: self.file = filepath # First check if we already have the source file cached. file_cache = FileCache() if self.source_checksum: algorithm, h...
airbnb/superset
superset/migrations/versions/956a063c52b3_adjusting_key_length.py
Python
apache-2.0
4,937
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
y obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the
License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """adjusting key length Revision ID: 956a063c52b3 Revises: f0fbf6129e13 Create Date: 2016-05-1...
alexurquhart/webgis
app/database.py
Python
mit
7,684
0.005466
from sqlalchemy import create_engine, distinct, func, desc from sqlalchemy.orm import sessionmaker from geoalchemy2 import functions as geo_func from datetime import datetime, timedelta import config from base import Base from schema import Tweet, Hashtag, Picture, Division import codecs, json class Database: def ...
Returns a list of all division ids def get_division_ids(self): ids = self.session.query(Division.id).all() return map(lambda x: x[0], ids) ''' with series as ( select * from generate_series( date_trunc('hour', now() - int
erval '1 week'), now(), interval '1 hour') time ), tw_count as ( select distinct date_trunc('hour', created_at) as time, count(*) over (partition by date_trunc('hour', created_at)) from tweets.tweets where created_at > now() - interval '1 week' and division_id...
learning-on-chip/studio
script/recorder.py
Python
mit
4,813
0.004986
#!/usr/bin/env python def die(message): raise SystemError(message) try: import subprocess except ImportError: die('expected to be compiled without --without-signal-module') import os, sim, sys, time class Config: def __init__(self): self.program = os.getenv('PROGRAM_NAME') if not sel...
'--queue', self.redis['queue'], '--caching', '--database', self.sqlite['database'], '--table', self.sqlite['dynamic'], ] print('Running `%s`...' % ' '.join(arguments))
process = subprocess.Popen(arguments) code = process.poll() if code is not None and code != 0: die('failed to run `%s`' % ' '.join(arguments)) self.dynamic = process def stop_dynamic(self): run('%s RPUSH %s recorder:halt > /dev/null' % ( self.redis['bin'], ...
CiscoSystems/fabric_enabler
setup_enabler.py
Python
apache-2.0
36,241
0.001462
# Copyright 2014 Cisco Systems, Inc. # 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 requi...
'start_agent': 'systemctl start fabric-enabler-agent', 'stop_keystone': 'systemctl stop httpd', 'start_keystone': 'systemctl start httpd', 'stop_server': 'systemctl sto
p fabric-enabler-server', 'start_server': 'systemctl start fabric-enabler-server', 'stop_neutron_server': 'systemctl stop neutron-server', 'start_neutron_server': 'systemctl start neutron-server', 'get_pty': True, } } class NexusFabricEnablerInstaller(object): """Represents Fab...
eliz79/is210-week-08-synthesizing
tests/test_task_02.py
Python
mpl-2.0
1,920
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for Task 02""" # Import Python libs import mock import unittest import task_02 class Task02TestCase(unittest.TestCase): """Test cases for Task 02""" def test_params(self): """Tests that login() has the correct required parameters.""" ms...
tly named, ordered, or (not) optional' with self.assertRaises(TypeError): task_02.login() with self.assertRaises(TypeError): task_02.login(maxattempts=0) self.assertFalse(task_02.login(username='blah', maxattempts=0), msg) def test_login_authentication(self): ...
'): mock_stdin = mock.Mock() mock_stdin.isatty = mock.Mock() mock_stdin.isatty.return_value = True self.assertTrue(task_02.login('veruca')) with mock.patch('getpass.getpass', return_value='corruption'): mock_stdin = mock.Mock() mock_stdin....
stvstnfrd/edx-platform
openedx/core/djangoapps/user_api/accounts/tests/test_serializers.py
Python
agpl-3.0
2,122
0.003299
""" Test cases to cover Accounts-related serializers of the User API application """ import logging from django.test import TestCase from django.test.client import RequestFactory from testfixtures import LogCapture from openedx.core.djangoapps.user_api.accounts.serializers import UserReadOnlySerializer from common....
s/') self.user = UserFactory.build(username='test_user'
, email='test_user@test.com') self.user.save() self.config = { "default_visibility": "public", "public_fields": [ 'email', 'name', 'username' ], } def test_serializer_data(self): """ Test serializer return data properly. ...
dimashi/TemprMonitor
src/wifi.py
Python
mit
133
0
class Wifi: state
= "supplicant_state" s
tate_completed = "completed" state_scanning = "scanning" ip = "ip_address"
mina-asham/pictures-dedupe-and-rename
pictures/rename/rename.py
Python
mit
1,752
0.001712
import logging import os import time import exifread logger = logging.g
etLogger(__name__) def rename(filenames): for filen
ame in filenames: new_filename = _new_filename_from(filename) if new_filename: os.rename(filename, new_filename) logger.info('Renamed %s to %s', filename, new_filename) def _new_filename_from(filename): dirname = os.path.dirname(filename) date_created = _date_created_fr...
anksp21/Community-Zenpacks
ZenPacks.community.HPEVAMon/ZenPacks/community/HPEVAMon/HPEVAStorageDiskEnclosure.py
Python
gpl-2.0
5,528
0.021527
################################################################################ # # This program is part of the HPEVAMon Zenpack for Zenoss. # Copyright (C) 2010 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zenoss.com/oss # #...
border='0'>\n" for line in self.enclosureLayout.split(','): result = result + "<tr>\n" for bay in line.strip().split(): result = result + "<td>%s</td>\n"%bays.get(int(
bay), '<img src="%s%s.png" />'%(self.blankimg, self.hLayout and '_h' or '_v')) result = result + "</tr>\n" result = result + "</table>\n</td>\n<td>" result = result + LINKTMPLT % (self.getPrimaryUrlPath(), s...
cosailer/caeproject
simulation_result/3/project3.py
Python
gpl-2.0
2,019
0.006439
# -*- coding: utf-8 -*- """ ------------------------------------- N A C S P Y T H O N S C R I P T ------------------------------------- NACS version: 2.0.2745 - pre3 NACS architecture: CENTOS 5.11 (X86_64) File generated at Tue Jan 20 16:55:05 2015 On host 'lse86' by 'cae42' """ from __future__ import division ...
esult(mech1.Result.Displacement(['exc_f_r', 'rec_f_r', 'sen
_coat_r', 'silicon_r'])) mech1.addResult(mech1.Result.Displacement(['observer_point_1', 'observer_point_2', 'observer_point_3', 'observer_point_4', 'observer_point_e4'], 'amplPhase', 'mesh', [text])) trans1.addPhysic(mech1) simulation.addAnalysis(trans1)
ercpe/pymax
tests/cube.py
Python
gpl-3.0
14,840
0.0031
# -*- coding: utf-8 -*- import socket import unittest import sys import datetime from pymax.objects import DeviceList, RFAddr if sys.version_info.major == 2 or (sys.version_info.major == 3 and sys.version_info.minor <= 2): from mock import Mock else: from unittest.mock import Mock from pymax.messages import ...
1", encoding='utf-8'))) return c def test_set_mode_auto(self): c = self._mocked_cube() response = c.set_mode_auto(123, '001122') c.send_message.assert_called_with(SetTemperatureAndModeMessage('001122', 123, 0x0)) self.assertIsInstance(response, SetResponse) def test_set...
elf): c = self._m
sileht/deb-openstack-nova
nova/tests/test_imagecache.py
Python
apache-2.0
27,589
0.000036
#!/usr/bin/python # vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 Michael Still and Canonical Inc # 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...
stance-00000003']) self.stubs.Set(os.path, 'exists', lambda x: x.find('instance-') != -1) self.stubs.Set(virtutils, 'get_disk_backing_file', lambda x: 'e97222e91fc4241f49a7f520d1dcf446751129b3_sm') found = os.path.join(FLAGS.instances_path, '_base',...
anager = imagecache.ImageCacheManager() image_cache_manager.unexplained_images = [found] image_cache_manager.instance_names = self.stock_instance_names inuse_images = image_cache_manager._list_backing_images() self.assertEquals(inuse_images, [found]) self.assertEquals(len(image...
harshilasu/LinkurApp
y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/unit/cloudsearch/test_search.py
Python
gpl-3.0
13,603
0.00147
#!/usr/bin env python from tests.unit import unittest from httpretty import HTTPretty import urlparse import json import mock import requests from boto.cloudsearch.search import SearchConnection, SearchServiceException HOSTNAME = "search-demo-use
rdomain.us-east-1.cloudsearch.amazonaws.com" FULL_URL = 'http://%s/2011-02-01/search' % HOSTNAME class CloudSearchSearchBaseTest(unittest.TestCase): hits = [ { 'id': '12341', 'title': 'Document 1', }, { 'id': '12342', 'title': 'Document 2', ...
'id': '12345', 'title': 'Document 5', }, { 'id': '12346', 'title': 'Document 6', }, { 'id': '12347', 'title': 'Document 7', }, ] content_type = "text/xml" response_status = 200 def get_args...
LucasMagnum/pyexplain
pyexplain/website/migrations/0003_auto__add_unique_category_name.py
Python
mit
1,760
0.007955
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm)
: # Adding unique constraint on 'Category', fields ['name'] db.create_
unique(u'website_category', ['name']) def backwards(self, orm): # Removing unique constraint on 'Category', fields ['name'] db.delete_unique(u'website_category', ['name']) models = { u'website.category': { 'Meta': {'object_name': 'Category'}, 'description': ('...
SBRG/ssbio
ssbio/protein/structure/homology/itasser/itasserprep.py
Python
mit
10,329
0.00242
from __future__ import print_function import getpass import logging import os import os.path as op from ssbio.protein.sequence.utils import fasta as fasta log = logging.getLogger(__name__) class ITASSERPrep(): """Prepare a protein sequence for an I-TASSER homology modeling run. The main utilities of this ...
return itasser_dir def prep_script_local(self, itasser_loc, itlib_loc): script_file = '{}.sh'.format(self.id) outfile = os.path.join(self.root_dir, script_file) itasser = {'executable': op.join(itasser_loc, 'I-TASSERmod/runI-TASSE
R.pl'), 'pkgdir': itasser_loc, 'libdir': itlib_loc, 'seqname': self.id, 'datadir': self.execute_dir, 'java_home': self.java_home, 'additional_options': self.additional_options, 'light': s...
numenta/htmresearch
projects/sdr_paper/sdr_paper_unions.py
Python
agpl-3.0
16,962
0.014562
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2016, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
rror probabilities with unions. # Probability a given bit is 0 after M union operation M = Symbol("M") p0 = Pow((1-(s/n)),M) # Expected number of ON bits after M union operations. numOnBits = (1-p0)*n # If a dendrite has s synapses, and the activity at time t is a union of # M patterns, plot probability of a false ...
dritevsMPatterns(n_=1000): a_ = 30 theta_ = 10 s_ = 20 # Arrays used for plotting MList = [] errorList = [] print "\n\nn=%d, a=%d, theta=%d, s=%d" % (n_,a_,theta_,s_) error = 0.0 for M_ in range(1, 40): # Number of bits active in At atAfterUnion = numOnBits.subs(n, n_).subs(s, a_).subs(M,M...
fedora-conary/rmake-2
rmake_test/functional_test/buildtest/buildtrovetest.py
Python
apache-2.0
1,443
0.001386
# # Copyright (c) SAS Institute Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
(1, trv.getName(), trv.getVersion(), trv.getFlavor()) f = failure.MissingDependencies([(trv.getNameVersionFlavor(), deps.parseDep('trove: blam trove:foo'))]) bt.setFailureReason(f) frz = apiutils.freeze('BuildTrove', bt) bt...
assert(bt2.getFlavor() == bt.getFlavor())
amadeusproject/amadeuslms
topics/migrations/0008_auto_20201017_0913.py
Python
gpl-2.0
490
0.002041
# -*- coding: utf-8 -*- #
Generated by Django 1.11.29 on 2020-10-17 12:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('topics', '0007_auto_20170123_1911'), ] operations = [ migrations.AlterField( model_name=...
name='All Students'), ), ]
vuquangtam/WebAPI-Flask
app/mod_remote/api/remotedesktop.py
Python
mit
696
0.00431
from PIL import ImageGrab from StringIO import StringIO import pyautogui class RemoteDesktop: def __init__(self): self.size = pyautogui.size() self.quality = 50 def changeQuality(self, quality): self.quality = quality return quality def getPicture(self...
return self.size def click(
self, x, y, button="left"): pyautogui.click(x=x, y=y, button=button) def typewrite(self, data): pyautogui.typewrite(data)
praekelt/go-contacts-api
go_contacts/tests/test_server.py
Python
bsd-3-clause
15,751
0.00019
""" Tests for contacts API cyclone server. These tests are run against both the real implementation of the API and the verified fake implementation in order to verify that both behave correctly. """ import json import yaml from twisted.internet.defer import inlineCallbacks, returnValue from vumi.persist.txriak_mana...
er_page": 10, }) err = self.assertRaises(ConfigError, ContactsApi, configfile) self.assertEqual( str(err), "Missing required config field 'max_groups_per_page'") def test_collections(self): api = self.mk_api() self.assertEqual(api.collections, ( ...
_collection), )) @inlineCallbacks def test_route(self): api = self.mk_api() collection = api.contact_backend.get_contact_collection( self.OWNER_ID.encode("utf-8")) key, data = yield collection.create(None, { "msisdn": u"+12345", }) contact...
winksaville/meson
mesonbuild/mconf.py
Python
apache-2.0
9,662
0.003933
#!/usr/bin/env python3 # Copyright 2014-2016 The Meson development team # 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...
self.coredata.external_link_args[lang] = newvalue elif k.endswith('args'): lang = k[:-4] if not lang in self.coredata.external_args: raise ConfException('Unknown language %s in compile args' % lang) # TODO same fix as above ...
else: raise ConfException('Unknown option %s.' % k) def print_conf(self): print('Core properties:') print(' Source dir', self.build.environment.source_dir) print(' Build dir ', self.build.environment.build_dir) print('') print('Core options:') ...
bboalimoe/ndn-cache-policy
docs/sphinx-contrib/nwdiag/sphinxcontrib/nwdiag.py
Python
gpl-3.0
10,218
0.001174
# -*- coding: utf-8 -*- """ nwdiag.sphinx_ext ~~~~~~~~~~~~~~~~~~~~ Allow nwdiag-formatted diagrams to be included in Sphinx-generated documents inline. :copyright: Copyright 2010 by Takeshi Komiya. :license: BSDL. """ from __future__ import absolute_import import os import re import tracebac...
>' % (x1, y1, x2, y2, node.href) self.body.append(areatag) self.body.append('</map>') def html_render_png(self, node): image = node.to_drawer('PNG', self.builder) if not os.path.isfile(image.
filename): image.draw() image.save() # align if 'align' in node['options']: align = node['options']['align'] self.body.append('<div align="%s" class="align-%s">' % (align, align)) self.context.append('</div>\n') else: self.body.append('<div>') self.co...
astrofrog/ginga
ginga/misc/Callback.py
Python
bsd-3-clause
2,723
0.005876
# # Callback.py -- Mixin class for programmed callbacks. # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. # import sys, traceback class CallbackError(Exception): pass...
#return self.cb.has_key(name) and (len(self.cb[name]) > 0) return self.cb.has_key(name
) def add_callback(self, name, fn, *args, **kwdargs): try: self.cb[name].append((fn, args, kwdargs)) except KeyError: raise CallbackError("No callback category of '%s'" % ( name)) # TODO: to be deprecated def set_callback(self, name, fn, *arg...
sangelone/gstack
stackmachine.py
Python
gpl-2.0
5,419
0.004982
import operator import math class Machine(): """Simple stack based machine designed for genetic programming (GP) experiments. Easy to use and forgiving with nonfatal errors. See README and tests for examples. """ def __init__(self, debug=False): self.stack = [] self.debug = ...
: line = line.strip().upper() print num, '\t', line def evaluate(self, line): if line: debug = self.debug if debug: print self._curline, '> ', line tokens = line.split() instr = tokens[0]
if instr == 'END': return False if len(tokens) > 1: values = tokens [1:] else: values = [] try: self.instructions[instr](*values) except Exception as e: if debug: print "Error:", e self.has_errors...
aronbierbaum/txsuds
suds/transport/sslverify.py
Python
lgpl-3.0
2,858
0.003499
import logging import re from OpenSSL import SSL from twisted.python.failure import Failure from twisted.internet.ssl import Certificate, VerificationError from twisted.internet._sslverify import ClientTLSOptions, OpenSSLCertificateOptions, verifyHostname log = logging.getLogger(__name__) def optionsForC...
ide the base implementation to provide better hostn
ame verification. @param connection: the connection which is handshaking. @type connection: L{OpenSSL.SSL.Connection} @param where: flags indicating progress through a TLS handshake. @type where: L{int} @param ret: ignored @type ret: ignored """ if whe...
JGulbronson/rmc
html_snapshots/snapshot.py
Python
mit
1,734
0
import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'), url, ] rendere...
full_url = os.path.join(base_url, file_url) rendered_html = crawl_page(full_url) print 'Writing: %s' % url utils.write(file_
path, rendered_html) if __name__ == "__main__": parser = argparse.ArgumentParser( description='Process snapshotting arguments') parser.add_argument('base_url', type=str) parser.add_argument('--overwrite', dest='overwrite', action='store_true') args = parser.parse_args() me.connect(c.MO...