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
mzdaniel/django-selenium-test-runner
tests/manage.py
Python
bsd-3-clause
665
0.003008
#!/usr/bin/env python from django.core.management import execute_manager try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr
.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(
If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) if __name__ == "__main__": # Allow Django commands to run even without package installation. import sys sys.path = ['..'] + sys.path execute_manager(settings)
edx-solutions/edx-platform
lms/djangoapps/courseware/tests/test_word_cloud.py
Python
agpl-3.0
8,875
0.000903
# -*- coding: utf-8 -*- """Word cloud integration tests using mongo modulestore.""" import json from operator import itemgetter from xmodule.x_module import STUDENT_VIEW from .helpers import BaseTestXmodule class TestWordCloud(BaseTestXmodule): """Integration test for word cloud xmodule.""" CATEGORY = "wo...
= [ u"small", u"big", u"spaced", u"few words", ] users_state = self._post_words(input_words) self.assertEqual( ''.join(set([ content['status'] for _, content in users_state.items() ...
])), 'success') correct_state = {} for index, user in enumerate(self.users): correct_state[user.username] = { u'status': u'success', u'submitted': True, u'display_student_percents': True, u'student_words':...
wannabeCitizen/quantifiedSelf
app/user_auth.py
Python
mit
6,825
0.000586
from tornado import gen from tornado import web from tornado import ioloop import uuid import os import pickle from lib.database.users import user_insert from lib.database.users import get_user from lib.database.users import get_user_from_email from lib.database.reservations import create_ticket_reservation from lib....
user = yield get_user_from_email(email) if user is not None: user_id = user['id'] self.set_secure_cookie("user_id", user_id) # check for any previous confirmed booking reservation = yield get_reservation_for_user(user_id)
if reservation is not None and\ reservation['confirmation_code'] != "": return self.error( 403, "Sorry, you already have a ticket for the show." ) else: user_id = yield user_insert(name, email, showtime_id) ...
0xporky/mgnemu-python
mgnemu/routes.py
Python
mit
1,677
0
# -*- coding: utf-8 -*- from os import urandom from flask import Flask from flask import request from flask_httpauth import HTTPDigestAuth from mgnemu.controllers.check_tape import CheckTape app = Flask(__name__) app.config['SECRET_KEY'] = str(urandom(24)) auth = HTTPDigestAuth() @auth.get_password def get_pw(usern...
te_nonce(): # TODO: we need add clear auth return str(urandom(8)) @auth.generate_opaque def generate_opaqu
e(): # TODO: we need add clear auth return str(urandom(8)) @auth.verify_nonce def verify_nonce(nonce): # TODO: we need add clear auth return True @auth.verify_opaque def verify_opaque(opaque): # TODO: we need add clear auth return True @app.route('/cgi/status', methods=['GET']) def get_sta...
renardchien/Software-Development-on-Linux--Open-Source-Course-
Labs/Lab 4/Student Files/Hello.py
Python
lgpl-3.0
766
0.007833
#!/usr/bin/env python # # Hello World # # Copyright 2012 Cody Van De Mark # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3.0 of the License, or (at your option) any...
General Public # License along with this library. If not, see <http://www.gnu.org/licenses/>. # # print("He
llo World")
paulocsanz/algebra-linear
scripts/runge_kutta_2a.py
Python
agpl-3.0
431
0.011601
#!/usr/bin/env python3 from math import log, exp def RungeKutta2aEDO (x0, t0, tf, h, dX): xold = x0 told = t0 ret = [] while (told <= tf): ret += [(told, xold)] k1 = dX(xold, told) k2 = dX(xold + h*k1, told+h) xold = xold + h/2 * (k1+k2) told
= roun
d(told + h,3) return ret if __name__ == "__main__": dX = lambda x, t: t + x RungeKutta2aEDO(0, 0, 1, 0.1, dX)
munhyunsu/Hobby
TestResponse/testresponse.py
Python
gpl-3.0
878
0.001139
#!/usr/bin/python3 # -*- coding: utf-8 -*- import urllib.request import time from bs4 impor
t BeautifulSoup def main(): url = 'http://www.pokemonstore.co.kr/shop/main/index.php' print('For exit, press ctrl + c') while(True): try: with urllib.request.urlopen(url) as f:
if f.code == 200: html = f.read() soup = BeautifulSoup(html, 'html5lib') if soup.title is not None: print(f.code, 'Success', soup.title.text, '\a') else: print(f.code, 'Connected but not html...
CTSRD-SOAAP/chromium-42.0.2311.135
native_client/buildbot/buildbot_lib.py
Python
bsd-3-clause
21,434
0.014276
#!/usr/bin/python # Copyright (c) 2012 The Native Client Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os.path import shutil import subprocess import sys import time import traceback ARCH_MAP = { '32': { ...
bot(): goma_opts = [ 'use_goma=1', 'gomadir=/b/build/goma', ] else: goma_opts = [] context.SetEnv('GYP_DEFINES', ' '.join( context['gyp_vars'] + goma_opts + extra_vars)) def SetupLinuxEn
vironment(context): SetupGyp(context, ['target_arch='+context['gyp_arch']]) def SetupMacEnvironment(context): SetupGyp(context, ['target_arch='+context['gyp_arch']]) def SetupAndroidEnvironment(context): SetupGyp(context, ['OS=android', 'target_arch='+context['gyp_arch']]) context.SetEnv('GYP_GENERATORS', '...
quickresolve/accel.ai
flask-aws/lib/python2.7/site-packages/ebcli/containers/multicontainer.py
Python
mit
2,306
0.001735
from . import commands from . import compose from . import dockerrun from ..core import fileoperations from ..objects.exceptions import CommandError class MultiContainer(object): """ Immutable class used to run Multi-containers. """ PROJ_NAME = 'elasticbeanstalk' def __init__(self, fs_handler, s...
eb local setenv a=b ..." but not ones in Dockerrun.aws.json merged_env = setenv_env.merge(opt_env) self.fs_handler.make_docker_compose(merged_env) def _up(self): commands.up(compose_path=self.pathconfig.compose_path(), allow_insecure_ssl=self.allo
w_insecure_ssl) def _remove(self): for service in self.list_services(): try: commands.rm_container(service, force=True) except CommandError: pass
Nth-iteration-labs/streamingbandit
app/defaults/E-Greedy/get_action.py
Python
mit
312
0.009615
e = .1 mean_list = base.List(self.get_theta(key="treatment"), base.Mean, ["control", "treatment"]) if np.random.binomial(1,e) == 1: self.action["treatment"] = mean_list.random()
self.action["propensity"] = 0.1*0.5 else: self.action["treatment"] = mean_list.max()
self.action["propensity"] = (1-e)
UltrasoundSam/TekDPO2000
TekScope.py
Python
gpl-3.0
7,366
0.007738
#!/usr/bin/env python # -*- coding: utf-8 -*- # # TekScope.py # # Copyright 2016 Samuel Hill <samuel.hill@warwick.ac.uk> # # 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...
) values[i+1] = buff * self.info['
YMult'] self.close() self.open() return (t, values.mean(axis=0)) def reset(self): ''' Resets scope to default settings ''' self.set_param('*RST')
davidcandal/gr-tfg
examples/testNWK.py
Python
gpl-3.0
4,815
0.0081
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: TFG # Author: David Candal # Description: SDR ZigBee # Generated: Mon Sep 19 21:01:18 2016 ################################################## if __name__ == '__main__': import ct...
on import eng_option from gnuradio.filter import firdes from ieee802_15_4_oqpsk_phy import ieee802_15_4_oqpsk_phy # grc-generated hier_block from optparse import OptionParser import foo import pmt import tfg class testNWK(gr.top_block, Qt.QWidget): def __init__(self): gr.top_block.__init__(self, "TFG") ...
pass self.top_scroll_layout = Qt.QVBoxLayout() self.setLayout(self.top_scroll_layout) self.top_scroll = Qt.QScrollArea() self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame) self.top_scroll_layout.addWidget(self.top_scroll) self.top_scroll.setWidgetResizable(True...
RevansChen/online-judge
Codewars/8kyu/geometry-basics-circle-area-in-2d/Python/solution1.py
Python
mit
100
0.02
# Python - 3.
6.0 circle_area = lambda circle: round(circle.radius ** 2 * __import__('math')
.pi, 6)
google/google-ctf
third_party/edk2/BaseTools/Source/Python/UPT/Parser/InfSourceSectionParser.py
Python
apache-2.0
5,413
0.003141
## @file # This file contained the parser for [Sources] sections in INF file # # Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials are licensed and made available # under the terms and conditions of the BSD License which accompanies this # dist...
COMMENT_SPLIT) > -1: TailComments = SrcLineContent[SrcLineContent.find(DT.TAB_COMMENT_SPLIT):] SrcLineContent = SrcLineContent[:SrcLineContent.find(DT.TAB_COMMENT_S
PLIT)] if LineComment is None: LineComment = InfLineCommentObject() LineComment.SetTailComments(TailComments) # # Find Macro # Name, Value = MacroParser((SrcLineContent, SrcLineNo), ...
rahulg/eulerswift
setup.py
Python
mit
1,487
0.002017
import sys import EulerPy try: from setuptools import setup except ImportError: from distutils.core import setup def readme(): with open('README.rst') as f: return f.re
ad() def requirements(): install_requires = [] with open('requirements.txt') as f: for line in f: install_requires.append(line.strip()) # Terminal colors for Windows if 'win32' in str(sys.platform).lower(): install_requires.append('colorama>=0.2.4') return install_requ...
version=EulerPy.__version__, description=EulerPy.__doc__.strip(), long_description=readme(), url='https://github.com/iKevinY/EulerPy', author=EulerPy.__author__, author_email='me@kevinyap.ca', license=EulerPy.__license__, packages=['EulerPy'], entry_points={'console_scripts': ['euler =...
plotly/plotly.py
packages/python/plotly/plotly/validators/scatter3d/marker/colorbar/_showexponent.py
Python
mit
546
0
import _plotly_utils.basevalidators class ShowexponentValidator(_plotly_utils.basevalidators.EnumeratedValidator): def __init__( self,
plotly_name="showexponent", parent_name="scatter3d.marker.colorbar", **kwargs ): super(ShowexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name
, edit_type=kwargs.pop("edit_type", "calc"), values=kwargs.pop("values", ["all", "first", "last", "none"]), **kwargs )
iotaledger/iota.lib.py
iota/api_async.py
Python
mit
57,097
0.000841
from typing import Dict, Iterable, Optional from iota import AdapterSpec, Address, BundleHash, ProposedTransaction, Tag, \ TransactionHash, TransactionTrytes, TryteString, TrytesCompatible from iota.adapter import BaseAdapter, resolve_adapter from iota.commands import CustomCommand, core, extended from iota.crypto...
ated with the adapter. # Logically, `local_pow` will decide if the api call does pow # via pyota-pow extension, or sends the request to a node. # But technically, the parameter belongs to the adapter. self.adapter.set_local_pow(local_pow) self.devnet = devnet def create_comm...
Creates a pre-configured CustomCommand instance. This method is useful for invoking undocumented or experimental methods, or if you just want to troll your node for awhile. :param str command: The name of the command to create. """ return CustomCommand(self.adapte...
edx/course-discovery
course_discovery/apps/course_metadata/migrations/0091_auto_20180727_1844.py
Python
agpl-3.0
1,487
0.00269
# Generated by Django 1.11.11 on 2018-07-27 18:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('course_metadata', '0090_degree_curriculum_reset'), ] operations = [ migrations.AddField( model_name='degree', nam...
options={'verbose_name_plural': 'Degrees'}
, ), ]
timothycrosley/thedom
thedom/social.py
Python
gpl-2.0
14,474
0.009811
""" Social.py Contains elements that enable connecting with external social sites. Copyright (C) 2015 Timothy Edmund Crosley 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;...
if description
: arguments['description'] = description return ClientSide.call("FB.
leedoowon/MTraceCheck
src_main/codegen_common.py
Python
apache-2.0
10,228
0.003911
#!/usr/bin/python ########################################################################## # # MTraceCheck # Copyright 2017 The Regents of the University of Michigan # Doowon Lee and Valeria Bertacco # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance ...
(%s) signature + t * TEST_BSS_SIZE_PER_THREAD + w * sizeof(%s);\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += "
%s result = (%s)*(%s*)address;\n" % (wordTypeString, wordTypeString, wordTypeString) cppString += " resultVector.push_back(result);\n" #cppString += "#ifndef NO_PRINT\n" cppString += "#if 0\n" cppString += " printf(\" 0x%%0%dlx\", result);\n" % (regBitWidth / 8 * 2...
dunkhong/grr
grr/server/grr_response_server/flows/general/checks_test.py
Python
apache-2.0
4,415
0.004304
#!/usr/bin/env python """Test the collector flows.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import os from absl import app from future.utils import iterkeys from grr_response_core import config from grr_response_core.lib.parsers import config_f...
onfigParser) @parser_test_lib.WithParser("Pswd", linux_file_parser.LinuxSystemPasswdParser) def
testChecksProcessResultContext(self): """Test the flow returns parser results.""" client_id = self.SetupLinuxUser() _, results = self.RunFlow(client_id) # Detected by result_context: PARSER exp = "Found: Sshd allows protocol 1." self.assertCheckDetectedAnom("SSHD-CHECK", results, exp) # Det...
cvdlab/lar-running-demo
py/computation/old/step_calcchains_serial_tobinary_filter.py
Python
mit
8,263
0.049498
# -*- coding: utf-8 -*- from lar import * from scipy import * import json import scipy import numpy as np import time as tm import gc from pngstack2array3d import * import struct import getopt, sys import traceback # import matplotlib.pyplot as plt # ------------------------------------------------------------ # Logg...
'Args: -r -b <borderfile> -x <borderX> -y <borderY> -z <borderZ> -i <inputdirectory> -c <colors> -d <coloridx> -o <outputdir> -q <bestimage>' try: opts, args = getopt.getopt(argv,"rb:x:y:z:i:c:d:o:q:") except getopt.GetoptError: print ARGS_STRING sys.exit(2) nx = ny = nz = imageDx = imageDy = imageDz = 64 ...
mandatory = 6 calculateout = False #Files BORDER_FILE = 'bordo3.json' BEST_IMAGE = '' DIR_IN = '' DIR_O = '' for opt, arg in opts: if opt == '-x': nx = ny = nz = imageDx = imageDy = imageDz = int(arg) mandatory = mandatory - 1 elif opt == '-y': ny = nz = imageDy = imageDz = int(arg) elif opt...
olbat/distem
test/experimental_testing/exps/latency.py
Python
gpl-3.0
1,573
0.003814
#!/usr/bin/env python # this program is used to test latency # don't test RTT bigger than 3 secs - it will break # we make sure that nothing breaks if there is a packet missing # this can rarely happen import select import socket import time import sys import struct def pong(): # easy, receive and send back ...
art) for x in xrange(10): # send many packets to be (almost) sure the other end is done s.sendto('x', (addr, 1234)) return errs >= 3 if __name__ == '__main__': if 'ping' in sys.argv: ret = ping(sys.argv[2], int(sys.argv[3])) elif 'pong' in sys.argv: ret = pong() els...
t(ret)
genehallman/node-berkeleydb
deps/db-18.1.40/dist/winmsi/genWix.py
Python
mit
10,795
0.036035
# # # genWix.py is used to generate a WiX .wxs format file that # can be compiled by the candle.exe WiX compiler. # # Usage: python genWix.py <output_file> # # The current directory is expected to be the top of a tree # of built programs, libraries, documentation and files. # # The list of directories traversed is at ...
akeId(self, id): tid = id.replace("-","_") if len(tid) > 70: #print "chopping string %s"%tid tid = tid[len(tid)-70:len(tid)] # id can't start with a number... i = 0 while 1: try: int(tid[i]) except: break i = i+1 return tid[i:len(tid)] return tid # turn na...
s into Windows 8.3 names. # A semi-unique "ID" is inserted, using 3 bytes of hex, # which gives us a total of 4096 "unique" IDs. If # that number is exceeded in one class instance, a bad # name is returned, which will eventually cause a # recognizable failure. Names look like: ABCD~NNN.EXT # ...
chrisdjscott/Atoman
atoman/filtering/filterer.py
Python
mit
18,810
0.005848
""" The filterer object. @author: Chris Scott """ from __future__ import absolute_import from __future__ import unicode_literals import copy import time import logging import numpy as np import six from six.moves import zip from .filters import _filtering as filtering_c from ..system.atoms import elements from . i...
r" % "".join(words) moduleName = filterObjectName[:1].lower() + filterObjectName[1:] self.logger.debug("Loading filter module: '%s'", moduleName) self.logger.debug("Creating filter object: '%s'", filterObjectName) # get module filterModule = g...
me) # load dialog filterObject = getattr(filterModule, filterObjectName, None) if filterObject is None: self.logger.error("Could not locate filter object for: '%s'", filterName) else: self.logger.info("Running filt...
grantstephens/pyluno
setup.py
Python
mit
1,485
0
from setuptools import setup, find_pa
ckages with open('pyluno/meta.py') as f: exec(f.read()) setup( name='pyluno', version=__version__, packages=find_packages(exclude=['tests']), description='A Luno API for Python', author='Cayle Sharrock/Grant Stephens', author_email='grant@stephens.co.za', scripts=['demo.py'], instal...
'https://github.com/grantstephens/pyluno', download_url='https://github.com/grantstephens/pyluno/tarball/%s' % (__version__, ), keywords='Luno Bitcoin exchange API', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OS...
HarmonyEnterpriseSolutions/harmony-platform
src/gnue/common/datasources/GLoginHandler.py
Python
gpl-2.0
9,003
0.026325
# GNU Enterprise Common Library - Base Login Handler # # Copyright 2000-2007 Free Software Foundation # # This file is part of GNU Enterprise. # # GNU Enterprise 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;...
==========================
================================================ class BasicLoginHandler (LoginHandler): """ Class implementing a basic login handler using raw_input () and getpass () as input methods. """ # --------------------------------------------------------------------------- # Constructor # ---------------------------...
caglar10ur/anvio
setup.py
Python
gpl-3.0
2,549
0.016869
import os import sys import glob try: import numpy except ImportError: print "You need to have numpy installed on your system to run setup.py. Sorry!" sys.exit() try: from Cython.Distutils import build_ext except ImportError: print "You need to have Cython installed on your system to run setup.py....
().strip(), scripts = [script for script in glob.glob('bin/*') if not script.endswith('-OBSOLETE')], include_package_data = True, packages = find_packages(), install_requires = ['bottle>=0.12.7', 'pysam>=0.8.3', 'hcluster>=0.2.0', 'ete2>=2.2', 'scipy', 'scikit-learn>=0.15', 'django>=1.7', 'cython>=0....
rofile', sources = ['./anvio/extensions/columnprofile.c']), Extension("anvio.vbgmm", sources=["./anvio/extensions/concoct/vbgmm.pyx", "./anvio/extensions/concoct/c_vbgmm_fit.c"], libraries =['gsl', 'gslcblas'], include_dirs=include_dirs_for_concoct), ...
pchmieli/h2o-3
h2o-py/tests/testdir_algos/glrm/pyunit_DEPRECATED_arrests_missingGLRM.py
Python
apache-2.0
3,136
0.009885
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils import numpy as np def glrm_arrests_miss(): missing_ratios = np.arange(0.1, 1, 0.1).tolist() print "Importing USArrests.csv data and saving for validation..." arrests_full = h2o.upload_file(pyunit_utils.locate("smal...
_values(fraction
=ratio) arrests_miss.describe() print "H2O GLRM with {0}% missing entries".format(100*ratio) arrests_glrm = h2o.glrm(x=arrests_miss, validation_frame=arrests_full, k=4, ignore_const_cols=False, loss="Quadratic", regularization_x="None", regularization_y="None", init="PlusPlus", max_iter...
wldcordeiro/servo
tests/wpt/web-platform-tests/tools/manifest/tests/test_sourcefile.py
Python
mpl-2.0
5,974
0.000167
from ..sourcefile import SourceFile def create(filename, contents=b""): assert isinstance(contents, bytes) return SourceFile("/", filename, "/", contents=contents) def items(s): return [ (item.item_type, item.url) for item in s.manifest_items() ] def test_name_is_non_test(): non...
ame_is_multi_global assert not s.name_
is_worker assert not s.name_is_reference assert not s.content_is_testharness assert items(s) == [] def test_testharness_svg(): content = b"""\ <?xml version="1.0" encoding="UTF-8"?> <svg xmlns="http://www.w3.org/2000/svg" xmlns:h="http://www.w3.org/1999/xhtml" version="1.1" ...
nozuono/calibre-webserver
setup/installer/windows/freeze.py
Python
gpl-3.0
32,114
0.004266
#!/usr/bin/env python # vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai from __future__ import with_statement __license__ = 'GPL v3' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import sys, os, shutil, glob, py_compile, subprocess, re, zipfile, time, textwrap fr...
base = self.j(self.SRC, 'calibre', 'plugins') for f in glob.glob(self.j(base, '*.pyd')): # We dont want the manifests as the manifest in the exe will be # used instead shutil.copy2(f, tgt) def fix_pyd_bootstraps_in(self, folder): for dirpath, dirnames, fi...
enames in os.walk(folder): for f in filenames: name, ext = os.path.splitext(f) bpy = self.j(dirpath, name + '.py') if ext == '.pyd' and os.path.exists(bpy): with open(bpy, 'rb') as f: raw = f.read().strip() ...
jricardo27/travelhelper
travelhelper/apps/lonelyplanet/models/sight.py
Python
bsd-3-clause
8,871
0.000789
""" Lonely Planet Sight Model """ from __future__ import absolute_import, print_function import re from bs4 import BeautifulSoup from django.db import models from django.utils.translation import ugettext as _ from core.models.sight import THSight from core.utils import urllib2 from .abstract import LonelyPlanetAbst...
@classmethod def update_sight(cls, sight, overwrite=False, **kwargs): """ Update some properties of the sight """ if not sight: return verbose = kwargs.get('verbose', 0) if sight.update_html_source(overwrite=overwrite, verbose=v
erbose): sight.save() cls._log( _(u'Saved sight: {name}'), name=sight.name, verbose=verbose, ) @classmethod def build_from_url(cls, url, parent=None, recursive=True, **kwargs): """ Given an url, extract and buil...
nteract/papermill
papermill/tests/test_execute.py
Python
bsd-3-clause
16,273
0.003318
import os import io import shutil import tempfile import unittest from functools import partial from pathlib import Path from nbformat import validate try: from unittest.mock import patch except ImportError: from mock import patch from .. import engines from ..log import logger from ..iorw import load_noteb...
me = os.path.join(self.test_dir, 'output_{}'.format(notebook_name)) execute_notebook(get_notebook_path(notebook_name), nb_test_executed_fname, {'msg': 'Hello'}) test_nb = load_notebook_node(nb_test_executed_fname) self.assertListEqual( test_nb.cells[0].get('source').split('\n'), ['# ...
est_nb.metadata.papermill.parameters, {'msg': 'Hello'}) def test_quoted_params(self): execute_notebook(self.notebook_path, self.nb_test_executed_fname, {'msg': '"Hello"'}) test_nb = load_notebook_node(self.nb_test_executed_fname) self.assertListEqual( test_nb.cells[1].get('sourc...
goal/uwsgi
plugins/emperor_zeromq/uwsgiplugin.py
Python
gpl-2.0
98
0
NAME = 'em
peror_zeromq' CFLAGS = [] LDFLAGS = [] LIBS = ['-lzmq'] GCC_LIST =
['emperor_zeromq']
matthew-brett/scipy
scipy/integrate/_ivp/tests/test_rk.py
Python
bsd-3-clause
1,326
0
import pytest from numpy.testing import assert_allclose, assert_ import numpy as np from scipy.integrate import RK23, RK45, DOP853 from scipy.integrate._ivp import dop853_coefficients @pytest.mark.parametrize("solver", [RK23, RK45, DOP853]) def test_coefficient_properties(solver): assert_allclose(np.sum(solver.B)...
def test_error_estimation_complex(solver_class
): h = 0.2 solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h) solver.step() err_norm = solver._estimate_error_norm(solver.K, h, scale=[1]) assert np.isrealobj(err_norm)
smokeyfeet/smokeyfeet-registration
src/smokeyfeet/registration/migrations/0001_initial.py
Python
mit
4,391
0.004555
# Generated by Django 3.1 on 2020-08-13 19:23 from django.db import migrations, models import django.db.models.deletion import django_countries.fields import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( nam...
'ordering': ['sort_order'], }, ), mi
grations.CreateModel( name='PassType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(choices=[('party', 'Party Pass'), ('full', 'Full Pass')], max_length=32)), ...
frankrousseau/weboob
weboob/tools/log.py
Python
agpl-3.0
2,262
0
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Romain Bignon # # This file is part of weboob. # # weboob 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...
rd) if levelname in COLORS: msg = COLORS[levelname] % msg return msg def createColoredFormatter(stream, format): if (sys.platform != 'win32') and stream.isatty(): return ColoredFormatter(format) else: return Formatter(format) if __name__ == '__mai
n__': for levelname, cs in COLORS.items(): print(cs % levelname, end=' ')
jaeilepp/eggie
mne/io/kit/kit.py
Python
bsd-2-clause
28,437
0
"""Conversion tool from SQD to FIF RawKIT class is adapted from Denis Engemann et al.'s mne_bti2fiff.py """ # Author: Teon Brooks <teon@nyu.edu> # # License: BSD (3-clause) import os from os import SEEK_CUR from struct import unpack import time import numpy as np from scipy import linalg from ..pick import pick_t...
as_date'] = int(time.time()) self.info['projs'] = [] self.info['comps'] = [] self.info['lowpass'] = self._sqd_params['lowpass'] self.info['highpass'] = self._sqd_params['highpass'] self.info['sfreq'] = float(self._sqd_params['sfreq']) # meg channels plus synthetic channel...
tim'] = None, None self.info['filename'] = None self.info['ctf_head_t'] = None self.info['dev_ctf_t'] = [] self._filenames = [] self.info['dig'] = None self.info['dev_head_t'] = None if isinstance(mrk, list): mrk = [read_mrk(marker) if isinstance(mark...
rhennigan/code
python/spaceshipTrajectory.py
Python
gpl-2.0
1,346
0.013373
# PROBLEM 3 # # Modify the below functions acceleration and # ship_trajectory to plot the trajectory of a # spacecraft with the given initial position # and velocity. Use the Forward Euler Method # to accomplish this. #from udacityplots import * import math import numpy import matplotlib h = 1.0 # ...
t * earth_mass / distance ** 2 * direction return acc def ship_trajectory(): num_steps = 13000 x = numpy.zeros([num
_steps + 1, 2]) # m v = numpy.zeros([num_steps + 1, 2]) # m / s x[0, 0] = 15e6 x[0, 1] = 1e6 v[0, 0] = 2e3 v[0, 1] = 4e3 for step in range(num_steps): x[step + 1] = x[step] + h * v[step] v[step + 1] = v[step] + h * acceleration(x[step]) return x, v x, v = ship...
simone-campagna/invoice
tests/unittests/test_db_types.py
Python
apache-2.0
11,568
0.005014
# -*- coding: utf-8 -*- # # Copyright 2015 Simone Campagna # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
rtIs(DateTimeList.db_from(None), None) self.assertEqual(DateTimeList.db_from("2015-01-04 13:34:45,2014-04-05 02:22:01"), [datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1)]) def test_db_to(self): self.assertIs(DateTimeList.db_to(None), None) self.assertEqual...
02:22:01") class TestDateTimeTuple(unittest.TestCase): def test_db_from(self): self.assertIs(DateTimeTuple.db_from(None), None) self.assertEqual(DateTimeTuple.db_from("2015-01-04 13:34:45,2014-04-05 02:22:01"), (datetime.datetime(2015, 1, 4, 13, 34, 45), datetime.datetime(2014, 4, 5, 2, 22, 1))) ...
scottclowe/python-continuous-integration
.github/workflows/system_info.py
Python
mit
575
0
""" Print out some
handy system info. """ import os import platform import sys print("Build system information") print() print("sys.version\t\t", sys.version.split("\n")) print("os.name\t\t\t", os.name) print("sys.platform\t\t", sys.platform) print("platform.system()\t", platform.system()) print("platform.machine()\t", platform.machin...
tform.uname()) if sys.platform == "darwin": print("platform.mac_ver()\t", platform.mac_ver())
BriData/DBus
dbus-mongo-extractor/tests/test_rollbacks.py
Python
apache-2.0
12,580
0.000636
# Copyright 2013-2016 MongoDB, 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 writin...
re replicated to doc manager") # Kill the new primary self.repl_set.secondary.stop(destroy=False) # Start both servers back up self.repl_set.primary.start() primary_admin = self.primary
_conn["admin"] assert_soon(lambda: primary_admin.command("isMaster")["ismaster"], "restarted primary never resumed primary status") self.repl_set.secondary.start() assert_soon(lambda: retry_until_ok(secondary.admin.command, 'replSetG...
mortbauer/openfoam-extend-Breeder-other-scripting-PyFoam
PyFoam/Basics/CustomPlotInfo.py
Python
gpl-2.0
5,311
0.024666
# ICE Revision: $Id$ """Information about custom plots""" from PyFoam.Basics.TimeLineCollection import TimeLineCollection from PyFoam.Basics.FoamFileGenerator import makeString from PyFoam.RunDictionary.ParsedParameterFile import FoamStringParser,PyFoamParserError from PyFoam.Error import error from PyFoam.ThirdPart...
Should
this plot be actually used?""" self.nr=CustomPlotInfo.nr CustomPlotInfo.nr+=1 # Setting sensible default values self.name="Custom%02d" % self.nr self.theTitle="Custom %d" % self.nr if name: self.name+="_"+name self.id=name self.theTitl...
aspaas/ion
test/functional/signrawtransactions.py
Python
mit
7,930
0.003153
#!/usr/bin/env python3 # Copyright (c) 2015-2016 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 transaction signing using the signrawtransaction RPC.""" from test_framework.test_framework impor...
rawTxSigned = self.nodes[0].signrawtransaction(rawTx, inputs, privKeys) # 1) The transaction has a complete set of signatures assert 'complete' in rawTxSigned assert_equal(rawTxSigned['complete'], True) # 2) No script verification error occurred assert 'errors' not in raw...
saction doesn't blow up on garbage merge attempts dummyTxInconsistent = self.nodes[0].createrawtransaction([inputs[0]], outputs) rawTxUnsigned = self.nodes[0].signrawtransaction(rawTx + dummyTxInconsistent, inputs) assert 'complete' in rawTxUnsigned assert_equal(rawTxUnsigned['complete'...
HybridF5/tempest_debug
tempest/api/identity/admin/v3/test_services.py
Python
apache-2.0
4,083
0
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
service(self, service_id): # Used for deleting the services created in this class self.services_client.delete_service(service_id) # Checking whether service is deleted successfully self.assertRaises(lib_exc.NotFound, self.
services_client.show_service, service_id) @test.attr(type='smoke') @test.idempotent_id('5193aad5-bcb7-411d-85b0-b3b61b96ef06') def test_create_update_get_service(self): # Creating a Service name = data_utils.rand_name('service') serv_type = data_utils.rand_...
mwiebe/dynd-python
dynd/nd/test/test_ctypes_interop.py
Python
bsd-2-clause
2,910
0.002405
import sys import unittest from dynd import nd, ndt import ctypes # ToDo: Reenable this with a Cython interface. # #class TestCTypesDTypeInterop(unittest.TestCase): # def test_type_from_ctype_typeobject(self): # self.assertEqual(ndt.int8, ndt.type(ctypes.c_int8)) # self.assertEqual(ndt.int16, ndt.type...
# def test_type_from_ctype_struct(
self): # class POINT(ctypes.Structure): # _fields_ = [('x', ctypes.c_int32), ('y', ctypes.c_int32)] # self.assertEqual(ndt.make_struct( # [ndt.int32, ndt.int32],['x', 'y']), # ndt.type(POINT)) # class DATA(ctypes.Structure): # ...
ramramps/mkdocs
mkdocs/relative_path_ext.py
Python
bsd-2-clause
4,804
0
""" # Relative Path Markdown Extension During the MkDocs build we rewrite URLs that link to local Markdown or media files. Using the following pages configuration we can look at how t
he output is changed. pages: - ['index.md'] - ['tutorial/install.md'] - ['tutorial/intro.md'] ## Markdown URLs When linking fr
om `install.md` to `intro.md` the link would simply be `[intro](intro.md)`. However, when we build `install.md` we place it in a directory to create nicer URLs. This means that the path to `intro.md` becomes `../intro/` ## Media URLs To make it easier to work with media files and store them all under one directory we...
jhamrick/nbgrader
nbgrader/alembic/versions/50a4d84c131a_add_kernelspecs.py
Python
bsd-3-clause
506
0
"""add kernelspecs Revision ID: 50a4d84c131a Revises: b6d005d67074 Create Date: 2017-06-01 16:48:02.243764 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '50a4d84c131a' down_revision = 'b6d005d67074' branch_labels = None depends_on = None def upgrade(): ...
n( 'kernelspec', sa.String(1024), nullable=False,
server_default='{}')) def downgrade(): op.drop_column('notebook', 'kernelspec')
benoitc/tproxy
tproxy/util.py
Python
mit
3,968
0.007056
# -*- coding: utf-8 - # # This file is part of tproxy released under the MIT license. # See the NOTICE for more information. try: import ctypes except MemoryError: # selinux execmem denial # https://bugzilla.redhat.com/show_bug.cgi?id=488396 ctypes = None except Impo
rtError: # Python on Solaris compiled with
Sun Studio doesn't have ctypes ctypes = None import fcntl import os import random import resource import socket # add support for gevent 1.0 from gevent import version_info if version_info[0] >0: from gevent.os import fork else: from gevent.hub import fork try: from setproctitle import setprocti...
paninetworks/neutron
neutron/db/ipam_non_pluggable_backend.py
Python
apache-2.0
22,516
0.000133
# Copyright (c) 2015 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
ackend(ipam_backend_mixin.IpamBackendMixin): @staticmethod def _generate_ip(context, subnets): try: return IpamNonPluggableBackend._try_generate_ip(context, subnets) except n_exc.IpAddressGenerationFailure: IpamNonPluggableBacke
nd._rebuild_availability_ranges(context, subnets) return IpamNonPluggableBackend._try_generate_ip(context, subnets) @staticmethod def _try_generate_ip(context, subnets): """Generate an IP address. The IP address will be ...
KoehlerSB747/sd-tools
src/main/python/util/StatsAccumulator.py
Python
apache-2.0
5,869
0.002897
# # Copyright 2008-2015 Semantic Discovery, 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 applicab...
urn self.getStandardDeviation() @property def variance(self): return self.getVariance() def clear(self, label=''): self._modlock.acquire() try: self._label = label self._n = 0 self._minimum = 0.0 self._maximum = 0.0 self....
mmaryInfo=None): ''' Initialize with the given values, preferring existing values from the dictionary. ''' if summaryInfo is not None: if 'label' in summaryInfo: label = summaryInfo['label'] if 'n' in summaryInfo: n = summaryInfo['n...
ahankinson/pybagit
pybagit/multichecksum.py
Python
mit
4,668
0.003856
#!/usr/bin/env python __author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of ...
for line in codecs.open(manifest_file, 'rb', encoding): checksum, file_ = line.strip().split(' ', 1) full_file = os.path.join(bag_root, file_) if full_file in files_to_checksum:
files_to_checksum.remove(full_file) checksums[os.path.join(bag_root, file_)] = checksum p = multiprocessing.Pool(processes=multiprocessing.cpu_count()) result = p.map_async(csumfile, files_to_checksum) checksums.update((k, v) for v, k in result.get()) p.close() p.join() mf...
jetyang2005/elastalert
elastalert/alerts.py
Python
apache-2.0
55,913
0.002755
# -*- coding: utf-8 -*- import copy import datetime import json import logging import subprocess import sys import warnings from email.mime.text import MIMEText from email.utils import formatdate from smtplib import SMTP from smtplib import SMTP_SSL from smtplib import SMTPAuthenticationError from smtplib import SMTPEx...
as an es result key, since it would have been matched in the lookup_es_key call above for i in xrange(len(alert_text_values)): if alert_text_values[i] is None: alert_value = self.rule.get(alert_text_args[i]) if alert_value: ale...
lert_value alert_text_values = [missing if val is None else val for val in alert_text_values] alert_text = alert_text.format(*alert_text_values) elif 'alert_text_kw' in self.rule: kw = {} for name, kw_name in self.rule.get('alert_text_kw').items(): ...
nicholasserra/sentry
tests/sentry/api/endpoints/test_group_notes.py
Python
bsd-3-clause
1,576
0
from __future__ import absolute_import from sentry.models import Activity from sentry.testutils import APITestCase cl
ass GroupNoteTest(APITestCase): def test_simple(self): group = self.group activity = Activity.objects.create( group=group, project=grou
p.project, type=Activity.NOTE, user=self.user, data={'text': 'hello world'}, ) self.login_as(user=self.user) url = '/api/0/issues/{}/comments/'.format(group.id) response = self.client.get(url, format='json') assert response.status_code == 200...
nhamplify/aminator
aminator/plugins/blockdevice/base.py
Python
apache-2.0
1,648
0.00182
# -*- coding: utf-8 -*- # # # Copyright 2013 Netflix, 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 ...
ning permissions and # limitations under the License. # # """ aminator.plugins.blockdevice.base ================================= Base class(es) for block device manager plugins """ import abc import logging from aminator.plugins.base import BasePlugin __all__ = ('BaseBlockDevicePlugin',) log = logging.getLogge...
class BaseBlockDevicePlugin(BasePlugin): """ BlockDevicePlugins are context managers and as such, need to implement the context manager protocol """ __metaclass__ = abc.ABCMeta _entry_point = 'aminator.plugins.blockdevice' @abc.abstractmethod def __enter__(self): return self @a...
khwilson/PynamoDB
pynamodb/tests/test_table_connection.py
Python
mit
16,242
0.001478
""" Test suite for the table class """ import six from pynamodb.compat import CompatTestCase as TestCase from pynamodb.connection import TableConnection from pynamodb.constants import DEFAULT_REGION from pynamodb.tests.data import DESCRIBE_TABLE_DATA, GET_ITEM_DATA from pynamodb.tests.response import HttpOK if six.PY3...
}, 'GlobalSecondaryIndexUpdates': [ {
'Update': { 'IndexName': 'foo-index', 'ProvisionedThroughput': { 'ReadCapacityUnits': 2, 'WriteCapacityUnits': 2, } } } ...
acx2015/ConfigArgParse
tests/test_configargparse.py
Python
mit
34,286
0.011287
import argparse import configargparse import functools import inspect import logging import sys import tempfile import types import unittest # enable logging to simplify debugging logger = logging.getLogger() logger.level = logging.DEBUG stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_hand...
0\n') # check values after setting args in both command line and config file ns = self.parse(args="file1.txt file2.txt --arg-x -y 3 --arg-z 100 ", config_file_contents="""arg-y = 31.5 arg-z = 30
""") self.format_help() self.format_values() self.assertListEqual(ns.filenames, ["file1.txt", "file2.txt"]) self.assertEqual(ns.arg_x, True) self.assertEqual(ns.y1, 3) self.assertEqual(ns.arg_z, [100]) self.assertRegex(self.format_values(), "Comman...
looker/sentry
src/sentry/south_migrations/0348_fix_project_key_rate_limit_window_unit.py
Python
bsd-3-clause
83,050
0.007851
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): db.commit_transaction() try: self._forwards(orm) except E...
eForeignKey', [], {'to': "orm['sentry.Project']"}), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ('sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], {'to': "orm['sentry.User']", 'null': 'True'}) }, 'sentry.apiapplicati
on': { 'Meta': {'object_name': 'ApiApplication'}, 'allowed_origins': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'client_id': ('django.db.models.fields.CharField', [], {'default': "'edca03fca6594a0bbb3bf8d1de291c64b3ec21abb7ed464d84a3e0e1b87a33ce'", ...
charlie-barnes/dipper-stda
pdf.py
Python
gpl-2.0
8,846
0.010513
#!/usr/bin/env python #-*- coding: utf-8 -*- ### 2008-2015 Charlie Barnes. ### 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 la...
return (string_to_expand * ((length/len(string_to_expand))+1))[:length] try: from fpdf import FPDF except ImportError: from p
yfpdf import FPDF class PDF(FPDF): def __init__(self, orientation,unit,format): FPDF.__init__(self, orientation=orientation,unit=unit,format=format) self.toc = [] self.numbering = False self.num_page_num = 0 self.toc_page_break_count = 1 self.set_left_margin(10) ...
xively/node-red-nodes
hardware/sensehat/sensehat.py
Python
apache-2.0
6,966
0.024978
#! /usr/bin/python # # Copyright 2016 IBM Corp. # # 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 i...
clear(col) elif data[0] ==
"P": data = data[1:].strip() s = data.split(',') for p in range(0,len(s),5): SH.set_pixel(int(s[p]),int(s[p+1]),int(s[p+2]),int(s[p+3]),int(s[p+4])) elif data[0] == "T": data = data[1:] tcol = (255,255,255) bcol = (0,0,0) speed = 0.1 s = data.split(':',1) ...
sadig/DC2
components/dc2-lib/dc2/lib/exceptions/authentication.py
Python
gpl-2.0
948
0
# -*- coding: utf-8 -*- # # (DC)² - DataCenter Deployment Control # Copyright (C) 2010, 2011, 2012, 2013, 2014 Stephan Adig <sh@sourcecode.de> # 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; eit...
CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License fo
r more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # class KerberosError(Exception): pass class KerberosTicketExpired(KerberosError): ...
reidmcy/pressScrapers
ubcScraper.py
Python
gpl-2.0
2,909
0.008594
import requests from bs4 import BeautifulSoup import sys import os import pandas import re targetURL = "http://www.ubcpress.ca/search/subject_list.asp?SubjID=45" bookLinks = "http://www.ubcpress.ca/search/" outputDir = "UBC_Output" def main(): r = requests.get(targetURL) soup = BeautifulSoup(r.content, "ht...
(outputDir, title)) with open("{}.html".format(title.replace('/','')), 'wb') as f: for chunk in r.iter_content(1024): f.write(chunk) booksDict['title'].append(title) booksDict['authors'
].append([a.text.strip() for a in soup.find_all("a", {"href" : "#author"})]) mainBodyText = soup.find("td", {"width" : "545", "colspan":"3"}).find("span" , {"class" : "regtext"}) regex = re.match(r"""(.*)About the Author\(s\)(.*)Table of Contents""", mainBodyText.text, flags = re.DOTALL) if rege...
adiq/MultitestApp
multitest/tests.py
Python
mit
3,600
0.003611
from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import TestCase, Client from multitest.models import Test, Question, Answer class MultitestViewsTests(TestCase): def setUp(self): self.user = User.objects.create(username='user', is_active=True, is_s...
t() response = guest.get(reverse('index')) self.assertTemplateUsed(response, 'multitest/index.html') response = guest.get(reverse('login')) self.assertTemplateUsed(response, 'multitest/login.html') response = guest.get(reverse('register')) self.assertTemplateUsed(response...
(self): guest = Client() response = guest.get(reverse('test', kwargs={'test_id': self.stest.id})) self.assertTemplateNotUsed(response, 'multitest/test.html') def test_list_all_tests(self): response = self.c.get(reverse('index')) self.failUnlessEqual(response.status_code, 200...
RonnyPfannschmidt/pluggy
src/pluggy/_callers.py
Python
mit
2,097
0.000477
""" Call loop machinery """ import sys from ._result import HookCallError, _Result, _raise_wrapfail def _multicall
(hook_name, hook_impls, caller_kwargs, firstresult): """Execute a call into multiple python functions/methods and return the result(s). ``caller_kwargs`` comes from _HookCaller.__call__(). """ __tracebackhide__ = True results = [] excinfo = None try: # run impl and wrapper setup functi...
s in a loop teardowns = [] try: for hook_impl in reversed(hook_impls): try: args = [caller_kwargs[argname] for argname in hook_impl.argnames] except KeyError: for argname in hook_impl.argnames: if...
mindpin/mindpin_oppia
core/domain/rights_manager_test.py
Python
apache-2.0
11,577
0
# Copyright 2014 The Oppia 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 # # ht
tp://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. """Tests for classes and methods relating to user rights.""" __author__ = 'Sean Lip' from core.domain import config_services from co...
backmari/moose
python/chigger/graphs/Line.py
Python
lgpl-2.1
7,589
0.002108
#pylint: disable=missing-docstring ################################################################# # DO NOT MODIFY THIS HEADER # # MOOSE - Multiphysics Object Oriented Simulation Environment # # # # (c) 2010...
vtk.vtkFloatArray() x.SetName('x-data') y = vtk.vtkFloatArray() y.SetName('y-data') self._vtktable = vtk.vtkTable() self._vtktable.AddColumn(x) self._vtktable.AddColumn(y) # Storage for tracing lines self._xtracer = None self._ytracer = None ...
'y', y_data) def setOptions(self, *args, **kwargs): """ Update line objects settings. """ super(Line, self).setOptions(*args, **kwargs) tracer = self.getOption('tracer') if tracer and not self.isOptionValid('xtracer'): self.setOption('xtracer', True) ...
google/myelin-acorn-electron-hardware
third_party/nanopb/generator/nanopb_generator.py
Python
apache-2.0
70,423
0.003664
#!/usr/bin/env python from __future__ import unicode_literals '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.''' nanopb_version = "nanopb-0.3.9.2" import sys import re import codecs from functools import reduce try: # Add some dummy imports to keep packaging tools happy. import google,...
_name): '''Parse Names() from FieldDescriptorProto type_name''' if type_name[0] != '.': raise NotImplementedError("Lookup of non-absolute type names is not supported") return Names(type_name[1:].split('.')) def varint_max_size(max_value): '''Returns the maximum number of bytes a varint can take...
if (max_value >> (i * 7)) == 0: return i raise ValueError("Value too large for varint: " + str(max_value)) assert varint_max_size(-1) == 10 assert varint_max_size(0) == 1 assert varint_max_size(127) == 1 assert varint_max_size(128) == 2 class EncodedSize: '''Class used to represent the encoded...
lunzhy/PyShanbay
gui/__init__.py
Python
mit
71
0.014085
#! /usr/bin/env python3 # -*- coding: utf-8
-*- __author__ =
'Lunzhy'
MSC19950601/TextRank4ZH
textrank4zh/TextRank4Keyword.py
Python
mit
7,411
0.013252
#-*- encoding:utf-8 -*- ''' Created on Nov 30, 2014 @author: letian ''' import networkx as nx from Segmentation import Segmentation import numpy as np class TextRank4Keyword(object): def __init__(self, stop_words_file = None, delimiters = '?!;?!。;…\n'): ''' `stop_words_file`:默认值为None,此时内部停止词表...
for w1, w2 in self.combine(word_list, window): if not sel
f.word_index.has_key(w1): continue if not self.word_index.has_key(w2): continue index1 = self.word_index[w1] index2 = self.word_index[w2] self.graph[index1][index2] = 1.0 self.graph[index2][index1] = ...
Caoimhinmg/PmagPy
data_files/LearningPython/ConvertStations.py
Python
bsd-3-clause
408
0.031863
#!/usr/bin/env python from __future__ import print_function import UTM # imports the UTM module Ellipsoid=23-1 # UTMs code for WGS-84 StationNFO=open('station.list').readlines() for line in StationNFO: nfo=line.strip('\n').split() lat=float(nfo[0]) lon=float(nfo[1]) StaName= nfo[3]
Zone,Easting, Northing=UTM.LLtoUTM(Ellipso
id,lon,lat) print(StaName, ': ', Easting, Northing, Zone)
Peddle/hue
desktop/libs/notebook/src/notebook/connectors/base.py
Python
apache-2.0
5,042
0.012297
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
f.document = document else: self.data = json.dumps
({ 'name': 'My Notebook', 'description': '', 'type': 'notebook', 'snippets': [], }) def get_json(self): _data = self.get_data() return json.dumps(_data) def get_data(self): _data = json.loads(self.data) if self.document is not None: _data['id']...
HewlettPackard/oneview-ansible
library/oneview_server_hardware.py
Python
apache-2.0
13,959
0.002866
#!/usr/bin/python # -*- coding: utf-8 -*- ### # Copyright (2016-2020) Hewlett Packard Enterprise Development LP # # 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/licen...
'1.1'} DOCUMENTATION = ''' --- module: oneview_server_hardware short_description: Manage OneView Server Hardware resources. description: - "Provides an interface to manage Server Hardware resources." version_added: "2.3" requirements: - "python >= 2.7.9" - "hpeOneView >= 5.4.0" author: "Gustavo Hennig (@Gu...
the desired state for the Server Hardware resource. C(present) will ensure data properties are compliant with OneView. C(absent) will remove the resource from OneView, if it exists. C(power_state_set) will set the power state of the Server Hardware. C(refresh_stat...
hlin117/statsmodels
statsmodels/tsa/statespace/tests/test_tools.py
Python
bsd-3-clause
4,268
0.011949
""" Tests for tools Author: Chad Fulton License: Simplified-BSD """ from __future__ import division, absolute_import, print_function import numpy as np import pandas as pd from statsmodels.tsa.statespace import tools # from .results import results_sarimax from numpy.testing import ( assert_equal, assert_array_eq...
assert_equal(result, constrained) class TestValidateMatrixShape(object): # name, shape, nrows, ncols, nobs valid = [ ('TEST', (5,2), 5, 2, None),
('TEST', (5,2), 5, 2, 10), ('TEST', (5,2,10), 5, 2, 10), ] invalid = [ ('TEST', (5,), 5, None, None), ('TEST', (5,1,1,1), 5, 1, None), ('TEST', (5,2), 10, 2, None), ('TEST', (5,2), 5, 1, None), ('TEST', (5,2,10), 5, 2, None), ('TEST', (5,2,10), 5, 2, 5), ...
eviljeff/olympia
src/olympia/amo/admin.py
Python
bsd-3-clause
5,736
0
import functools from django.contrib import admin from django.contrib.admin.options import operator from django.core.exceptions import FieldDoesNotExist from django.db import models from django.db.models.constants import LOOKUP_SEP from .models import FakeEmail class CommaSearchInAdminMixin: def get_search_id_f...
e search terms are all numeric and there is more than one, then we also restrict the fields we search to the one returned by get_search_id_field(request) using a __in ORM lookup directly. """ # Apply keyword searches. def construct_search(f
ield_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] elif field_name.startswith('='): return "%s__iexact" % field_name[1:] elif field_name.startswith('@'): return "%s__icontains" % field_name[1:] ...
rmcgurrin/PyQLab
instruments/Digitizers.py
Python
apache-2.0
6,043
0.025484
""" For now just Alazar cards but should also support Acquiris. """ from Instrument import Instrument from atom.api import Atom, Str, Int, Float, Bool, Enum, List, Dict, Coerced import itertools, ast import enaml from enaml.qt.qt_application import QtApplication class Digitizer(Instrument): pass class AlazarATS987...
','DC').tag(desc='Trigger coupling') triggerSlope = Enum('rising','falling').tag(desc='Trigger slope') recordLength = Int(1024).tag(desc='Number of samples in each record') nbrSegments = Int(1).tag(desc='Number of segments in memory') nbrWaveforms = Int(1).tag(desc='Number of times each segment is repeated') nbrRo...
elf, matlabCompatible=False): if matlabCompatible: "For the Matlab experiment manager we seperately nest averager, horizontal, vertical settings" jsonDict = {} jsonDict['address'] = self.address jsonDict['deviceName'] = 'AlazarATS9870' jsonDict['horizontal'] = {'delayTime':self.delay, 'samplingRate':se...
ezequielpereira/Time-Line
libs64/wx/webkit.py
Python
gpl-3.0
11,969
0.009608
# This file was created automatically by SWIG 1.3.29. # Don't modify this file, modify the SWIG interface instead. """ wx.webkit.WebKitCtrl for Mac OSX. """ import _webkit import new new_instancemethod = new.instancemethod def _swig_setattr_nondynamic(self,class_type,name,value,static=1): if (name == "thisown"): ...
faultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=WebKitNameStr) -> WebKitCtrl """ _webkit.WebKitCtrl_swiginit(self,_webkit.new_WebKitCtrl(*args, **kwargs)) self._setOORInfo(self) def Create(*args, **kwargs): ...
g style=0, Validator validator=DefaultValidator, String name=WebKitNameStr) -> bool """ return _webkit.WebKitCtrl_Create(*args, **kwargs) def LoadURL(*args, **kwargs): """LoadURL(self, String url)""" return _webkit.WebKitCtrl_LoadURL(*args, **kwargs) def CanGoBack(...
phith0n/mooder
archives/migrations/0004_postimage.py
Python
lgpl-3.0
1,192
0.004288
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-04 19:14 from __future__ import unicode_literals import archives.models from djang
o.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('archives', '000
3_attachment'), ] operations = [ migrations.CreateModel( name='PostImage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.ImageField(blank=True, upload_to='images/%Y/%m/%...
eltonkevani/tempest_el_env
tempest/api/image/v2/test_images_tags_negative.py
Python
apache-2.0
1,762
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 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. import uuid ...
geocryology/HorizonPy
Examples/Example_1/Example_1_v2.py
Python
gpl-3.0
948
0.004219
################################################################ #
## # Example 1: Converting ArcGIS solar radiation graphics to ## # horizon coordinate points ## ################################################################ #### # 0. Import packages #### from horizonpy import arcsky from os import path ##### # 1. Set path ...
r"E:\Users\Nick\Documents\src\HorizonPy\Examples\Example 1" in_file = path.join(EXDIR, "ArcGIS_Skymap.tif") out_file = path.join(EXDIR, "horizon_pts.txt") ##### # 2. Converting raster image to coordinate points for horizon ##### # create ArcSky object AS = ArcSky.ArcSky() # Set the classified pixel value of the sky...
szarroug3/X-Ray_Calibre_Plugin
lib/utilities.py
Python
gpl-3.0
6,752
0.003258
# utilities.py '''General utility functions used throughout plugin''' import re import os import time import socket from httplib import HTTPException from calibre.library import current_library_path from calibre_plugins.xray_creator.lib.exceptions import PageDoesNotExist HONORIFICS = 'mr mrs ms esq prof dr fr rev pr ...
mats {ChristianName}, {Surname} and {ChristianName} {Lastname} in special cases # i.e. The Lord Ruler should never have "The Ruler", "Lord" or "Ruler" as aliases # Same for John
the Great if christian_name not in COMMON_WORDS and (len(parts) == 0 or parts[0] not in COMMON_WORDS): aliases.append(christian_name) aliases.append(surname) aliases.append("%s %s" % (christian_name, surname)) elif title: # Odd, but got Title Name (eg. Lord Butts...
Kismuz/btgym
btgym/research/encoder_test/aac.py
Python
lgpl-3.0
30,478
0.00233
import tensorflow as tf import numpy as np import time import datetime from btgym.algorithms import BaseAAC from btgym.algorithms.math_utils import cat_entropy # from btgym.algorithms.runner.synchro import BaseSynchroRunner from btgym.research.encoder_test.runner import RegressionRunner # class EncoderClassifier(Bas...
.accuracy( # # labels=tf.argmax(pi.expert_actions, axis=-1), # # predictions=tf.argmax(class_logits, axis=-1) # # ) # # self.accuracy = tf.metrics.accuracy( # labels=tf.argmax(pi.expert_actions[..., 1:3], axis=-1), # predictions=tf....
= [ # tf.summary.scalar('class_loss', class_loss), # tf.summary.scalar('class_accuracy', self.accuracy[0]) # ] # # Accumulate total loss: # loss = float(self.class_lambda) * class_loss + float(self.aac_lambda) * on_pi_loss\ # - float(s...
mahyarap/httpclient
tests/test_httpclient.py
Python
gpl-3.0
1,500
0.002
#!/usr/bin/env python3 import unittest import argparse from httpclient.httpclient import HttpRequest class HttpRequstTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_parse_url(self): host, port, resource = HttpRequest._parse_url('127.0.0.1') ...
ssertEqua
l(port, 80) self.assertEqual(resource, '/foo/bar') def test_send_http_request_options(self): request = HttpRequest('http://localhost', method='OPTIONS') response = request.send() self.assertEqual(response.status, 200) def test_send_http_request_get(self): request = Http...
plotly/plotly.py
packages/python/plotly/plotly/validators/heatmap/colorbar/_showexponent.py
Python
mit
518
0.001931
import _plotly_utils.basevalidators class ShowexponentValidator(_plotly_utils.basevalidators.Enumerat
edValidator): def __init__( self, plotly_name="showexponent", parent_name="heatmap.colorbar", **kwargs ): super(ShowexponentValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), ...
"first", "last", "none"]), **kwargs )
igemsoftware2017/USTC-Software-2017
biohub/core/plugins/serializers.py
Python
gpl-3.0
391
0
from
rest_framework import serializers class PluginSerializer(serializers.Serializer): name = serializers.CharField(read_only=True) author = serializers.CharField(read_only=True) title = serializers.CharField(read_only=True) description = serializers.CharField(read_only=True) js_url = serializers.Char...
s = '__all__'
HappyFaceGoettingen/HappyFaceCore
modules/dCacheInfoPool.py
Python
apache-2.0
16,649
0.007209
# -*- coding: utf-8 -*- # # Copyright 2012 Institut für Experimentelle Kernphysik - Karlsruher Institut für Technologie # # 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://...
status'] = 1.0 appending['total'] = 0 appending['free'] = 0 appending['precious'] = 0 appending['removable'] = 0 for met...
if metric.get('name') == 'total': appending['total'] = float(metric.text) / self.unit elif metric.get('name') == 'free': appending['free'] = float(metri...
eguil/ENSO_metrics
pmp_driver/parallel_driver.py
Python
bsd-3-clause
5,888
0.002548
#!/usr/bin/env python """ Usage example: 1. First realization per model ./parallel_driver.py -p my_Param_ENSO.py --mip cmip6 --modnames all --realization r1i1p1f1 --metricsCollection ENSO_perf 2. All realizations of individual models ./parallel_driver.py -p my_Param_ENSO.py --mip cmip6 --modnames all --realization all...
_dir): os.makedirs(log_dir) # number of tasks to submit at the same time num_workers = 7 #num_workers = 10 #num_workers = 30 #num_workers = 25 print("Start : %s" % time.ctime()) # submit tasks and wait for subset of tasks to complete procs_list = [] for p, cmd in enumerate(cmds_list): timenow
= time.ctime() print(timenow, p, ' '.join(cmd)) model = cmd[-3] run = cmd[-1] log_filename = '_'.join(['log_enso', mc_name, mip, exp, model, run, case_id]) log_file = os.path.join(log_dir, log_filename) with open(log_file+"_stdout.txt", "wb") as out, open(log_file+"_stderr.txt", "wb") as err: ...
shikhir-arora/Giesela
musicbot/bot.py
Python
mit
30,622
0.001665
import asyncio import inspect import logging import os import re import shutil import sys import traceback from collections import defaultdict from contextlib import suppress from datetime import datetime from random import choice from textwrap import indent, wrap import aiohttp import discord from discord import Clie...
ver][ "last_np_msg"] if last_np_msg and last_np_msg.channel == channel: # if the last np message isn't the last message in the channel; # delete it async for lmsg in self.logs_from(channel, limit=1): if lmsg != last_np_msg ...
_specific_data[channel.server][ "last_np_msg"] = None
google/upvote_py2
upvote/gae/lib/voting/api_test.py
Python
apache-2.0
56,967
0.004055
# Copyright 2017 Google 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 required by applicable law or a...
d(bundle.key) allowed, reason = ndb.transaction(fn, xg=True) self.assertTrue(allowed) self.assertIsNone(reason) mock_flagged_binary.assert_not_called() mock_flagged_cert.assert_not_called() def testSantaBundle_FlaggedCert(self): santa_certificate = test_utils.CreateSantaCertificate() b...
cert_key=santa_certificate.key) bundle = test_utils.CreateSantaBundle(bundle_binaries=[blockable]) with self.LoggedInUser(): allowed, reason = api.IsVotingAllowed(bundle.key) self.assertTrue(allowed) santa_certificate.flagged = True santa_certificate.put() allowed, reason = api...
rcarmo/soup-strainer
html5lib/inputstream.py
Python
mit
32,655
0.003859
from __future__ import absolute_import import codecs import re import types import sys from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase from .constants import encodings, ReparseException from . import utils from io import StringIO try: from io import BytesIO except ImportError: Bytes...
or streams that do not have buffering of their own The buffer is implemented as a list of chunks on the assumption that joining many strings will be slow since it is O(n**2) """ def __init__(self, stream): self.stream = stream self.buffer = [] s
elf.position = [-1,0] #chunk number, offset __init__.func_annotations = {} def tell(self): pos = 0 for chunk in self.buffer[:self.position[0]]: pos += len(chunk) pos += self.position[1] return pos tell.func_annotations = {} def seek(self, pos): asser...
jasonleaster/Machine_Learning
K_Means/tester4.py
Python
gpl-2.0
691
0.002894
""" Programmer : EOF File : tester3.py Date : 2016.01.10 E-mail : jasonleaster@163.com Description : """ import numpy from matplotlib import pyplot from km import KMeans Original_Data = numpy.array([ [1, 1.5], [1, 0.5], [0.5, 0.5], [1.5, 1.5
], [5, 5], [6, 5.5], [4, 5],
[5, 1], [6, 0.5], [7, 1.5], [1, 10], [1.5, 11] ]).transpose() a = KMeans(Original_Data, K = 3) for i in range(a.SampleNum): pyplot.plot(Original_Data[0][i], Original_Data[1][i], "+r", markersize=12) pyplot.title("Original Training Data (Figure by Jason Leaster)") pyplot.axis([-2, 14, -2, 1...
HappyFaceGoettingen/HappyFaceCore
render.py
Python
apache-2.0
2,708
0.005174
#!/usr/bin/env python # -*- co
ding: utf-8 -*- # # Copyright 2012 Institut für Experimentelle Kernphysik - Karlsruher Institut für Technologie # # 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...
T WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os,sys if __name__ != '__main__': # unfortunately we need this rather hacky path change # because mod_wsgi for some reason does n...
aweisberg/cassandra-dtest
upgrade_tests/repair_test.py
Python
apache-2.0
1,656
0
import time import pytest import logging from repair_tests.repair_test import BaseRepairTest since = pytest.mark.since logger = logging.getLogger(__name__) LEGACY_SSTABLES_JVM_ARGS = ["-Dcassandra.streamdes.initial_mem_buffer_size=1", "-Dcassandra.streamdes.max_mem_buffer_size=5", ...
2.2.5") cluster.set_install_dir(version="2.2.5") self._populate_cluster() self._do_upgrade(default_install_dir) self._repair_and_verify(True) def _do_upgrade(self, default_install_dir): cluster = self.cluster for node in cluster.nodelist(): logger.debu...
de.is_running(): node.flush() time.sleep(1) node.stop(wait_other_notice=True) node.set_install_dir(install_dir=default_install_dir) node.start(wait_other_notice=True, wait_for_binary_proto=True) cursor = self.patient_cql_connection(node...
Clarity-89/clarityv2
src/clarityv2/crm/migrations/0002_auto_20150924_1716.py
Python
mit
1,692
0.004728
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from decimal import Decimal import autoslug.fields class Migration(migrations.Migration): dependencies = [ ('crm', '0001_initial'), ] operations = [ migrations.CreateModel( ...
de', field=models.CharField(verbose_name='postal code', max_length=10, blank=True),
), migrations.AlterUniqueTogether( name='project', unique_together=set([('client', 'slug')]), ), ]
schubergphilis/twitterwall
tweety/basic_auth.py
Python
apache-2.0
4,682
0.002349
# Copyright 2013 Gert Kremer # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You
may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # ...
s and # limitations under the License. import base64 from django.http import HttpResponse from django.contrib.auth import authenticate, login ############################################################################# # def view_or_basicauth(view, request, test_func, realm = "", *args, **kwargs): ...
hvnsweeting/pho
setup.py
Python
mit
637
0
#!/usr/bin/env python2 # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup import pho requisites = [] setup( name='mpho', version=pho.__version__, description='PytHon utility for Organizing tasks', scripts=['scripts/pho'],
long_description=open('README.rst').read(), author='Viet Hung Nguyen', author_email='hvn@familug.org', url='https://github.com/hvnsweeting/pho', packages=['pho'], license='MIT', classifiers=[ 'Environment :: Console', '
Topic :: Terminals :: Terminal Emulators/X Terminals', ], )
tongxindao/shiyanlou
shiyanlou_cs892/sub.py
Python
apache-2.0
469
0
from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1, projection="3d") x = np.linspace(
-6 * np.pi, 6 * np.pi, 1000) y = np.sin(x) z = np.cos(x) ax1.plot(x,
y, z) ax2 = fig.add_subplot(1, 2, 2, projection="3d") X = np.arange(-2, 2, 0.1) Y = np.arange(-2, 2, 0.1) X, Y = np.meshgrid(X, Y) Z = np.sqrt(X ** 2 + Y ** 2) ax2.plot_surface(X, Y, Z, cmap=plt.cm.winter) plt.show()
reidlindsay/gostop
gostop/core/agent.py
Python
mit
794
0
from .hand import Hand, TakenCards class Agent(object): """An Agent is a player in the game and may be controll
ed by a human or by computer. """ def __init__(self, name): self.name = name self.hand = Hand() self.taken_cards = TakenCards() self.score = 0 def __str__(self): return self.name def get_action(self, state, poss
ible_actions): """The Agent receives a GameState and must return an action from one of `possible_actions`. """ raise NotImplementedError() def win(self, state): """Notify the Agent of a win for the purpose of record keeping.""" pass def loss(self, state): ...
caio2k/pulseaudio-dlna
pulseaudio_dlna/streamserver.py
Python
gpl-3.0
18,157
0.00022
#!/usr/bin/python # This file is part of pulseaudio-dlna. # pulseaudio-dlna 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. # pulsea...
__init__(self, bridge, sock): self.bridge = bridge try: self.ip, self.port = sock.getpeername() except: logger.info('Could not get socket IP and Port. Setting to ' 'unknown.') self.ip = 'unknown' self.port = 'unknown' d...
raise NotImplementedError def __gt__(self, other): if isinstance(other, RemoteDevice): return self.ip > other.ip raise NotImplementedError @functools.total_ordering class ProcessStream(object): def __init__(self, path, recorder, encoder, manager): self.path = path ...
RedHatInsights/insights-core
insights/parsers/x86_debug.py
Python
apache-2.0
3,411
0
""" Parsers for file ``/sys/kernel/debug/x86/*_enabled`` outputs ============================================================ This module provides the following parsers: X86PTIEnabled - file ``/sys/kernel/debug/x86/pti_enabled`` ---------------------------------------------------------- X86IBPBEnabled - file ``/sys/...
Raises:
SkipException: When input content is empty """ def parse_content(self, content): if not content: raise SkipException("Input content is empty") # it is a digit self.value = int(content[0]) @parser(Specs.x86_ibpb_enabled) class X86IBPBEnabled(X86DebugEnabled): """ ...
andresmargalef/xbmc-plugin.video.ted.talks
resources/lib/settings_test.py
Python
gpl-2.0
1,603
0.003119
import unittest import settings class TestSettings(unittest.TestCase): def setUp(self): unittest.TestCase.setUp(self) self.enable_subtitles = settings.enable_subtitles self.xbmc_language = settings.xbmc_language self.subtitle_language = settings.subtitle_language def tearDown(...
f): settings.enable_subtitles = 'true' setting
s.xbmc_language = 'Portuguese' settings.subtitle_language = "" # Default is "en", if pref unset then XBMC will replace with "". self.assertEqual(['pt'], settings.get_subtitle_languages()) def test_get_subtitle_languages_enabled_standard_nomatch(self): settings.enable_subtitles = 'tr...