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
SINGROUP/pycp2k
pycp2k/classes/_diis_info3.py
Python
lgpl-3.0
668
0.002994
from pycp2k.inputsection import InputSection from ._each174 import _each174 class _diis_info3(InputSection): def __init__(self): InputSection.__init__(self) self.Section_parameters = None self.Add_last = None self.Common_iteration_levels = None self.Filename = None ...
ILENAME', 'Add
_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS'} self._subsections = {'EACH': 'EACH'} self._attributes = ['Section_parameters']
sdpp/python-keystoneclient
keystoneclient/tests/unit/v2_0/test_tenants.py
Python
apache-2.0
13,149
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 # d...
ription": "None", "name": "demo", "id": self.DEMO_ID, }, { "enabled": True,
"description": "None", "name": "admin", "id": self.ADMIN_ID, }, { "extravalue01": "metadata01", "enabled": True, "description": "For test...
mbuesch/toprammer
libtoprammer/chips/microchip8/microchip8_18_common.py
Python
gpl-2.0
13,142
0.035915
""" # TOP2049 Open Source programming suite # # Microchip8_18_common - basic file for 8bit PIC18 MCU # # Copyright (c) 2013 Pavel Stemberk <stemberk@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by #...
#print("writing {:x} value to
addr {:x}\n".format(byte2int(image[addr]), addr)) self.setEEPROMAddr(addr) self.executeCode((0x0E00 | (byte2int(image[addr]) & 0xFF), 0x6EA8)) self.executeCode((0x84A6, 0x0E55, 0x6EA7, 0x0EAA, 0x6EA7)) self.executeCode((0x82A6, 0x0, 0x0)) self.top.hostDelay(self.delayP11 + self.delayP10) self.executeC...
WxOutside/software
telemetry/sensors/weatherPiArduino/Adafruit_Python_GPIO/setup.py
Python
unlicense
846
0.035461
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages import sys # D
efine required packages. requires = [] # Assume spidev is required on non-windows & non-mac platforms (i.e. linux). if sys.platform != 'win32' and sys.platform != 'darwin': requires.append('spidev') setup(name = 'Adafruit_GPIO', version = '0.8.0', author = 'Tony DiCola...
one Black using the RPi.GPIO and Adafruit_BBIO libraries.', license = 'MIT', url = 'https://github.com/adafruit/Adafruit_Python_GPIO/', install_requires = requires, packages = find_packages())
scottdaniel/LatentStrainAnalysis
LSA/LSA.py
Python
mit
182
0.049451
class LSA(object): def __init__(self,input_path,output_path): super(LSA,se
lf).__init__() self.input_path = input_path self.output_path = output_path self.hpfx =
'k, bins: ['
040medien/furnaceathome
furnace.py
Python
gpl-2.0
9,961
0.012449
#!/usr/bin/env python import os import uuid import cgi import hashlib import webapp2 as webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp import util from google.appengine.ext import db from google.appengine.api import users import datetime from calendar import timegm import time ...
r'))) home = str(cgi.escape(self.request.get('h'))) outside = str(float(cgi.escape(self.request.get('o')))) mode = str(cgi.escape(self.request.get('m'))) strS = str(cgi.escape(self.request.get('s'))) # secret added since I don't want just anyone to pollute my furnace data ...
= DailyTemperatureEntry.gql( "WHERE date > :1 ORDER BY date DESC", dayAgo) rightNow = str(rightNow) if recent_record.count()!=0: # update entry dayObj = recent_record[0] dayObj.temp_entry = dayObj.temp_entry + \ ...
agoose77/hivesystem
hiveguilib/PGui/PDroneCreator.py
Python
bsd-2-clause
807
0
from __future__ import print_function, absolute_import import weakref class PDroneCreator(object): def __init__(self, mainwindow, clipboard, title="drones"): self._mainwindow =
mainwindow self._clipboard = clipboard self._subwin = mainwindow.newSubWindow(title) from . import PTree self._tree = PTree(self._subwin.wrapwidget(), self._select_drone) self._subwin.setWidget(self._tree.widget()) def _select_drone(self, dronetype): dronetype = "....
plit(".")) self._tree.append(key) def remove(self, dronename): key = tuple(dronename.split(".")) self._tree.remove(key)
Heyn2016/Python
ApalisT30/Pbox/proto/PBoxModbus.py
Python
gpl-3.0
4,314
0.001159
# -*- coding:UTF-8 -*- """ pyBox Modbus""" # !/usr/bin/python # Python: 3.5.2 # Platform: Windows/ARMv7 # Author: Heyn # Program: Modbus RTU & TCP # History: 2017/02/14 V1.0.0 [Heyn] # 2017/03/08 V1.0.1 [Heyn] Send return string. # 2017/04/07 V1.0.2 [Heyn] Redesign PBoxModbus class functions. ...
xcept BaseException as err: print(err) return ret
def readstring(self, readlist, size=1): """ Read String from Device. readlist = [function code, address, data type] """ if self.isopened is False: return None try: ret = pymodbus.read_registers(readlist[0:3], size) except Base...
XKNX/xknx
xknx/__version__.py
Python
mit
48
0
"""XKNX version."""
__version__ = "0.
19.2.dev"
prashanthr/wakatime
wakatime/packages/pygments_py3/pygments/lexers/actionscript.py
Python
bsd-3-clause
11,179
0.004652
# -*- coding: utf-8 -*- """ pygments.lexers.actionscript ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for ActionScript and MXML. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexer import RegexLexer, bygroups, using,...
DOTALL tokens = { 'root': [ (r'\s+', Text), (r'//.*?\n', Comment.Single), (r'/\*.*?\*/', Comment.Multiline
), (r'/(\\\\|\\/|[^/\n])*/[gim]*', String.Regex), (r'[~^*!%&<>|+=:;,/?\\-]+', Operator), (r'[{}\[\]();.]+', Punctuation), (words(( 'case', 'default', 'for', 'each', 'in', 'while', 'do', 'break', 'return', 'continue', 'if', 'else', 'throw', ...
psy0rz/zfs_autobackup
tests/test_zfsnode.py
Python
gpl-3.0
8,088
0.003709
from basetest import * from zfs_autobackup.LogStub import LogStub from zfs_autobackup.ExecuteNode import ExecuteError class TestZfsNode(unittest2.TestCase): def setUp(self): prepare_zpools() # return super().setUp() def test_consistent_snapshot(self): logger = LogStub() descr...
"zfs_autobackup:test", logger=logger, description=description) with self.subTest("test invalid option")
: self.assertFalse(node.valid_command(["zfs", "send", "--invalid-option", "nonexisting"])) with self.subTest("test valid option"): self.assertTrue(node.valid_command(["zfs", "send", "-v", "nonexisting"])) def test_supportedsendoptions(self): logger = LogStub() descri...
wandering007/ProjectEuler
src/103.py
Python
apache-2.0
1,733
0.018465
import time # about 60 s def countBinOnes(x): cnt = 0 while x != 0: cnt += 1 x &= x - 1 return cnt def isSpecialSumSet(A): N = ( 1 << len(A) ) - 1 subset = N * [None] for i in range(1, N): subset[i] = 0 for j in range(len(A)): if (i >> j) & 1 == 1: ...
f subset[i] == subset[j]: # rule i fails return False if subset[i] > subset[j]: if countBinOnes(i) < countBinOnes(j): # rule ii fails
return False elif countBinOnes(i) > countBinOnes(j): # rule ii fails return False return True # for loop is too ugly, recursion is beautiful def findSpecialOptimum(a, pos): if pos > 1: while a[0] + a[1] > a[pos]: if isSpecialSumSet(a[:pos + 1]) =...
nesdis/djongo
tests/django_tests/tests/v22/tests/db_functions/tests.py
Python
agpl-3.0
2,439
0.00082
from django.db.models import CharField, Value as V from django.db.models.functions import Coalesce, Length, Upper from django.test import TestCase from django.test.utils import register_lookup from .models import Author class UpperBilateral(Upper): bilateral = True class FunctionTests(TestCase): def test_...
, ], lambda a: a.name ) def test_func_transform_bilateral(self): with register_lookup(CharField, UpperBilateral): Au
thor.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.filter(name__upper__exact='john smith') self.assertQuerysetEqual( authors.order_by('name'), [ 'John Smith', ], ...
anhstudios/swganh
data/scripts/templates/object/building/poi/shared_tatooine_desert_demons_camp_medium.py
Python
mit
465
0.047312
#### NOTICE: THIS FILE IS AUTO
GENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Building() result.template = "object/building/poi/shared_tatooine_desert_demons_camp_medium.iff" result.attribute_template_id = -1 result.stfN...
Rolinh/pydeo
pydeo/test/functional/errors_controller_test.py
Python
bsd-3-clause
378
0
import unittest from webtest import TestApp import test_helper cl
ass ErrorsControllerTests(unittest.TestCase): def test_error_404(self): app = TestApp(test_helper.get_app()) assert app.get('/error/404').status == '200 OK' def test
_error_500(self): app = TestApp(test_helper.get_app()) assert app.get('/error/500').status == '200 OK'
iwm911/plaso
plaso/__init__.py
Python
apache-2.0
934
0.003212
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2012 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 L...
uted 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. __version__ = '1.1.1' VERSION_DEV = True VERSION_DATE = '20140606' def GetVersi...
rmation for plaso.""" if not VERSION_DEV: return __version__ return u'{}_{}'.format(__version__, VERSION_DATE)
kapucko/django-konfera
payments/tests.py
Python
mit
7,832
0.001404
import datetime import logging from unittest.mock import patch from django.test import TestCase from django.test.utils import override_settings from konfera import models from payments import utils from payments.models import ProcessedTransaction def make_payment(new_data): data = { 'date': datetime.dat...
qual( list(utils._get_payments_for_order(self.order, payments)), [make_payment({'variable_symbol': self.order.variable_symbol})] ) def test_multiple_payments_found_for_order(self): payments = [ make_payment({'variable_symbol': self.order.variable_symbol}), ...
make_payment({'variable_symbol': self.order.variable_symbol}), ] self.assertEqual( list(utils._get_payments_for_order(self.order, payments)), [ make_payment({'variable_symbol': self.order.variable_symbol}), make_payment({'variable_symbol': se...
ddico/odoo
addons/event_crm_sale/__manifest__.py
Python
agpl-3.0
511
0.001957
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file
for full copyright and licensing details. { 'name': 'Event CRM Sale', 'version': '1.0', 'category': 'Marketing/Events', 'website': 'https://www.odoo.com/page/events', 'description': "Add information of sale order linked to the registration for the creation of the lead.", 'depends': ['event_crm'...
a': [ 'views/event_lead_rule_views.xml', ], 'installable': True, 'auto_install': True, }
fedora-infra/pdc-updater
pdcupdater/tests/handler_tests/test_retirement.py
Python
lgpl-2.1
11,525
0.000347
import mock from pdcupdater.tests.handler_tests import BaseHandlerTest, mock_pdc import pdcupdater.services import pdcupdater.handlers.retirement from pdcupdater.handlers.retirement import RetireComponentHandler class TestRetiredComponents(BaseHandlerTest): handler_path = 'pdcupdater.handlers.retirement:RetireCo...
result) def test_cannot_handle_unretire_msg(self): idx = '2017-d20c1ee0-9c00-4ab8-9364-0fdf120e822c' msg = pdcupdater.utils.get_fedmsg(idx) result = self.handler.can_handle(None, msg) self.assertFalse(result) @mock_pdc def test_can_process_retire_msg(self, pdc): pdc...
": 89151, "global_component": "iwhd", "name": "f26", "slas": [ { "id": 178020, "sla": "bug_fixes", "eol": "2222-07-01" }, { ...
carlb15/Python
boggle.py
Python
mit
785
0.049682
dictionary = {"GEEKS", "FOR", "QUIZ", "GO"} N, M = 3, 3 board = [['G','I','Z'], ['U','E','K'], ['Q','S','E']] class Graph: class Vertex: def __int__(self, v): self.val = v self.adj = [] def findWords(board=board): def search(node, word, visited): if node not in visited: visited.appen...
de) word.append(node.val) for adjNode in node.adj: search(node, word, visited) if word not in dictionary: word.pop() result = [] g = creategraph(bo
ard) for u in g.vertices(): visited = [] visited.append(u) word = "" for adj in u.adj: search(adj, word, visited) if word in dictionary: result.append(word) return result if __name__=="__main__": print(findWords())
SimonXming/Lab
backend/app.py
Python
mit
207
0.009662
# -*- encoding:utf-8 -*- fr
om flask import Flask app = Flask(__name__) @app.route('/config') def hello_world(): return '
Hello World!' if __name__ == '__main__': app.run(host="0.0.0.0", port=8080)
mtnman38/Aggregate
aggForFoundation/setup.py
Python
gpl-2.0
311
0
""" This is a setup.py script generated by
py2applet Usage: python setup.py py2app """ from setuptools import setup APP = ['aggregate.py'] DATA_FILES = [] OPTIONS = {'argv_emulation': True} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2
app'], )
rsalmaso/django-cms
menus/exceptions.py
Python
bsd-3-clause
97
0
class NamespaceAl
readyRegistered(Exception): pass class NoParentFound(Excepti
on): pass
neel9102/eo_tools
image_processing/Landsat/reflectance_landsat_8_multiple_release.py
Python
gpl-3.0
13,296
0.019179
#!/usr/bin/python # Landsat 8 TOA reflactance and brightness temparature calculation # Author Riazuddin Kawsar # email: r.kawsar@spatial-business-integration # date: 30th july 2015 # Landsat 8 bands #--------------------------------------------------------- #Band 1 - Coastal aerosol 0.43 - 0.45 30 #Band 2 - Blue ...
e nrow = dataset.RasterYSize band = rasterband.ReadAsArray(0,0,ncol,nrow) band = band.astype(numpy.uint16) return band
,geoTransform,proj,ncol,nrow dataset = None band = None # will return '/media/Arc/eo_archive_proc/VHR_SAT_IMAGE/SPOT6/20140704_SPOT/binned_SPOT6_20140704/B0.binned_SPOT6_20140704.tif' # the function input defined in the beginining: out_put_dir, product just we have to change the product name..... def product...
wanqizhu/mtg-python-engine
test.py
Python
mit
466
0.006438
import cP
rofile import unittest import pstats if __name__ == '__main__': suite = unittest.TestLoader().discover('.') def runtests(): # set verbosity to 2 to see each test unittest.TextTestRunner(verbosity=1, buffer=True).run(suite) cProfile.run( 'runtests()', filename='test_cprofile_resul...
)
imjonsnooow/vivisect
vivisect/analysis/generic/switchcase.py
Python
apache-2.0
5,920
0.010473
''' Analysis plugin for supporting WorkspaceEmulators during analysis pass. Finds and connects Switch Cases, most specifically from Microsoft. ''' import envi import envi.archs.i386 as e_i386 import vivisect import vivisect.analysis.generic.codeblocks as vagc def analyzeJmp(amod, emu, op, starteip): ''' Top ...
rraybase while True: off = vw.readMemValue(ptr+imagebase, 4) ova = imagebase + off tgtva = makeSwitchCase(vw, vajmp, ova) if not tgtva: break tracker.append((count, tgtva)) count += 1 ptr += 4 # FIXME: this doesn't take into ...
st == None: lst = [] naming[va] = lst lst.append("%xh" % idx) #TODO: analyze indiroffbase to determine case information for va, opts in naming.items(): options = "_".join(opts) name = "switch_case_%s_%.8x" % (options, va) vw.makeName(va, name) #...
anandpdoshi/frappe
frappe/utils/data.py
Python
mit
21,230
0.03024
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals # IMPORTANT: only import safe functions as this module will be included in jinja environment import frappe import operator import re, urllib, datetime, math import babel.dates fr...
me_str or "").startswith("0000-00-00"): return None return parser.parse(datetime_str) def to_timedelta(time_str): if isinstance(time_str, basestring): t = parser.parse(time_str) retu
rn datetime.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond) else: return time_str def add_to_date(date, years=0, months=0, days=0): """Adds `days` to the given date""" from dateutil.relativedelta import relativedelta as_string, as_datetime = False, False if date==None: ...
hansroh/skitai
tests/level4/test_late_respond.py
Python
mit
675
0.020741
import pytest import os def test_launch (launch): serve = '../../atila/example/serve.py' if not os.path.isfile (serve): return wit
h launch (serve) as engine: for i in range (2): resp = engine.axios.get ('/apis/rest-api{}'.format (i == 1 and 2 or '')) assert resp.st
atus_code == 200 assert 'result' in resp.data assert 'info' in resp.data ['result'] for i in range (2): resp = engine.axios.get ('/apis/rest-api{}'.format (i == 1 and 2 or '')) assert resp.status_code == 200 assert 'result' in resp.data as...
lmacken/moksha
moksha/config/environment.py
Python
apache-2.0
779
0.002567
# This file is part of Moksha. # Copyright (C) 2008-2010 Red Hat, 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 ...
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.
from moksha.config.app_cfg import base_config #Use base_config to setup the environment loader function load_environment = base_config.make_load_environment()
fuzzy-id/midas
midas/scripts/fetch_crunchbase_companies.py
Python
bsd-3-clause
2,306
0.001301
# -*- coding: utf-8 -*- import logging import threading from midas.compat import HTTPError from midas.compat import Queue from midas.crunchbase_company import CompanyList import midas.scripts class FetchCrunchbaseCompanies(midas.scripts.MDCommand): """ Crawl the companies information from crunchbase.com an...
al('{0}: Got 404'.format(self.inst)) elif tries < 2 and (e.code == 503 or e.code == 504): logging.critical( '{0}: Got 504 ({1} attempt[s])'.format(self.inst, tries + 1) ) self.make_update(tries + 1) el
se: logging.exception(e) except Exception as e: logging.critical( '{0}: An exception occured'.format(self.inst)) logging.exception(e)
anhstudios/swganh
data/scripts/templates/object/mobile/shared_dressed_weaponsmith_trainer_02.py
Python
mit
455
0.046154
#### NOTICE: THIS FILE IS
AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_weaponsmith_trainer_02.iff" result.attribute_template_id = 9 result.stfName("np...
## #### END MODIFICATIONS #### return result
Stanford-Online/edx-ora2
openassessment/workflow/test/test_api.py
Python
agpl-3.0
21,103
0.002275
import ddt from mock import patch from nose.tools import raises from django.db import DatabaseError from django.test.utils import override_settings from openassessment.assessment.models import PeerWorkflow, StudentTrainingWorkflow from openassessment.test_utils import CacheResetTest import openassessment.workflow.api...
the wrong type with self.assertRaises(workflow_api.AssessmentWorkflowRequestError): _ = workflow_api.create_workflow(123, data["steps"])
@patch('submissions.models.Submission.objects.get') @ddt.file_data('data/assessments.json') @raises(workflow_api.AssessmentWorkflowInternalError) def test_unexpected_submissions_errors_wrapped(self, data, mock_get): mock_get.side_effect = Exception("Kaboom!") workflow_api.create_workflow("zz...
KGPML/Hyperspectral
patch_size.py
Python
gpl-3.0
14
0.071429
patch_siz
e =
1
Mansilla1/Sistema-SEC
apps/evaluacion/urls.py
Python
apache-2.0
2,293
0.024422
from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from .views import * urlpatterns = [ # Listado url(r'^evaluacion-lista/', login_required(evaluacion_list), name='listar_evaluacion'), # Evaluacion paso a paso url(r'^generar/step1/$', login_required(evaluacion_ste...
e='evaluacion_step2'), url(r'^generar/step3/(?P<evaluacion_id>\d+)/$', login_required(evaluacion_step3), name='evaluacion_step3'), url(r'^generar/step4/(
?P<evaluacion_id>\d+)/$', login_required(evaluacion_step4), name='evaluacion_step4'), # Evaluacion automatica url(r'^automatica/step1/$', login_required(evaluacion_rapida_step1), name='evaluacion_rapida_step1'), url(r'^automatica/step2/(?P<evaluacion_id>\d+)/$', login_required(evaluacion_rapida_step2), name='evalua...
bbockelm/root
tutorials/dataframe/tdf006_ranges.py
Python
lgpl-2.1
2,283
0.004818
## \file ## \ingroup tutorial_tdataframe ## \notebook -nodraw ## This tutorial shows how to express the concept of ranges when working with the TDataFrame. ## \macro_code ## ## \date March 2017 ## \author Danilo Piparo import ROOT fill_tree_code = ''' void fill_tree(const char *filename, const char *treeName) { TF...
= b1 % 2").Count() # An important thing to notice is that the counts of a filter are relative to the # number of entries a filter "sees". Therefore, if a Range depends on a filter, # the Range will act on the entries passing the filter only. c_0_3_after_even_b1 = d.Filter("0 == b1 % 2").Range(0, 3).Count() # Ok, time...
print all counts! print("Usage of ranges:") print(" - All entries:", c_all.GetValue()) print(" - Entries from 0 to 30:", c_0_30.GetValue()) print(" - Entries from 15 onwards:", c_15_end.GetValue()) print(" - Entries from 15 onwards in steps of 3:", c_15_end_3.GetValue()) print(" - Entries from 0 to 50, odd only:", c_0_...
LethusTI/supportcenter
vendor/django/tests/regressiontests/signals_regress/tests.py
Python
gpl-3.0
3,724
0.003222
from __future__ import absolute_import from django.db import models from django.test import TestCase from .models import Author, Book signal_output = [] def pre_save_test(signal, sender, instance, **kwargs): signal_output.append('pre_save signal, %s' % instance) if kwargs.get('raw'): signal_output....
signal_output.append('Is raw') def pre_delete_test(signal, sender, instance, **kwargs): signal_output.append('pre_save signal, %s' % instance) signal_output.append('instance.id is not None: %s' % (instance.id != None)) def pos
t_delete_test(signal, sender, instance, **kwargs): signal_output.append('post_delete signal, %s' % instance) signal_output.append('instance.id is not None: %s' % (instance.id != None)) class SignalsRegressTests(TestCase): """ Testing signals before/after saving and deleting. """ def get_signal...
Conan-Kudo/bodhi
bodhi/tests/server/consumers/test_automatic_updates.py
Python
gpl-2.0
18,330
0.00131
# Copyright © 2019 Red Hat, Inc. # # This file is part of Bodhi. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # T...
og.records) @pytest.mark.parametrize('change
log', (True, None, "")) @mock.patch('bodhi.server.models.RpmBuild.get_changelog') def test_changelog(self, mock_generate_changelog, changelog): """Assert that update notes contain the changelog if it exists.""" if changelog: # fill the changelog here rather than in the decorator ...
qrohlf/cf-client
lib/cfclient/utils/mux/__init__.py
Python
gpl-2.0
7,589
0.00448
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
if not, write to the Free Software #
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """ """ __author__ = 'Bitcraze AB' __all__ = ['InputMux'] import os import glob import logging from cflib.utils.callbacks import Caller logger = logging.getLogger(__name__) MAX_THRUST = 65000 class InputMux(object): def __ini...
p/webracer
webracer/testcase.py
Python
bsd-2-clause
4,545
0.007261
import types import funct
ools import unittest from .agent import Config, Agent # XXX bring into compliance with python 2.7 unittest api class AssertRaisesContextManager(object): def __init__(self, expected): self.expected = expected def __enter__(self): return self def __exit__(self, type, value, tracebac...
raise AssertionError('%s expected, not `%s`' % (self.expected.__class__, str(value))) self.exception = value # silence exception return True class WebTestCase(unittest.TestCase): def __init__(self, *args, **kwargs): super(WebTestCase, self).__init__(*args, **kwargs) # ...
iastro-pt/ObservationTools
docs/source/conf.py
Python
mit
5,035
0.001192
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ObservationTools documentation build configuration file, created by # sphinx-quickstart on Sun Apr 30 14:32:48 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in ...
tart file, name, description, authors, manual section). man_pages = [ (master_doc, 'observationtools', 'ObservationTools Documentation', [a
uthor], 1) ] # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'ObservationTools', 'ObservationT...
hirolovesbeer/sekiwake
src/setup.py
Python
mit
223
0.017937
from distutils.core import setup from di
stutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("capture", ["capture.pyx"])]
)
PegasusWang/WeiPython
wechat/wechatService.py
Python
mit
4,478
0.001638
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import ...
频消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LOCATION: respContent = u'您发送的是地理位置消息!'
elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK: respContent = u'您发送的是链接消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT: eventType = requestMap.get(u'Event') if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE: respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(...
4Kaylum/Steamfront
steamfront/userapp.py
Python
mit
1,396
0.006447
from .app import App as _App class UserApp(_App): ''' An object based on the relationship between a user and an app. A subclass of :class:`steamfront.app.App`. This will not contain any of the attributes for :class:`steamfront.app.App` until :meth unlazify: has been called. Should not be called manua...
(appdata['appid']) self.play_time = appdata['playtime_forever'] self.player_id = user.id64 self.player = user if lazy == False: super().__init__(self.appid) self.lazy = lazy def unlazify(self): ''' To get all of the app attributes of an app, this...
laurent-george/weboob
modules/cic/browser.py
Python
agpl-3.0
8,378
0.003703
# -*- coding: utf-8 -*- # Copyright(C) 2010-2011 Julien Veyssier # # 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 yo...
content = unicode(self.response().get_data(), self.ENCODING) insufficient_amount_message = u'Montant insuffisant.' maximum_allowed_balance_message = u'Solde maximum autorisé dépassé.' if content.find(insufficient_amount_message) != -1: raise TransferError('The amount yo...
d to transfer is too low.') if content.find(maximum_allowed_balance_message) != -1: raise TransferError('The maximum allowed balance for the target account has been / would be reached.') # look for the known "all right" message ready_for_transfer_message = u'Confirmez un virement e...
huaxz1986/git_book
chapters/Cluster_EM/cluster.py
Python
gpl-3.0
3,182
0.021348
# -*- coding: utf-8 -*- """ 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs # from .agglomerative_clustering impor...
mponents # from .kmeans import test_Kmeans,test_Kmeans_n_init,test_Kmeans_nclusters def create_data(centers,num=100,std=0.7): ''' 生成用于聚类的数据集 :param centers: 聚类的中心点组成的数组。如果中心点是二维的,则产生的每个样本都是二维的。 :param num: 样本数 :param std: 每个簇中样本的标准差 :return: 用于聚类的数据集。是一个元组,第一个元素为样本集,第二个元素为样本集的真实簇分类标记 ''' ...
一个元组。元组元素依次为:第一个元素为样本集,第二个元素为样本集的真实簇分类标记 :return: None ''' X,labels_true=data labels=np.unique(labels_true) fig=plt.figure() ax=fig.add_subplot(1,1,1) colors='rgbyckm' # 每个簇的样本标记不同的颜色 for i,label in enumerate(labels): position=labels_true==label ax.scatter(X[position,0],X...
CSCI1200Course/csci1200OnlineCourse
modules/dashboard/utils.py
Python
apache-2.0
2,730
0
# Copyright 2014 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 ...
rd/resources' RESOURCES_DIR = os.path.join(appengine_config.BUNDLE_ROOT, RESOURCES_PATH.lstrip('/')) def build_assets_url(tab_name): return '/dashboard?action=assets&tab=%s' % tab_name def list_files(handler, subfolder, merge_local_files=False, all_paths=None): """Makes a list o...
ist. merge_local_files: boolean. If True, the returned list will contain files found on either the datastore filesystem or the read-only local filesystem. If a file is found on both, its datastore filesystem version will trump its local filesystem version. ...
Onirik79/aaritmud
src/socials/social_blblbl.py
Python
gpl-2.0
97
0.010309
# -*- coding: utf-8 -*- def soci
al_blblbl(entity, argument): return True #- Fine F
unzione -
domenicosolazzo/practice-django
venv/lib/python2.7/site-packages/django/db/migrations/questioner.py
Python
mit
6,265
0.001915
from __future__ import unicode_literals import importlib import os import sys from django.apps import apps from django.utils import datetime_safe, six from django.utils.six.moves import input from .loader import MIGRATIONS_MODULE_NAME class MigrationQuestioner(object): """ Gives the autodetector responses ...
n None def ask_rename(self, model_name, old_name, new_name, field_instance): "Was this field
really renamed?" return self.defaults.get("ask_rename", False) def ask_rename_model(self, old_model_state, new_model_state): "Was this model really renamed?" return self.defaults.get("ask_rename_model", False) def ask_merge(self, app_label): "Do you really want to merge these m...
scorphus/scrapy
tests/test_settings/default_settings.py
Python
bsd-3-clause
27
0
TEST_D
EFAULT = 'defvalue'
box/box-python-sdk
boxsdk/object/terms_of_service.py
Python
apache-2.0
3,849
0.002078
import json from typing import TYPE_CHECKING, Optional from boxsdk.util.text_enum import TextEnum from boxsdk.exception import BoxAPIException from .base_object import BaseObject if TYPE_CHECKING: from boxsdk.object.user import User from boxsdk.object.terms_of_service_user_status import TermsOfServiceUserStat...
> 'TermsOfServiceUserStatus': """ Create a terms of service user status. :param is_accepted: Indicates whether a use has accepted or rejected a terms of service. :param user: The :class:`User` to assign the terms of service to. :returns: A new...
'tos': { 'type': self.object_type, 'id': self.object_id, }, 'is_accepted': is_accepted, } if user is not None: body['user'] = { 'type': user.object_type, 'id': user.object_id, } ...
Perkville/django-tastypie
docs/code/myproject/wsgi.py
Python
bsd-3-clause
409
0.002445
""" WSGI config for myp
roject project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") from django.core.wsgi import get_wsgi...
noqa application = get_wsgi_application()
ojii/readthedocs.org
readthedocs/core/models.py
Python
mit
1,768
0.002828
from django.db import models from django.db.models.signals import post_save from django.db.utils import DatabaseError from django.dispatch import receiver from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _, ugettext STANDARD_EMAIL = "anonymous@readthedocs.org" class Us...
= models.permalink(get_absolute_url) def get_contribution_details(self): """ Gets the line to put into commits to attribute the author. Returns a tuple (name, email) """ if self.user.first_name and self.user.last_name: name = '%
s %s' % (self.user.first_name, self.user.last_name) else: name = self.user.username if self.allow_email: email = self.user.email else: email = STANDARD_EMAIL return (name, email) @receiver(post_save, sender=User) def create_profile(sender, **kwargs):...
kvesteri/postgresql-audit
tests/test_sql_files.py
Python
bsd-2-clause
1,919
0
# -*- coding: utf-8 -*- import pytest from .util
s import last_activity @pytest.mark.usefixtures('versioning_manager', 'table_creator') class TestActivityCreationWithColumnExclusion(object): @pytest.fixture def audit_trigger_creator(self, session, user_class): session.execute( '''SELECT audit_table('{0}', '{{"age"}}')'''.format( ...
user = user_class(name='John', age=15) session.add(user) session.flush() return user def test_insert(self, user, connection): activity = last_activity(connection) assert activity['old_data'] == {} assert activity['changed_data'] == { 'id': user.id, ...
xyuanmu/XX-Net
python3.8.2/Lib/http/server.py
Python
bsd-2-clause
47,254
0.000614
"""HTTP server classes. Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST, and CGIHTTPRequestHandler for CGI scripts. It does, however, optionally implement HTTP/1.1 persistent connections, as of version 0.3. Notes on CGIHTT...
ST, <path> is a string containing path information for the request, and <version> should be the string "HTTP/1.0" or "HTTP/1.1". <path> is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx). The specification specifies that lines are separated by CRLF ...
llowing multiple spaces between components and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine. If the first line of the request has the form <command> <path> (i.e. <version> is left out) then this ...
KoreaCloudObjectStorage/swift3
swift3/subresource.py
Python
apache-2.0
16,885
0
# Copyright (c) 2014 OpenStack Foundation. # # 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...
com/AmazonS3/latest/dev/acl-overview.html """ def encode_acl(resource, acl): """ Encode an ACL instance to Swift metadata. Given a resource type and an ACL instance, this method returns HTTP headers, which can be used for Swift metadata. """ header_value = {"Owner": acl.owner.id} grants ...
or grant in acl.grants: grant = {"Permission": grant.permission, "Grantee": str(grant.grantee)} grants.append(grant) header_value.update({"Grant": grants}) headers = {} key = sysmeta_header(resource, 'acl') headers[key] = json.dumps(header_value, separators=(',', ':')) ...
PatrickSpieker/pricesleuth
tests/TestElsevierScraper.py
Python
mit
321
0
import unittest from scrape
rs.journalscrapers import ElsevierScraper class TestElsevierScraper(unittest.TestCase): def setUp(self): self.instance = ElsevierScraper("../data/elsevier/2016-uncleaned.csv") def test_strip_chars(self): for row in self.instance.get_entries(
): print row
greenoaktree/measurement_toolbox
gr-mtb/python/qa_task_frontend.py
Python
gpl-3.0
2,935
0.008862
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Marcus Müller. # # This is free software; you ca
n redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at
your option) # any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of ...
laurey/py
py/iterating.dic.py
Python
gpl-2.0
103
0.029126
# ITERATING DIC
TIONARY d = {'x':1, 'y':2, 'z':3} for key in d: print key, 'corresponds to
', d[key]
osgcc/ryzom
nel/tools/build_gamedata/processes/rbank/0_setup.py
Python
agpl-3.0
2,998
0.004336
#!/usr/bin/python # # \file 0_setup.py # \brief Setup rbank # \date 2009-03-10-22-43-GMT # \author Jan Boon (Kaetemi) # Python port of game data build pipeline. # Setup rbank # # NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> # Copyright (C) 2010 Winch Gate Property Limited # # This program is free soft...
rectory + "/" + ZoneWeldBuildDirectory) for dir in IgLookupDirectories: mkPath(log, ExportBuildDirectory + "/" + dir) for dir in ShapeLookupDirectories: mkPath(log, ExportBuildDirectory + "/" + dir) mkPath(log, ExportBuildDirectory + "/" + RbankBboxBuildDirectory) mkPath(log, ExportBuildDirectory + "/" + IgLandBuildD...
ory + "/" + RbankSmoothBuildDirectory) mkPath(log, ExportBuildDirectory + "/" + RbankRawBuildDirectory) mkPath(log, ExportBuildDirectory + "/" + RbankPreprocBuildDirectory) mkPath(log, ExportBuildDirectory + "/" + RbankRetrieversBuildDirectory) mkPath(log, ExportBuildDirectory + "/" + RbankOutputBuildDirectory) # Setu...
irenalanc/JupyterPythonPals
jupyter_workflow/tests/test_data.py
Python
mit
234
0.021368
from jupyter_workflow.data import get_fremont_data import pandas as pd def test_frem
ont_data(): data = get_fremont_data() assert all(data.columns == [
'West','East','Total']) assert isinstance(data.index,pd.DatetimeIndex)
christi3k/zulip
analytics/migrations/0010_clear_messages_sent_values.py
Python
apache-2.0
1,174
0.001704
# -*- coding: utf-8 -*- from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps from django.db import migrations def clear_message_sent_by_message_type_values(apps, schema_editor): # type: (StateApps, DatabaseSchemaEditor) -> None UserCoun...
sages_sent:message_type:day' UserCount.objects.filter(property=property).delete() StreamCount.objects.filter(property=property).delete() RealmCount.objects.filter(property=property).delete() InstallationCount.objects.filter(property=property).delete() FillState.objects.filter(property=property).dele...
es = [('analytics', '0009_remove_messages_to_stream_stat')] operations = [ migrations.RunPython(clear_message_sent_by_message_type_values), ]
stephanie-wang/ray
streaming/python/config.py
Python
apache-2.0
859
0
class Config: STREAMING_JOB_NAME = "streaming.job.name" STREAMING_OP_NAME = "streaming.op_name" T
ASK_JOB_ID = "streaming.task_job_id" STREAMING_WORKER_NAME = "streaming.worker_name" # channel CHANNEL_TYPE = "channel_type" MEMORY_CHANNEL = "memory_channel" NATIVE_CHANNEL = "native_channel" CHANNEL_SIZE = "channel_size" CHANNEL_SIZE_DEFAULT = 10**8
IS_RECREATE = "streaming.is_recreate" # return from StreamingReader.getBundle if only empty message read in this # interval. TIMER_INTERVAL_MS = "timer_interval_ms" STREAMING_RING_BUFFER_CAPACITY = "streaming.ring_buffer_capacity" # write an empty message if there is no data to be written in this ...
chadspratt/AveryDB
gui.py
Python
apache-2.0
16,903
0.000592
# """All things dealing strictly with the GUI.""" ## # Copyright 2013 Chad Spratt # 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 # ...
.' action = gtk.FILE_CHOOSER_ACTION_OPEN dialog = gtk.FileChooserDialog(title, None, action, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) for filetype in filetypes: filefilter = gtk.FileFilter() filefilter.set_name(filetype) for mimetype in filetypes[filetype
jvilaplana/PiMotionGallery
pmg.py
Python
gpl-3.0
8,027
0.007849
#!/usr/bin/env python import logging # http://docs.python.org/2/howto/logging.html#logging-basic-tutorial import pysftp # https://code.google.com/p/pysftp/ from configobj import ConfigObj # http://www.voidspace.org.uk/python/configobj.html import os import sys import time import curses import Image import ImageTk impo...
)") print tmp_host print tmp_user print tmp_base print tmp_port if(self.checkConnection()): print "Successfully connected to the remote host." else: keep = '' while (keep != 'y') and (kee...
er() or 'n' if(keep == 'no'): keep = 'n' elif(keep == 'yes'): keep = 'y' if(keep == 'n'): self.askParameters() self...
arrivance/gyazo-to-imgur
src/utility.py
Python
mit
3,148
0.014295
import praw import urllib.request import json import requests import requests.auth import os.path import re from imgurpython import ImgurClient from bs4 import BeautifulSoup imgur_gif_regex = re.compile("https?:\/\/i\.imgur\.com\/[a-z0-9]+.gif") def gyazo_link_parser(link): """ Parses Gyazo links into their ...
her unknown fault.") else: print("Successfully commented on comment ID", comment.id) def file_checker(filename): if os.path.isfile(filename) == True: return True else: return False def file_maker(filename, structure): with open(filename, "w") as data_file: json.dump(structure, filename) return...
ient_secret"]) post_data = {"grant_type": "password", "username": login_details["reddit_user"], "password": login_details["reddit_pass"]} headers = {"User-Agent": user_agent} print("Attempting to get the access_token from reddit...") response = requests.post("https://www.reddit.com/api/v1/access_token",...
cavestruz/L500analysis
derived_fields/collections/temperature/derived_field_functions.py
Python
mit
5,126
0.013461
from L500analysis.derived_fields.derived_fields import * from L500analysis.derived_fields.derived_field_functions import * from L500analysis.derived_fields.collections.peak_height.derived_field_functions \ import * from L500analysis.derived_fields.derived_field_tools.non_thermal_temperature \ import calculate_T...
gr'][hid],vr=d['vr'][hid], sigt=d['sigt'][hid],vt=d['vt'][hid],
Tmw=d['T_mw'][hid]) T_tot_normalized[hid] = Ttot/Tdelta T_tot_normalized[hid] = make_profile(x=d['Rscaled'][hid], y=T_tot_normalized[hid]) return T_tot_normalized def calculate_total_temperature_profile(input_data) : d = inpu...
sjsrey/pysal_core
pysal_core/io/IOHandlers/dat.py
Python
bsd-3-clause
3,059
0.000327
import os.path import gwt from ...weights import W from warnings import warn __author__ = "Myunghwa Hwang <mhwang4@gmail.com>" __all__ = ["DatIO"] class DatIO(gwt.GwtIO): """ Opens, reads, and writes file objects in DAT format. Spatial weights objects in DAT format are used in Dr. LeSage's MatLab Ec...
>>> w[1] {2.0: 0.3333, 5.0: 0.3333, 6.0: 0.3333} """ if self.pos > 0: raise StopIteration id_type = float weights, neighbors = self._readlines(id_type) self.pos += 1 return W(neighbors, weights) def write(self, obj): """ ...
accepts a weights object Returns ------ a DAT file write a weights object to the opened DAT file. Examples -------- >>> import tempfile, pysal, os >>> testfile = pysal.open(pysal.examples.get_path('wmat.dat'),'r') >>> w = testfile.read() ...
faylau/oVirt3.3WebAPITest
src/TestData/Template/ITC070202_GetTemplateDiskInfo.py
Python
apache-2.0
1,439
0.004892
#encoding:utf-8 __authors__ = ['"Wei Keke" <keke.wei@cs2c.com.cn>'] __version__ = "V0.1" ''' # ChangeLog: #--------------------------------------------------------------------------------- # Version Date Desc Author #----------------------------------------------------...
temp_info=''' <template> <name>%s</name> <vm id="%s"/> </template> ''' % (temp_name, vm_id) '''--------------------------------------------------------------------------------------------------- @note: ExpectedData -----------------------
----------------------------------------------------------------------------''' expected_status_code = 200
onshape-public/onshape-clients
python/onshape_client/oas/models/callback.py
Python
mit
4,774
0
# coding: utf-8 """ Onshape REST API The Onshape REST API consumed by all clients. # noqa: E501 The version of the OpenAPI document: 1.113 Contact: api-support@onshape.zendesk.com Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import re # noqa: F401 im...
openapi_types (dict): The key is attribute name and the value is attribute type. """ return { "empty": (bool,), # noqa: E501 "extensions": ( {str: (bool, date, datetime, dict, float, int, list, str,)}, ), # noqa: E501 ...
# noqa: E501 } @staticmethod def discriminator(): return None attribute_map = { "empty": "empty", # noqa: E501 "extensions": "extensions", # noqa: E501 "getref": "get$ref", # noqa: E501 } @staticmethod def _composed_schemas(): return None ...
infinnovation/micropython
tests/run-tests-exp.py
Python
mit
2,697
0.002225
# # This is minimal MicroPython variant of run-tests script, which uses # .exp files as generated by run-tests --write-exp. It is useful to run # testsuite on systems which have neither CPython3 nor unix shell. # This script is intended to be run by the same interpreter executable # which is to be tested, so should use...
icode", "extmod", "unix" ] if sys.platform == 'win32': MICROPYTHON = "micropython.exe" else: MICROPYTHON = "micropython" def should_skip(test): if test.startswith("native"): return True if test.startswith("viper"): return True test_count = 0 passed_count = 0 skip_count = 0 for suite...
# dir /b prints only contained filenames, one on a line # http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/dir.mspx r = os.system("dir /b %s/*.py >tests.lst" % suite) else: r = os.system("ls %s/*.py | xargs -n1 basename >tests.lst" % suite) assert r =...
sschultz/FHSU-GSCI-Weather
Weather/admin.py
Python
mit
524
0.003817
from django.contrib import admin from Weather.models impo
rt * from Weather.util import updateForecast def update_forecast(modeladmin, request, queryset): for forecast in queryset:
updateForecast(forecast) update_forecast.short_description = "Force forecast update from NWS" class forecastAdmin(admin.ModelAdmin): actions = [update_forecast] class WMSRadarOverlayAdmin(admin.ModelAdmin): pass admin.site.register(Forecast, forecastAdmin) admin.site.register(WMSRadarOverlay, WMSRadarOv...
stianrh/askbot-nordic
askbot/conf/badges.py
Python
gpl-3.0
5,005
0.002198
""" Settings for reputation changes that apply to user in response to various actions by the same users or others """ from askbot.conf.settings_wrapper import settings from askbot.conf.super_groups import REP_AND_BADGES from askbot.deps.livesettings import ConfigurationGroup, IntegerValue from django.utils.translation...
'NECROMANCER_BADGE_MIN_UPVOTES', default=3, description=_('Necromancer: minimum upvotes') ) ) settings.register( IntegerValue( BADGES, 'NECROMANCER_BADGE_MIN_DELAY', default=30, description=_('Necromancer: minimum delay in days') ) ) settings.regist...
ption=_('Associate Editor: minimum number of edits') ) ) settings.register( IntegerValue( BADGES, 'FAVORITE_QUESTION_BADGE_MIN_STARS', default=5, description=_('Favorite Question: minimum stars') ) ) settings.register( IntegerValue( BADGES, 'STELLAR_QUES...
KEMPtechnologies/python-kemptech-api
examples/real_server_pooling.py
Python
apache-2.0
4,377
0.000914
from python_kemptech_api import * # Specify the LoadMaster connection credentials here: loadmaster_ip = "" username = "" password = "" vs_ip_1 = "" vs_ip_2 = "" rs_ip_1 = "" rs_ip_2 = "" vs_port = "" rs_port = "" class RealServerPool(object): healthcheck_parameters = [ "checktype", "checkport", ...
ther settings new_rs.save() for attr in self.rs_parameters: print("attr: {}".format(attr)) if hasattr(rs, attr) and rs.__getattribute__(attr) is not None: print("set attr: {}={}".format(attr, rs.__getattribute__(attr))
) new_rs.__setattr__(attr, rs.__getattribute__(attr)) new_rs.update() for attr in self.healthcheck_parameters: print("attr: {}".format(attr)) if hasattr(self, attr) and self.__getattribute__(attr) is not None: print("set attr: {}={}".form...
atodorov/anaconda
tests/nosetests/pyanaconda_tests/module_disk_select_test.py
Python
gpl-2.0
5,967
0.00067
# # Copyright (C) 2019 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
geError): self.disk_selection_interface.GetUsableDisks()
self.disk_selection_module.on_storage_changed(create_storage()) self.assertEqual(self.disk_selection_interface.GetUsableDisks(), [])
giacomov/pyggop
pyggop/config/Configuration.py
Python
mit
2,359
0.038152
import json import os #This helper class allows to access members of the configuration #as c.attr1.attr2.attr3 instead of c[attr1][attr2][attr3] class DictToAttr( object ): def __init__( self, dictionary ): self.dict = dict( dictionary ) def __getattr__(self, attr): ...
if isinstance( token, dict ): return DictToAttr( token )
else: return token else: raise ValueError("'%s' does not exists in configuration" %(attr)) class Configuration( object ): def __init__(self): #Read configuration file ...
j0ju/iot-carbon-esp
modules/iotesp.py
Python
gpl-2.0
651
0.006144
# LICENSE: GPLv2, see attached License # Author: Joerg Jungermann def get_mac(): from network import WLAN from ubinascii import hexlify return hexlify(WLAN().config('mac'),'-').decode() def s
leep(sec, deepsleep = False): import time
if deepsleep: import machine rtc = machine.RTC() rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP) rtc.alarm(rtc.ALARM0, sec * 1000) print('iotesp.sleep():', sec, 's / DEEPSLEEP') machine.deepsleep() time.sleep_us(100) else: # print('sleep:', sec...
garrettcap/Bulletproof-Backup
wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/nsistags.py
Python
gpl-2.0
3,752
0.001866
############################################################################### # Name: nsistags.py # # Purpose: Generate Tags for Nullsoft Installer Scripts # # Author: Cody Precord <cprecord@editra.org> # ...
d parts[1][0] not in ['"', "'", "`"]: rtags.AddElement('section', taglib.Section(parts[1], lnum)) else:
for idx, part in enumerate(parts[1:]): if parts[idx][-1] in ['"', "'", "`"]: rtags.AddElement('section', taglib.Section(part, lnum)) break elif parselib.IsToken(line, 0, u'!macro'): parts = line.split() if le...
archlinux/archweb
packages/utils.py
Python
gpl-2.0
16,261
0.000553
from collections import defaultdict from itertools import chain from operator import itemgetter import re from django.core.serializers.json import DjangoJSONEncoder from django.db import connection from django.db.models import Count, Max, F from django.db.models.query import QuerySet from django.contrib.auth.models im...
WHEN ml.pkgname LIKE %s THEN SUBSTR(ml.pkgname, 1, LENGTH(ml.pk
gname) - 9) ELSE ml.pkgname END """ else: pkgname_sql = """ CASE WHEN ml.pkgname LIKE %s THEN SUBSTRING(ml.pkgname, 7) WHEN ml.pkgname LIKE %s THEN SUBSTRING(ml.pkgname FROM 1 FOR CHAR_LENGTH(ml.pkgname) ...
asciimoo/searx
searx/answerers/statistics/answerer.py
Python
agpl-3.0
1,243
0.001609
from sys import version_info from functools import reduce from operator import mul from flask_babel import gettext if version_info[0] == 3: unicode = str keywords = ('min', 'max', 'avg', 'sum', 'prod') # required answerer function # can return a list of results (...
= None if func == b'min': answer = min(args) elif func == b'max': answer = max(args) elif func == b'avg': answer = sum(args) / len(args) elif func == b'sum': answer = sum(args) elif func == b'prod': answer = reduce(mul, args, 1) if answer is None:
return [] return [{'answer': unicode(answer)}] # required answerer function # returns information about the answerer def self_info(): return {'name': gettext('Statistics functions'), 'description': gettext('Compute {functions} of the arguments').format(functions='/'.join(keywords)), ...
rainaashutosh/MyTestRekall
rekall-core/rekall/plugins/windows/gui/windowstations.py
Python
gpl-2.0
5,615
0.000534
# Rekall Memory Forensics # Copyright (C) 2007,2008 Volatile Systems # Copyright (C) 2010,2011,2012 Michael Hale Ligh <michael.ligh@mnin.org> # Copyright 2013 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 ...
, Base: {2:addr}, " "Limit: {3:addr}\n",
desktop.pheapDesktop.v(), (desktop.DeskInfo.pvDesktopLimit.v() - desktop.DeskInfo.pvDesktopBase.v()), desktop.DeskInfo.pvDesktopBase, desktop.DeskInfo.pvDesktopLimit, ...
Eric89GXL/mne-python
mne/connectivity/envelope.py
Python
bsd-3-clause
6,631
0
# Authors: Eric Larson <larson.eric.d@gmail.com> # Sheraz Khan <sheraz@khansheraz.com> # Denis Engemann <denis.engemann@gmail.com> # # License: BSD (3-clause) import numpy as np from ..filter import next_fast_len from ..source_estimate import _BaseSourceEstimate from ..utils import verbose, _check_c...
= 0] = 1 # correlation is dot product divided by variances corr[li] = np.sum(label_data_o
rth * data_mag_nomean, axis=1) corr[li] /= data_mag_std corr[li] /= label_data_orth_std if orthogonalize is not False: # Make it symmetric (it isn't at this point) if absolute: corr = np.abs(corr) corr = (corr.T + corr) / 2. cor...
TheGentlemanOctopus/thegentlemanoctopus
octopus_code/core/octopus/patterns/eqPattern.py
Python
gpl-3.0
2,854
0.004905
from pattern import Pattern import itertools import random import colorsys import time class EqPattern(Pattern): def __init__(self, meter_color=(255,100,50), background_color=(0,50,255)): self.meter_r = meter_color[0] self.meter_g = meter_color[1] self.meter_b = meter_color[2] self...
level = next(eq) for led_strip in tentacle.led_strips: pixel_colors = [] n_meter_pixels = int(len(led_strip.pixels)*float(level)) pixel_colors.extend([meter_color for x in range(n_meter_pixels)]) n_background_pixels = len(led_strip...
led_strip.put_pixels(pixel_colors)
AlexandroPQC/sara-ani
Saranani/apps/users/pipelines.py
Python
gpl-3.0
270
0.007407
def get_avatar(backend, strategy, details, response, user=None, *args, **kwargs): url = None if backend
.name == 'facebook'
: url = "http://graph.facebook.com/%s/picture?type=small"%response['id'] if url: user.avatar = url user.save()
qedsoftware/commcare-hq
corehq/apps/toggle_ui/migration_helpers.py
Python
bsd-3-clause
868
0
from couchdbkit import ResourceNotFound from
toggle.models import Toggle from toggle.shortcuts import update_toggle_cache, parse_toggle def move_toggles(from_toggle_id, to_toggle_id): """ Moves all enabled items from one toggle to another. """ try: from_toggle = Toggle.get(from_toggle_id) except ResourceNotFound: # if no sou...
oggle(slug=to_toggle_id, enabled_users=[]) for item in from_toggle.enabled_users: if item not in to_toggle.enabled_users: to_toggle.enabled_users.append(item) namespace, item = parse_toggle(item) update_toggle_cache(to_toggle_id, item, True, namespace=namespace) to_...
sbilinski/coffea
coffea/java/tests/test_java_scanner.py
Python
apache-2.0
8,818
0.0093
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright 2013 Szymon Biliński # # 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 # # Un...
with SampleEar() as exploded_ear:
ear = exploded_ear.compress() scanner.callback.reset_mock() self.assertEquals(scanner.scan(ear), 7) self.assertEquals(scanner.callback.call_count, 7) def test_scan_directory(self): scanner = self.scanner with SampleJar() as exploded_jar: ...
luotao1/Paddle
python/paddle/fluid/tests/unittests/test_math_op_patch_var_base.py
Python
apache-2.0
24,962
0.0002
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
== b_np)) self.assertTrue(np.array_equal(res2.numpy(), a_np == c_np)) def test_not_equal(self): a_np = np.asarray([1, 2, 3, 4, 5]) b_np = np.asarray([1, 2, 3, 4, 5]) c_np = np.asarray([1, 2, 2, 4, 5]) with fluid.dygraph.guard(): a = fluid.dygraph.to_variable(...
le(b_np) c = fluid.dygraph.to_variable(c_np) res1 = (a != b) res2 = (a != c) self.assertTrue(np.array_equal(res1.numpy(), a_np != b_np)) self.assertTrue(np.array_equal(res2.numpy(), a_np != c_np)) def test_less_than(self): a_np = np.random.random(...
swiftstack/kinetic-swift
test_kinetic_swift/test_diskfile.py
Python
apache-2.0
13,975
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 the...
tions = { 'default': None,
'writethrough': 1, 'writeback': 2, 'flush': 3, } for option, expected in expectations.items(): conf = {'synchronization': option} mgr = server.DiskFileManager(conf, self.logger) self.assertEqual(mgr.synchronization, expected) def test...
ximion/Clementine-LibDanceTag
data/pythonlibs/uic/Loader/loader.py
Python
gpl-3.0
849
0.004711
from PythonQt import QtGui, QtCore from uic.uiparser import UIParser from uic.Loader.qobjectcreator import LoaderCreatorPolicy class DynamicUILoader(UIParser): def __init__(self): UIParser.__init__(self, QtCore, QtGui, LoaderCreatorPolicy()) def createToplevelWidget(self, classname, widgetname): ...
tory.findQObjectType(classname)): raise TypeError(("Wrong base class of toplevel widget", (type(self.toplevelInst), classname))) re
turn self.toplevelInst else: return self.factory.createQObject(classname, widgetname, ()) def loadUi(self, filename, toplevelInst = None): self.toplevelInst = toplevelInst return self.parse(filename)
pgjones/nusoft
packages/nusoft/bzip2.py
Python
mit
2,422
0.009083
#!/usr/bin/env python # # Bzip2 # # Bzip2 packages and versions # # Author P G Jones - 2014-08-15 <p.g.jones@qmul.ac.uk> : New file. #################################################################################################### import nusoft.package.conditional as conditional_package import os class Bzip2(condit...
pass def _remove(self): """ Remove the install directory."
"" self._system.remove(self.get_install_path()) def _is_installed(self): """ Check if root is installed by looking for the root executable in the bin directory. :return: True if installed """ return self._system.exists(os.path.join(self.get_install_path(), "include/bzlib.h")...
yanyuechuixue/tumblr2onedriver
Main.py
Python
gpl-3.0
2,513
0.018305
#!/usr/bin/python import feedparser import wget import sqlite3 import time RssUrlList = ['http://postitforward.tumblr.com/rss','http://for-war3-blog-blog.tumblr.com/rss'] sleep=3600/len(RssUrlList) def mkdir(path): import os path=path.strip() path=path.rstrip("\\") isExists=os.path.exists(path) ...
'TEST','TEST')" % table) mkdir(rss_url[7:-4]) for post in feeds.entries: thisposttime=float(time.mktime(time.strptime(post.published[:-6],"%a, %d %b %Y %H:%M:%S"))) if conn.execute("SELECT MAX(DATE) FROM %s"%table).next()[0] == thisposttime: break if post.description.fi...
sourceadd= post.description.find("source src=") tumblradd= post.description[sourceadd:].find("tumblr_") typeadd = post.description[sourceadd:][tumblradd:].find("type=\"video") video_id=post.description[sourceadd:][tumblradd:][:typeadd-2] if video_id.find("/") !=-1: video...
Gokender/velib
dataParsing.py
Python
mit
1,135
0.009692
import requests import json import sqlite3 import time #searching the api key of velib key_file = open('jcdecaux.key','r') api_key = key_file.readline().rstrip('\n') key_file.close() startime = time.time() url = 'https://api.jcdecaux.com/vls/v1/stations?contract=Paris&apiKey=' + api_key response = requests.get(url...
ES(?, ?, ?, ?, ?, ?, ?)""", (number,request_date,status,bike_stands,available_bike_stands,available_bikes,last_update
)) conn.commit() endtime = time.time() print(int(endtime - startime)) conn.close()
uranusjr/pycontw2016
src/proposals/tests/conftest.py
Python
mit
1,232
0
import pytest from proposals.models import AdditionalSpeaker, TalkProposal, TutorialProposal @pytest.fixture def talk_proposal(user): proposal = TalkProposal.objects.create( id=42, subm
itter=user, title='Beyond the Style Guides<br>', ) return proposal @pytest.fixture def cancelled_talk_proposal(talk_proposal): talk_proposal.cancelled = True talk_proposal.save() return talk_proposal @pytest.fixture def tutorial_proposal(user): proposal = TutorialProposal.objects.cre...
42, submitter=user, title='Beyond the Style Guides<br>', ) return proposal @pytest.fixture def cancelled_tutorial_proposal(tutorial_proposal): tutorial_proposal.cancelled = True tutorial_proposal.save() return tutorial_proposal @pytest.fixture(params=['talk', 'tutorial']) def pro...
rrahn/gdf_tools
include/seqan/apps/samcat/tests/run_tests.py
Python
gpl-3.0
3,112
0.001285
#!/usr/bin/env python """Execute the tests for the samcat program. The golden test outputs are generated by the script generate_outputs.sh. You have to give the root paths to the source and the binaries as arguments to the program. These are the paths to the directory that contains the 'projects' directory. Usage: ...
============================================================ conf = app_tests.TestConf( program=path_to_program, args=[ph.inFile('ex1_a1.sam'), ph.inFile('ex1_a2.sam'), ph.inFile('ex1_a3.sam'),
'-o', ph.outFile('ex1_merged.sam')], to_diff=[(ph.inFile('ex1_merged.sam'), ph.outFile('ex1_merged.sam'))]) conf_list.append(conf) conf = app_tests.TestConf( program=path_to_program, args=[ph.inFile('ex1_a1.sam'), ph.inFile('ex1_a2.sam'), ...
maoy/zknova
nova/image/s3.py
Python
apache-2.0
16,517
0.000848
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compli...
image_uuid = image_copy['id'] except KeyError:
pass else: image_copy['id'] = ec2utils.glance_id_to_id(context, image_uuid) for prop in ['kernel_id', 'ramdisk_id']: try: image_uuid = image_copy['properties'][prop] except (KeyError, ValueError): pass else: ...
President3D/Quality-SPC
src/InResources_rc.py
Python
gpl-3.0
124,824
0.00004
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.6.2) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x06\x92\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x64\x0...
\xe3\x90\x9f\xad\x7d\xf3\x49\x8c\x45\x10\x83\xb9\xd1\x17\ \xcc\x45\x0b\xb5\x60\x30\xd6\x8b\xd2\x33\x34\x81\x0b\x57\xaa\x91\ \xff\x7d\xe1\x34\x97\x96\x1e\x1b\xf0\x99\x29\x76\x90\x50\x30\x42\ \x45\x09\x19\x43\xec\x20\xeb\xc1\x08\x16\x65\x5d\x18\x62\x06\xd9\ \x08\x46\x20\x94\x9e\xa1\x09\x9c\x37\x98\xdf\x85\x8c\x21\x56\x90...
\x8f\x51\x6e\x34\x3b\x71\xe1\xaa\xf9\ \x7d\x56\x61\x79\x47\x86\xde\xf4\xe9\xb7\x29\x0a\xb2\x39\x18\x8b\ \x0d\xf6\x96\x41\xa5\xe3\x90\x57\x5c\x34\xcd\x19\xd6\xf1\xc9\x10\ \x1b\xc8\x66\x62\xcc\x8e\x96\xa2\xdd\xbc\x77\xee\x7a\xe9\x97\x4f\ \x36\x84\x21\x16\x90\x48\x60\xdc\xfb\x29\xa1\xc3\x6a\x0a\xf0\xa3\ \x8f\x82\x44\x02\x...
edwardbadboy/vdsm-ubuntu
vdsm/supervdsm.py
Python
gpl-2.0
3,064
0.000326
# # Copyright 2011 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in th...
self._manager = None self._svdsm = None self._connect() def open(self, *args, **kwargs): return self._manager.open(*args, **kwar
gs) def _connect(self): self._manager = _SuperVdsmManager(address=ADDRESS, authkey='') self._manager.register('instance') self._manager.register('open') self._log.debug("Trying to connect to Super Vdsm") try: utils.retry(self._manager.connect, Exception, timeout=...
ttanner/kryptomime
setup.py
Python
lgpl-3.0
3,207
0.005926
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This file is part of kryptomime, a Python module for email kryptography. # Copyright © 2013,2014 Thomas Tanner <tanner@gmx.net> # # This program is free software: you can redistribute it and/or modify it # under the terms
of the GNU General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS ...
______ from __future__ import absolute_import from __future__ import print_function import setuptools, sys from setuptools.command.test import test as TestCommand __author__ = "Thomas Tanner" __contact__ = 'tanner@gmx.net' __url__ = 'https://github.com/ttanner/kryptomime' class PyTest(TestCommand): user_option...
YouthBread/CEVE-KB
kb.py
Python
gpl-2.0
26,992
0.000664
# coding:utf-8 ''' 8b d8 88 Y8, ,8P ,d 88 Y8, ,8P 88 88 "8aa8" ,adPPYba, 88 88 MM88MMM 88,dPPYba, `88' a8" "8a 88 88 88 88P' "8a 88 8b d8 88 88 88 88 88 88 "8...
基本信息 killmail = {'kill': [], 'lost': [], 'atk': []} if self.URL_kill: killmail['kill'] = self.get_km_basic_info(self.URL_kill) print '成功获取最新的击杀KM', len(killmail['kill']) killmail['lost'] = self.get_km_basic_info(self.URL_lost) print '成功获取最新的损失KM', len(kill...
print 'ERROR' return killmail def get_km_basic_info(self, url): # 返回URL页面中所有KM的基本信息 r = client.get(url) soup = BeautifulSoup(r.text, 'html.parser') a = soup.find('table',id='kbtable').find('tbody').find_all('tr') info = [] url_info = [] killmail =...
clearlinux/autospec
autospec/download.py
Python
gpl-3.0
2,543
0
#!/usr/bin/true # # download.py - part of autospec # Copyright (C) 2018 Intel Corporation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option)...
except pycurl.error as e: if is_fatal: print_fatal("Unable to fetch {}: {}".format(url, e)) sys.exit(1) return None finally: c.close() # write to dest if specified if dest: try: with open(dest, 'wb') as fp: fp.write(bu...
os.unlink(dest) if is_fatal: print_fatal("Unable to write to {}: {}".format(dest, e)) sys.exit(1) return None if dest: return dest else: return buf
avi-software/bmicalc
app/tests/autopilot/weightcalc/tests/test_main.py
Python
gpl-3.0
671
0
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*- from autopilot.matchers import Eventually from testtools.matchers import Equals from bmicalc import tests class MainViewTestCase(tests.BaseTestCase): """Tests for the mainview""" def setUp(self): super(MainViewTestCase, self)...
evice.click_object(button) #
Make an assertion about what should happen label = self.app.main_view.get_label() self.assertThat(label.text, Eventually(Equals('..world!')))