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
zimeon/iiif
iiif/manipulator_pil.py
Python
gpl-3.0
7,627
0.000787
"""Implementation of IIIF Image API manipulations using the Python Image Library. Uses the Python Image Library (PIL) for in-python manipulation: http://www.pythonware.com/products/pil/index.htm """ import re import os import os.path import subprocess import tempfile from PIL import Image from .error import IIIFErr...
plicit format is requested. """ fmt = ('jpg' if (format is None) else format) if (fmt == 'png'): self.logger.debug("format: png") self.mime_type = "image/png" self.output_format = fmt format = 'png' elif (fmt == 'jpg'): self.log...
f.output_format = fmt format = 'jpeg' elif (fmt == 'webp'): self.logger.debug("format: webp") self.mime_type = "image/webp" self.output_format = fmt format = 'webp' else: raise IIIFError(code=415, parameter='format', ...
ianjuma/octopus
manage.py
Python
apache-2.0
789
0.003802
import os f
rom gevent.pywsgi import WSGIServer from gevent import monkey monkey.patch_all() from flask.ext.script import Manager from flask.ext.migrate import Migrate, MigrateCommand from app i
mport app def push_to_server(): # just use git hooks already pass def background_task(instance): # gunicorn -c config_gunicorn.py instance:app pass def runserver(instance): port = int(os.environ.get("PORT", 8001)) instance.config['DEBUG'] = True instance.config['use_reloader'] = True ...
yunstanford/GraphiteSetup
carbon_relay.py
Python
mit
1,348
0.030415
import subprocess import sys import string import os def start_carbon_relay_instance(name): path = os.path.realpath(__fil
e__) subprocess.call(["python", "{0}/carbon-relay.py".format(os.path.dirname(pat
h)), "--instance={0}".format(name), "start"]) def stop_carbon_relay_instance(name): path = os.path.realpath(__file__) subprocess.call(["python", "{0}/carbon-relay.py".format(os.path.dirname(path)), "--instance={0}".format(name), "stop"]) def usage(): print("carbon_relay [start/stop] [instance name type: letter ...
klmitch/nova
nova/tests/unit/api/openstack/compute/test_server_groups.py
Python
apache-2.0
37,885
0.002191
# Copyright (c) 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 r...
port objects from nova.policies import server_groups as sg_policies from nova import test from nova.tests import fixtures from nova.tests.unit.api.openstack import fakes from nova.tests.unit import policy_fixture class AttrDict(dict): def __getattr__(self, k): ret
urn self[k] def server_group_template(**kwargs): sgroup = kwargs.copy() sgroup.setdefault('name', 'test') return sgroup def server_group_resp_template(**kwargs): sgroup = kwargs.copy() sgroup.setdefault('name', 'test') if 'policy' not in kwargs: sgroup.setdefault('policies', []) ...
bizoru/sqlite-cake
sqlitecake/core/__init__.py
Python
gpl-2.0
130
0
from .cakesync
import CakeSync from .caketable import CakeTable from .caketypes import CakeTypes from .cakemodel impor
t CakeModel
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/openstack/network/v2/vpn_service.py
Python
mit
1,751
0
# 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 t...
type=bool) #: Human-readable descripti
on for the vpnservice. description = resource.prop('description') #: The unique ID for the vpnservice. id = resource.prop('id') #: The vpnservice name. name = resource.prop('name') #: ID of the router into which the VPN service is inserted. router_id = resource.prop('router_id') #: The p...
ClusterHQ/pyzfs
libzfs_core/_error_translation.py
Python
apache-2.0
22,509
0.001333
# Copyright 2015 ClusterHQ. See LICENSE file for details. """ Helper routines for converting ``errno`` style error codes from C functions to Python exceptions defined by `libzfs_core` API. The conversion heavily depends on the context of the error: the attempted operation and the input parameters. For this reason, t...
): raise lzc_exc.NameInvalid(lastsnap) elif len(firstsnap) > MAXNAMELEN: raise lzc_exc.N
ameTooLong(firstsnap) elif len(lastsnap) > MAXNAMELEN: raise lzc_exc.NameTooLong(lastsnap) elif _pool_name(firstsnap) != _pool_name(lastsnap): raise lzc_exc.PoolsDiffer(lastsnap) else: raise lzc_exc.SnapshotMismatch(lastsnap) if ret == errno.ENOENT: ...
xiang12835/python_web
py2_web2py/web2py/gluon/packages/dal/pydal/dialects/postgre.py
Python
apache-2.0
11,219
0.000535
from ..adapters.postgres import Postgre, PostgreNew, PostgreBoolean from ..helpers.methods import varquote_aux from ..objects import Expression from .base import SQLDialect from . import dialects, sqltype_for, register_expression @dialects.register_for(Postgre) class PostgreDialect(SQLDialect): true_exp = "TRUE" ...
rst, second, query_env={}): return 'ST_Within(%s,%s)' % ( self.expand(first, query_env=query_env), self.expand(second, first.type, query_env=query_env)) def st_dwithin(self, first, tup, query_env={}): return 'ST_DWithin(%s,%s,%s)' % (
self.expand(first, query_env=query_env), self.expand(tup[0], first.type, query_env=query_env), self.expand(tup[1], 'double', query_env=query_env)) @register_expression('doy') def extract_doy(self, expr): return Expression(expr.db, self.extract, expr, 'doy', 'integer') @...
buffalotheory/critter_list
pyplayer/pyplayerd.py
Python
gpl-2.0
7,138
0.003502
#!/usr/bin/env python3 # daemon.py """ originally from the Python Cookbook (version 3) 11.8. Implementing Remote Procedure Calls 12.2. Determining If a Thread Has Started 12.14. Launching a Daemon Process on Unix (perhaps more) """ import os import sys import atexit import signal import json from datetime ...
PIDFILE, stdout=pyplayer.config.stdout_file, stderr=pyplayer.config.stderr_file ) TRACE('%s started' % PIDFILE) except RuntimeError as e: TRACE(e) raise SystemExit(1) main() def daemon_stop(): if os.path.exists(PIDFILE): with open(PIDFILE) as...
don't exit until the process is confirmed dead TRACE('%s stopped' % DAEMON) else: TRACE('Not running') raise SystemExit(1) def daemon_status(): if not os.path.exists(PIDFILE): TRACE('Not running. %s does not exist.' % PIDFILE) raise SystemExit(1) pid = int(open(PID...
emgee/formal
formal/test/test_types.py
Python
mit
6,660
0.003904
from datetime import date, time try: from decimal import Decimal haveDecimal = True except ImportError: haveDecimal = False from twisted.internet import defer from twisted.trial import unittest import formal from formal import validation class TestValidators(unittest.TestCase): def testHasValidator(s...
tFloatFailure(self): self.runFailureTests(formal.Float, [ ([], {'required': True}, None, formal.FieldValidationError), ]) if haveDecimal: def testDecimalSuccess(self): return self.runSuccessTests(formal.Decimal
, [ ([], {}, None, None), ([], {}, Decimal('0'), Decimal('0')), ([], {}, Decimal('0.0'), Decimal('0.0')), ([], {}, Decimal('.1'), Decimal('.1')), ([], {}, Decimal('1'), Decimal('1')), ([], {}, Decimal('-1'), Decimal('-1')), ...
AzamYahya/shogun
examples/undocumented/python_modular/graphical/kernel_ridge_regression.py
Python
gpl-3.0
969
0.026832
from pylab import figure,pcolor,scatter,contour,colorbar,show,subplot,plot,connect from numpy import array,meshgrid,reshape,linspace,min,max from numpy import concatenate,transpose,ravel from modshogun import * from modshogun import * from modshogun import * import util util.set_title('KernelRidgeRegression') width=2...
"r.") # negative examples neg=util.get_realdata(False) plot(neg[0,:], neg[1,:], "b.") # train svm labels = util.get_labels(type='regression') train = util.get_realfeatures(pos, neg) gk=GaussianKernel(train, train, width) krr = KernelRidgeRegression() krr.set_labels(labels) krr.set_kernel(gk) krr.set_tau(1e-3) krr.tra...
e_output_plot_isolines(krr, gk, train, regression=True) pcolor(x, y, z, shading='interp') contour(x, y, z, linewidths=1, colors='black', hold=True) connect('key_press_event', util.quit) show()
auto-mat/klub
apps/api/frontend/unknown_user_apply_for_membership_unit.py
Python
gpl-3.0
4,109
0.000731
from rest_framework import generics from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from aklub.models import UserProfile, AdministrativeUnit from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope from rest_framework import serializers from rest_framework.p...
"iam alergic to bees", "age_group": 2012, "birth_month": 12, "birth_day": 12, "street": "Belmont Avenu
e 2414", "city": "New York", "zip_code": "10458", "administrative_unit": administrative_unit_1.pk, "skills": "cooking", } current_date = timezone.now() with freeze_time(current_date): response = app_request.post(url, post_data) assert response.status_code == 200 ...
ioam/geoviews
geoviews/element/__init__.py
Python
bsd-3-clause
3,017
0.001989
from holoviews.element import ( ElementConversion, Points as HvPoints, Polygons as HvPolygons, Path as HvPath ) from .geo import (_Element, Feature, Tiles, is_geographic, # noqa (API import) WMTS, Points, Image, Text, LineContours, RGB, FilledContours, Path, Polygons, Sh...
, mdims, **kwargs) def image(self, kdims=None, vdims=None, mdims=None, **kwargs): return self(Image, kdims, vdims, mdims, **kwargs) def points(self, kdims=None, vdims=None, mdims=None, **kwargs): if kdims is None: kdims = self._element.kdims el_type = Points if is_geographic(self._elem...
def polygons(self, kdims=None, vdims=None, mdims=None, **kwargs): if kdims is None: kdims = self._element.kdims el_type = Polygons if is_geographic(self._element, kdims) else HvPolygons return self(el_type, kdims, vdims, mdims, **kwargs) def path(self, kdims=None, vdims=None, mdims=Non...
UnbDroid/robomagellan
Codigos/Raspberry/desenvolvimentoRos/build/tf2_py/catkin_generated/pkg.installspace.context.pc.py
Python
gpl-3.0
395
0
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_IN
CLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "rospy;tf2".replace(';', ' ') PKG_CO
NFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "tf2_py" PROJECT_SPACE_DIR = "/home/pi/Documents/desenvolvimentoRos/install" PROJECT_VERSION = "0.5.13"
tommartensen/arion-backend
arionBackend/tests/api/__init__.py
Python
mit
47
0
""" This module
contains all api tests. """
nicko96/Chrome-Infra
infra/services/mastermon/test/pollers_test.py
Python
bsd-3-clause
8,592
0.004772
# Copyright (c) 2015 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. import json import os import tempfile import unittest import mock import requests from infra_libs import temporary_directory from infra.services.master...
ke_increment): result1 = {'builder': 'b1', 'slave': 's1', 'result': 'r1', 'project_id': 'chromium'} r
esult2 = {'builder': 'b1', 'slave': 's1', 'result': 'r1', 'project_id': 'unknown'} # Check that we've listed all the required metric fields. self.assertEqual(set(result1), set(pollers.FilePoller.field_keys)) self.assertEqual(set(result2), set(pollers.FilePoller.field_keys)) data1 = resul...
akshaybabloo/Car-ND
Term_1/Finding_Lane_Lines_1/2_color_region_masking.py
Python
mit
2,501
0.003599
import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import sys try: image = mpimg.imread('test.jpg') except FileNotFoundError as e: print(e) sys.exit(1) print('This image is: {}, with dimensions: {}'.format(type(image), image.shape)) ysize = image.shape[0] xsize = image.sha...
, 2] < rgb_threshold[2]) # See https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html for more info xx, yy = np.meshgrid(np.arange
(0, xsize), np.arange(0, ysize)) region_thresholds = (yy > (xx * fit_left[0] + fit_left[1])) & (yy > (xx * fit_right[0] + fit_right[1])) & ( yy < (xx * fit_bottom[0] + fit_bottom[1])) # Mask color selection color_select[color_thresholds | ~region_thresholds] = [0, 0, 0] # Find where image is both colored right and in ...
D4wN/brickv
src/build_data/windows/OpenGL/raw/GL/EXT/vertex_array.py
Python
gpl-2.0
8,036
0.036212
'''OpenGL extension EXT.vertex_array Automatically generated by the get_gl_extensions script, do not edit! ''' from OpenGL import platform, constants, constant, arrays from OpenGL import extensions from OpenGL.GL import glget import ctypes EXTENSION_NAME = 'GL_EXT_vertex_array' _DEPRECATED = False GL_VERTEX_ARRAY_EXT ...
AME, resultType=None, argTypes=(constants.GLint,), doc='glArrayElementEXT(GLint(i)) -> None', argNames=('i',), deprecated=_DEPRECATED, ) glColorPointerEXT = platform.createExtensionFunction( 'glColorPointerEXT',dll=platform.GL, extension=EXTENSION_NAME, resultType=None, argTypes=(constants.GLint,constants.GLenum,co...
stants.GLsizei,ctypes.c_void_p,), doc='glColorPointerEXT(GLint(size), GLenum(type), GLsizei(stride), GLsizei(count), c_void_p(pointer)) -> None', argNames=('size','type','stride','count','pointer',), deprecated=_DEPRECATED, ) glDrawArraysEXT = platform.createExtensionFunction( 'glDrawArraysEXT',dll=platform.GL, exten...
EdDev/vdsm
tests/storage_volume_test.py
Python
gpl-2.0
7,900
0
# # Copyright 2016 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at you
r option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have receive
d 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 # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import from contextlib impo...
Happyholic1203/ransomcare
ransomcare/sniffers.py
Python
mit
5,790
0
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import json import logging import threading import thread import time import signal import psutil import eventlet from . import event logger = logging.getLogger(__name__) pid_cwd = {} def get_absolute_path(event_raw): ''' Keeps a ca...
rates file events: EventFileOpen (pid, path) EventListDir (pid, path) EventFileRead (pid, path, size) EventFileWrite (pid, path, size) EventFileUnlink (pid, path) EventFileClose (pid, path) The path generated from dtrace might be relative paths, sniffer is repons...
][fd] gives the filename self._sniffer_reader = None # eventlet greenthread self._sniffer_output = eventlet.Queue() def read_sniffer(self): logger.info('Sniffer started') while True: try: line = self._sniffer.stdout.readline() event_raw =...
bikeshare/bikeshare-web
bikeshare.py
Python
gpl-2.0
4,352
0.006893
import syslog from flask import Flask, request, render_template, send_from_directory from flask.ext.bootstrap import Bootstrap import json import re import syslog import urllib2 from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper import sstoreclient ...
display the "view all riders" page @app.rou
te('/users') def view_all_riders(): apiroute = '/REST/1.0/users/all' r = requests.get(apiurl + apiroute) if r.status_code == 200: data = r.json() return render_template('users.html', users=data['users']) else: return render_template('500.html') # This is a GET route to display t...
google/rekall
rekall-core/rekall/plugins/response/interpolators.py
Python
gpl-2.0
3,264
0
# Rekall Memory Forensics # Copyright 2016 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later ver...
path = hit["path"] m = re.search( r"(S-(\d+-)+\d+)$", path.filename.name or "", re.I) if m: result.append(m.group(1)) return result @registry.memoize def _get_homedirs(self): """
On windows the homedirs are the paths of the user's profile.""" result = [] for artifact_hit in self.session.plugins.artifact_collector( "WindowsRegistryProfiles"): for hit_result in artifact_hit.get("result", []): profile_path = hit_result.get("value") ...
nuodb/nuodb-django
test/auth/tests/views.py
Python
bsd-3-clause
22,169
0.001443
import os import re from django.conf import global_settings, settings from django.contrib.sites.models import Site, RequestSite from django.contrib.auth.models import User from django.core import mail from django.core.exceptions import SuspiciousOperation from django.core.urlresolvers import reverse, NoReverseMatch fr...
headers can't be used for reset emails" # This attack is based on the way browsers handle URLs. The colon # should be used to separate the port, but if the URL contains an @, # the colon is interpreted as part of a username for login purposes, # making 'evil.com' the request domain. Sinc...
ost() # is invoked, but we check here as a practical consequence. with self.assertRaises(SuspiciousOperation): self.client.post('/password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST='www.example:dr.frankenstein@evil.tld' ) sel...
mikel-egana-aranguren/SADI-Galaxy-Docker
galaxy-dist/lib/tool_shed/grids/admin_grids.py
Python
gpl-3.0
22,408
0.025036
import logging import os from galaxy.web.framework.helpers import grids from galaxy.web.framework.helpers import time_ago from galaxy.webapps.tool_shed import model from galaxy.model.orm import and_ import tool_shed.util.shed_util_common as suc from tool_shed.util import hg_util from tool_shed.grids.repository_grids im...
n( grids.GridColumn ): def get_value( self, trans, grid, user ): if user.purged:
return "purged" elif user.deleted: return "deleted" return "" class EmailColumn( grids.GridColumn ): def filter( self, trans, user, query, column_filter ): if column_filter == 'All': return query return query.filter( and_( m...
GoogleCloudPlatform/cloudml-samples
sklearn/notebooks/census_training/train.py
Python
apache-2.0
5,507
0.002179
# [START setup] import datetime import pandas as pd import joblib from google.cloud import storage from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import SelectKBest from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.preprocessing import Lab...
lassifier. categorical_pipelines = [] # Each categorical column needs to be extracted individually an
d converted to a numerical value. # To do this, each categorical column will use a pipeline that extracts one feature column via # SelectKBest(k=1) and a LabelBinarizer() to convert the categorical value to a numerical one. # A scores array (created below) will select and extract the feature column. The scores array is...
rackerlabs/lambda-uploader
lambda_uploader/uploader.py
Python
apache-2.0
8,157
0
# Copyright 2015-2016 Rackspace US, 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 i...
lf._config.alias) resp = self._lambda_client.create_alias( FunctionName=self._config.name, Name=self._config.alias, FunctionVersion=self.version, Description=self._config.alias_description, ) LOG.debug("AWS create_alias resp
onse: %s" % resp) '''Update alias''' def _update_alias(self): LOG.debug("Updating alias %s" % self._config.alias) resp = self._lambda_client.update_alias( FunctionName=self._config.name, Name=self._config.alias, FunctionVersion=self.version, ...
tmr232/ida-plugins
autostruct/autostruct.py
Python
mit
1,657
0.001207
import idaapi import idc import sark class AutoStruct(idaapi.plugin_t): flags = 0 comment
= "AutoStruct struct creator" help = "Automagically Create and Apply Structs" wanted_name = "Auto
Struct" wanted_hotkey = "Shift+T" def init(self): self._prev_struct_name = "" return idaapi.PLUGIN_KEEP def term(self): pass def run(self, arg): start, end = sark.get_selection() struct_name = idc.AskStr(self._prev_struct_name, "Struct Name") if not st...
JShadowMan/package
python/zdl/error_logger/error_logger/net/sms_notification.py
Python
mit
187
0.005348
#!/usr/bin/env python # # Copyright (C) 2017 DL # from error_logger.net import email_notificatio
n from error_logger.utils import logger def send_sms(config, to_list,
contents): pass
epuzanov/ZenPacks.community.HPMon
ZenPacks/community/HPMon/cpqScsiPhyDrv.py
Python
gpl-2.0
1,513
0.00727
################################################################################ # # This program is part of the HPMon Zenpack for Zenoss. # Copyright (C) 2008, 2009, 2010, 2011 Egor Puzanov. # # This program can be used under the GNU General Public License version 2 # You can find full information here: http://www.zen...
, 'Bad Cable'), 6: (DOT_RED, SEV_CRITICAL, 'Missing was Ok'), 7: (DOT_RED, SEV_CRITICAL, 'Missing was Failed'), 8: (DOT_ORANGE, SEV_ERROR, 'Predictive Failure'), 9: (DOT_RED, SEV_CRITICAL, 'Missing was Predictive Failure'), 10:(DOT_RED, SEV...
Class(cpqScsiPhyDrv)
viktorRock/myFirstPythonAPI
pythapp/nltk/nltk_constants.py
Python
unlicense
222
0.009009
DEFAULT_STEMMER = 'snowball' DEFAULT_TOKENIZER = 'word'
DEFAULT_TAGGER = 'pos' TRAINERS = ['news', 'editorial', 'reviews', 'religion', 'learned',
'science_fiction', 'romance', 'humor'] DEFAULT_TRAIN = 'news'
hpeter/Linot
test_temp/Plugins/TestPluginBase.py
Python
bsd-2-clause
1,918
0.001043
from linot.Plugins.PluginBase import PluginBase from linot.LinotArgParser import LinotParser from nose.tools import ok_ from nose.tools import raises class MockLine: def __init__(self): self.msg_recv = [] self.msg_text = [] def sendMessageToClient(self, recv, msg): self.msg_recv.appen...
self.plugin.stop() def test_stop_normal(self): def mock_stop(): pass self.plugin.stop() self.plugin._started = True self.plugin._stop = mock_stop self.plugin.stop() ok_(self.plugin.is_start() is False) def test_cmd_process(self): self.plug...
in._line.msg_recv[0] == 'sender') ok_('Unknown' in self.plugin._line.msg_text[0], self.plugin._line.msg_text[0]) self.plugin._cmd_process('test', 'sender') ok_(self.plugin._line.msg_recv[1] == 'sender') ok_('not implemented' in self.plugin._line.msg_text[1], self.plugin._line.msg_text[1]...
rmelo19/rmelo19-arduino
python/readSerial.py
Python
gpl-3.0
430
0.025581
#!/usr/bin/env python import serial sr = serial.Serial('/dev/ttyACM0', 115200) currentLine = sr.readline() while
currentLine.find('PRESSURES: ') == -1: currentLine = sr.readline() while True: currentLine = sr.readline() parsedLine = currentLine[currentLine.find('[')
+1:currentLine.find(']')].split(',') intParsedLine = [int(element) for element in parsedLine] for element in intParsedLine: print element sr.close()
ToontownUprising/src
toontown/golf/GolfGlobals.py
Python
mit
12,858
0.001555
from direct.directnotify import DirectNotifyGlobal import random MAX_PLAYERS_PER_HOLE = 4 GOLF_BALL_RADIUS = 0.25 GOLF_BALL_VOLUME = 4.0 / 3.0 * 3.14159 * GOLF_BALL_RADIUS ** 3 GOLF_BALL_MASS = 0.5 GOLF_BALL_DENSITY = GOLF_BALL_MASS / GOLF_BALL_VOLUME GRASS_SURFACE = 0 BALL_SURFACE = 1 HARD_SURFACE = 2 HOLE_SURFACE = 3...
le10.bam', 'physicsData': 'golfGreen10', 'blockers': ()}, 11: {'name': '', 'par': 3, 'maxSwing': 6, 'terrainModel': 'phase_6/models/golf/hole11.bam', 'physicsData': 'golfGreen11', 'blockers': ()}, 12: {'name': '', 'par': 3, 'maxSwing': 6, 'terrainModel': 'ph...
hysicsData': 'golfGreen12', 'blockers': ()}, 13: {'name': '', 'par': 3, 'maxSwing': 6, 'terrainModel': 'phase_6/models/golf/hole13.bam', 'physicsData': 'golfGreen13', 'blockers': ()}, 14: {'name': '', 'par': 3, 'maxSwing': 6, 'terrainModel': 'phase_6/models/golf/h...
MyRobotLab/pyrobotlab
home/steveh110/parser.py
Python
apache-2.0
833
0.062425
def parser(lien,nb) : if lien == 1: lien = "http://www.lesbonsnumeros.com/euromillions/rss.xml" elif lien == 2: lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro" elif li
en == 3: lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=313&lang=ro" elif lien == 4: lien = "http://www.20min.ch/rss/rss.tmpl?ty
pe=rubrik&get=526&lang=ro" else : lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro" d = feedparser.parse(lien) i = 0 if nb == "de" : nb = 2 if nb <= len(d['entries']) and nb != 0 : nb = nb else : nb = len(d['entries']) while i < nb : texte = d['entries'][i]['title'] + ". ...
stvstnfrd/edx-platform
openedx/core/lib/blockstore_api/models.py
Python
agpl-3.0
2,551
0.001176
""" Data models used for Blockstore API Client """ from datetime import datetime from uuid import UUID import attr import six def _convert_to_uuid(value): if not isinstance(value, UUID): return UUID(value) return value @attr.s(frozen=True) class Collection(object): """ Metadata about a blo...
digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class DraftFile(BundleFile): """ Metadata about a file in a blockstore draft. """ modified = attr.ib(type=bool) # Was this file modified in the draft? @attr.s(frozen=True) class LinkReference(object): """ A pointer to a speci
fic BundleVersion """ bundle_uuid = attr.ib(type=UUID, converter=_convert_to_uuid) version = attr.ib(type=int) snapshot_digest = attr.ib(type=six.text_type) @attr.s(frozen=True) class LinkDetails(object): """ Details about a specific link in a BundleVersion or Draft """ name = attr.ib(...
hiorws/ulakbus
ulakbus/services/personel/hitap/hizmet_nufus_sorgula_kaydet.py
Python
gpl-3.0
5,170
0.003095
# -*- coding: utf-8 -*- """ HITAP HizmetNufusSorgula Zato Servisi """ # Copyright (C) 2015 ZetaOps Inc. # # This file is licensed under the GNU General Public License v3 # (GPLv3). See LICENSE.txt for details. from zato.server.service import Service import os import urllib2 from pyoko.exceptions import Multiple...
assed.kuruma_baslama_tarihi = record_values['kuruma_baslama_tarihi'] nufus_kayitlari_passed.emekli_sicil_6495 = record_values['emekli_sicil_6495'] nufus_kayitlari_passed.gorev_tarihi_6495 = record_
values['gorev_tarihi_6495'] nufus_kayitlari_passed.durum = record_values['durum'] nufus_kayitlari_passed.sebep = record_values['sebep'] tckn = self.request.payload['personel']['tckn'] conn = self.outgoing.soap['HITAP'].conn hitap_dict = {} # connects with soap c...
stormandco/aiohttp_debugtoolbar
aiohttp_debugtoolbar/middlewares.py
Python
apache-2.0
6,287
0
import asyncio import sys import aiohttp_jinja2 from aiohttp import web from .toolbar import DebugToolbar from .tbtools.tbtools import get_traceback from .utils import addr_in, REDIRECT_CODES, APP_KEY, TEMPLATE_KEY, hexlify, \ ContextSwitcher __all__ = ['toolbar_middleware_factory', 'middleware'] HTML_TYPES = ('t...
rn (yield from handler(request)) toolbar = DebugToolbar(r
equest, panel_classes, global_panel_classes) _handler = handler context_switcher = ContextSwitcher() for panel in toolbar.panels: _handler = panel.wrap_handler(_handler, context_switcher) try: response = yield from context_switcher(_handler(request)) exc...
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_09_01/models/virtual_network_usage.py
Python
mit
1,905
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
------------------------ from msrest.serialization import Model class VirtualNetworkUsage(Model): """Usage details for subnet. Variables are only populated by the server, and will be ignored when sending a request. :ivar current_value: Indicates number of IPs used from the Subnet. :
vartype current_value: float :ivar id: Subnet identifier. :vartype id: str :ivar limit: Indicates the size of the subnet. :vartype limit: float :ivar name: The name containing common and localized value for usage. :vartype name: ~azure.mgmt.network.v2017_09_01.models.VirtualNetworkUsageName...
nlhkabu/connect
connect/accounts/view_utils.py
Python
bsd-3-clause
2,407
0
from urllib.parse import urlsplit from django.contrib import messages from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.db
impo
rt IntegrityError, transaction from django.shortcuts import redirect from django.utils.translation import ugettext as _ from connect.accounts.models import UserLink, UserSkill, LinkBrand def save_paired_items(request, user, formset, Model, item_name, counterpart_name): """ Handle saving...
ashutoshvt/psi4
psi4/share/psi4/databases/A24alt.py
Python
lgpl-3.0
29,758
0.00746
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
'%s-%s-monoB-CP' % (dbse, rxn) : -1, '%s-%s-monoA-unCP' % (dbse, rxn) : -1, '%s-%s-monoB-unCP' % (dbse, rxn) : -1 } ACTV_SA['%s-%s' % (dbse, rxn)] = ['%s-%s-dimer' % (dbse, rxn) ] ACTV_CP['%s-%s' % (dbse, rxn)] = ['%s-%s-dim...
%s-%s-monoA-CP' % (dbse, rxn), '%s-%s-monoB-CP' % (dbse, rxn) ] ACTV[ '%s-%s' % (dbse, rxn)] = ['%s-%s-dimer' % (dbse, rxn), '%s-%s-monoA-unCP' % (dbse, rxn), '%s-%s-monoB-unCP' % (dbse, rxn...
invenfantasy/software-factory
docs/conf.py
Python
apache-2.0
8,403
0
# -*- coding: utf-8 -*- # # software-factory documentation build configuration file, created by # sphinx-quickstart on Mon May 5 13:05:13 2014. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated fi...
file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static
files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path =...
Diacamma2/syndic
diacamma/condominium/printmodel/Owner_0001.py
Python
gpl-3.0
28,968
0.004108
# -*- coding: utf-8 -*- ''' Printmodel django module for condominium @author: Laurent GAY @organization: sd-libre.fr @contact: info@sd-libre.fr @copyright: 2016 sd-libre.fr @license: This file is part of Lucterios. Lucterios is free software: you can redistribute it and/or modify it under the terms of the GNU General...
border_style="" border_width="0.2" text_align="right" line_height="11" font_family="sans-serif" font_weight="" font_size="10"> {[b]}%(total_current_owner)s{[/b]} </cell> <cell border_color="black
" border_style="" border_width="0.2" text_align="right" line_height="11" font_family="sans-serif" font_weight="" font_size="10"> #total_current_owner </cell> </rows> <rows> <cell border_color="black" border_style="" border_width="0.2" text_align="right" line_height="11" font_family="sans...
Royce/GammaJS
support/APIgen/generate.py
Python
mit
4,851
0.024531
######################## ### ### IMPORTS ### ######################## ######################## ### BUILTIN ######################## from datetime import date import codecs import shutil import time import sys import re import os ######################## ### LOCAL ###################...
NERATOR ### ######################## class Generator(object): def __init__(self , outDir = os.path.join(here, "docs") , tempdir = os.path.join(here, "tmp") , assetDirs = None , showPrivate = False , templateDirs = None ): self.outDir = ...
te self.templateDirs = templateDirs if not self.templateDirs: self.templateDirs = [os.path.join(here, "templates"), ""] for new, onKls in [(templateDirs, self.templateDirs), (assetDirs, self.assetDirs)]: if new: if type(new) in (str, unicode): ...
matslindh/codingchallenges
knowit2017/23.py
Python
mit
2,089
0.004787
import copy def execute(moves): players = [ {'name': 'Xena', 'score': 0}, {'name': 'Ophelia', 'score': 0}, ] idx = 0 first_player = 0 draw_count = 0 move_count = 0 init_map = [[False]*3, [False]*3, [False]*3] map = copy.deepcopy(init_map) for move
in moves:
move = int(move) player_idx = (idx + first_player) % 2 player = players[player_idx] idx += 1 row = (move - 1) // 3 column = (move - 1) % 3 move_count += 1 map[row][column] = 'X' if player_idx == first_player else 'O' done = False ...
mozilla/normandy
normandy/studies/urls.py
Python
mpl-2.0
242
0
from django.conf.urls import u
rl, include app_name = "studies" urlpatterns = [ url(r"^api/v1/", include("normandy.studies.api.v1.urls", namespace="v1")), url(
r"^api/v3/", include("normandy.studies.api.v3.urls", namespace="v3")), ]
sametmax/Django--an-app-at-a-time
ignore_this_directory/django/utils/formats.py
Python
mit
8,973
0.000892
import datetime import decimal import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, datetime_safe, numberformat from django.utils.functional import lazy from django.utils.translation import ( check_for_language, get_language, to_locale, ) # f...
: break if val is None: if format_type not in FORMAT_SETTINGS: return format_type val = getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS: # If a list of input formats from on
e of the format_modules was # retrieved, make sure the ISO_INPUT_FORMATS are in this list. val = list(val) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: val.append(iso_input) _format_cache[cache_key] = val return val get_f...
GNOME/orca
test/keystrokes/firefox/aria_slider_tpg.py
Python
lgpl-2.1
8,352
0.000239
#!/usr/bin/python """Test of ARIA horizontal sliders using Firefox.""" from macaroon.playback import * import utils sequence = MacroSequence() #sequence.append(WaitForDocLoad()) sequence.append(PauseAction(10000)) sequence.append(KeyComboAction("Tab")) sequence.append(KeyComboAction("Tab")) sequence.append(utils.S...
E: 'Volume 25 % horizontal slider'", " VISIBLE: 'Volume 25 % horizontal slider', cursor=1", "SPEECH OUTPUT: '25 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("Page_Down")) sequence.append(utils.AssertPresentationAction( "11. Volume Page
Down", ["BRAILLE LINE: 'Volume 0 % horizontal slider'", " VISIBLE: 'Volume 0 % horizontal slider', cursor=1", "SPEECH OUTPUT: '0 %'"])) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAction("End")) sequence.append(utils.AssertPresentationAction( "12. Volume End", ["B...
lynxis/libavg
src/samples/rotcustompivot.py
Python
lgpl-2.1
291
0.024055
#!/usr/bin/env python # -*- coding: ut
f-8 -*- from libavg import avg, player canvas = player.createMainCanvas(size=(160,120)) rootNode = canvas.getRootNode() avg.ImageNode(pos=(80,30), size=(40,30), href="rgb24-64x64.png", angle=1.570, pivot=(0,0), par
ent=rootNode) player.play()
asweigart/tortuga
docs/conf.py
Python
bsd-3-clause
8,154
0.006255
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Tortuga documentation build configuration file, created by # sphinx-quickstart on Wed Sep 9 16:36:12 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # au...
is directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show pa
ge references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual pa...
thijsmie/madmin
gui_lib/container.py
Python
mit
2,228
0.002244
from widget import Widget from gui_util import intersect # Simple container, list of children is not meant to be mutable class Container(Widget): def __init__(self, width, height): super(Container, self).__init__(width, height) self.children = [] self.curFocus = 0 def draw(self, canvas...
ld_x, child_y):
self.children[index] = (child_x, child_y, self.children[index][2]) def numChildren(self): return len(self.children) def onFocus(self): while self.curFocus < len(self.children): if self.children[self.curFocus][2].onFocus(): return True self.curFo...
sjsucohort6/openstack
python/venv/lib/python2.7/site-packages/novaclient/tests/unit/fixture_data/availability_zones.py
Python
mit
3,264
0
# 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 t...
om novaclient.tests.unit.fixture_
data import base class V1(base.Fixture): base_url = 'os-availability-zone' zone_info_key = 'availabilityZoneInfo' zone_name_key = 'zoneName' zone_state_key = 'zoneState' def setUp(self): super(V1, self).setUp() get_os_availability_zone = { self.zone_info_key: [ ...
alex-mitrevski/delta-execution-models
rule_learner/utils/conversion.py
Python
gpl-3.0
1,716
0.002914
''' Copyright 2017 by Alex Mitrevski <aleksandar.mitrevski@h-brs.de> This file is part of delta-execution-models. delta-execution-models 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...
t it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Gen
eral Public License for more details. You should have received a copy of the GNU General Public License along with delta-execution-models. If not, see <http://www.gnu.org/licenses/>. ''' class Types(object): BOOL = 0 INT = 1 class TypeConverter(object): '''An interface to various static type conv...
barisariburnu/viaspider
viaspider/items.py
Python
mit
2,467
0.008107
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy from viaspider.settings import SUMMARY_LIMIT class ViaspiderItem(scrapy.Item): # define the fields for your item here like: url = scrapy.Field()...
turn (self.seperator.join(result.split(self.
seperator)[:-1])).strip() else: return result @property def summary(self): result = self.response.xpath('//head/meta[@property="og:description"]/@content').extract()[0] return result[:-(SUMMARY_LIMIT + 3)] + '...' if len(result) > SUMMARY_LIMIT else result @pro...
abulte/docker-dbaas
manage.py
Python
mpl-2.0
757
0.003968
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2013 Alexandre Bulté <alexandre[at]bulte[dot]net> # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0
/. from flask.ext.script import
Manager from contextlib import closing import docker_lib as docker from webapp import app, connect_db manager = Manager(app) @manager.command def init_db(): print 'Starting...' with closing(connect_db()) as db: with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript...
ActiveState/code
recipes/Python/435694_Evaluate_upperletters_variable_name_constants/recipe-435694.py
Python
mit
7,266
0.002477
#### # compile.py #!/usr/bin/env python import re import os import sys import new import imp import time import struct import marshal import compiler from compiler.ast import Const, AssName, AssTuple __author__ = 'Shimomura Ikkei' __date__ = '2005-06-23' __all__ = ['ConstantCompiler'] # Check the string is valid c...
return CodeWrapper(filename, code) class CodeWrapper: """An utility class to save code object as .pyc file.""" def __init__(self, src_filename, code): "CodeWrapper(code) This class only wrap an object for method chain." assert isinstance(src_filename, str) and src_filename a...
filename self.__code = code def getCode(self): "getCode() ... Returns code object." assert isinstance(self.__code, new.code) return self.__code def __timestamp(self, pyc_filename): "__get_timestamp(pyc_filename) Gets timestamp stored in .pyc file." assert isins...
matiasherranz/keyczar
python/tests/keyczar_tests/util_test.py
Python
apache-2.0
7,078
0.008336
#!/usr/bin/python # # Copyright 2011 LightKeeper LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
sertTrue(b64_data.endswith('==')) self.__testRead(b64_data, double_pad_data) self.__testRead(b64_data[:-1], double_pad_data) self.__testRead(b64_data[:-2], double_pad_data) def testSimulateDecrypter(self): enc_data = \ 'AJehaFGwoOrkzpDCnF1zqIi721eCOMYWRmLyRyn3hxyhh_mYwpnDN6jKN057gr5lz' \ ...
Decode(enc_data) stream = util.IncrementalBase64WSStreamReader(StringIO.StringIO(enc_data)) result = stream.read(5) result += stream.read(15) read_data = True while read_data: read_data = stream.read(4096) result += read_data self.assertEquals(result, expected_result) class ParseX50...
krukru/shell-me-up-scotty
scripts/generators.py
Python
apache-2.0
1,272
0.000786
import os from .helpers import get_user from shutil import copyfile def enable_vhosts(): tmp = [] conf_path = "/usr/local/etc/httpd/httpd.conf" with open(conf_path, 'r') as input_file: for line in input_file.readlines(): if line == "#Include /usr/local/etc/httpd/extra/httpd-vhosts.co...
ut_file: for line in tmp: output_file.write(line) output_file.close() def generate_hosts(): data_path = os.path.dirname(__file__) + "/../files/hosts" hosts_path = "/private/etc/hosts" copyfile(data_path, hosts_path) def generate_vhosts(): tmp = [] data_path = os.pa...
xtra/httpd-vhosts.conf" user = get_user() with open(data_path, 'r') as vhost_template: for line in vhost_template.readlines(): tmp.append(line.replace("{USERNAME}", user)) vhost_template.close() print(tmp) # with open(vhosts_path, 'w') as output_file: # for line ...
quantmind/pulsar-agile
tests/test_githubapi.py
Python
bsd-3-clause
2,024
0
import os import asyncio import tests class TestGithubApi(tests.GithubMix, tests.AgileTest): def test_url(self): repo = self.repo self.assertTrue(repo.api_url) self.assertEqual(repo.api_url, '%s/repos/%s' % (self.github.api_url, tests.REPO)) self.assertEq...
self.assertTrue(releases) self.assertTrue(len(releases) <= 100) async def test_latest_release(
self): repo = self.repo release = await repo.releases.latest() self.assertTrue(release) async def test_release_by_tag(self): repo = self.repo release = await repo.releases.latest() self.assertTrue(release) bytag = await repo.releases.tag(release['tag_name']) ...
Backflipz/plugin.video.excubed
resources/lib/cache/tests.py
Python
gpl-2.0
4,445
0
# coding=utf-8 import random import time import threading import unittest from lru_cache import LruCache class TesLruCache(unittest.TestCase): def test_cache_normal(self): a = [] @LruCache(maxsize=2, timeout=1) def foo(num): a.append(num) return num foo(1)...
st_cache_when_timeout_and_maxsize_is_none(self): a = [] @LruCache()
def foo(num): a.append(num) return num foo(1) foo(1) self.assertEqual(a, [1]) def test_cache_when_timeout_is_none(self): a = [] @LruCache(maxsize=10) def foo(num): a.append(num) return num foo(1) foo...
BMeu/Orchard
orchard/system_status/system/memory.py
Python
mit
1,413
0
# -*- coding: utf-8 -*- """ Retrieve information on system memory (RAM). """ import psutil import orchard.extensions def free() -> int: """ Get the amount of memory available for usage. :return: The memory in Bytes that can be used. """ memory = psutil.virtual_memory() return m...
- free() def swap_available() -> int: """ Get the amount of swap memory available for usage. :return: The amount of swap memory in Bytes that can be used. """ swap = psutil.swap_memory() return swap.free @orchard.extensions.cache.memoize() def swap_total() -> int: """ G...
swap = psutil.swap_memory() return swap.total def swap_used() -> int: """ Get the amount of swap memory used. :return: The amount of swap memory in Bytes that is being used. """ swap = psutil.swap_memory() return swap.used
undoware/neutron-drive
google_appengine/google/appengine/ext/mapreduce/output_writers.py
Python
bsd-3-clause
23,260
0.007352
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
all__ = [ "BlobstoreOutputWriter", "BlobstoreOutputWriterBase", "BlobstoreRecordsOutputWriter", "FileOutputWriter", "FileOutputWriterBase", "FileRecordsOutputWriter", "KeyValueBlobstoreOutputWriter", "KeyValueFileOutputWriter", "COUNTER_IO_
WRITE_BYTES", "COUNTER_IO_WRITE_MSEC", "OutputWriter", "RecordsPool", ] import gc import itertools import logging import time from google.appengine.api import files from google.appengine.api.files import file_service_pb from google.appengine.api.files import records from google.appengine.ext.mapreduce...
civisanalytics/civis-python
civis/tests/test_io.py
Python
bsd-3-clause
61,250
0
import tempfile import csv import gzip import io import json import os from io import StringIO, BytesIO from unittest import mock from tempfile import TemporaryDirectory import zipfile import pytest import requests import vcr try: import pandas as pd has_pandas = True except ImportError: has_pandas = Fals...
escaped=False, execution='imm
ediate', credential_id=None, polling_interval=None, hidden=True ) @pytest.mark.civis_file_to_table @mock.patch('civis.io._tables._process_cleaning_results') @mock.patch('civis.io._tables._run_cleaning') def test_civis_file_to_table_table_exists(self, ...
shaunduncan/helga-wiki-whois
helga_wiki_whois.py
Python
mit
487
0.004107
from helga import settings from helga.plugins import com
mand @command('showme', aliases=['whois', 'whothehellis'], help="Show a URL for the user's intranet page. Usage: helga (showme|whois|whothehellis) <nick>") def wiki_whois(client, channel, nick, message, cmd, args): # pragma: no cover """ Show the intranet page for a user. Settings must have a WIKI_U...
able substring named {user} """ return settings.WIKI_URL.format(user=args[0])
Asparagirl/ArchiveBot
uploader/uploader.py
Python
mit
9,855
0.003551
#!/usr/bin/python3 """uploader.py: upload WARC files toward the Internet Archive rsync mode (RSYNC_URL set): upload everything to an rsync endpoint such as fos. s3 mode (S3_URL set): upload everything directly to the Internet Archive """ from __future__ import print_function import os import time import subproces...
None: raise RuntimeError('Must specify IA_ITEM_PREFIX if using IA S3 ' '(hint: archiveteam_archivebot_go_$pipeline_name' '_}') self.ia_access = os.environ.get('IA_ACCESS') if self.ia_access is None: ...
'(hint: your access key)') self.wait = os.environ.get('WAIT', 5) def try_mkdir(path): try: os.mkdir(path) except OSError: pass def should_upload(basename): assert not '/' in basename, basename return not basename.startswith('.') and \ (basename.endswith('.warc...
rajashreer7/autotest-client-tests
linux-tools/nss_softokn/nss_softokn.py
Python
gpl-2.0
1,474
0.007463
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error class nss_softokn(test.test): """ Autotest module for testing basic functionality of nss_softokn @author Anitha MallojiRao amalloji@in.ibm.com ## ""...
the test. """ self.nfail = 0 ret_val = subprocess.Popen(['make', 'PERL=/usr/bin/perl', 'tests'], cwd="%s/nss_softokn/test" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail += 1 logging.info('\n Test initialize successfully') def run_onc...
""" Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.Popen(['./nss-softokn.sh'], cwd="%s/nss_softokn" %(test_path)) ret_val.communicate() if ret_val.returncode != 0: self.nfail +=...
Ziqi-Li/bknqgis
pandas/pandas/io/parsers.py
Python
gpl-2.0
119,743
0.0001
""" Module contains tools for processing files into DataFrames or other objects """ from __future__ import print_function from collections import defaultdict import re import csv import sys import warnings import datetime from textwrap import fill import numpy as np from pandas import compat from pandas.compat import...
re the callable function evaluates to True. An example of a valid callable argument would be ``lambda x: x.upper() in ['AAA', 'BBB', 'DDD']``. Using this parameter results in much faster parsing time and lower memory usage. as_recarray : boolean, default False .. deprecated:: 0.19.0 Please call `...
eturn a NumPy recarray instead of a DataFrame after parsing the data. If set to True, this option takes precedence over the `squeeze` parameter. In addition, as row indices are not available in such a format, the `index_col` parameter will be ignored. squeeze : boolean, default False If the parsed data ...
codekoala/django-pendulum
pendulum/tests/pause.py
Python
mit
3,889
0.001543
from django.test import TestCase from django.test.client import Client from django.core.urlresolvers import reverse from pendulum.tests.utils import VALID_PASSWORD, VALID_USER, ffd from pendulum.models import Entry class PauseTestCase(TestCase): """ Check to make sure that entries can be paused and unpaused as...
------------------------------------------------- # 2. ENTRY THAT IS ALREADY PAUSED id = 2 # check to make sure that
log entry is paused entry = Entry.objects.get(pk=id) self.assertTrue(entry.is_paused) # try pausing an already paused entry response = self.get_response(id) self.assertEquals(response.status_code, 302) # check to make sure that log entry is no longer paused entr...
oshepherd/eforge
eforge/views.py
Python
isc
2,416
0.003313
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWA...
port project_page, has_project_perm, user_page, group_page from django.shortcuts import get_object_or_404, render_to_response, redirect from django.http import HttpResponse from django.template import RequestContext @project_page def summary(request, project): return render_to_response('eforge/summary.html', { ...
manage(request, project): tabs = plugins.provider['managepg'] print tabs if not 'pg' in request.GET: return render_to_response('eforge/manage.html', { 'project': project, 'tabs': tabs.items(), }, context_instance=RequestContext(request)) else: pg = reques...
twatteyne/dustlink_academy
views/web/dustWeb/viz/VizTimeLine.py
Python
bsd-3-clause
3,559
0.007305
import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('VizTimeLine') log.setLevel(logging.ERROR) log.addHandler(NullHandler()) import VizMorris class VizTimeLine(VizMorris.VizMorris): #======================== header ==================...
ID}(data) {{ if (graph_{VIZID}==
0) {{ graph_{VIZID} = Morris.Line({{ element: 'chart_div_{VIZID}', data: data.datapoints, xkey: 'timestamp', ykeys: data.metadata.axis, labels: data.metadata.axis, xLabels: ...
idlesign/django-admirarchy
admirarchy/tests/conftest.py
Python
bsd-3-clause
174
0
from pytest_djangoapp import configure_djangoapp_plugin pytest
_plugins = configure_djangoapp_plugin( { 'LANGUAGE_CODE': 'ru', }, admi
n_contrib=True, )
byxor/limp
tests/unit/syntax_tree_test.py
Python
gpl-3.0
14,784
0.000473
import limp.syntax_tree as SyntaxTree import limp.tokens as Tokens from nose.tools import assert_equals TT = SyntaxTree.Types data = [ ([], None), # Booleans ('true', (TT.Boolean, 'true')), ('false', (TT.Boolean, 'false')), # Integers ('100', (TT.Integer, '100')), ('500', (TT.Integer,...
'reverse'), [(TT.List, [(TT.List, [(TT.Symbol, 'a')]), (TT.List, [(TT.Symbol, 'b')])])])), # Anonymous Funct
ions ('(->10)', (TT.Function, [], (TT.Integer, '10'))), ('(->20)', (TT.Function, [], (TT.Integer, '20'))), ('(->(foo))', (TT.Function, [], (TT.FunctionCall, (TT.Symbol, 'foo'), []))), ('(->(+ 0x9 0x10))', (TT.Function, [], (TT.FunctionCall, ...
sxslex/rows
to-do/ods_draft.py
Python
gpl-3.0
1,998
0.000501
# coding: utf-8 import HTMLParser import zipfile from re import compile as regexp_compile, DOTALL from unicodedata import normalize html_parser = HTMLParser.HTMLParser() regexp_tags = regexp_compile(r'<[ \t]*[a-zA-Z0-9!"./_-]*[^>]*>', flags=DOTALL) regexp_comment = regexp_compile(r'<!--.*?-->', flags=DOTALL) regex...
r'(</table:table>)', flags=DOTALL) regexp_ods_table_row = regexp_compile(r'(<table:table-row[^>]*>)(.*?)' r'(</table:table-row>)', flags=DOTALL) regexp
_ods_table_cell = regexp_compile(r'(<table:table-cell[^>]*>)(.*?)' r'(</table:table-cell>)', flags=DOTALL) # TODO: encoding? # TODO: replace &...; # TODO: name/id of tables # TODO: re.MULTILINE # TODO: identify types # TODO: clear empty rows? # TODO: clear non-table rows? def t...
MrSurly/micropython-esp32
tests/basics/attrtuple1.py
Python
mit
364
0
# test attrtuple # we can't test this type directly so we use sys.implementation object import sys t = sys.implementation # It can be just a normal tuple on small ports try: t.name except AttributeError: print("SKIP") raise SystemExit # test printing of attrtuple pr
int(str(t).find("versi
on=") > 0) # test read attr print(isinstance(t.name, str))
NLeSC/MAGMa
web/magmaweb/script.py
Python
apache-2.0
5,092
0
#!/usr/bin/env python """Manage MAGMa web user accounts """ import argparse import os import sys from transaction import commit from paste.deploy import appconfig from sqlalchemy import engine_from_config from magmaweb.user import init_user_db, User, JobMeta from magmaweb.job import make_job_factory class MagmaComma...
unc=self.add) sc_update = sp.add_parser( "update", help=self.update.__doc__, description=self.update.__doc__) sc_update.add_argument( '-u', '--
user', help="change user id)", default=argparse.SUPPRESS, type=str) sc_update.add_argument( '-n', '--name', help="change display name", default=argparse.SUPPRESS, type=str) sc_update.add_argument( '-e', '--email', help="change email", default=a...
torufuru/oolhackathon
ryu/ofproto/ofproto_v1_2_parser.py
Python
apache-2.0
159,337
0
# Copyright (C) 2012 Nippon Telegraph and Telephone Corporation. # Copyright (C) 2012 Isaku Yamahata <yamahata at valinux co jp> # # 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://...
ofproto.OFPET_EXPERIMENTER: return OFPErrorExperimenterMsg.parser(datapath, version, msg_type, msg_len, xid, buf) msg = super(OFPErrorMsg, cls).parser(datapath, version, msg_type,
msg_len, xid, buf) msg.type, msg.code = struct.unpack_from( ofproto.OFP_ERROR_MSG_PACK_STR, msg.buf, ofproto.OFP_HEADER_SIZE) msg.data = msg.buf[ofproto.OFP_ERROR_MSG_SIZE:] return msg def _serialize_body(self): assert sel...
jaor/python
bigml/tests/test_09_ensemble_prediction.py
Python
apache-2.0
4,365
0.003438
# -*- coding: utf-8 -*- # # Copyright 2015-2021 BigML # # 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 ...
s When I create an ensemble prediction for "<data_input>" And I wait until the prediction is ready less than <time_4> secs Then the prediction for "<objective>" is "<prediction>" Examples: | data | time_1
| time_2 | time_3 | time_4 | number_of_models | tlp | data_input | objective | prediction | | ../data/iris.csv | 10 | 10 | 50 | 20 | 5 | 1 | {"petal width": 0.5} | 000004 | Iris-versicolor | | ../data/iris_sp_chars.csv | 10 | 10 ...
SeanHayes/swarm-war
swarm_war/teams/models.py
Python
agpl-3.0
3,862
0.039109
# -*- coding: utf-8 -*- #Copyright (C) 2011 Seán Hayes #Python imports import logging import pdb #Django imports from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.db import models, IntegrityError from django.db.models.signals import post_save from django.utils import...
get deleted when a related team gets deleted team = models.ForeignKey(Team, null=True) objects = FacebookRequestManager() def html(self): s = u'%s has invited you to join a Team: %s.' % (self.user.username, self.team.html) return safestring.mark_safe(s) def conf
irm(self, friend): try: if self.team is None: raise TeamNoLongerExistsError() if self.user.id not in [u.id for u in self.team.members.all()]: raise Exception('Can\'t join %s because %s isn\'t a member anymore.' % (self.team.name, self.user.username)) friend.teamprofile.join_team(self.team) fina...
pombredanne/parakeet
parakeet/builder/array_builder.py
Python
bsd-3-clause
9,545
0.025144
from ..ndtypes import (make_slice_type, make_array_type, ptr_type, ArrayT, TupleT, ScalarT, Type, PtrT, Int64, IntT, Float64) from ..syntax import (Alloc, AllocArray, ArrayView, Const, Index, Slice, Struct, Var, Select, Expr) from ..syntax.helpers import (const, zero_i64, wrap_if_constant, slic...
if rank == 1: assert axis == 0 return idx indices = [] for i in xrange(rank): if i == axis: indices.append(idx) else: s = self.
slice_value(self.none, self.none, self.int(1)) indices.append(s) return self.tuple(indices) def elts_in_slice(self, start, stop, step): start_minus_start = self.sub(stop, start, name = "stop_minus_start") nelts = self.div(self.cast(start_minus_start, Float64), step, name = "nelts") ceil = sel...
coteyr/home-assistant
homeassistant/components/downloader.py
Python
mit
4,237
0
""" homeassistant.components.downloader ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides functionality to download files. For more details about this component, please refer to the documentation at https://home-assistant.io/components/downloader/ """ import logging import os import re import threading import requests fr...
logger.info("%s -> %s", url, final_path) with open(final_path, 'wb') as fil: for chunk in req.iter_content(1024): fil.write(chunk) logger.info("Downloading of %s done", url) except requests.exceptions.ConnectionEr...
if final_path and os.path.isfile(final_path): os.remove(final_path) threading.Thread(target=do_download).start() hass.services.register(DOMAIN, SERVICE_DOWNLOAD_FILE, download_file) return True
haim0n/miko
travis_pypi_setup.py
Python
isc
3,755
0.000266
#!/usr/bin/env python # -*- coding: utf-8 -*- """Update encrypted deploy password in Travis config file """ from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.h...
_main__' == __name__: import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo', default=GITHUB_REPO, help='GitHub repo (default: %s)' % GITHUB_REPO) parser.add_argument('--password', help='PyPI password (will promp...
args = parser.parse_args() main(args)
evernym/zeno
plenum/test/replica/test_buffers_cleaning.py
Python
apache-2.0
3,313
0.001811
from plenum.common.event_bus import InternalBus from plenum.common.startable import Mode from plenum.common.timer import QueueTimer from plenum.common.util import get_utc_epoch from plenum.server.consensus.primary_selector import RoundRobinConst
antNodesPrimariesSelector from plenum.server.database_manager import DatabaseManager from plenum.server.quorums import Quorums from plenum.server.replica import Replica from plenum.test.testing_utils import FakeSomething def test_ordered_cleaning(tconf): global_view_no = 2 node = FakeSomething( name=...
o, utc_epoch=get_utc_epoch, get_validators=lambda: [], db_manager=DatabaseManager(), requests=[], mode=Mode.participating, timer=QueueTimer(), quorums=Quorums(4), write_manager=None, poolManager=FakeSomething(node_names_ordered_by_rank=lambda: []),...
wojas/django-pgrunner
pgrunner/management/commands/pg_psql.py
Python
mit
539
0.003711
from __future__ import absolute_import, division, print_functio
n, unicode_literals from django.core.management.base import BaseCommand, CommandError import subprocess from pgrunner import bin_path from pgrunner.commands import get_port class Command(BaseCommand): help = 'Run psql with correct database' def run_from_argv(self, argv): port = get_port() cm...
print(' '.join(cmd)) subprocess.call(cmd)
brettcs/diffoscope
diffoscope/comparators/text.py
Python
gpl-3.0
2,721
0.002575
# -*- coding: utf-8 -*- # # diffoscope: in-depth comparison of files, archives, and directories # # Copyright © 2014-2015 Jérémy Bobbio <lunar@debian.org> # # diffoscope 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 Fou...
difference = Difference.from_text_readers(my_conte
nt, other_content, self.name, other.name, source) # Check if difference is only in line order. if difference and order_only_difference(difference.unified_diff): difference.add_comment("ordering differences only") if my_encoding != other_encoding: ...
HybridF5/jacket
jacket/storage/zonemanager/drivers/cisco/cisco_fc_zone_client_cli.py
Python
apache-2.0
18,157
0.000386
# (c) 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 # # Unl...
oncurrency import processutils from oslo_log import log as logging from oslo_utils import excutils import six from jacket.storage import exception from jacket.storage.i18n import _, _LE, _LI, _LW from jacket.storage import ssh_utils from jacket.storage import utils import jacket.storage.zonemanager.drivers.cisco.fc_zo...
"""Cisco FC zone client cli implementation. OpenStack Fibre Channel zone client cli connector to manage FC zoning in Cisco SAN fabrics. Version history: 1.0 - Initial Cisco FC zone client cli """ switch_ip = None switch_port = '22' switch_user = 'admin' switch_pwd = 'none' ...
easmetz/inasafe
safe/report/impact_report.py
Python
gpl-3.0
24,112
0.000249
# coding=utf-8 """ Module to generate impact report using QgsComposition. Contact : ole.moller.nielsen@gmail.com .. note:: 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 ...
"""Set the layer that will be used for stats, legend and reporting. :param layer: Layer that will be used for stats, legend and reporting. :type layer: QgsMapLayer, Q
gsRasterLayer, QgsVectorLayer """ self._layer = layer @property def extra_layers(self): """Getter to extra layers extra layers will be rendered alongside impact layer """ return self._extra_layers @extra_layers.setter def extra_layers(self, extra_layers...
cgstudiomap/cgstudiomap
main/parts/connector-telephony/crm_phone/crm_phone.py
Python
agpl-3.0
4,443
0
# -*- encoding: utf-8 -*- ############################################################################## # # CRM phone module for Odoo/OpenERP # Copyright (c) 2012-2014 Akretion (http://www.akretion.com) # @author: Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free software: you can re...
# in his preferences, cf server/openerp/addons/base/res/res_users.py #
in "def write()" of "class res_users(osv.osv)" context_propose_creation_crm_call = fields.Boolean( string='Propose to create a call in CRM after a click2dial', default=True) class PhoneCommon(models.AbstractModel): _inherit = 'phone.common' @api.model def click2dial(self, erp_number):...
blxble/mesh-core-on-nrf
nrf5_sdk/external/nano-pb/generator/camel_case_splitter.py
Python
apache-2.0
854
0.001171
def split_camel_case(input): def remove_camel_case(camel_case_input): no_camel_case = "" if len(camel_case_input) <= 0: return "" no_camel_case += camel_case_input[0].lower() for c in camel_case_input[1:]: if c.isupper(): no_camel_case += "_" +...
mel_case_name(i): retval += remove_camel_case(i) + "_" else: retval += i + "_" return retval[:-1].replace("__", "_") def is_camel_case_name(input): if '_' in input: return False if input.islower(): return False if input.isupper(): return F
alse return True
ooici/coi-services
ion/processes/event/notification_sent_scanner.py
Python
bsd-2-clause
5,398
0.005372
#!/usr/bin/env python """ @package ion.processes.event @file ion/processes/event/notification_sent_scanner.py @author Brian McKenna <bmckenna@asascience.com> @brief NotificationSentScanner plugin. An EventPersister plugin scanning for, and keeping state(count) of, NotificationEvent's """ import time from datetime imp...
# next_midnight is used to flush the counts (see NOTE in method) self.next_midnight = self._midnight(days=1) self.persist_interval = 300 # interval in seconds to persist/reload counts TODO: use CFG self.time_last_persist = 0 # initalize volatile counts (memory only, should be routinely...
ations can happen >1 depending on len(event_list) for e in event_list: # skip if not a NotificationEvent if e.type_ not in NOTIFICATION_EVENTS: continue user_id = e.user_id notification_id = e.notification_id notification_max = e.notifi...
mapzen/vector-datasource
integration-test/1596-junk-healthcare-values.py
Python
mit
10,521
0
# -*- encoding: utf-8 -*- from . import FixtureTest class HealthcareTest(FixtureTest): def test_blood_donation(self): import dsl z, x, y = (16, 11205, 26166) self.generate_fixtures( # https://www.openstreetmap.org/way/227712531 dsl.way(227712531, dsl.tile_box(z, ...
/', }), ) self.assert_has_feature( z, x, y, 'pois', { 'id': 123526145, 'kind': 'blood_bank',
}) def test_chiropractor(self): import dsl z, x, y = (16, 13686, 25100) self.generate_fixtures( # https://www.openstreetmap.org/node/429672737 dsl.point(429672737, (-104.815915, 38.767464), { 'healthcare': 'chiropractor', ...
apache/allura
Allura/allura/lib/utils.py
Python
apache-2.0
27,100
0.001144
# 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 (t...
t-stream' return content_type class ConfigProxy: '''Wrapper for loading config values at module-scope so we don't have problems when a module is imported b
efore tg.config is initialized ''' def __init__(self, **kw): self._kw = kw def __getattr__(self, k): return self.get(k) def get(self, key, default=None): return tg.config.get(self._kw.get(key, key), default) def get_bool(self, key): return asbool(self.get(key)) ...
cropleyb/pentai
pentai/base/mock.py
Python
mit
16,157
0.006313
# # (c) Dave Kirby 2001 - 2005 # mock@thedeveloperscoach.com # # Original call interceptor and call assertion code by Phil Dawes (pdawes@users.sourceforge.net) # Call interceptor code enhanced by Bruce Cropley (cropleyb@yahoo.com.au) # # This Python module and associated files are released under the FreeBSD # lice...
on. # # 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 PURPOSE ARE # DISCLAIMED. IN
NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON # ...
elandini/CoMPlEx
GUIs/CoMPlEx_hwConfig_Dialog.py
Python
mit
17,425
0.004706
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'GUIs\CoMPlEx_hwConfig_Dialog.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: ...
, QtGui.QFormLayout.FieldRole, self.afmIpLine) self.label_2 = QtGui.QLabel(self.groupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.label_2) self.afmSubPortNum = QtGui.QSpinBox(self.groupBox) self.afm
SubPortNum.setButtonSymbols(QtGui.QAbstractSpinBox.NoButtons) self.afmSubPortNum.setMaximum(100000000) self.afmSubPortNum.setObjectName(_fromUtf8("afmSubPortNum")) self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.afmSubPortNum) self.label_14 = QtGui.QLabel(self.groupBox) ...
Kunal57/MIT_6.00.1x
final/problem7.py
Python
mit
518
0.015444
# Problem 7 # 20.0 points possible (graded)
# Write a function called general_poly. def general_poly(L): """ L, a list of numbers (n0, n1, n2, ... nk) Returns a function, which when applied to a value x, returns the value n0 * x^k +
n1 * x^(k-1) + ... nk * x^0 """ numList = L[::-1] def apply(number): value = 0 for i in range(len(numList)): result = numList[i] * (number ** i) value += result return value return apply L = [1, 2, 3, 4] print(general_poly([1, 2, 3, 4])(10))
pombredanne/swfshield-cli
swfshield/main.py
Python
bsd-3-clause
922
0.002169
import logging import sys from cliff.app import App from cliff.commandmanager import CommandMana
ger class SwfShield(App): log = logging.getLogger(__name__) def __init__(self): super(SwfShield, self).__init__( description='SwfShield CLI', version='0.1', command_manager=CommandManager('swfshield.cli'), ) def initialize_app(self, argv): s...
('clean up') if err: self.log.debug('got an error: {!s}'.format(err)) def main(argv=sys.argv[1:]): app = SwfShield() requests_log = logging.getLogger("requests") requests_log.setLevel(logging.WARNING) return app.run(argv) if __name__ == '__main__': sys.exit(main(sys.argv[1:]...
ljjt/azure-sdk-for-python
tests/test_tableservice.py
Python
apache-2.0
44,444
0.000406
# coding: utf-8 #------------------------------------------------------------------------- # Copyright (c) Microsoft. 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 #...
_create
_default_entity_dict(self, partition, row): ''' Creates a dictionary-based entity with fixed values, using all of the supported data types. ''' return {'PartitionKey': partition, 'RowKey': row, 'age': 39, 'sex': 'male', ...
gencer/sentry
tests/sentry/web/frontend/test_setup_wizard.py
Python
bsd-3-clause
1,341
0
from __future__ import absolute_import from django.core.urlresolvers import reverse from django.core.cache import cache from sentry.testutils import PermissionTestCase from sentry.api.endpoints.setup_wizard import SETUP_WIZARD_CACHE_KEY class SetupWizard(PermissionTestCase): def test_redirect(self): use...
rtTemplateUsed(resp, 'sentry/setup-wizard.html') def test_redirect_to_org(self): self.create_organization(owner=self.user) self.login_as(self.user) url = reverse('sentry-project-wizard-fetch', kwargs={ 'wizard_hash': 'xyz' })
resp = self.client.get(url) assert resp.status_code == 302
nickw444/MediaBrowser
Item.py
Python
mit
106
0
class
Item(object): def __init__(self, path, name): self.path = path
self.name = name
kyleparrott/kubos-sdk
kubos/test/test_licenses.py
Python
apache-2.0
1,774
0.005073
# Kubos SDK # Copyright (C) 2016 Kubos 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 required by applicable law or ...
t kubos import mock import os import sys import unittest from kubos.test.utils import get_arg_list, KubosTestCase class KubosLicenseTest(KubosTestCase): def setUp(self): super(KubosLicenseTest, self).setUp() self.test_command = 'licenses' sys.argv.append(self.test_command) sys.stdo...
l_args_list) self.assertTrue(self.test_command in arg_list) def tearDown(self): super(KubosLicenseTest, self).tearDown() class KubosLicsTest(KubosTestCase): def setUp(self): super(KubosLicsTest, self).setUp() self.test_command = 'lics' sys.argv.append(self.test_comman...
gurkslask/alexistheman
tests/factories.py
Python
bsd-3-clause
612
0.003268
# -*- coding: utf-8 -*- from factory import Sequence, PostGenerationMethodCall from factory.alchemy import SQLAlchemyModelFactory from alexistheman.user.models import User from alexistheman.database import db class BaseFactory(SQLAlchemyModelFactory): cl
ass Meta: abstract = True sqlalchemy_session
= db.session class UserFactory(BaseFactory): username = Sequence(lambda n: "user{0}".format(n)) email = Sequence(lambda n: "user{0}@example.com".format(n)) password = PostGenerationMethodCall('set_password', 'example') active = True class Meta: model = User
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python3.4/unittest/case.py
Python
gpl-2.0
55,456
0.001226
"""Test case imp
lementation""" import sys import functools import difflib import logging import pprint import re import warnings import collections import contextlib import traceback from . import result from .util import (strclass, safe_repr, _count_diff_all_purpose, _count_diff_hashable, _common_shorten_repr) _...
it.') class SkipTest(Exception): """ Raise this exception in a test to skip it. Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly. """ class _ShouldStop(Exception): """ The test should stop. """ class _UnexpectedSuccess(Except...