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
Chunfang/defmod-swpc
example/F3Dp/F3D_syn.py
Python
mit
4,626
0.043234
#!/usr/bin/env python import numpy as np import os,sys from mpl_toolkits.mplot3d import Axes3D from matplotlib import pyplot as plt import argparse ap=argparse.ArgumentParser() ap.add_argument('-vis') # 1 plot cropped point cloud ap.add_argument('-refine') #
1 refine mesh ap.add_argument('-clean') # 1 remove tmp files if ap.parse_args().vis==None: vis=0 else: vis=int(ap.parse_args()
.vis) if ap.parse_args().refine==None: refine=0 else: refine=int(ap.parse_args().refine) if ap.parse_args().clean==None: clean=0 else: clean=int(ap.parse_args().clean) # Synthetic fault pixels z=np.linspace(.2, -.8, num=100) y=np.linspace(-.625,.625, num=120) grid=np.meshgrid(y,z) x=np.zeros((len(z)*le...
cloudify-cosmo/cloudify-plugins-common
setup.py
Python
apache-2.0
2,007
0
######## # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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...
ES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. from setuptools import setup install_requires = [ 'cloudify-rest-client==4.4.dev1', 'pika==0.9.14', 'networkx==1.9.1', 'proxy_tools=...
importlib') try: import argparse # NOQA except ImportError as e: install_requires.append('argparse==1.2.2') try: from collections import OrderedDict # noqa except ImportError: install_requires.append('ordereddict==1.1') setup( name='cloudify-plugins-common', version='4.4.dev1', author...
tonikelope/python-passport-trace-attack
pypassport/iso7816.py
Python
gpl-2.0
7,834
0.016977
# Copyright 2009 Jean-Francois Houzard, Olivier Roger # # This file is part of pypassport. # # pypassport is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at...
toSend = apdu.CommandAPDU(cla, ins, os[0:2], os[2:4], lc, data, "") return self.transmit(toSend, "Update Binary") def getChallenge(self): toSend = apdu.CommandAPDU("00", "84", "00", "00", "", "", "08") return self.transmit(toSend, "Get Challenge") def internalAu...
"00", lc, data, "00") res = self.transmit(toSend, "Internal Authentication") return res # def mutualAuthentication(self, data): # data = binToHexRep(data) # lc = hexToHexRep(len(data)/2) # toSend = apdu.CommandAPDU("00", "82", "00", "00", lc, data, "28") # r...
geoscript/geoscript-py
geoscript/plot/curve.py
Python
mit
991
0.0222
from org.jfree.data.xy import XYSeries, XYSeriesCollection from org.jfree.chart.plot import PlotOrientation from org.jfree.chart import ChartFactory from geoscript.plot.chart
import Chart from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer def
curve(data, name="", smooth=True, trid=True): """ Creates a curve based on a list of (x,y) tuples. Setting *smooth* to ``True`` results in a spline renderer renderer is used. Setting *trid* to ``True`` results in a 3D plot. In this case the ``smooth`` argument is ignored. """ dataset = XYSerie...
WarrenWeckesser/scipy
scipy/stats/_hypotests.py
Python
bsd-3-clause
45,046
0
from collections import namedtuple from dataclasses import make_dataclass import numpy as np import warnings from itertools import combinations import scipy.stats from scipy.optimize import shgo from . import distributions from ._continuous_distns import chi2, norm from scipy.special import gamma, kv, gammaln from . im...
id evaluating _cdf_cvm_inf(x) twice in _cdf_cvm. Implementation based on MAPLE code of Julian Faraway and R code of the function pCvM in the package goftest (v1.1.1), permission granted by Adrian Baddeley. Main difference in the implementation: the code here keeps adding terms of the series until t...
_ed3(y): z = y**2 / 4 c = np.exp(-z) / np.sqrt(np.pi) return c * (y/2)**(5/2) * (2*kv(1/4, z) + 3*kv(3/4, z) - kv(5/4, z)) def _Ak(k, x): m = 2*k + 1 sx = 2 * np.sqrt(x) y1 = x**(3/4) y2 = x**(5/4) e1 = m * gamma(k + 1/2) * _ed2((4 * k + 3)/sx) / (9...
hasibi/TAGME-Reproducibility
nordlys/wikipedia/utils.py
Python
mit
966
0.006211
""" Wikipedia utils. @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ from urllib import quote class WikipediaUtils(object): mongo = None @staticmethod def wiki_title_to_uri(title): """ Converts wiki page title to wiki_uri based on https://en.wikipedia.org/wiki/Wikip...
ikipediaUtils.wiki_title_to_uri("Tango (genre m
usical)") if __name__ == "__main__": main()
Chandra-MARX/marxs
marxs/tests/test_analysis.py
Python
gpl-3.0
4,162
0.002162
# Licensed under GPL vers
ion 3 - see LICENSE.rst import numpy as np import transforms3d fr
om astropy.table import Table from astropy.coordinates import SkyCoord import astropy.units as u from ..analysis import (find_best_detector_position, resolvingpower_per_order) from ..math.utils import e2h from ..source import PointSource, FixedPointing from ..simulator import Sequence from ..op...
egassem/python_study
src/com/xiaobei/util/CalenderUtils.py
Python
apache-2.0
763
0.0192
''' Created on 2016年9月16日 @author: Administrator ''' import calendar #返回year的日历 def getYear(year): return calendar.calendar(year) #返回year-month的日历 def getMonth(year, month): return calendar.month(year, month) #返
回某年某月的第一天是星期几(从0开始, 0是星期一,6是星期日)和该月天数 def getMonthRange(year, month): return calendar.monthrange(year, month) #返回某个月以每一周为元素的序列 def getMonthYear(year, month): return calendar.monthcalendar(year, month) #判断year是是否闰年 def isLeap(year): return calendar.isleap(year) print(getYear(2016)) print(getMonth(2016, 10...
6))
Arkapravo/morse-0.6
src/morse/sensors/jido_posture.py
Python
bsd-3-clause
5,867
0.004091
import logging; logger = logging.getLogger("morse." + __name__) import morse.core.sensor class JidoPostureClass(morse.core.sensor.MorseSensorClass): """ Jido posture sensor. Currently working with PTU and KUKA arm """ def __init__(self, obj, parent=None): """ Constructor method. Receives the ...
### # Check if robot parent has a child named "PTUname" for child in self.robot_parent
.blender_obj.children: if str(child) == self.blender_obj['PTUname']: self._ptu_obj = child # Get the references to the childen object and # store a transformation3d structure for their position for child in self._ptu_obj.childrenRecursive: if 'Pa...
lyy289065406/expcodes
python/99-project/django-web/ExpPH/ExpPH/utils/BaseUtils.py
Python
gpl-3.0
1,328
0.009632
# -*- coding: utf8 -*- ''' 基本工具 Created on 2014年5月14日 @author: Exp ''' ''' 获取系统时间 ''' def getSysTime(format = "%Y-%m-%d %H:%M:%S"): import time return time.strftime(format) # End Fun getSysTime() ''' 判断是否为本地运行环境,否则为SAE运行环境 ''' def isLocalEnvironment(): from os import environ retu...
ng(ciphertext) # End Fun decrypt() ''' 简单编码转换,把未知编码的orgStr转码为aimCharset,其中orgStr的源编码由系统自动判断 ''' def simpleTranscoding(orgStr, aimCharset): import chardet orgCharset = chardet.detect(orgStr)['encoding'] #自动判断编码 return transcoding(orgStr, orgCharset, aimCharset) # End Fun simpleTranscoding() '...
# End Fun transcoding()
V8Wookiee/Python_Learning
Resources/sysmon.py
Python
gpl-3.0
3,922
0.024987
# Copyright 2015 Matt Hawkins # # Update : July 2016 # added CPU and disk monitoring to script # johnty.wang@mail.mcgill.ca # # additional requirement: psutil # #-------------------------------------- from subprocess import PIPE, Popen import smbus import psutil import os import time # Define some device param...
uses 0 bus = smbus.SMBus(1) # Rev 2 Pi uses 1 def lcd_init(): # Initialise display lcd_byte(0x33,LCD_CMD) # 110011 Initialise lcd_byte(0x32,LCD_CMD) # 110010 Initialise lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction lcd_byte(0x0C,LCD_CMD) # 0
01100 Display On,Cursor Off, Blink Off lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size lcd_byte(0x01,LCD_CMD) # 000001 Clear display time.sleep(E_DELAY) def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() ...
etherkit/OpenBeacon2
client/win/venv/Lib/site-packages/PyInstaller/hooks/hook-gi.repository.xlib.py
Python
gpl-3.0
593
0.003373
#----------------------------------------------------------------------------- # Copyright (c) 2005-2019, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License with exception # for distributing bootloader. # # The full license is in the file COPYING.txt, distributed with this s...
--- """ Import hook for PyGObject https://wiki.gnome.org/PyGObject """ from PyInstaller.utils.hooks import get_gi_typelibs binaries, datas, hiddenimports = get_gi
_typelibs('xlib', '2.0')
buddyli/android_intership
controller/restaurant_oper.py
Python
apache-2.0
2,323
0.037517
#!/usr/bin/env python #-*- encoding:utf-8 -*- import json from datetime import datetime from bottle import route, mako_template as template, redirect, request, response, get, post from bottle import static_file, view #为了不经过controller直接返回诸如html,css等静态文件引入 from model.documents import * from setting import * DATE_FORM...
request.params.get('start') or '0' size = request.params.get
('size') or '1000' items = Restaurant.objects[int(start):(int(start) + int(size))] data = { 'items': items } return template('views/system/item/list', data = data, site_opt = site_opt) @route('/del_item') def del_item(): id = request.params.get('id') Restaurant.objects(id=id).delete() # cascade delete menus ...
coreycb/horizon
openstack_dashboard/dashboards/project/networks/tables.py
Python
apache-2.0
7,635
0
# Copyright 2012 NEC 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 ag...
t, datum=None): # Only administrator is allowed to create and manage shared networks. if datum and datum.shared: return False return True class DeleteNetwork(policy.PolicyTargetMixin, CheckNetworkEditable, tables.DeleteAction): @staticmethod def action_p...
tworks", count ) @staticmethod def action_past(count): return ungettext_lazy( u"Deleted Network", u"Deleted Networks", count ) policy_rules = (("network", "delete_network"),) def delete(self, request, network_id): network...
eduNEXT/edx-platform
common/djangoapps/track/backends/tests/test_mongodb.py
Python
agpl-3.0
1,162
0.001721
# lint-amnesty, pylint: disable=missing-module-docstring from unittest.mock import patch from django.test import TestCase from common.djangoapps.track.backends.mongodb import MongoBackend class TestMongoBackend(Tes
tCase): # lint-amnesty, pylint: disable=missing-class-docstring def setUp(self): super().setUp() self.mongo_patcher = patch('common.djangoapps.track.backends.mongodb.MongoClient') self.mongo_patcher.start() self
.addCleanup(self.mongo_patcher.stop) self.backend = MongoBackend() def test_mongo_backend(self): events = [{'test': 1}, {'test': 2}] self.backend.send(events[0]) self.backend.send(events[1]) # Check if we inserted events into the database calls = self.backend.col...
georgestarcher/TA-SyncKVStore
bin/ta_synckvstore/solnlib/packages/schematics/validate.py
Python
mit
3,988
0.001254
# -*- coding: utf-8 -*- from __future__ import unicode_literals, absolute_import import functools import inspect from .common import * # pylint: disable=redefined-builtin from .datastructures import Context from .exceptions import FieldError, DataError from .transforms import import_loop, validation_converter from ....
initions. Default: False :param strict: Complain about unre
cognized keys. Default: False :param trusted_data: A ``dict``-like structure that may contain already validated data. :param convert: Controls whether to perform import conversion before validating. Can be turned off to skip an unnecessary conversion step if all values are known ...
NeCTAR-RC/karaage-user
kguser/conf/settings.py
Python
gpl-3.0
1,269
0.003152
# Django settings for kguser project. from os import path fr
om karaage.conf.defaults import * TEMPLATE_DIRS += ( '/usr/share/kguser/templates', ) ROOT_URLCONF = 'kguser.conf.urls' SITE_ID = 2 STATIC_ROOT = '/var/lib/karaage-user/static' STATIC_URL = '/kguser_media/' LOGIN_URL = 'kgauth_login_select' ALLOW_REGISTRATIONS = False SESSION_EXPIRE_AT_BROWSER_CLOSE = True ...
na.bootstrapcdn.com/bootswatch/3.1.1/simplex/bootstrap.min.css', 'theme_url': None, 'javascript_url': None, 'horizontal_label_class': 'col-md-2', 'horizontal_field_class': 'col-md-4', 'set_required': True, } INSTALLED_APPS = INSTALLED_APPS + ('kgauth', 'kgkeystone', 'kguser', 'bootstrap3', 'django_...
DominoTree/servo
tests/wpt/web-platform-tests/tools/wpt/tests/test_revlist.py
Python
mpl-2.0
6,239
0.000641
import mock from tools.wpt import revlist def test_calculate_cutoff_date(): assert revlist.calculate_cutoff_date(3601, 3600, 0) == 3600 assert revlist.calculate_cutoff_date(3600, 3600, 0) == 3600 assert revlist.calculate_cutoff_date(3599, 3600, 0) == 0 assert revlist.calculate_cutoff_date(3600, 3600, ...
assert tagged_revisons.next() == 'E' assert tagged_revisons.n
ext() == 'D' assert tagged_revisons.next() == 'C' assert len(list(tagged_revisons)) == 0 # generator exhausted # check: max_count with less returned candidates items than the needed # # mon tue wed thu fri sat sun mon # | | | | | | | # ...
pravsripad/mne-python
mne/io/ctf/info.py
Python
bsd-3-clause
19,623
0
"""Populate measurement info.""" # Author: Eric Larson <larson.eric.d<gmail.com> # # License: BSD-3-Clause from time import strptime from calendar import timegm import os.path as op import numpy as np from ...utils import logger, warn, _clean_names from ...transforms import (apply_trans, _coord_frame_name, invert_t...
ations for %d HPI coils added'
% n_coil_dev) return dig, [hpi_result] def _convert_time(date_str, time_str): """Convert date and time strings to float time.""" for fmt in ("%d/%m/%Y", "%d-%b-%Y", "%a, %b %d, %Y"): try: date = strptime(date_str.strip(), fmt) except ValueError: pass else...
maleficarium/youtube-dl
test/test_http.py
Python
unlicense
6,282
0.001595
#!/usr/bin/env python # coding: utf-8 from __future__ import unicode_literals # Allow direct execution import os import sys import unittest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from youtube_dl import YoutubeDL from youtube_dl.compat import compat_http_server, compat_urllib_r...
info[0] == 3: # XXX: Python 3 http server does not allow non-ASCII header value
s self.send_response(404) self.end_headers() return new_url = 'http://localhost:%d/中文.html' % http_server_port(self.server) self.send_response(302) self.send_header(b'Location', new_url.encode('utf-8')) self.end_headers() ...
fairbird/OpenPLI-BlackHole
lib/python/Tools/Transponder.py
Python
gpl-2.0
11,703
0.033923
from enigma import eDVBFrontendParametersSatellite, eDVBFrontendParametersCable, eDVBFrontendParametersTerrestrial, eDVBFrontendParametersATSC from Components.NimManager import nimmanager def orbpos(pos): return pos > 3600 and "N/A" or "%d.%d\xc2\xb0%s" % (pos > 1800 and ((3600 - pos) / 10, (3600 - pos) % 10, "W") or...
pe"] = _("Terrestrial") ret["bandwidth"] =
{ 0 : _("Auto"), 10000000 : "10 MHz", 8000000 : "8 MHz", 7000000 : "7 MHz", 6000000 : "6 MHz", 5000000 : "5 MHz", 1712000 : "1.712 MHz"}.get(tp.get("bandwidth")) ret["code_rate_lp"] = { eDVBFrontendParametersTerrestrial.FEC_Auto : _("Auto"), eDVBFrontendParametersTerrestrial.FEC_1_2 : "1/2...
mjoblin/netdumplings
tests/console/test_sniff.py
Python
mit
20,005
0
import asyncio import builtins import importlib.util import json import logging import types import asynctest import click.testing import pytest from netdumplings.console.sniff import ( sniff_cli, get_valid_chefs, network_sniffer, dumpling_emitter, send_dumplings_from_queue_to_hub, ) class TestSniffCLI: ...
t(logger, 'error') runner = click.testing.CliRunner() result = runner.invoke( sniff_cli, [ '--kitchen-name', 'test_kitchen', ], ) mock_error.assert_called_once_with( 'test_kitchen: No valid che
fs found. Not starting sniffer.' ) assert result.exit_code == 1 class TestSniffChefList: """ Test the chef_list() function. """ def test_chef_list(self, mocker): """ Test requesting a chef list. """ mock_list_chefs = mocker.patch( 'netdumpli...
architecture-building-systems/CEAforArcGIS
cea/technologies/chiller_absorption.py
Python
mit
20,692
0.004253
""" Absorption chillers """ import cea.config import cea.inputlocator import pandas as pd import numpy as np from math import log, ceil import sympy from cea.constants import HEAT_CAPACITY_OF_WATER_JPERKGK from cea.analysis.costs.equations import calc_capex_annualized, calc_opex_annualized __author__ = "Shanshan Hsieh...
. The following code was used to create the expression to calculate ``q_hw_kW`` with:: # use symbolic computation to derive a formula for q_hw_kW: # first, make sure all the variables are s
ympy symbols: T_chw_in_C, T_chw_out_C, T_cw_in_C, T_hw_in_C, mcp_cw_kWperK, mcp_hw_kWperK, q_chw_kW = sympy.symbols( "T_chw_in_C, T_chw_out_C, T_cw_in_C, T_hw_in_C, mcp_cw_kWperK, mcp_hw_kWperK, q_chw_kW") T_hw_out_C, T_cw_out_C, q_hw_kW = sympy.symbols('T_hw_out_C, T_cw_out_C, q_hw_kW') ...
TomBaxter/waterbutler
tests/tasks/test_move.py
Python
apache-2.0
6,692
0.001494
import sys import copy import time import asyncio import hashlib from unittest import mock import celery import pytest from waterbutler import tasks # noqa from waterbutler.core import remote_logging from waterbutler.core import utils as core_utils from waterbutler.core.path import WaterButlerPath import tests.util...
('Unexpected provider')
monkeypatch.setattr(move.utils, 'make_provider', make_provider) return src_provider, dest_provider @pytest.fixture(autouse=True) def log_to_keen(monkeypatch): mock_log_to_keen = test_utils.MockCoroutine() monkeypatch.setattr(remote_logging, 'log_to_keen', mock_log_to_keen) return mock_log_to_keen ...
kdheepak/psst
psst/case/matpower/reader.py
Python
mit
1,747
0.006869
from __future__ import print_function, absolute_import import re import logging import numpy as np from ...utils import int_else_float_except_string logging.basicConfig() logger = logging.getLogger(__file__) def find_name(string): return re.search('function\s*mpc\s*=\s*(?P<data>.*?)\n', string).groupdict()['d...
return _list else: return match def search_file(attribute, string): if attribute in ['gen', 'gencost', 'bus', 'branch']: pattern = r'mpc\.{}\s*=\s*\[[\n]?(?P<data>.*?)[\n]?\];'.format(attribute) elif attribute in ['version', 'baseMVA']: pattern = r'mpc\.{}\s*=\s*(
?P<data>.*?);'.format(attribute) elif attribute == 'bus_name': pattern = r'mpc\.{}\s*=\s*\{{[\n]?(?P<data>.*?)[\n]?\}};'.format('bus_name') else: logger.warning('Unable to parse mpc.%s. Please contact the developer.', attribute) return None match = re.search(pattern, string, re.DOTA...
zlalanne/msp430-webcontrol
msp430webcontrol/tcp_comm/views.py
Python
bsd-3-clause
2,798
0.006076
from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from msp430.models import * from tcp_comm.client import push_config from msp430.models import MSP430 import json @csrf_exempt def register(request): """When an MSP430 connects to the TCP server this...
', mimetype='application/json') @csrf_exempt def disconnect(request): if request.method == 'POST': try: jreq = json.loads(reque
st.body.decode('UTF-8'))['json'] except: return HttpResponseBadRequest('Unable to parse post json key', mimetype='application/json') # verify fields exist if 'mac' not in jreq: return HttpResponseBadRequest('Does not have required fields - mac', mimetype='application/jso...
cboling/SDNdbg
docs/old-stuff/pydzcvr/pydzcvr/tests/alltests.py
Python
apache-2.0
2,190
0.00137
#!/usr/bin/env python ''' alltests.py - This module runs the automated tests in all the components. To run specific test cases, pass one or more names of package/module names on the command line which contain the test cases to be run. Usage: python AllTests.py - Runs all the unittests python...
ile' @author: Chip Boling @copyright: 2015 Boling Consulting Solutions. All rights reserved. @license: Artistic License 2.0, http://opensource.org/licenses/Artistic-2.0 @contact: support@bcsw.net @deffield updated: Updated ''' import unittest as uTest #import site import sys import logging alltestnames = [ ...
f no arguments are given, all of the test cases are run. if len(sys.argv) == 1: testnames = alltestnames verbosity = 2 logging.getLogger().setLevel(logging.INFO) print 'Loading all Webware Tests...' else: testnames = sys.argv[1:] # Turn up verbosity and logging le...
rockychen-dpaw/oim-cms
registers/utils.py
Python
apache-2.0
806
0
from django.contrib.admin import ModelAdmin from django.utils.encoding import smart_text class OimModelAdmin(ModelAdmin): """ OimModelAdmin""" def has_module
_permission(self, request): user = r
equest.user if user.is_superuser: return True if user.is_staff: if user.groups.filter(name="OIM Staff").exists(): return True return False def smart_truncate(content, length=100, suffix='....(more)'): """Small function to truncate a string in a sen...
burnpanck/traits
traits/tests/test_property_delete.py
Python
bsd-3-clause
730
0
""" Unit tests to ensure that we can call reset_traits/delete on a property trait (regression tests for Github issue #67). """ from traits import _py2to3 from traits.api import Any, HasTraits, Int, Property, TraitError from traits.testing.unittest_tools import unittest class E(HasTraits): a = Property(Any) ...
table = e.reset_traits() _py2to
3.assertCountEqual(self, unresetable, ['a', 'b'])
Saevon/DMP-Career-Share
server.py
Python
mit
3,413
0.002344
# !/usr/bin/env python # -*- coding: UTF-8 -*- from functools import wraps import bottle import datetime import json import os from error import DMPException from profile import ProfileHandler app = bottle.Bottle() def json_return(func): @wraps(func) def wrapper(*args, **kwargs): data = json.dumps(...
urn data return wrapper @app.route('/favicon.ico') def favicon(): bottle.response.status = 404 @app.route('/') @json_return def root(): return { 'status': 200, 'data': "Welcome, go to '/profile_name' to sync you
r profile>" } @app.route('/<name>') @json_return def sync(name): ''' Shows the data in the root folder ''' try: profile_handler.merge_profile(name) except KeyError as err: return { 'status': 404, 'error': 'Profile not Found', } except DMPExcep...
jessrosenfield/pants
tests/python/pants_test/option/test_option_value_container.py
Python
apache-2.0
3,394
0.004714
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import copy import u...
o we test them. o = OptionValueContainer() o.foo = 1 o.bar = {'a'
: 111} p = copy.copy(o) # Verify that the result is in fact a copy. self.assertEqual(1, p.foo) # Has original attribute. o.baz = 42 self.assertFalse(hasattr(p, 'baz')) # Does not have attribute added after the copy. # Verify that it's a shallow copy by modifying a referent in o and reading ...
kiall/designate-py3
designate/objects/recordset.py
Python
apache-2.0
8,399
0
# Copyright (c) 2014 Rackspace Hosting # 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 req...
by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import log...
port utils from designate.objects import base from designate.objects.validation_error import ValidationError from designate.objects.validation_error import ValidationErrorList LOG = logging.getLogger(__name__) class RecordSet(base.DictObjectMixin, base.PersistentObjectMixin, base.DesignateObject): ...
luchasei/http-log-app
tests/logEntryTests.py
Python
mit
2,432
0.00699
import unittest from logEntry import LogEntry class TestLogEntry(unitt
est.TestCase): def test_parse_log_1(self): line = '188.45.108.168 - - [12/Dec/2015:19:44:09 +0100] "GET /images/stories/raith/almhuette_raith.jpg HTTP/1.1" 200 43300 "http://www.almhuette-raith.at/" "Mozilla/5.0 (Linux; Android 4.4.2; de-at; SAMSUNG GT-I9301I Build/KOT49H) AppleWebKit/537.36 (KHTM...
ecko) Version/1.5 Chrome/28.0.1500.94 Mobile Safari/537.36" "-"' entry = LogEntry(line) self.assertEqual(entry.clientIp,'188.45.108.168') self.assertEqual(entry.clientId, '-') self.assertEqual(entry.userName, '-') self.assertEqual(entry.requestLine, 'GET /images/stories/raith/alm...
hb9kns/PyBitmessage
src/bitmessageqt/safehtmlparser.py
Python
mit
5,318
0.006205
from HTMLParser import HTMLParser import inspect import re from urllib import quote, quote_plus from urlparse import urlparse class SafeHTMLParser(HTMLParser): # from html5lib.sanitiser acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b'...
tag(self, tag, attrs): if tag in SafeHTMLParser.acceptable_elements: self.has_html = True self.add_if_acceptable(tag, attrs) def handle_data(self, data): self.sanitised += data def handle_charref(self, name): self.sanitised += "&#" + name + ";" ...
, data): try: data = unicode(data, 'utf-8') except UnicodeDecodeError: data = unicode(data, 'utf-8', errors='replace') HTMLParser.feed(self, data) tmp = SafeHTMLParser.replace_pre(data) tmp = SafeHTMLParser.uriregex1.sub( r'<a href="\1">\1</a>'...
ImWalkinHere/Calculator
tests/test_operations.py
Python
lgpl-2.1
1,523
0.006566
"""Brief description of what this file should test""" import pytest from Calculator import operations def tes
t_addition(): assert operations.add(1, 2) == 3 def test_subtraction(): assert operations.subtract(1 ,2) == -1 def test_multiplication(): assert operations.multiply(2, -1) == -2 def test_divide(): # test for floating point division returns floating point assert isinstance(operations.divide(3, 2), ...
Error is raised with pytest.raises(Exception): operations.divide(1, 0) @pytest.mark.parametrize("given, expected", [ (0, 0), (-0.76, 0.76), (1, 1), ]) def test_abs_val(given, expected): assert operations.abs_val(given) == expected @pytest.mark.parametrize("given, expected", [ (0, 0), ...
DDT-INMEGEN/opendata
webservice.py
Python
agpl-3.0
1,056
0.012311
from flask import Flask, session, redirect, url_for, escape, request, jsonify from flask.ext.pymo
ngo import PyMongo from pprint import pformat import sys import os import re app = Flask("download") mongo = PyMongo(app) local_repo = '/home/rgarcia/opendata' server_repo = '/home/rgarcia/public_html' ############ # anuncios # ############
@app.route('/register', methods=['POST']) def anuncio_save(): downloader = request.get_json() try: downloader.pop('email_repeat') path = downloader['path'] oid = mongo.db.downloaders.save(downloader) local_path = os.path.join( local_repo, path ) server_path = os.path.jo...
avenet/hackerrank
find_the_robot_iterator.py
Python
mit
377
0.018568
def spiral_iterator(): x, y =
0, 0 direction = [(1, 0), (0, 1), (-1, 0), (0, -1)] i = 1 print x,y while True: dir_index = (i - 1) % 4 vector = i * direction[dir_index][0], i * direction[dir_index][1] x += vector[0] y += v
ector[1] print x,y i += 1 raw_input() result = spiral_iterator()
arshvin/scripts
zabbix/T_hdfs_space_checker/hdfs_space_metric_server.py
Python
apache-2.0
3,517
0.033551
import asyncore, socket, logging, time, asynchat, os from hdfs_space_common import get_tree_from_cache, get_child_node, TreeNode FORMAT = '%(asctime)
-15s: %(levelname)s %(module)s - %(funcName)
s: %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) class ChatHandler(asynchat.async_chat): def __init__(self, sock): asynchat.async_chat.__init__(self, sock = sock) self.ibuffer = [] self.obuffer = '' self.set_terminator("\n") def collect_incoming_data(self, data): self.ibuffer.app...
bjornwallner/proq2-server
apps/modeller9v8/examples/python/steepest_descent.py
Python
gpl-3.0
1,980
0.000505
from modeller.optimizers import state_optimizer class SteepestDescent(state_optimizer): """Very simple steepest descent optimizer, in Python""" # Add options for our optimizer _ok_keys = state_optimizer._ok_keys + ('min_atom_shift', 'min_e_diff', 'step_size', 'ma...
state_optimizer.__init__(self, step_size=step_size, min_atom_shift=min_atom_shift, min_e_diff=min_e_diff, max_iterations=max_iterations, **vars) def optimize(self, atmsel, **vars): # Do normal optimizat...
atmsel, **vars) # Get all parameters alpha = self.get_parameter('step_size') minshift = self.get_parameter('min_atom_shift') min_ediff = self.get_parameter('min_e_diff') maxit = self.get_parameter('max_iterations') # Main optimization loop state = self.get_state...
goal/uwsgi
plugins/gevent/uwsgiplugin.py
Python
gpl-2.0
213
0
from dis
tutils import sysconfig NAME = 'gevent' CFLAGS = [ '
-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True) ] LDFLAGS = [] LIBS = [] GCC_LIST = ['gevent', 'hooks']
jasonehines/mycroft-core
mycroft/client/enclosure/api.py
Python
gpl-3.0
6,761
0
# Copyright 2016 Mycroft AI, Inc. # # This file is part of Mycroft Core. # # Mycroft Core 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 versio...
lf.ws.emit(Message("enclosure.reset")) def system_reset(self): """T
he enclosure hardware should reset any CPUs, etc.""" self.ws.emit(Message("enclosure.system.reset")) def system_mute(self): """Turn off the system microphone (not listening for wakeword).""" self.ws.emit(Message("enclosure.system.mute")) def system_unmute(self): """Turn the sys...
SciLifeLab/genologics
examples/get_samples2.py
Python
mit
756
0
"""Python interface to GenoLogics LIMS via its REST API. Usage examples: Get some samples, and sample info. Per Kraulis, Science for Life Labo
ratory, Stockholm, Sweden. """ from genologics.lims import * from genologics.config import BASEURI, USERNAME, PASSWORD lims = Lims(BASEURI, USERNAME, PASSWORD) lims.check_version() project = Project(lims, id='KRA61') samples = lims.get_samples(projectlimsid=project.id) print(len(samples), 'samples in'
, project) for sample in samples: print(sample, sample.name, sample.date_received, sample.artifact) name = 'spruce_a' artifacts = lims.get_artifacts(sample_name=name) print(len(artifacts), 'artifacts for sample', name) for artifact in artifacts: print(artifact, artifact.name, artifact.qc_flag)
jawilson/home-assistant
tests/components/fritzbox/test_switch.py
Python
apache-2.0
5,502
0.000727
"""Tests for AVM Fritz!Box switch component.""" from datetime import timedelta from unittest.mock import Mock from requests.exceptions import HTTPError from homeassistant.components.fritzbox.const import ( ATTR_STATE_DEVICE_LOCKED, ATTR_STATE_LOCKED, DOMAIN as FB_DOMAIN, ) from homeassistant.components.se...
ate assert state.state == "5.678" assert state.attributes[ATTR_FRIENDLY_NAME] == f"{CONF_FAKE_NAME} Power Consumption" assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == POWER_WATT assert state.attributes[ATTR_STATE_CLASS] == STATE_CLASS_MEASUREMENT state = hass.states.get(f"{SEN
SOR_DOMAIN}.{CONF_FAKE_NAME}_total_energy") assert state assert state.state == "1.234" assert state.attributes[ATTR_FRIENDLY_NAME] == f"{CONF_FAKE_NAME} Total Energy" assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == ENERGY_KILO_WATT_HOUR assert state.attributes[ATTR_STATE_CLASS] == STATE_CLASS_T...
wazari972/WebAlbums
WebAlbums-FS/WebAlbums-Utils/Photowall/photowall.py
Python
gpl-3.0
15,846
0.023224
#!/usr/bin/env python import os import tempfile import pipes import subprocess import time import random import shutil try: from wand.image import Image from wand.display import display except ImportError as e: # cd /usr/lib/ # ln -s libMagickWand-6.Q16.so libMagickWand.so print("Couldn't import Wand packag...
ndom wall options ## "SLEEP_TIME": 0, "HELP": False } DEFAULTS = dict([(key, value) for key, value in PARAMS.items()]) DEFAULTS_docstr = dict([(KEY_TO_OPT[key][0], value) for key, value in PARAMS.items()]) usage = """Photo Wall for WebAlbums 3. Usage: photowall.py <path> <target> [options] Arguments: <path> ...
ept in POLAROID+RANDOM mode, the image will be blanked out first. [default: %(<target>)s] Options: --polaroid Use polaroid-like images for the wall --width <width> Set final image width. [default: %(--width)d] --nb-lines <nb> Number on lines of the target image. [default: %(--nb-line...
symbooglix/boogie-runner
BoogieRunner/Runners/GPUVerify.py
Python
bsd-3-clause
2,173
0.010584
# vim: set sw=2 ts=2 softtabstop=2 expandtab: from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def __init__(self, msg)...
's timeout function and enforce the # requested timeout and enforce a hard timeout slightly later self.maxTimeInSeconds = self.maxTimeInSeconds + self.softTimeoutDiff if not self.toolPath.endswith('.py'): raise GPUVerifyRunnerException( 'toolPath needs to be the GPUVerify python script') ...
urn "gpuverify" def _buildResultDict(self): results = super(GPUVerifyRunner, self)._buildResultDict() # TODO: Remove this. It's now redundant results['hit_hard_timeout'] = results['backend_timeout'] return results def GetNewAnalyser(self, resultDict): return GPUVerifyAnalyser(resultDict) de...
andela-bmwenda/cp2-bucketlist-api
app/models.py
Python
mit
2,762
0
from datetime import datetime from flask_login import UserMixin from marshmallow import Schema, fields from werkzeug.security import generate_password_hash, check_password_hash from app import db class User(db.Model, UserMixin): _
_tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True) password = db.Column(db.String(50)) def __init__(self, username, password): self.username = username self.set_password(password=bytes(str(password), 'utf-8')) sel...
rd): self.pwd_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password, password) def __repr__(self): return '<User %r>' % self.username class BucketList(db.Model): __tablename__ = 'bucketlists' id = db.Column(db.Int...
dhamaniasad/flask-elasticsearch
app.py
Python
unlicense
188
0
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) db = SQL
Alchemy(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db
' app.debug = True
jtakayama/makahiki-draft
install/run_initialize_instance.py
Python
mit
7,542
0.004243
import os import sys import subprocess import shlex import sys import StringIO import datetime sys.path.append(os.path.dirname(os.path.realpath(__file__)) + os.sep + os.pardir + os.sep + "makahiki" + os.sep) from apps.utils import script_utils def termination_string(): """ Gets the current system time and app...
h I/O back, write output to logfile sys.stdout = normal_stdout output = output_capturer.getvalue() logfile.write(output) print(output) # Clear the logfile buffer. logfile.flush() os.fsync(logfile) # Print a closin...
ination_string() logfile.write(end_time) print end_time return logfile except subprocess.CalledProcessError as cpe: logfile.write("CalledProcessError: ") print "CalledProcessError: " logfile.write(cpe.output) print cpe.output logfi...
BBN-Q/pyqgl2
test/code/bugs/84.py
Python
apache-2.0
1,119
0.006256
from qgl2.qgl2 import qgl2decl, qgl2main, qreg from qgl2.qgl2 import QRegister from qgl2.qgl1 import X, Y, Z, Id, Utheta from itertools import product @qgl2decl def cond_helper(q: qreg, cond): if cond: X(q) @qgl2decl def t1(): """ Correct result is [ X(q1) ] """ q1 = QRegister('q1') ...
ust to make sure that the compiler doesn't # freak out X(q1) @qgl2decl def t3(): """ Like t2, but with a function call """ q1 = QRegister('q1') q2 = QRegister('q2') cond_helper(q1, True) @qgl2decl def t4(): """ Like t3, but the function call does nothing """ q1 =
QRegister('q1') q2 = QRegister('q2') cond_helper(q1, False) X(q1) # need to do something @qgl2decl def t5(): """ Like t3, but the function call does nothing """ q1 = QRegister('q1') q2 = QRegister('q2') # don't do anything at all
digistump/gerbmerge3
gerbmerge/aptable.py
Python
gpl-3.0
11,947
0.003264
#!/usr/bin/env python """ Manage apertures, read aperture table, etc. -------------------------------------------------------------------- This program is licensed under the GNU General Public License (GPL) Version 3. See http://www.fsf.org for details of the license. Rugged Circuits LLC http://ruggedcircuits.com/g...
, GAMT, RevGAMT): if self.apname in ('Macro',): # Construct a rotated macro, see if it's in the GAMT, and set self.dimx # to its name if so. If not, add the rotated macro to the GAMT and set # self.dimx to the new name. Recall that GAMT maps name to macro # (e.g.,...
# macro name (e.g., RevGAMT[hash] = 'M9') AMR = GAMT[self.dimx].rotated() hash = AMR.hash() try: self.dimx = RevGAMT[hash] except KeyError: AMR = amacro.addToApertureMacroTable(GAMT, AMR) # adds to GAMT and modifies name to global name...
julienaubert/clothstream
clothstream/collection/signals.py
Python
mit
404
0
from django.db.models.signals import post_save from django.dispatch import receiver from clothstream.user_profile.models import UserProfile @receiver(post_save, sender=UserPr
ofile) def create_initial_collection(sender, created, instance, **kwargs): from clothstream.collection.models import Collection if created: Collection.objects.create(owner=instance, title=u'My first c
ollection')
toystori/v2
app/toy/views.py
Python
mit
396
0
from django.urls import reverse_lazy from django.views.generic import ListView from django.vi
ews.generic.edit import UpdateView from .models import Toy class ToyEditView(UpdateView): model = Toy fields = '__all__' template_name_suffix = '_edit' success_url = reverse_lazy('toy:list
') class ToyListView(ListView): def get_queryset(self): return Toy.objects.all()
plajjan/pybgp
pybgp/nlri.py
Python
mit
5,029
0.003977
import array import struct import socket from odict import OrderedDict as OD class NLRI: def __init__(self, afi, safi, val): self.afi = afi self.safi = safi self.val = val def encode(self): return self.val class vpnv4(NLRI): def __init__(self, labels, rd, prefix): ...
(other.labels, other.rd, other.prefix), ) return -1 def encode(self): plen = 0 v = '' labels = self.labels[:] if not labels: return '\0' labels = [l<<4 for l in labels] labels[-1] |= 1 for l in labels: ...
plen += 24 l, r = self.rd.split(':') if '.' in l: ip = socket.inet_aton(l) rd = struct.pack('!H4sH', 1, ip, int(r)) else: rd = struct.pack('!HHI', 0, int(l), int(r)) v += rd plen += 64 ip, masklen = self.prefix.split('/') ip ...
RuiNascimento/krepo
plugin.video.sparkle/resources/lib/modules/subreddits.py
Python
gpl-2.0
3,534
0.004527
import os, sys, re, json from praw2 import Reddit reload(sys) try: from xbmc import log except: def log(msg): print(msg) sys.setdefaultencoding("utf-8") CLIENT_ID = 'J_0zNv7dXM1n3Q' CLIENT_SECRET = 'sfiPkzKDd8LZl3Ie1WLAvpCICH4' USER_AGENT = 'sparkle streams 1.0' class SubRedditEvents(object): as...
title = submission.title title = title.encode('utf-8') subs.append({'submission_id': sub_id, 'title'
: title, 'score': score }) return sorted(subs, key=lambda d: d['score'], reverse=True) def get_event_links(self, submission_id): submission = self.client.submission(id=submission_id) links = [] scores = {} # Add the extracted links and details tuple for c in submissi...
iamdork/compose
dork_compose/__init__.py
Python
mit
92
0
__ve
rsion__ = '1.13.0.0.0.1
' if __name__ == "__main__": from main import run run()
lasr/orbital_mechanics
orbit/mee2coe.py
Python
mit
1,025
0
"""Created on Sat Oct 01 2015 16:14. @author: Nathan Budd """ import numpy as np def mee2coe(MEE, mu=1.): """ Convert modified equinoctial elements to classical orbital elements. Parameters ---------- MEE : ndarray mx6 array of elements ordered as [p f g h k L]. mu : float St...
icity e = (f**2 + g**2)**.5 # argument of periapsis w_bar = np.mod(np.arctan2(g, f), 2*np.pi) w = np.mod(w_bar - W, 2*np.pi) # true anomaly f = np.m
od(L - w_bar, 2*np.pi) return np.concatenate((p, e, i, W, w, f), 1)
tmthydvnprt/pfcompute
pf/report.py
Python
mit
345
0
""" report.py Functions to create various reports. project : pf version : 0.0.0 status : development modifydate : createdate : website : https://github.com/tmthydvnprt/pf author : tmthydvn
prt e
mail : tim@tmthydvnprt.com maintainer : tmthydvnprt license : MIT copyright : Copyright 2016, tmthydvnprt credits : """
dwrpayne/zulip
zerver/tests/test_decorators.py
Python
apache-2.0
5,333
0.001313
# -*- coding: utf-8 -*- from django.test import TestCase from zerver.decorator import \ REQ, has_request_variables, RequestVariableMissingError, \ RequestVariableConversionError, JsonableError from zerver.lib.validator import ( check_string, check_dict, check_bool, check_int, check_list ) import ujson cl...
alidation, but the error message should be customized. # This is an ex
ample. def check_person(val): error = check_dict([ ['name', check_string], ['age', check_int], ])('_', val) if error: return 'This is not a valid person' person = {'name': 'King Lear', 'age': 42} self.assertEqua...
samyk/proxmark3
tools/findbits_test.py
Python
gpl-2.0
1,837
0.003266
#!/usr/bin/env python3 import unittest, sys, findbits class TestFindBits(unittest.TestCase): def setUp(self): self.old_stdout = sys.stdout sys.stdout = OutputBuffer() def tearDown(self): sys.stdout = self.old_stdout INVERT_CASES = [ ('10', '01'), ('', ''),...
tion, cases): self.unary_operation_test(operation, cases) self.unary_operation_test(operation, map(reversed, cases)) def unary_operation_test(self, operation, cases): for case_in, case_out in cases: self.assertEqual(operation(ca
se_in), case_out) class OutputBuffer(object): def __init__(self): self.clear_buffer() def clear_buffer(self): self.content = '' def write(self, data): self.content += data if __name__ == '__main__': unittest.main()
OJFord/IARAI
IARAI/iarai.py
Python
mit
4,896
0.045761
#!/usr/bin/env python3 from sys import argv, exit from cmd import Cmd from copy import deepcopy from tabulate import tabulate import json import shlex __author__ = 'OJFord' __version__ = '1.0dev' class Interpreter(Cmd): """IARAI: A Relational Algebra Interpreter.""" def __init__(self, relfile): super().__i...
fter @staticmethod def chainable(cmd, args): return cmd + ('_' + args[1:] if args[1:] else '') + ' ' def cmdloop(self): try: return super().cmdloop() except KeyboardInterrupt: # cancel command without crashing out of interpreter
self.intro = None return self.cmdloop() def precmd(self, line): if not line or line == 'EOF' or line.find('help') == 0: return line argsend = line.find('(') if argsend == -1: argsend = line.find('$') rel = line[argsend:] cmd = line[0] args= shlex.split( line[1:argsend] ) if len(args) >= 2...
pcapriotti/pledger
pledger/rule.py
Python
mit
1,570
0.000637
import itertools class RuleCollection(object): def __
init__(self): self.rules = {} def add_rule(self, rule, level=0): self.rules.setdefault(level, []) self.
rules[level].append(rule) def apply(self, transaction, entry): entries = [entry] levels = list(self.rules.keys()) levels.sort() for level in levels: rules = self.rules[level] new_entries = [] for entry in entries: new_entries.app...
Maple0/Algorithm
leetcode/merge-overlapping-intervals.py
Python
mit
1,961
0.042325
#Author: Maple0 #Github:https://github.com/Maple0 #4th Sep 2016 #Given a collection of intervals, merge all overlapping intervals. #For example, #Given [1,3],[2,6],[8,10
],[15,18], #return [1,6],[8,10],[15,18]. class Interval(object): def __init__(self, s=0, e=0): self.start = s self.end = e class Merge_ResultSet(object): def __init__(self,is_modified,
merged_numbers): self.is_modified = is_modified self.merged_numbers = merged_numbers class Solution(object): def inner_merge(self,numbers): is_modified=False length=len(numbers) merged_numbers=[numbers[0]] for i in range(1,length): c_start=numbers[i].start c_end=numbers[i].end ...
shenfei/oj_codes
leetcode/python/n219_Contains_Duplicate_II.py
Python
mit
659
0.003035
from collections import defaultdict class Solution: def containsNearbyDuplicate(self, nu
ms, k): """
:type nums: List[int] :type k: int :rtype: bool """ indices = defaultdict(list) for i, x in enumerate(nums): indices[x].append(i) for _, v in indices.items(): if len(v) <= 1: continue v.sort() for i in ran...
mjn19172/Savu
savu/test/simple_tomo_test.py
Python
apache-2.0
1,360
0.001471
# Copyright 2014 Diamond Light Source Ltd. # # 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 t...
ons) if __name__ ==
"__main__": unittest.main()
susanctu/Crazyfish-Public
webgen/webgen.py
Python
mit
8,518
0.008922
import sys import re import argparse import os.path BLOCK_TAG_START = '{%' BLOCK_TAG_END = '%}' tag_re = (re.compile('(%s.*?%s)' % (re.escape(BLOCK_TAG_START), re.escape(BLOCK_TAG_END)))) name_extract_re = (re.compile('%s\W*block\W+([^\W]+)\W*?%s' % (re.escape(BLOCK_TAG_START), re.escape...
s with. Blocks should be specified in templates as {% block central %} contents of block, blah, blah, blah {% endblock %} where the block can be given an
y name without whitespace (here, the block is called 'central') Note that in the above example, index.html is just index_template with all block tags removed but their contents preserved (i.e., if you don't specify a block by name in PAGES but it exists in the template, the page will be generated ...
pylbert/upm
examples/python/lsm303d.py
Python
mit
2,423
0.001651
#!/usr/bin/env python # Author: Jon Trulson <jtrulson@ics.com> # Copyright (c) 2017 Intel Corporation. # # The MIT License # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restrictio...
ensor = sensorObj.LSM303D() ## Exit handlers ## # This function stops python from printing a stacktrace when you # hit control-C def SIGINTHandler(signum, frame): raise SystemExit # This function lets you run code on exit def exitHandler(): print("Exiting") sys.exit(0) ...
er exit handlers atexit.register(exitHandler) signal.signal(signal.SIGINT, SIGINTHandler) # now output data every 250 milliseconds while (1): sensor.update() data = sensor.getAccelerometer() print("Accelerometer x:", data[0], end=' ') print(" y:", data[1], end=' ') ...
samihuc/PolyglotDB
polyglotdb/query/lexicon/query.py
Python
mit
1,736
0.004608
from ..base import BaseQuery class LexiconQuery(BaseQuery): def __init__(self, corpus, to_find): super(LexiconQuery, self).__init__(corpus, to_find) def create_subset(self, label):
""" Set properties of the returned tokens. """ labels_to_add = [] if self.to_find.node_type not in self.corpus.hierarchy.subset_types or \ label not in self.corpus.hierarchy.subset_types[self.to_find.node_type]: labels_to_add.append(label) ...
o_find.node_type, labels_to_add) self.corpus.encode_hierarchy() def remove_subset(self, label): """ removes all token labels""" super(LexiconQuery, self).remove_subset(label) self.corpus.hierarchy.remove_type_labels(self.corpus, self.to_find.node_type, [label]) def set_propert...
codinuum/cca
python/src/cca/factutil/rdf.py
Python
apache-2.0
9,601
0
#!/usr/bin/env python3 ''' Factutil: helper scripts for source code entities Copyright 2012-2021 Codinuum Software Lab <https://codinuum.com> 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...
ct self.predicate = predicate self.object = object s = None p = None o = None if isinstance(subject, Resource): s = subject.as_node() if isinstance(predicate, Predicate): p = predicate.as_node() ...
RDFNode): o = object.as_node() self._stmt = (s, p, o) def __eq__(self, other): res = False if isinstance(other, Statement): res = reduce(lambda x, y: x and y, [self.subject == other.subject, self.predicate =...
Yellowen/Owrang
accounts/doctype/account/test_account.py
Python
agpl-3.0
1,859
0.024744
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes def make_test_records(verbose): from webnotes.test_runner import make_test_o
bjects accounts = [ # [account_name, parent_account, group_or_ledger] ["_Test Account Bank Account", "Bank Accounts", "Ledger"], ["_Test Account Stock Expenses", "Direct Expenses", "Group"], ["_Test Account Shipping Charges", "_Test Account Stock Expenses", "Ledger"], ["_Test Account Customs Duty", "_T...
Account Service Tax", "_Test Account Tax Assets", "Ledger"], ["_Test Account Reserves and Surplus", "Current Liabilities", "Ledger"], ["_Test Account Cost for Goods Sold", "Expenses", "Ledger"], ["_Test Account Excise Duty", "_Test Account Tax Assets", "Ledger"], ["_Test Account Education Cess", "_Test Acco...
raildo/nova
nova/network/neutronv2/api.py
Python
apache-2.0
88,749
0.000237
# Copyright 2012 OpenStack Foundation # All Rights Reserved # Copyright (c) 2012 NEC 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/lic...
law or agreed to in writing, software #
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # import copy import time import uuid from keystoneclient import ...
jldaniel/Gaia
Algorithms/algorithm_base.py
Python
mit
29,920
0.000836
__author__ = 'jdaniel' import copy import random import itertools import operator import math import struct import os import sys import json from collections import defaultdict class AlgorithmBase(object): def __init__(self, objective_function): """ Base Algorithm class which contains utility fun...
:return: None """ # Check if between (0.0, 1.0)
if value < 0.0 or value > 1.0: err_msg = 'The crossover probability p_cross must be between 0.0 and 1.0' raise AlgorithmException(err_msg) @staticmethod def check_p_mut(value): """ Check the mutation probability value :p
kramwens/order_bot
venv/lib/python2.7/site-packages/tests/pricing/test_messaging_countries.py
Python
mit
3,318
0
import unittest from mock import patch from nose.tools import assert_equal from tests.tools import create_mock_json from twilio.rest.resources.pricing.messaging_countries import ( MessagingCountries ) AUTH = ("AC123", "token") BASE_URI = "https://pricing.twilio.com/v1" class MessagingCountriesTest(unittest.TestC...
de") assert_equal(inbound_sms_prices[1]['base_price'], "0.0075") assert_equal(inbound_sms_prices[1]['current_price'],
"0.005") assert_equal(inbound_sms_prices[2]['number_type'], "toll-free") assert_equal(inbound_sms_prices[2]['base_price'], "0.0075") assert_equal(inbound_sms_prices[2]['current_price'], "0.0075") request.assert_called_with( "GET", "{0}/Messaging/Countries/US".f...
mdmintz/seleniumspot
seleniumbase/plugins/selenium_plugin.py
Python
mit
7,978
0
""" This plugin gives the power of Selenium to nosetests by providing a WebDriver object for the tests to use. """ from nose.plugins import Plugin from pyvirtualdisplay import Display from seleniumbase.core import proxy_helper from seleniumbase.fixtures import constants class SeleniumBrowser(Plugin): """ The...
ify_delay', default=None, help="""Setting this overrides the default wait time before each MasterQA verification pop-up.""") parser.add_option( '--timeout_multiplier', action='store', dest='timeout_multiplier', default=None, help=""...
ltiplier when waiting for page elements. Unused when tests overide the default value.""") def configure(self, options, conf): super(SeleniumBrowser, self).configure(options, conf) self.enabled = True # Used if test class inherits BaseCase self.options = options ...
nsavch/xanmel
xanmel/logcfg.py
Python
gpl-3.0
723
0
def logging_config(level): return { 'version': 1, 'propagate': True, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '%(asctime)s [%(levelname)s] %(message)s' } },
'handlers': {
'console': { 'class': 'logging.StreamHandler', 'level': level, 'formatter': 'simple' } }, # 'loggers': { # 'asyncio': { # 'level': 'DEBUG', # 'handlers': ['console'] # }, ...
Justyer/KuaikanSpider
KuaikanSpider/KuaikanSpider/pipelines.py
Python
mit
1,794
0.002787
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import codecs import scrapy from collections import OrderedDict from scrapy.pipelines.images import ImagesPipeline...
n' picindex = picindex + 1 self.file.write(line) return item class ImgDownload
Pipeline(ImagesPipeline): def get_media_requests(self, item, info): if item['image_urls'] is not None: for image_url in item['image_urls']: yield scrapy.Request(image_url) def item_completed(self, results, item, info): image_paths = [x['path'] for ok, x in results i...
wwj718/edx-video
lms/djangoapps/instructor/tests/test_hint_manager.py
Python
agpl-3.0
7,620
0.001969
import json from django.test.client import Client, RequestFactory from django.test.utils import override_settings from courseware.models import XModuleContentField from courseware.tests.factories import ContentFactory from courseware.tests.tests import TEST_DATA_MONGO_MODULESTORE import instructor.hint_manager as vie...
self.assertTrue('3.14' in json.loads(problem_hints)) def test_approve(self): """ Check that instructors can approve hints. (Move them from the mod_queue to the hints.) """ request = RequestFactory() post = request.post(self.url, {'field': 'mod_queue', ...
1: [self.problem_id, '2.0', '2']}) view.approve(post, self.course_id, 'mod_queue') problem_hints = XModuleContentField.objects.get(field_name='mod_queue', definition_id=self.problem_id).value self.assertTrue('2.0' not in json.loads(problem_hints) or len(json.loads(probl...
omprakasha/odoo
openerp/osv/orm.py
Python
agpl-3.0
6,222
0.002572
import simplejson from lxml import etree from ..exceptions import except_orm from ..models import ( MetaModel, BaseModel, Model, TransientModel, AbstractModel, MAGIC_COLUMNS, LOG_ACCESS_COLUMNS, ) from openerp.tools.safe_eval import safe_eval as eval # extra definitions for backward compatibilit...
ult_values[modif[0]] != modif[1]: state_exceptions[modif[0]].append(state) for attr, default_value in default_values.items(): if state_exceptions[attr]:
modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])] else: modifiers[attr] = default_value # Don't deal with groups, it is done by check_group(). # Need the context to evaluate the invisible attribute on tree views. # For non-tree views, the context should...
nylas/sync-engine
tests/imap/network/test_drafts_syncback.py
Python
agpl-3.0
3,701
0
import uuid from datetime import datetime import pytest from tests.util.crispin import crispin_client ACCOUNT_ID = 1 NAMESPACE_ID = 1 THREAD_ID = 2 # These tests use a real Gmail test account and idempotently put the account # back to the state it started in when the test is done. @pytest.fixture(scope='function'...
INBOX-ID'] with crispin_client(account.id, account.provider) as c: criteria = ['DRAFT', 'NOT DELETED', 'HEADER X-INBOX-ID {0}'.format(inbox_uid)] c.conn.select_folder(account.drafts_folder.name, readonly=False) uids = c.co
nn.search(criteria) assert uids, 'Message missing from Drafts folder' # Delete on remote remote_delete_draft(account, account.drafts_folder.name, inbox_uid, db.session) c.conn.select_folder(account.drafts_folder.name, readonly=False) uids = c.conn.se...
kwss/keystone
keystone/credential/backends/sql.py
Python
apache-2.0
3,229
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack 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 requ...
efs = session.query(CredentialModel).all() return [ref.to_dict() for ref in refs] def _get_creden
tial(self, session, credential_id): ref = session.query(CredentialModel).get(credential_id) if ref is None: raise exception.CredentialNotFound(credential_id=credential_id) return ref def get_credential(self, credential_id): session = self.get_session() return sel...
rizar/actor-critic-public
bin/pack_to_hdf5.py
Python
mit
2,224
0.001349
#!/usr/bin/env python import h5py import numpy import argparse import cPickle from fuel.datasets.hdf5 import H5PYDataset def pack(f, name, dataset_pathes): datasets = [cPickle.load(open(path)) for path in dataset_pathes] data = sum(datasets, []) dtype = h5py.special_dtype(vlen=numpy.dtype('int32')) t...
', default=False, help="Add integer IDs") pa
rser.add_argument('dest', help="Destination") args = parser.parse_args() assert len(args.sources) == len(args.targets) assert len(args.sources) == len(args.names) with h5py.File(args.dest, mode='w') as f: lengths = pack(f, "sources", args.sources) assert numpy.all(lengths == pack(f, "ta...
atykhonov/fget
fget/settings.py
Python
mit
1,884
0
import os import pkg_resources import yaml from fget.utils import fgetprint from fget.resource.root import Root class CachedSettings(object): def __init__(self, cache_dir): self.cache_dir = cache_dir def init(self): settings_filename = 'fget.yaml' cached_filename = 'fget.jobs' ...
tr(job['name'])) with open(cached_settings_file, 'w') as f:
for key in self.cached_settings.keys(): f.write(key + '\n') for value in self.cached_settings[key]: f.write(value + '\n') fgetprint('Initiating. Finished.') else: with open(cached_settings_file) as f: for...
mogoweb/chromium-crosswalk
tools/perf/measurements/rasterize_and_record.py
Python
bsd-3-clause
7,809
0.005506
# Copyright (c) 2012 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 time from metrics import smoothness from telemetry.page import page_measurement class StatsCollector(object): def __init__(self, timeline): ...
d"] if best_rasterize_time == float('inf'): best_rasterize_time = 0 self.total_best_rasterize_
time += best_rasterize_time def GatherRecordStats(self, frame_number): for event in self.renderer_process.IterAllSlicesOfName( "PictureLayer::Update"): if event.args["source_frame_number"] == frame_number: for record_loop_event in event.GetAllSubSlicesOfName("RecordLoop"): best_re...
vileopratama/vitech
src/openerp/report/printscreen/ps_list.py
Python
mit
11,008
0.007813
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import openerp from openerp.report.interface import report_int import openerp.tools as tools from openerp.tools.safe_eval import safe_eval as eval from lxml import etree from openerp.report import render, report_sxw imp...
= model.read_group(cr, uid, domain, fields_order, groupby , 0, None, context) for rec in records: rec['__group'] = True rec['__no_leaf'] = self.groupby_no_leaf rec['__grouped_by'] = groupby[0] if (isinstance(groupby, list) and groupby) else g...
rec.update({f:False}) elif isinstance(rec[f], tuple): rec[f] = rec[f][1] rows.append(rec) inner_groupby = (rec.get('__context', {})).get('group_by',[]) inner_domain = rec.get('__domain', []) ...
spyder-ide/qtawesome
setupbase.py
Python
mit
12,662
0.001422
# -*- coding: utf-8 -*- import os import re import io import sys import csv import json import shutil import hashlib import zipfile import tempfile try: from fontTools import ttLib except ImportError: ttLib = None from urllib.request import urlopen import distutils.cmd import distutils.log HERE = os.path.ab...
: 'Font Awesome 5 Free Regular' # ID 2: 'Regular' # ID 3: 'Font
Awesome 5 Free Regular-5.14.0' # ID 4: 'Font Awesome 5 Free Regular' # ID 5: '331.264 (Font Awesome version: 5.14.0)' # ID 6: 'FontAwesome5Free-Regular' # ID 10: "The web's most popular icon set and toolkit." # ID 11: 'https://fontawesome.com' # ID 16: 'Font Awesome 5 Free' # ID 17: 'Regula...
vivhou/Python-coursework-files
final project data analysis/webscraping scripts/public_school_tuition_data.py
Python
artistic-2.0
2,976
0.023522
import requests import math import re from bs4 import BeautifulSoup ROOT_URL = "http://nces.ed.gov/collegenavigator" INDEX_URL = ROOT_URL + "?s=all&l=93&ct=1&ic=1&an=5&ax=50" PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg" def get_num_pages(pagination): """Returns the total number of pages given p...
ttrs={"id": "expenses"}) table = expenses.find("tbody") try: # Get In-state Tuition Change row = table.find(string="In-state").parent.parent cols = row.find_all("td") college['In-state'] = cols[5].get_text() # Get Out-of-state Tuition Change row = table.find(string="Out-of-state").parent.parent cols =...
has no tuition data, skipping!!" + '\033[0m') college['In-state'] = "-" college['Out-of-state'] = "-" # Get initial list of colleges and links print("Getting initial list of colleges") colleges = get_colleges() # Get additional tuition data for each college for college in colleges: print(college['name'] + ": Ret...
inspirehep/invenio-records
invenio_records/signals.py
Python
gpl-2.0
2,474
0
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 CERN. # # Invenio 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...
_insert = _signals.signal('before-record-insert') """Signal sent before a record is inserted. Example subscriber .. code-block:: python def listener(sender, *args, **kwargs): sender['key'] = sum(args) from invenio_records.signals import before_record_insert before_record_insert.connect( ...
tion are allowed on record object. """ before_record_update = _signals.signal('before-record-update') """Signal sent before a record is update.""" after_record_update = _signals.signal('after-record-update') """Signal sent after a record is updated.""" before_record_index = _signals.signal('before-record-index') """...
endlessm/chromium-browser
third_party/catapult/third_party/gsutil/gslib/vendored/boto/tests/integration/gs/test_basic.py
Python
bsd-3-clause
22,160
0.002211
# -*- coding: utf-8 -*- # Copyright (c) 2006-2011 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2010, Eucalyptus Systems, Inc. # Copyright (c) 2011, Nexenta Systems, Inc. # Copyright (c) 2012, Google, Inc. # All rights reserved. # # Permission is hereby granted, free of charge, t
o any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to ...
conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PA...
martinkiefer/join-kde
code/JoinSampleCodeGenerator.py
Python
gpl-3.0
10,901
0.013026
#Code generator for gauss kernel import Utils local_size = 64 def generatePreamble(f): print >>f, """ #pragma OPENCL EXTENSION cl_khr_fp64 : enable #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880168872420969808 #endif typedef double T; """ def rangeEstimateFunction(f): print >>f, """ unsigned...
with open("./%s_kernels.cl" % i,'w') as cf: generatePreamble(cf) cols = Utils.generateInvariantColumns(query) for j,indices in enumerate(cols): qtype.extend([query.tables[j].columns[index].type for index in indices ]) remap.extend([(j,index) fo
r index in indices ]) rangeEstimateFunction(cf) pointEstimateFunction(cf) generateEstimateKernel(cf,"estimate",qtype) with open("./%s_GPUJS.cpp" % i,'w') as cf: generateCIncludes(cf) generateGPUJoinSampleParameterArray(cf,query,estimator,qtype) Utils.generateGPUVector...
BambooHR/rapid
rapid/master/data/migrations/versions/ce9be6e8354c_test_history_date_created.py
Python
apache-2.0
1,560
0.005769
""" Copyright (c) 2015 Michael Bright and Bamboo HR LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in...
st_histories', sa.Column('date_created', sa.DateTime(), default=datetime.datetime.utcnow())) else: op.add_column('qa_test_histories'
, sa.Column('date_created', sa.DateTime(), nullable=False, server_default=func.now(), default=datetime.datetime.utcnow())) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('qa_test_histories', 'date_created') ### end Alembic comma...
ludia/kinesis_producer
kinesis_producer/accumulator.py
Python
mit
1,297
0
import time class RecordAcc
umulator(object): def __init__(self, buffer_class, config): self.config = config self.buffer_time_limit = con
fig['buffer_time_limit'] self._buffer_class = buffer_class self._reset_buffer() def _reset_buffer(self): self._buffer = self._buffer_class(config=self.config) self._buffer_started_at = None def try_append(self, record): """Attempt to accumulate a record. Return False if...
Taapat/enigma2-plugin-youtube
test/RcModel.py
Python
gpl-2.0
424
0.03066
class RcModel: RcModels = {} def r
cIsDefault(self): return True def getRcFile(self, ext=''): return ext def getRcFolder(self, GetDefault=True): return 'enigma2/data/' def getRcImg(self): return self.getRcFile('enigma
2/data/rc.png') def getRcPositions(self): return self.getRcFile('enigma2/data/rcpositions.xml') def getRcLocation(self): return self.getRcFile('enigma2/data/') rc_model = RcModel()
xbmc/atv2
xbmc/lib/libPython/Python/Lib/test/test_codecmaps_cn.py
Python
gpl-2.0
1,062
0.00565
#!/usr/bin/env python # # test_codecmaps_cn.py # Codec mapping tests for PRC encodings # # $CJKCodecs: test_codecmaps_cn.py,v 1.3 2004/06/19 06:09:55 perky Exp $ from test import test_support from test import test_multibytecodec_support import unittest class TestGB2312Map(test_multibytecodec_support.TestBase_Mappin...
t.TestCase): encoding = 'gb2312' mapfilename = 'EUC-CN.TXT' mapfileurl = 'http://people.freebsd.org/~perky/i18n/EUC-CN.TXT' class TestGBKMap(test_multibytecodec_support.TestBase_Mapping, unittest.TestCase): encoding = 'gbk' mapfilename = 'CP936.TXT' mapfil
eurl = 'http://www.unicode.org/Public/MAPPINGS/VENDORS/' \ 'MICSFT/WINDOWS/CP936.TXT' def test_main(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestGB2312Map)) suite.addTest(unittest.makeSuite(TestGBKMap)) test_support.run_suite(suite) test_multibytecodec_support....
ShaguptaS/python
bigml/tests/create_dataset_steps.py
Python
apache-2.0
5,400
0.005926
import time import json from datetime import datetime, timedelta from world import world, res_filename from bigml.api import HTTP_CREATED from bigml.api import HTTP_OK from bigml.api import HTTP_ACCEPTED from bigml.api import FINISHED from bigml.api import FAULTY from bigml.api import get_status import read_dataset_st...
def make_the_dataset_public(
step): resource = world.api.update_dataset(world.dataset['resource'], {'private': False}) world.status = resource['code'] assert world.status == HTTP_ACCEPTED world.location = resource['location'] world.dataset = resource['object'] #@step(r'I get the dataset ...
proteus-cpi/pyside-chaco-template
chaco-in-pyside/chaco-in-pyside/__main__.py
Python
lgpl-3.0
147
0.006803
from ChacoInPyS
ideUi import * import sys if __name__ == '__main__': print "Starting chaco_in_pysi
de app" ChacoInPySideUi_main(sys.argv)
ritstudentgovernment/PawPrints
petitions/management/commands/renderfiles.py
Python
apache-2.0
3,203
0.000312
""" Renders css/js files to use config data in config.yml Peter Zujko """ from django.core.management.base import BaseCommand from django.conf import settings from django.template.loader import render_to_string from os import listdir from os.path import isfile, join import os import json import base64 class Comma...
settings.BASE_DIR, 'static/css/'+file) elif ext == "js": static_dir = os.path.join(settings.BASE_DIR, 'static/js/'+file) with open(static_dir, 'w+') as f: f.writ
e(template) print("Rendered the following " + str(petition_file_names) + str(profile_file_names))
witten/borgmatic
tests/integration/config/test_validate.py
Python
gpl-3.0
6,931
0.001299
import io import string import sys import pytest from flexmock import flexmock from borgmatic.config import validate as module def test_schema_filename_returns_plausable_path(): schema_path = module.schema_filename() assert schema_path.endswith('/schema.yaml') def mock_config_and_schema(config_yaml, sche...
acking_examples_does_not_raise(): mock_config_and_schema( ''' location: source_directories: - /home repositories: - hostname.borg ''', ''' map: location: required: true map: ...
required: true seq: - type: scalar ''', ) module.parse_configuration('config.yaml', 'schema.yaml') def test_parse_configuration_inlines_include(): mock_config_and_schema( ''' location: source_directori...
benaustin2000/ShanghaiHousePrice
GetChengJiaoListV0.2.py
Python
apache-2.0
7,661
0.022519
# -*- coding: utf-8 -*- """ Created on Tue Nov 27 23:40:50 2018 @author: austin """ import requests import re from bs4 import BeautifulSoup,SoupStrainer #import matplotlib.pyplot as plt from fake_useragent import UserAgent import time,random,sys import pandas#pandas大法好 #ua=UserAgent()#使用随机header,模拟人类 #headers1={'Us...
ftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time())) df.to_csv(datetimestr+'-'+HouseLocMajorString+'-LianJia.csv') begin = time.time() for PianQuGet in PianQuList:
i=1 RetryTimes=0 PianQuNum=PianQuList.index(PianQuGet) while i<=TotalPage: # 100页最大值 #http://sh.lianjia.com/chengjiao/tangzhen/pg1/ domain = 'http://sh.lianjia.com'+PianQuLink[PianQuNum]+'pg'+str(i) headers1 = {'User-Agent': UserAgent().random, 'Accept-Language': 'zh-CN,zh;q=0.8'}#使用...
ooici/coi-services
ion/agents/data/test/test_dsa_moas_dosta.py
Python
bsd-2-clause
2,513
0.004377
#!/usr/bin/env python """ @package ion.agents.data.test.test_moas_dosta @file ion/agents/data/test_moas_dosta @author Bill French @brief End to end testing for moas dosta """ __author__ = 'Bill French' import gevent from pyon.public import log from nose.plugins.attrib import attr from ion.agents.data.test.dataset_...
nitialize( instrument_device_name = 'DOSTA-01', preload_scenario= 'GENG,DOSTA', stream_name= 'ggldr_dosta_delayed', # Uncomment this line to load driver from a locak repository #mi_repo = '/Users/wfrench/Workspace/code/wfrench/marine-integrations' ) ...
"" Verify file import and connection ids """ self.assert_initialize() self.create_sample_data("moas_dosta/file_1.mrg", "unit_363_2013_245_6_6.mrg") self.create_sample_data("moas_dosta/file_2.mrg", "unit_363_2013_245_10_6.mrg") granules = self.get_samples(self.test_confi...
Boussadia/weboob
modules/sachsen/pages.py
Python
agpl-3.0
4,869
0.004518
# -*- coding: utf-8 -*- # Copyright(C) 2010-2014 Florent Fourcot # # 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...
() img = Regexp(Attr('.//img', 'src'), "(.*?)/(.*)", "\\2")(div) data = unicode(el.attrib['onmouseover']) \ .strip('pegelein(').strip(')').replace(",'", ",").split("',") self.env['id'] = data[7].strip() self.env['name'] = data[0]
self.env['object'] = data[1] self.env['datetime'] = data[2] self.env['levelvalue'] = data[3] self.env['flowvalue'] = data[4] self.env['forecast'] = data[5] self.env['alarm'] = img def add_sensor(self, sensors, name...
DJones81/GTNewsDev
gtnewsdev/geonewsapi/migrations/0017_auto_20151201_1555.py
Python
gpl-2.0
420
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('geonewsapi', '0016_auto_20
151201_1517'), ] operations = [ migrations.AlterField( model_name='article',
name='category', field=models.CharField(max_length=20, blank=True), ), ]