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
fablab-bayreuth/fablight
Fablight-Gui/hsv_picker.py
Python
mit
16,281
0.021559
from numpy import * from colorsys import * import Tkinter as tk import ttk import PIL.Image, PIL.ImageTk #----------------------------------------------------------------------------------------- # HSV picker # Three horizontal scales for Hue, Sat, Val class HSV_Picker: panel_size = 290, 32 hue, sat, val = ...
x=8, pady=0, sticky=tk.W) self.sat_panel.grid(
column=0, row=3, padx=8, pady=(0,6), sticky=tk.W+tk.E) tk.Label(self.frame, text='Value (Brightness)').grid(column=0, row=4, padx=8, pady=0, sticky=tk.W) self.val_panel.grid(column=0, row=5, padx=8, pady=(0,6), sticky=tk.W+tk.E) ##self.hue_panel.grid(column=0, row=0, padx=8, pady=8, sticky=tk.W+...
dani-i/bachelor-project
graphics/output/test_sess/test_sess_overall_results_output_f.py
Python
apache-2.0
5,036
0.000397
from graphics.widgets.single_line_output_f import SingleLineOutputF from utils.test_sess_overall_results import TestSessOverallResults import constants.output_constants as const import tkinter as tk class TestSessOverallResultsOutputF(tk.Frame): """ - Use to display overall results for a test session. ""...
se ValueError('Overall results are not valid:\n\n' + str(overall_results)) def enable(self): """ Enables all the widgets.""" self._lbl_title.config(state='normal') self._slo_precision.enable() self._slo_f_measure.enable() self._slo_subtitle.enab...
f._slo_identifiers_classes: item.enable() def disable(self): """ Disables all the widgets.""" self._slo_recall.disable() self._slo_subtitle.disable() self._slo_f_measure.disable() self._slo_precision.disable() self._lbl_title.config(state='disabled') ...
AutorestCI/azure-sdk-for-python
azure-servicefabric/azure/servicefabric/models/restart_deployed_code_package_description.py
Python
mit
1,899
0.002106
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
str'}, 'code_package_instance_id': {'
key': 'CodePackageInstanceId', 'type': 'str'}, } def __init__(self, service_manifest_name, code_package_name, code_package_instance_id, service_package_activation_id=None): self.service_manifest_name = service_manifest_name self.service_package_activation_id = service_package_activation_id ...
SimyungYang/py-flask-signup
application.py
Python
apache-2.0
4,769
0.00692
# Copyright 2013. Amazon Web Services, 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 ...
s" % ex.message) @application.errorhandler(404) def not_found_error(error): print u'{ "Page Not Found": "%s" }' % error theme = application.config['THEME'] return flask.render_template('404.html', theme=theme, title='404 File Not Found'), 404 @application.errorhandler(500) def internal_error(error): ...
'500.html', theme=theme, title='Unexpected Error Occured'), 500 if __name__ == '__main__': application.run(host='0.0.0.0')
aidanheerdegen/payu
payu/fsops.py
Python
apache-2.0
4,890
0.003067
# coding: utf-8 """payu.experiment =============== Basic file system operations for Payu :copyright: Copyright 2011 Marshall Ward, see AUTHORS for details. :license: Apache License, Version 2.0, see LICENSE for details. """ # Standard library import errno import sys, os import subprocess import shlex # ...
path into all directories and files.""" head, tail = os.path.split(path) if tail == '': return head, elif head == '': return tail, else: return splitpath(head) + (tail,) def patch_lustre_path(f_path): """Patch any 60-character pathnames, to avoid a current Lustre bug.""" ...
= './' + f_path return f_path def get_commit_id(filepath): """ Return git commit hash for filepath """ cmd = shlex.split("git log -n 1 --pretty=format:%H -- ") cmd.append(filepath) try: with open(os.devnull, 'w') as devnull: hash = subprocess.check_output(cmd, stderr=d...
adelina-t/compute-hyperv
hyperv/nova/__init__.py
Python
apache-2.0
687
0
# Copyright (c) 2014 C
loudbase Solutions Srl # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License.
You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or impli...
imoverclocked/ServoBot
apwm_home/controller/controller/settings.py
Python
mit
5,602
0.001428
# Django settings for controller project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Tim Spriggs', 'tims@arizona.edu'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '/home/apw...
s.DefaultSt
orageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '^0@$9mm^v@+f#^su8&ee+=1y8q44#t2+$aiy%@)c6e1%_o27o$' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_...
sunfounder/SunFounder_SensorKit_for_RPi2
Python/15_joystick_PS2.py
Python
gpl-2.0
1,235
0.045344
#!/usr/bin/env pytho
n3 #------------------------------------------------------ # # This is a program for JoystickPS2 Module. # # This program depend on PCF8591 ADC chip. Follow # the ins
truction book to connect the module and # ADC0832 to your Raspberry Pi. # #------------------------------------------------------ import PCF8591 as ADC import time def setup(): ADC.setup(0x48) # Setup PCF8591 global state def direction(): #get joystick result state = ['home', 'up', 'down', 'left', 'right', '...
krathjen/studiolibrary
src/mutils/tests/test_attribute.py
Python
lgpl-3.0
5,307
0.002638
# Copyright 2020 by Kurt Rathjen. All Rights Reserved. # # This library is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. This ...
when setting animation keyframe" def test_attribute_limit3(self): """ Test the minimum attribute limit when setting a keyframe. """ attr = mutils.Attribute("sphere", "testLimit") attr.setKeyframe(-200) value = maya.cmds.keyframe("sphere.testLimit", query=True, eval...
animation keyframe" def test_non_keyable(self): """ Test if non-keyable attributes can be keyed. """ range_ = (-100, 100) maya.cmds.cutKey("sphere", cl=True, time=range_, f=range_, at="testNonKeyable") attr = mutils.Attribute("sphere", "testNonKeyable") attr...
dwatkinsweb/django-skin
skin/views/views.py
Python
mit
1,288
0.001553
from django.contrib.sites.models import Site from django.utils._os import safe_join from django.views.generic import TemplateView from skin.conf import settings from skin.template.loaders.util import get_site_skin class TemplateSkinView(TemplateView): """ A view that extends Djangos base TemplateView to allo...
ot None: for template_name in template_names: skin_template_
names.append(safe_join(skin_path, template_name)) return skin_template_names + template_names
PaddlePaddle/Paddle
python/paddle/fluid/nets.py
Python
apache-2.0
27,095
0.004687
# 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...
st or tuple, it must contain two integers, (conv_stride_H, conv_stride_W). Otherwise, the conv_stride_H = conv_stride_W = conv_stride. Default: conv_stride = 1. conv_padding (int|list|tuple): The padding size of the conv2d Layer. If padding is a list or tuple, it must contain two
integers, (conv_padding_H, conv_padding_W). Otherwise, the conv_padding_H = conv_padding_W = conv_padding. Default: conv_padding = 0. conv_dilation (int|list|tuple): The dilation size of the conv2d Layer. If dilation is a list or tuple, it must contain two integers, (conv_dilation_H, con...
Thetoxicarcade/ac
congredi/auth/test/test_token.py
Python
gpl-3.0
1,288
0.000776
#!/usr/bin/env python # -*-
coding: utf-8 -*- """ JWT tokens (for web interface, mostly, as all peer operations function on public key cryptography) JWT tokens can be one of: * Good * Expired * Invalid And granting them should not take database access. They are mea
nt to figure out if a user is auth'd without using the database to do so. """ from __future__ import absolute_import from __future__ import unicode_literals import datetime from ...utils.timing import TimedTestCase from ..token import token, jwt_get, jwt_use class test_token(TimedTestCase): def test_good_token(...
rlindner81/pyload
module/plugins/hoster/OronCom.py
Python
gpl-3.0
493
0
# -*- coding: utf-8 -*- from module.p
lugins.internal.DeadHoster import DeadHoster class OronCom(DeadHoster): __name__ = "OronCom" __type__ = "hoster" __version__ = "0.18" __status__ = "stable" __pattern__ = r'https?://(?:www\.)?o
ron\.com/\w{12}' __config__ = [] # @TODO: Remove in 0.4.10 __description__ = """Oron.com hoster plugin""" __license__ = "GPLv3" __authors__ = [("chrox", "chrox@pyload.org"), ("DHMH", "DHMH@pyload.org")]
paour/weblate
weblate/trans/migrations/0027_auto__chg_field_subproject_template.py
Python
gpl-3.0
15,556
0.007716
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # 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, eithe...
{'ordering': "['name']", 'object_name': 'Language'}, 'code': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'direction': ('django.db.models.fields.CharField', [], {'default': "'ltr'", 'm
ax_length': '3'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'nplurals': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}), 'plural_type': ('django....
ATNF/askapsdp
Tools/Dev/rbuild/askapdev/rbuild/utils/pkginfo.py
Python
gpl-2.0
3,666
0.004364
# @brief helper function to turn pkgconfig files into ASKAP package.info # # @copyright (c) 2006 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Ep
ping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ASKAP software distribution. # # The ASKAP software distribution 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 the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABI...
heiths/allura
Allura/allura/lib/helpers.py
Python
apache-2.0
42,752
0.000678
# -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apach...
, and user names re_project_name = re.compile(re_mount_points['re_project_name']) # validat
es tool mount point names re_tool_mount_point = re.compile(re_mount_points['re_tool_mount_point']) re_tool_mount_point_fragment = re.compile(re_mount_points['re_tool_mount_point_fragment']) re_relaxed_tool_mount_point = re.compile(re_mount_points['re_relaxed_tool_mount_point']) re_relaxed_tool_mount_point_fragment = re...
RevansChen/online-judge
Codefights/arcade/python-arcade/level-5/34.Multiplication-Table/Python/test.py
Python
mit
2,320
0.007759
# Python3 from solution1 import multiplicationTable as f qa = [ (5, [[1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], [4, 8, 12, 16, 20], [5, 10, 15, 20, 25]]), (2, [[1, 2], [2, 4]]), (4, [[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12...
print('
[ok]') print(' output:', ans) print()
01org/cloudeebus
setup.py
Python
apache-2.0
1,949
0.040021
#!/usr/bin/env python # Cloudeebus # # Copyright (C) 2012 Intel Corporation. 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/LICEN...
uiraud@intel.com> # Frederic Paut <frederic.paut@intel.com> # Patrick Ohly <patrick.ohly@intel.com> # from setuptools import setup setup(name = "cloudeebus", version = "0.6.1", description = "J
avascript-DBus bridge", author = "Luc Yriarte, Christophe Guiraud, Frederic Paut, Patrick Ohly", author_email = "luc.yriarte@intel.com, christophe.guiraud@intel.com, frederic.paut@intel.com, patrick.ohly@intel.com", url = "https://github.com/01org/cloudeebus/wiki", license = "http://www.apache.org/licenses/LICENSE-...
Kryz/sentry
src/sentry/web/frontend/project_notifications.py
Python
bsd-3-clause
3,802
0.000263
from __future__ import absolute_import from django.conf import settings from django.contrib import messages from django.http import HttpResponseRedirect, HttpResponse from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from sentry import constants from sentry.models i...
ct.get_option( 'mail:subject_prefix', settings.EMAIL_SUBJECT_PREFIX), }, ) if general_form.is_valid(): project.update_opti
on( 'mail:subject_prefix', general_form.cleaned_data['subject_prefix']) messages.add_message( request, messages.SUCCESS, OK_SETTINGS_SAVED) return HttpResponseRedirect(request.path) else: general_form = Notif...
chippey/gaffer
python/GafferArnoldUITest/ArnoldShaderUITest.py
Python
bsd-3-clause
4,413
0.027646
########################################################################## # # Copyright (c) 2016, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
L THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, IND
IRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NE...
tensorflow/tensorflow
tensorflow/python/training/tracking/base_delegate.py
Python
apache-2.0
5,796
0.008282
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
ear as if it were the trackable passed to the constructor, from a Checkpoint's perspective. LossScaleOptimizer uses this mixin, so that the checkpoint format for a LossScaleOptimizer is identical to the checkpoint format for a normal optimizer.
This allows a model to be saved with a normal Optimizer and restored with a LossScaleOptimizer, or vice versa. The only difference in checkpoint format is that the loss scale is also saved with a LossScaleOptimizer. """ def __init__(self, trackable_obj): self._trackable = trackable_obj # pylint: disa...
madhat2r/plaid2text
src/python/plaid2text/renderers.py
Python
gpl-3.0
15,244
0.00105
#! /usr/bin/env python3 from abc import ABCMeta, abstractmethod import csv import os import re import subprocess import sys import plaid2text.config_manager as cm from plaid2text.interact import separator_completer, prompt class Entry: """ This represents one entry (transaction) from Plaid. """ def...
journal_file = options.journal_file self.journal_lines = [] self.options = options self.get_possible_accounts_and_payees() # Add payees/accounts/tags from mappings for m in self.mappings: self.possible_payees.add(m[1]) self.possible_accounts.add(m[2]) ...
[0].split(':'))) else: self.possible_tags.update([t.replace('#', '') for t in m[3][0].split(' ')]) def read_mapping_file(self): """ Mappings are simply a CSV file with three columns. The first is a string to be matched against an entry description. ...
TwilioDevEd/api-snippets
ip-messaging/rest/services/update-service/update-service.6.x.py
Python
mit
504
0
# Download the Python helper library from twilio.com/docs/
python/install import os from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/user/account # To set up environmental variables, see http://twil.io/secure account = os.environ['TWILIO_ACCOUNT_SID'] token = os.environ['TWILIO_AUTH_TOKEN'] client = Client(account, token) service = client.chat...
y_name="NEW_FRIENDLY_NAME" ) print(service.friendly_name)
epage/telepathy-bluewire
src/protocol/backend.py
Python
lgpl-2.1
13,051
0.022067
#!/usr/bin/python """ Resources: http://code.google.com/p/pybluez/ http://lightblue.sourceforge.net/ http://code.google.com/p/python-bluetooth-scanner """ from __future__ import with_statement import select import logging import bluetooth import gobject import util.misc as misc_utils _moduleLogger = logging.getL...
SS.LAN = BluetoothClass("LAN/Network Access Point") MAJOR_CLASS.AV = BluetoothClass("Audio/Video") MAJOR_CLASS.PERIPHERAL = BluetoothClass("Peripheral") MAJOR_CLASS.IMAGING = BluetoothClass("Imaging") MAJOR_CLASS.UNCATEGORIZED = BluetoothClass("Uncategorized") MAJOR_CLASS.MISCELLANEOUS.RESERVED = BluetoothClass("Reser...
BluetoothClass("Desktop workstation") MAJOR_CLASS.COMPUTER.SERVER = BluetoothClass("Server-class computer") MAJOR_CLASS.COMPUTER.LAPTOP = BluetoothClass("Laptop") MAJOR_CLASS.COMPUTER.HANDHELD = BluetoothClass("Handheld PC/PDA (clam shell)") MAJOR_CLASS.COMPUTER.PALM_SIZE = BluetoothClass("Palm sized PC/PDA") MAJOR_CL...
tilacog/rows
tests/tests_plugin_txt.py
Python
gpl-3.0
2,876
0.000696
# coding: utf-8 # Copyright 2014-2015 Álvaro Justen <https://github.com/turicas/rows/> # # 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 yo...
_line.split('|') if field.strip()] self.asse
rtEqual(expected_fields, fields) expected_fields = table_fields[2:5] self.assertNotEqual(expected_fields, table_fields) fobj.seek(0) rows.export_to_txt(utils.table, temp.file, field_names=expected_fields) fobj.seek(0) _, second_line = fobj.readline(), fobj.readline() ...
Zedmor/powerball
src/powerball/urls.py
Python
mit
852
0
from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static import profiles.urls import accounts.urls from . import views urlpattern
s = [ url(r'^$', views.HomePage.as_view(), name='home'), url(r'^users/', include(profiles.urls, namespace='profiles')), url(r'^admin/', include(admin.site.urls)), url(r'^', include(accounts.urls, namespace='accounts')), url(r'^post_url/$', views.HomePage.as_view(), name='post') ] # User-uploaded fi...
OT) # Include django debug toolbar if DEBUG is on if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
apyrgio/snf-ganeti
test/py/ganeti.mcpu_unittest.py
Python
bsd-2-clause
9,694
0.006911
#!/usr/bin/python # # Copyright (C) 2009, 2011 Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistributions of source code must retain the above copyright notice, # this l...
tted.pop(0) self.assertRaises(IndexError, self._submitted.pop) self.assertEqual(op1.priority, constants.OP_PRIO_LOW) self.assertTrue("OP_TEST_DUMMY" in op1.comment) self.assertEqual(op1.debug_level, 3) self.assertEqual(op2.priority, consta
nts.OP_PRIO_HIGH) self.assertEqual(op2.comment, "foobar") self.assertEqual(op2.debug_level, 3) class _FakeLuWithLocks: def __init__(self, needed_locks, share_locks): self.needed_locks = needed_locks self.share_locks = share_locks class _FakeGlm: def __init__(self, owning_nal): self._owning_n...
falcon-org/Falcon
test/TestCache.py
Python
bsd-3-clause
2,048
0.025879
#!/usr/bin/env python import time makefile = ''' { "rules": [ { "inputs": [ "source1" ], "outputs": [ "output" ], "cmd": "cat source1 > output && cat source2 >> output && echo 'output: source1 source2' > deps", "depfile": "deps" } ] } ''' def set_version_1(test): test.writ...
"output"]) == set(test.get_dirty_targets())) test.build() assert(test.get_dirty_targets() == []) assert(test.get_file_content('output') == '23') set_version_1(test) test.expect_watchman_trigger("source1") test.expect_watchman_trigger("source2") assert(set(["source1", "source2", "output"]) == set(test.ge...
['cmds'][0] == { 'cache' : 'output' }) assert(test.get_dirty_targets() == []) assert(test.get_file_content('output') == '12') set_version_2(test) test.expect_watchman_trigger("source1") test.expect_watchman_trigger("source2") assert(set(["source1", "source2", "output"]) == set(test.get_dirty_targets())) ...
valley3405/testMongo01
test02.py
Python
gpl-2.0
2,298
0.046386
#!/usr/bin/env python #coding:utf-8 # Author: --<qingfengkuyu> # Purpose: MongoDB的使用 # Created: 2014/4/14 #32位的版本最多只能存储2.5GB的数据(NoSQLFan:最大文件尺寸为2G,生产环境推荐64位) import pymongo import datetime import random #创建连接 conn = pymongo.MongoClient('localhost',27017) #连接数据库 db = conn.study #db = conn['study'] #打印所有聚集名称,连接聚集...
print u'删除指定记录:\n',posts.find_one({"AccountID":22,"UserName":"libing"}) posts.remove({"AccountID"
:22,"UserName":"libing"}) #修改聚集内的记录 posts.update({"UserName":"urling"},{"$set":{'AccountID':random.randint(20,50)}}) #查询记录,统计记录数量 print u'记录总计为:',posts.count(),posts.find().count() print u'查询单条记录:\n',posts.find_one() print posts.find_one({"UserName":"liuw"}) #查询所有记录 print u'查询多条记录:' #for item in posts.find():#查询全...
wolf1986/log_utils
log_utils/helper.py
Python
lgpl-3.0
4,265
0.001407
import datetime import io import logging import logging.handlers import os import sys from collections import deque from time import perf_counter import colorlog class LogHelper: FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{') FORMATTER = logging.F...
e.datetime.now() if with_ms: return time.strftime('%Y%m%d_%H%M%S.%f')[:-3] else: return time.strftime('%Y%m%d_%H%M%S') class PerformanceMetric: def __init__(self, *, n_samples=1000, units_suffix='', units_format='.2f', name=None): super().__init__() self.n...
t def reset(self): self.total = 0 self.last = 0 self.queue_samples.clear() @property def n_samples(self): return len(self.queue_samples) def __str__(self): str_name = f'[{self.name}] ' if self.name else '' if self.n_samples == 0: return f'{s...
lalinsky/mb2freedb
mb2freedb/utils.py
Python
mit
2,120
0.000472
# Copyright (C) 2011 Lukas Lalinsky # Distributed under the MIT license, see the LICENSE file for details. import re import syslog from logging import Handler from logging.handlers import SysLogHandler class LocalSysLogHandler(Handler): """ Logging handler that logs to the local syslog using the syslog modul...
Handler.__init__(self) self.facility = facility if isinstance(facility, basestring): self.facility = self.facility_names[facility] options = 0 if log_pid: options |= syslog.LOG_PID syslog.openlog(ident, options, self.facility) self.format
ter = None def close(self): Handler.close(self) syslog.closelog() def emit(self, record): try: msg = self.format(record) if isinstance(msg, unicode): msg = msg.encode('utf-8') priority = self.priority_map[record.levelname] ...
HanWenfang/syncless
examples/demo_gevent_only.py
Python
apache-2.0
4,479
0.016522
#! /usr/local/bin/stackless2.6 # by pts@fazekas.hu at Fri Jun 17 14:08:07 CEST 2011 """Demo for hosting a gevent application with Stackless, without Syncless.""" __author__ = 'p
ts@fazekas.hu (Peter Szabo)' import sys # Import best_greenlet before gevent to add greenlet emulation for Stackless # if necessary. import syncless.best_greenlet import gevent import gevent.hub import gevent.socket class Lprng(object): __slots__ = ['seed'] def __init__(self, seed=0): self.seed = int(seed) &...
ef next(self): """Generate a 32-bit unsigned random number.""" # http://en.wikipedia.org/wiki/Linear_congruential_generator self.seed = ( ((1664525 * self.seed) & 0xffffffff) + 1013904223) & 0xffffffff return self.seed def __iter__(self): return self def Worker(client_socket, addr): pri...
feliam/pysymemu
setup.py
Python
bsd-3-clause
1,306
0.022971
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "pysymemu", version = "0.0.1-alpha", author = "Felipe Andres Manzano", author_email = "feliam@binamuse.com", description = ("A tool for symbolic execution of...
"Natural Language :: English", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 2.7", "Topic :: Software Development :: Testing" "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Deve
lopment :: Quality Assurance", ], test_suite="test", )
srange/SU2
preconfigure.py
Python
lgpl-2.1
28,082
0.012143
#!/usr/bin/env python ## \file configure.py # \brief An extended configuration script. # \author T. Albring # \version 6.2.0 "Falcon" # # The current SU2 release has been coordinated by the # SU2 International Developers Society <www.su2devsociety.org> # with selected contributions from the open-source community. #...
s-through" option parsing -- an OptionParser that ignores # unknown options and lets them pile up in the leftover argument # list. Useful to pass u
nknown arguments to the automake configure. class PassThroughOptionParser(OptionParser): def _process_long_opt(self, rargs, values): try: OptionParser._process_long_opt(self, rargs, values) except BadOptionError as err: self.largs.append(err.opt_str) def _process_short_...
dougo/chugchanga-poll
musicbrainz.py
Python
agpl-3.0
3,581
0.004747
# Copyright 2009-2010 Doug Orleans. Distributed under the GNU Affero # General Public License v3. See COPYING for details. from google.appengine.api import urlfetch import urllib from xml.dom import minidom import time mbns = 'http://musicbrainz.org/ns/mmd-1.0#' extns = 'http://musicbrainz.org/ns/ext-1.0#' # Since...
return ReleaseGroup.search(artistid=self.id) @classmethod def search(cls, **fields): artists = cls.searchElements(**fields) return [Artist(elt=elt) for elt in artists] class ReleaseGroup(Resource): type = 'release-group' def __init__(self, id=None, elt=None): if elt == None: ...
d, 'artist') self.score = elt.getAttributeNS(extns, 'score') self.id = elt.getAttribute('id') self.type = elt.getAttribute('type') self.artist = Artist(elt=elementField(elt, 'artist')) self.title = elementFieldValue(elt, 'title') @classmethod def search(cls, **fields): ...
Aurorastation/BOREALISbot2
cogs/dm_eval.py
Python
agpl-3.0
13,511
0.003553
import os import aiohttp import random import string import asyncio import shutil import re from threading import Thread from io import BytesIO from zipfile import ZipFile from discord.ext import commands from core import BotError DEFAULT_MAJOR = "512" DEFAULT_MINOR = "1416" class WindowsProcessThread(Thread): ...
ose pieces do not exist, they are to be set as None. As to avoid key errors further down the call stack. """ res = self._arg_expression.match(code) if not res or not res.groupdict(): raise BotError("No valid code sent.", "process_args") code_segs = {"pre
_proc": None, "proc": None, "to_out": None} res_dict = res.groupdict() for key in code_segs: if key in res_dict: code_segs[key] = res_dict[key] if (code_segs["pre_proc"] and not code_segs["pre_proc"].endswith(";") and not code_segs...
marshallward/payu
payu/models/test.py
Python
apache-2.0
649
0
"""Test driver interface :copyright: Copyright 2019 Marshall Ward, see AUTHORS
for details :license: Apache License, Version 2.0, see LICENSE for details """ import os import shlex import shutil import subprocess from payu.models.model import Model config_files = [ 'data', 'diag', 'input.nml' ] class Test(Model): def __init__(self, expt, name,...
uration self.model_type = 'test' self.default_exec = 'test.exe' self.config_files = config_files
cyanogen/uchroma
uchroma/client/dbus_client.py
Python
lgpl-3.0
2,107
0.002373
# # uchroma - Copyright (C) 20
21 Stefanie Kondik # # This program is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published # by the Free Software Foundation, version 3. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without eve...
ICULAR PURPOSE. See the GNU Lesser General Public # License for more details. # # pylint: disable=invalid-name import re import pydbus BASE_PATH = '/org/chemlab/UChroma' SERVICE = 'org.chemlab.UChroma' class UChromaClient(object): def __init__(self): self._bus = pydbus.SessionBus() def get_dev...
rentalita/django-lutefiskdemo
src/python/lutefiskdemo/development.py
Python
mit
475
0
#
-*- coding: utf-8 -*- from lutefiskdemo.settings import * DEBUG = True TEMPLATE_DEBUG = DEBUG SITE_ID = 1 MAINTENANCE_MODE = 'DEVELOPMENT'
EMAIL_PORT = 1025 INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE_CLASSES += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INTERNAL_IPS = ( '127.0.0.1', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, } # Local Variables: # indent-tabs-mode: nil # End: # vim: ai et...
sou81821/chainer
cupy/elementwise.py
Python
mit
22,222
0
import string import numpy import six import cupy from cupy import carray from cupy import cuda from cupy import util six_range = six.moves.range six_zip = six.moves.zip def _get_simple_elementwise_kernel( params, operation, name, preamble, loop_prep='', after_loop='', options=()): module_code...
elif not isinstanc
e(arg, scalar_type): raise TypeError('Unsupported type %s' % type(arg)) def _get_args_info(args): ret = [] carray_Indexer = carray.Indexer ret_append = ret.append for a in args: t = type(a) if t == carray_Indexer: dtype = None else: dtype = a...
LoganRickert/foox
test/species/test_fourth.py
Python
mit
6,328
0.000474
""" Tests for the module that encompasses fourth species counterpoint. """ import unittest from foox.species.fourth import (Genome, create_population, is_parallel, make_fitness_function, make_generate_function, make_halt_function, MAX_REWARD, REWARD_SUSPENSION) from foox.species.utils import is_suspension # T...
he mutation_range and mutation_rate are used correctly given the context given by a cantus firmus. """ cantus_firmus = [1, 1, 1, 1, 1] # mutate every time. mutation_rate = 1 # will always mutate to thirds above the cf note. mutation_range = 2 genom...
mus) self.assertEqual([3, 3, 3, 3, 3], genome.chromosome)
mrawls/APO-1m-phot
imginventory.py
Python
mit
9,017
0.007541
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from astropy.io import ascii import astropy.coordinates as coord import astropy.units as u from astropy.time import Time from astropy.time import TimeDelta import os ''' Read in 1m observation metadata t...
on* index here # Save eclipse midpoints pri_eclipse_mid[j].append(newbjd0 + i*Porbs_time[j]) sec_eclipse_mid[j].append(newbjd0 + i*Porbs_time[j] + sep[j]*Porbs_time[j]) # Save primary eclipse start & end times pri_eclipse_start[j].append(pri_eclipse_mid[j][i] - pwid[j]*Porbs_time...
.append(pri_eclipse_mid[j][i] + pwid[j]*Porbs_time[j]/2) # Save secondary eclipse start & end times sec_eclipse_start[j].append(sec_eclipse_mid[j][i] - swid[j]*Porbs_time[j]/2) sec_eclipse_end[j].append(sec_eclipse_mid[j][i] + swid[j]*Porbs_time[j]/2) print('Done') # Make a plot as a function o...
nkgilley/home-assistant
homeassistant/components/rfxtrx/__init__.py
Python
apache-2.0
13,930
0.000431
"""Support for RFXtrx devices.""" import binascii from collections import OrderedDict import logging import RFXtrx as rfxtrxmod import voluptuous as vol from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_NAME, ATTR_STATE, CONF_DEVICE, CONF_DEVICES, CONF_HOST, CONF_PORT, EVENT_HOMEA...
ATA_BITS = "data_bits" CONF_AUTOMATIC_ADD = "automatic_a
dd" CONF_DATA_TYPE = "data_type" CONF_SIGNAL_REPETITIONS = "signal_repetitions" CONF_FIRE_EVENT = "fire_event" CONF_DUMMY = "dummy" CONF_DEBUG = "debug" CONF_OFF_DELAY = "off_delay" EVENT_BUTTON_PRESSED = "button_pressed" DATA_TYPES = OrderedDict( [ ("Temperature", TEMP_CELSIUS), ("Temperature2", T...
pannellr/3132GroupProject
modules/database/where.py
Python
unlicense
34
0.029412
class
Where: string
= ''
timsnyder/bokeh
bokeh/sampledata/us_cities.py
Python
bsd-3-clause
1,884
0.010085
#----------------------------------------------------------------------------- # Co
pyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with thi
s software. #----------------------------------------------------------------------------- ''' ''' #----------------------------------------------------------------------------- # Boilerplate #----------------------------------------------------------------------------- from __future__ import absolute_import, divisio...
lukas-hetzenecker/home-assistant
homeassistant/components/cast/media_player.py
Python
apache-2.0
31,771
0.000913
"""Provide functionality to interact with Cast devices on the network.""" from __future__ import annotations import asyncio from contextlib import suppress from datetime import datetime, timedelta import functools as ft import json import logging from urllib.parse import quote import pychromecast from pychromecast.co...
spatcher import async_dispatcher_connect from homeassistan
t.helpers.network import NoURLAvailableError, get_url import homeassistant.util.dt as dt_util from homeassistant.util.logging import async_create_catching_coro from .const import ( ADDED_CAST_DEVICES_KEY, CAST_MULTIZONE_MANAGER_KEY, CONF_IGNORE_CEC, CONF_UUID, DOMAIN as CAST_DOMAIN, SIGNAL_CAST...
smithbr/ut-itunes-import
import.py
Python
mit
5,276
0.005497
# -*- coding: utf-8 -*- """ this script is crap but I don't feel like fixing it. """ import shutil import os import sys import time import tempfile from bencode import * base_dir = tempfile.gettempdir() + "\\ut-itunes-import" item_list = [] file_count = 0 file_types = ['.mp3',] if "--help" in str(sys.argv[1]).low...
ADD_TO_ITUNES_SOURCE_FILE = str(FINISHED_FOLDER_PATH + "\\" + media_file) THIS_TORRENTS_FILE_LIST.append(ADD_TO_ITUNES_SOURCE_FILE) any_mp3s_in_here = True file_count += 1 print "Found %s %s files.....
if not THIS_TORRENTS_FILE_LIST == []: print str(THIS_TORRENTS_FILE_LIST) if not file_count > 0: print "Skipping copy..." else: print "Copying files to %s" + str(ADD_TO_ITUNES_FOLDER) for file in THIS_TO...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/stevedore/driver.py
Python
agpl-3.0
5,248
0
from .named import NamedExtensionManager class DriverManager(NamedExtensionManager): """Load a single plugin with a given name from the namespace. :param namespace: The namespace for the entry points. :type namespace: str :param name: The name of the driver to load. :type name: str :param inv...
args, invoke_kwds=invoke_kwds, on_load_failure_callback=on_load_failure_callback,
verify_requirements=verify_requirements, ) @classmethod def make_test_instance(cls, extension, namespace='TESTING', propagate_map_exceptions=False, on_load_failure_callback=None, verify_requirements=False): """Cons...
nathandh/udacity-fullstack-MovieTrailerWebsite
fresh_tomatoes.py
Python
mit
6,106
0.003767
import webbrowser import os import re # Styles and scripting for the page main_page_head = ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Fresh Tomatoes!</title> <!-- Bootstrap 3 --> <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap....
<div class="modal-content"> <a href="#" class="hanging-close" data-dismiss="modal" aria-hidden="true"> <img src="https://l
h5.ggpht.com/v4-628SilF0HtHuHdu5EzxD7WRqOrrTIDi_MhEG6_qkNtUK5Wg7KPkofp_VJoF7RS2LhxwEFCO1ICHZlc-o_=s0#w=24&h=24"/> </a> <div class="scale-media" id="trailer-video-container"> </div> </div> </div> </div> <!-- Main Page Content --> <div class="container"> <div...
woddx/privacyidea
setup.py
Python
agpl-3.0
5,648
0.001593
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os import glob import sys #VERSION="2.1dev4" VERSION="2.6dev5" # Taken from kennethreitz/requests/setup.py package_directory = os.path.realpath(os.path.dirname(__file__)) def get_file_contents(file_path): """Get the context of the file u...
yidea-fix-access-rights', 'tools/privacyidea-create-ad-users', 'tools/privacyidea-fetchssh.sh',
'tools/privacyidea-create-userdb.sh' ], extras_require={ 'dev': ["Sphinx>=1.3.1", "sphinxcontrib-httpdomain>=1.3.0"], 'test': ["coverage>=3.7.1", "mock>=1.0.1", "nose>=1.3.4", "responses>=0.4.0", "si...
mjstealey/exposures-api
python-client/exposures_api/models/date_range.py
Python
mit
4,058
0.000246
# coding: utf-8 """ Environmental Exposures API API for environmental exposure models for NIH Data Translator program OpenAPI spec version: 1.0.0 Contact: stealey@renci.org Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "L...
value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict")
else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/encodings/cp437.py
Python
gpl-3.0
34,564
0.019355
""" Python Character Mapping Codec cp437 generated from 'VENDORS/MICSFT/PC/CP437.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict...
P SINGLE AND RIGHT DOUBLE 0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x00d6: 0x2553, # BOX DRAWINGS
DOWN DOUBLE AND RIGHT SINGLE 0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT 0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT 0x00db: 0x2...
pcmoritz/ray-1
python/ray/tune/tests/test_horovod.py
Python
apache-2.0
3,092
0
import pytest import ray from ray import tune pytest.importorskip("horovod") try: from ray.tune.integration.horovod import ( DistributedTrainableCreator, _train_simple, _train_validate_session) except ImportError: pass # This shouldn't be reached - the test should be skipped. @pytest.fixture def r...
s teardown code. ray.shutdown() @pytest.fixture def ray_connect_cluster(): try: address_info =
ray.init(address="auto") except Exception as e: pytest.skip(str(e)) yield address_info # The code after the yield will run as teardown code. ray.shutdown() def test_single_step(ray_start_2_cpus): trainable_cls = DistributedTrainableCreator( _train_simple, num_hosts=1, num_slots=2) ...
chiamingyen/PythonCAD_py3
Interface/Entity/arrowitem.py
Python
gpl-2.0
1,388
0.029539
#QLinearGradient myGradient; #QPen myPen; #QPolygonF myPolygon; #QPainterPath myPath; #myPath.addPolygon(myPolygon); #QPainter painter(this); #painter.
setBrush(myGradient); #painter.setPen(myPen); #painter.drawPath(myPath); import math from PyQt5 import QtCore, QtGui, QtWidgets class ArrowItem(QtWidgets.QGraphicsItem): def definePath(self): poligonArrow=QtGui.QPolygonF() poligonArrow.append(QtCore.QPointF(0.0, 5.0)
) poligonArrow.append(QtCore.QPointF(60.0, 5.0)) poligonArrow.append(QtCore.QPointF(60.0, 10.0)) poligonArrow.append(QtCore.QPointF(80.0, 0.0)) poligonArrow.append(QtCore.QPointF(60.0, -10.0)) poligonArrow.append(QtCore.QPointF(60.0, -5.0)) poligonArrow.append(QtC...
A425/django-nadmin
nadmin/plugins/mobile.py
Python
mit
904
0.004425
#coding:utf-8 from nadmin.sites import site from nadmin.views import BaseAdminPlugin, CommAdminView class MobilePlugin(BaseAdminPlugin): def _test_mobile(self): try: return self.request.META['HTTP_USER
_AGENT'].find('Android') >= 0 or \ self.request.META['HTTP_USER_AGENT'].find('iPhone') >= 0 except Exception: return False def init_request(self, *args, **kwargs): return self._test_mobile() def get_context(self, context): #context['base_template'] = '
nadmin/base_mobile.html' context['is_mob'] = True return context # Media # def get_media(self, media): # return media + self.vendor('nadmin.mobile.css', ) def block_extrahead(self, context, nodes): nodes.append('<script>window.__admin_ismobile__ = true;</script>') site.reg...
JohnReid/biopsy
Python/bio_server/main_server.py
Python
mit
11,092
0.014245
import biopsy import bifa_server import base64, threading , os, socket from sslUserCheck import Check
UserEngine from soaplib.wsgi_soap import WSGISoapApp from soaplib.wsgi_soap import SoapServiceBase from soaplib.service import soapmethod from soaplib.client
import make_service_client from soaplib.serializers.primitive import String, Integer, Array, Boolean, Float from soaplib.serializers.binary import Attachment from soaplib.serializers.clazz import ClassSerializer # This does not need to be changed for local Windows testing LOCALID = 'wsbc.warwick.ac.uk' from tempfile ...
frostidaho/python-gpopup
tests/test_ipc2.py
Python
bsd-2-clause
2,655
0.008286
import pytest def test_pack_unpack(): header = ('json', 301) from gpopup.ipc import _pack_header, _unpack_header header_bytes = _pack_header(*header) header_out = _unpack_header(header_bytes) assert header == header_out assert header[0] == header_out.type assert header[1] == header_out.leng...
o(42) assert c.serial_method == 'json' assert kwargs == {} a
ssert pargs == [42,] c.kill_server() def test_no_server(IpcServer): Client = IpcServer.get_client() with pytest.raises(ConnectionError): Client().ping() def test_busy(IpcServer): serv = IpcServer() serv2 = IpcServer() assert serv.sock_name == serv2.sock_name Client = serv.get_clien...
Microvellum/Fluid-Designer
win64-vc/2.78/scripts/presets/tracking_camera/Nikon_DX.py
Python
gpl-3.0
192
0
import bpy camera = bpy.context.edit_movieclip.tracking.camera camera.sensor_width = 23.6 camera.units = 'MILLIMETERS' camera.pixel_aspect = 1 camera.k1 = 0.0
camera.k2 = 0.0 camera.k3 = 0
.0
felixbade/minecraft-proxy
app/server_manager/ec2.py
Python
artistic-2.0
902
0.001109
#!/usr/bin/env python import logging import boto.ec2 import config class EC2Client: def __init__(self): self.conn = boto.ec2.connect_to_region(config.ec2_region) def stop(self): if self.get_status() in ['running', 'pending']: logging.info('Stopping server...') self....
onfig.ec2_instance_id]) def start(self): if self.get_status() == 'stopped': logging.info('Starting server...') self.conn.start_instances(instance_ids=[config.ec2_instance_id]) def get_status(self): return self.get_instance()._sta
te.name def get_ip(self): return self.get_instance().ip_address def get_instance(self): for instance in self.conn.get_only_instances(): if instance.id == config.ec2_instance_id: return instance return None
martinjrobins/hobo
pints/tests/test_toy_stochastic_degradation_model.py
Python
bsd-3-clause
4,627
0
#!/usr/bin/env python3 # # Tests if the stochastic degradation (toy) model works. # # This file is part of PINTS (https://github.com/pints-team/pints/) which is # released under the BSD 3-clause license. See accompanying LICENSE.md for # copyright notice and full license details. # import unittest import numpy as np im...
model.simulate(parameters, times) self.assertEqual(len(values), len(times)) self.assertEqual(values[0], 20) self.assertEqual(values[-1], 0) self.assertTrue(np.all(values[1:] <= values[:-1])) def test_suggested(self): model = pints.toy.StochasticDegradationModel(20) t...
.assertTrue(len(times) == 101) self.assertTrue(parameters > 0) def test_simulate(self): times = np.linspace(0, 100, 101) model = StochasticDegradationModel(20) time, mol_count = model.simulate_raw([0.1]) values = model.interpolate_mol_counts(time, mol_count, times) s...
parallel-fs-utils/fs-drift
unit_test_module.py
Python
apache-2.0
295
0.00339
# for backwards compatibility with earlier python versions unit_test_module = None def get_unit_test_module(): try: import unittest u
nit_test_module = unittest except ImportError: import unittest2 unit_test
_module = unittest2 return unit_test_module
dagargo/phatty
tests/test_connector.py
Python
gpl-3.0
11,804
0.001779
# -*- coding: utf-8 -*- # # Copyright 2017 David García Goñi # # This file is part of Phatty. # # Phatty 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) a...
lue
(): return [i for i in range(0, 192)] self.connector.tx_message = Mock() self.connector.rx_message = Mock(side_effect=return_value) value = self.connector.get_panel() self.connector.tx_message.assert_called_once_with( phatty.connector.REQUEST_PANEL) self....
punalpatel/st2
contrib/runners/action_chain_runner/tests/unit/test_actionchain.py
Python
apache-2.0
40,041
0.002273
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
L_PATH = FixturesLoader().get_fixture_file_path_abs( FIXTURES_PACK, 'actionchains', 'chain_second_task_parameter_render_fail.yaml') CHAIN_LIST_TEMP_PATH = FixturesLoader().get_fixture_file_path_abs( FIXTURES_PACK, 'actionchains', 'chain_list_template.yaml') CHAIN_DICT_TEMP_PATH = FixturesLoader().get_fixture_fi...
dict_template.yaml') CHAIN_DEP_INPUT = FixturesLoader().get_fixture_file_path_abs( FIXTURES_PACK, 'actionchains', 'chain_dependent_input.yaml') CHAIN_DEP_RESULTS_INPUT = FixturesLoader().get_fixture_file_path_abs( FIXTURES_PACK, 'actionchains', 'chain_dep_result_input.yaml') MALFORMED_CHAIN_PATH = FixturesLoade...
budnyjj/vkstat
utils/print.py
Python
mit
1,418
0.000705
# Various functions for printing various specific values # in human-readable format import sys import time import pprint # pretty print object pp = pprint.PrettyPrinter(indent=4) def pretty_print(value): pp.pprint(value) # print timedelta, provided in seconds, # in human-readable format def print_elapsed_tim...
) print() def print_progress(cur_value, max_value, width=72): """Print progress bar in form: [###-------].""" progress = int((cur_value * 100) / max_value) # effective width -- width of bar without brackets e_width = width - 2 # number of "#" in bar num_hashes = int((cur_value * e_width) ...
centage}%'.format(hashes='#' * num_hashes, minuses='-' * num_minuses, percentage=progress)) sys.stdout.flush()
erudit/zenon
eruditorg/erudit/migrations/0111_auto_20190312_1251.py
Python
gpl-3.0
422
0.002375
# Generated by Django 2.0.10 on 2019-03-12 17:51 from django.db import migrations, mode
ls class Migration(migrations.Migration): dependencies = [ ('erudit', '0110_auto_20181123_1558'), ] operations = [ migrations.AlterField( model_name='issue', name='is_published', field=models.BooleanField(default=Fa
lse, verbose_name='Est publié'), ), ]
hetica/bentools
modules/manager/manager.py
Python
gpl-3.0
9,426
0.006265
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Manage modules """ import sys, os import time import grp #from subprocess import Popen, PIPE from pathlib import Path import shutil from getpass import getpass __appname__ = "manager" __licence__ = "none" __version__ = "0.1" __author__ = "Benoit Guibert <benoit.guib...
help = "reference genome (fasta file)", metavar = 'genome', nargs = 1, required = True, ) ### ARGUMENT WITHOUT OPTION parser.add_argument('--verbose', # positional argument ...
plamut/ggrc-core
src/ggrc_workflows/notification/data_handler.py
Python
apache-2.0
14,000
0.007143
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> import urllib from copy import deepcopy from datetime import date from logging import getLogger from urlparse import urljoin from sqlalchemy import and_ from ggrc import db from ggrc import utils from ggr...
tions": { notification.id: force },
"cycle_starts_in": { workflow.id: { "workflow_owners": workflow_owners, "workflow_url": get_workflow_url(workflow), "start_date": workflow.next_cycle_start_date, "start_date_statement": utils.get_digest_date_statement( wor...
karllessard/tensorflow
tensorflow/lite/tools/flatbuffer_utils_test.py
Python
apache-2.0
8,309
0.003972
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
test_utils.build_mock_model() final_model = copy.deepcopy(initial_model
) # 2. INVOKE # Invoke the strip_strings function flatbuffer_utils.strip_strings(final_model) # 3. VALIDATE # Validate that the initial and final models are the same except strings # Validate the description self.assertNotEqual('', initial_model.description) self.assertEqual('', final_...
sdroege/cerbero
cerbero/utils/git.py
Python
lgpl-2.1
8,593
0.00128
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; eit...
@re
turn: true if git config is core.autorlf=false @rtype: bool ''' if platform != Platform.WINDOWS: return True val = shell.check_call('%s config --get core.autocrlf' % GIT, env=CLEAN_ENV) if ('false' in val.lower()): return True return False def init_directory(git_dir): ''' ...
carolinux/QGIS
python/plugins/processing/algs/otb/OTBSpecific_XMLLoading.py
Python
gpl-2.0
12,848
0.001946
# -*- coding: utf-8 -*- """ *************************************************************************** OTBUtils.py --------------------- Date : 11-12-13 Copyright : (C) 2013 by CS Systemes d'information (CS SI) Email : otb at c-s dot fr (CS SI) Contrib...
Oscar Picas (CS SI) - Alexia Mondot (CS SI) - split otbspecific into 2 files add functions *************************************************************************** * * * ...
bertjwregeer/pyramid_keystone
pyramid_keystone/__init__.py
Python
isc
1,415
0.003534
from pyramid.exceptions import ConfigurationError from p
yramid.interfaces import ISessionFactory from .settings import parse_settings def includeme(config): """ Set up standard configurator registrations.
Use via: .. code-block:: python config = Configurator() config.include('pyramid_keystone') """ # We use an action so that the user can include us, and then add the # required variables, upon commit we will pick up those changes. def register(): registry = config.registry ...
skipmodea1/plugin.video.xbmctorrent
resources/site-packages/xbmctorrent/scrapers/btdigg.py
Python
gpl-3.0
2,061
0.001456
#!/usr/bin/env python # -*- coding: UTF-8 -*- from xbmctorrent import plugin from xbmctorrent.scrapers import scraper from xbmctorrent.ga import tracked from xbmctorrent.caching import cached_route from xbmctorrent.utils import ensure_fanart from
xbmctorrent.library import library_context BASE_URL = plugin.get_setting("base_
btdigg") HEADERS = { "Referer": BASE_URL, } SORT_RELEVANCE = 0 SORT_POPULARITY = 1 SORT_ADDTIME = 2 SORT_SIZE = 3 SORT_FILES = 4 @scraper("BTDigg - DHT Search Engine", "%s/logo.png" % BASE_URL) @plugin.route("/btdigg") @ensure_fanart @tracked def btdigg_index(): plugin.redirect(plugin.url_for("btdigg_search")...
Azure/azure-sdk-for-python
sdk/rdbms/azure-mgmt-rdbms/azure/mgmt/rdbms/mariadb/aio/operations/_operations.py
Python
mit
3,780
0.004233
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
t import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as
_models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class Operations: """Operations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and...
Daniel-Brosnan-Blazquez/DIT-100
examples/IMU/acc/raw_data.py
Python
gpl-3.0
461
0.023861
# Program to print raw data of the accelerometer device import sys sys.path.
append ("../../../lib") import accel import time import num
py import os A = accel.Init () while(1): time.sleep(0.25) os.system ("clear") print "\n\n\n\n" (status, x) = accel.get_x (A) (status, y) = accel.get_y (A) (status, z) = accel.get_z (A) print("\t{:7.2f} {:7.2f} {:7.2f}".format(x, y, z)) print "\t|A| = %6.3F" % numpy.sqrt (x*x + y*y + z...
tboyce021/home-assistant
homeassistant/components/image_processing/__init__.py
Python
apache-2.0
6,082
0.000658
"""Provides functionality to interact with image processing services.""" import asyncio from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import ATTR_ENTITY_ID, ATTR_NAME, CONF_ENTITY_ID, CONF_NAME from homeassistant.core import callback from homeassistant.exceptions impo...
None def process_image(self, image): """Process image.""" raise NotImplementedError() async def async_process_image
(self, image): """Process image.""" return await self.hass.async_add_executor_job(self.process_image, image) async def async_update(self): """Update image and process it. This method is a coroutine. """ camera = self.hass.components.camera image = None ...
TangXT/GreatCatMOOC
common/lib/xmodule/xmodule/open_ended_grading_classes/combined_open_ended_modulev1.py
Python
agpl-3.0
49,426
0.00346
import json import logging import traceback from lxml import etree from xmodule.timeinfo import TimeInfo from xmodule.capa_module import ComplexEncoder from xmodule.progress import Progress from xmodule.stringify import stringify_children from xmodule.open_ended_grading_classes import self_assessment_module from xmod...
nt', 3) self.min_to_calibrate = instance_state.get('min_to_calibrate', 3) self.max_to_calibrate = instance_state.get('max_to_calibrate', 6) self.peer_grade_finished_submissions_when_none_pending = instance_state.get( 'peer_grade_finished_submissions_when_none_pending', False ...
te = instance_state.get('due', None) grace_period_string = instance_state.get('graceperiod', None) try: self.timeinfo = TimeInfo(due_date, grace_period_string) except Exception: log.error("Error parsing due date information in location {0}".format(location)) ...
bukun/TorCMS
tester/test_model/test_entity.py
Python
mit
2,865
0.002115
# -*- coding:utf-8 -*- from torcms.core import tools from torcms.model.entity_model import MEntity class TestMEntity(): def setup(self): print('setup 方法执行于本类中每条用例之前') self.uid = tools.get_uuid() self.path = '/static/123123' def test_create_entity(self): uid = self.uid ...
eate_entity(self.uid, self.path, desc, kind) def test_query_recent(self): a = MEntity.get_by_uid(self.uid) assert a == None self.add_message() a = MEntity.get_by_uid(self.uid) assert a self.tearDown() def test_query_all(self): self.add_message() ...
if i.uid == self.uid: tf = True assert tf self.tearDown() def test_get_by_kind(self): self.add_message() a = MEntity.get_by_kind(kind='f') tf = False for i in a: if i.uid == self.uid: tf = True assert tf s...
jeremiedecock/snippets
python/pyqt/pyqt4/fullscreen.py
Python
mit
2,472
0.004049
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2012 Jérémie DECOCK (http://www.jdhp.org) # 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 restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Softwar
e is # furnished to do so, subject to the following 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 W...
n2o/guhema
products/migrations/0057_auto_20160118_2025.py
Python
mit
2,432
0.004527
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-18 20:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('products', '0056_auto_20160118_2012'), ] operations = [ migrations.AddField(...
field=models.CharField(blank=True, max_length=255, verbose_name='TP'), ), migrations.AddField( model_name='bandsawbladeindicator', name='UE', field=models.CharField(blank=True, max_length=255, verbose_name='Ü'), ),
migrations.AddField( model_name='bandsawbladeindicator', name='UP', field=models.CharField(blank=True, max_length=255, verbose_name='UP'), ), migrations.AddField( model_name='bandsawbladeindicator', name='VP', field=models.C...
croxis/kmr
app/user/__init__.py
Python
mit
107
0.018692
__author__ = 'croxis' fr
om flask import Blueprint user = Blueprint('user', __name__) fr
om . import views
effa/flocs
practice/services/__init__.py
Python
gpl-2.0
53
0.018868
"""Service lay
er (domain model) of practice app """
eikiu/tdf-actividades
_admin-scripts/jsontocsv(activities-name).py
Python
cc0-1.0
814
0.045455
''' run where the files are ''' import json import os final_file = "tipo,nombre,nombre_alt\n" for root, subFolders, files in os.walk(os.getcwd()): for filename in files: filePath = os.path.join(root, filename) if not filePath.endswith(".json") or filename.startswith("_"): continue print (" processi...
ing='utf-8-sig') as readme: current_text = readme
.read() tmp_file = json.loads(current_text) nombre_alt = "\"\"" if "nombre_alt" in tmp_file: nombre_alt = tmp_file["nombre_alt"] final_file += tmp_file["tipo"] + "," + tmp_file["nombre"] + "," + nombre_alt + "\n" with open(os.path.join(os.getcwd(),"actividades_merged.csv"), 'w', encoding='utf...
LowResourceLanguages/hltdi-l3
l3xdg/graphics.py
Python
gpl-3.0
10,943
0.004132
from tkinter import * # from tkinter.font import * import math CW = 800 CH = 600 SENT_H = 50 Y_OFF = 10 X_OFF = 20 DIM_GAP = 10 DIM_OFF = 70 class Multigraph(Canvas): """Canvas for displaying the multigraph for a sentence.""" node_rad = 3 def __init__(self, parent, width=CW, height=CH, nnodes=9, ...
abel(self): x = self.coords
[0] + 25 y = self.coords[1] + 10 self.label_id = self.canvas.create_text(x, y, text=self.label, font = ("Helvetica", "14")) def make_node(self, index, offset, eos=False, filled=True): node = Node(self.canvas, ...
CarlosCebrian/RedesII_Ejercicios
Practica2_RedesII/chatudp.py
Python
gpl-2.0
1,117
0.014324
#!/usr/bin/env python3 from socket import * import _thread import sys def enviardatos(sock): data = input() enviar = data.encode() sock.sendto(enviar,('localh
ost',23456)) if data == "bye": print("Closing Client\n") sock.close() return 0 _thread.start_new_thread(recibirdatos,(('localhost',23456),sock)) while 1: data = input() enviar = data.encode() sock.sendto(enviar,('localhost',23456)) if data == "bye...
break else: if data == "bye": print("Closing client\n") sock.close() sys.exit(0) def recibirdatos(tupla,sock): while 1: try: msg,server = sock.recvfrom(1024) except OSError: sys.exit(0) data = msg.d...
TheSighing/climber
climber/__init__.py
Python
mit
7,197
0.000973
__version__ = '0.1.4' import requests import re import json from bs4 import BeautifulSoup # TODO: def see_also() => makes a whole set of related thhings to the topic # chosen # TODO: # def chossy() => parse disambiguation pages can be called # when the page reached durign climb or # any given method in the clas...
tions = {} if not options else options def climb(self, topic): self.depth = self.options["depth"] if "depth" in self.options.keys() else None self.summary = self.options["summary"] if "summary" in self.options.keys() else None if(topic is None): return None else: ...
content = requests.get(url) self.soup = BeautifulSoup(content.text, "html.parser") check = self.soup.find_all(id="disambigbox") return self.get_scaffold(check) # Extracts images given a topic. def climb_images(self, topic=None): images = [] if(topic ...
matthiaskramm/corepy
examples/spu_interspu.py
Python
bsd-3-clause
5,421
0.009592
# Copyright (c) 2006-2009 The Trustees of Indiana University. # All rights reserved. # # Redistribution and use in source and binary forms, with or without ...
nters to PS maps. psinfo = extarray.extarray('I', SPUS * 4) for i in xrange(0, SPUS * 4, 4): psinfo[i] = id[i / 4].spups psinfo
.synchronize() # Send the psinfo address to all the SPUs. addr = psinfo.buffer_info()[0] for i in xrange(0, SPUS): env.spu_exec.write_signal(id[i], 1, addr) # Wait for a mailbox message from each SPU; the value should be the preceding # rank. Join each SPU once the message is received, too. for i in ...
pozdnyakov/chromium-crosswalk
tools/telemetry/telemetry/page/page_measurement.py
Python
bsd-3-clause
5,239
0.004772
# 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. imp
ort os import sys from telemetry.page import block_page_measurement_results from telemetry.page import buildbot_page_measurement_results from telemetry.page import csv_page_measurement_results from telemetry.page import page_measurement_results from telemetry.page import page_test class MeasurementFailure(page_test.F...
for problem.""" pass class PageMeasurement(page_test.PageTest): """Glue code for running a measurement across a set of pages. To use this, subclass from the measurement and override MeasurePage. For example: class BodyChildElementMeasurement(PageMeasurement): def MeasurePage(self, page, tab, res...
kmiller96/Shipping-Containers-Software
lib/containers.py
Python
mit
14,805
0.002972
# AUTHOR: Kale Miller # DESCRIPTION: Contains the core classes for the program. # 50726f6772616d6d696e6720697320627265616b696e67206f66206f6e652062696720696d706f737369626c65207461736b20696e746f20736576 # 6572616c207665727920736d616c6c20706f737369626c65207461736b732e # DEVELOPMENT LOG: # 05/12/16: Initialized...
): _BaseContainer.__init__(self, id, info, destination) # Call the parent class' constructor. self.settype('heavy') self._auxilarylabelsalreadyadded = F
alse def addauxilarylabels(self, debug=False): """Adds the extra labels that are required on the container.""" self.addlabel(self._informationlabel(), quiet=True) self.addlabel('NOTE: Heavy container.', quiet=True) self._auxilarylabelsalreadyadded = True return None ...
kanethemediocre/1strand
1strandbushinga002.py
Python
gpl-2.0
6,978
0.019633
#1strand Bushing Tool #Standalone program for minimized cruft import math print "This program is for printing the best possible circular bushings" print "Printer config values are hardcoded for ease of use (for me)" xpath = [] #These are initialized and default values ypath = [] zpath = [] step = [] epath = [] xstart...
usionWidth) print "Brim Thickness = ", BrimThickness print "Brim Perimeters = ", BrimPerimeters #Brim layer is first, and treated separately. j=0 i=0 radius = BrimDiameter/2 - (j+0.5)*ActualExtrusionWidth xpath.append(centerx+radius) ypath.append(centery) zpath.append(LayerHeight) while (j<BrimPerimeter
s): radius = BrimDiameter/2 - (j+0.5)*ActualExtrusionWidth j=j+1 i=0 while (i<N): i=i+1 #print "i=", i, "j=", j, "radius=", radius xpath.append(centerx+radius*math.cos(i*anglestep)) ypath.append(centery+radius*math.sin(i*anglestep)) zpath.append(LayerHeight) # # #...
frink182/pi_temps
mqtt_listener.py
Python
gpl-2.0
882
0.003401
#!/usr/bin/env python import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect...
ge is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("slug", 1883, 60) # Blocking call that processes network traffic, dispatches
callbacks and # handles reconnecting. # Other loop*() functions are available that give a threaded interface and a # manual interface. client.loop_forever()
DakRomo/2017Challenges
challenge_4/python/ning/challenge_4.py
Python
mit
790
0
class BTree: def __init__(self, b_tree_list=list()): self.b_tree_list = b_tree_list self.levels = len(b_tree_list) def visualise(self): for index, level in enumerate(self.b_tree_list): spacing = 2 ** (self.levels - index) - 1 print(((spacing-1)//2)*' ', end='') ...
evel: if node is None: print(' ', end='') else: print(node, end='') print(spacing * ' ', end='') print('') # newline def invert(self): for level in self.b_tree_list:
level.reverse() example_tree = BTree([ [4], [2, 7], [1, 3, 6, 9]]) example_tree.visualise() example_tree.invert() example_tree.visualise()
dhuang/incubator-airflow
airflow/providers/amazon/aws/hooks/glue.py
Python
apache-2.0
7,995
0.002126
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
AwsGlueJobHook(AwsBaseHook): """ Interact with AWS Glue - create job, trigger, crawler :param s3_bucket: S3 bucket where logs and local etl script will be uploaded :type s3_bucket: Optional[str] :param job_name: unique job name per AWS account :type job_name: Optional[str] :param desc: job ...
pe desc: Optional[str] :param concurrent_run_limit: The maximum number of concurrent runs allowed for a job :type concurrent_run_limit: int :param script_location: path to etl script on s3 :type script_location: Optional[str] :param retry_limit: Maximum number of times to retry this job if it fails ...
lorensen/VTKExamples
src/Python/DataManipulation/LineOnMesh.py
Python
apache-2.0
5,546
0
#!/usr/bin/env python import numpy as np import vtk def main(): named_colors = vtk.vtkNamedColors() # Make a 32 x 32 grid. size = 32 # Define z values for the topography. # Comment out the following line if you want a different random # distribution each time the script is run. np.rand...
Create a polydata object. trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata. trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared! clea...
to smooth the data (will add triangles and smooth). smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for smoothed dataset. mapper = vtk.vtkPolyDataMapper() mapper.SetInp...
jkadlec/knot-dns-zoneapi
tests-extra/tests/dnssec/case_sensitivity/test.py
Python
gpl-3.0
1,244
0.001608
#!/usr/bin/env python3 '''Test for no resigning if the zone is properly signed.''' from dnstest.utils import set_err from dnstest.test import Test import subprocess def patch_zone(t, server, zone, script): """ Update zone file on a master server. """ zone = zone[0] zonefile = "%s/master/%s" % (se...
patch_zone(t, server, zone, script) server.start() new_serial = server.zone_wait(zone) signed = new_serial != serial if signed != resign: set_err("Invalid state after %s change" % name) break serial = new_
serial t.stop()
wesley1001/WeVoteServer
config/wsgi.py
Python
bsd-3-clause
1,622
0
""" WSGI config for WebAppPublic project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATI...
plication = DjangoWhiteNoise(application) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorld
Application # application = HelloWorldApplication(application)
yaoxuanw007/forfun
leetcode/python/countAndSay.py
Python
mit
720
0.0125
# https://oj.leetcode.com/problems/count-and-say/ # 10:56 - 11:11 class Solution: # @return a string def countAndSay(self, n): result = "1" # n == 1, result == '1', not when n == 0 for i in xrange(1, n): last, count, nextResult = result[0], 1, "" for j in xrange(1, len(result)): cu...
+ str(last) count = 0 count += 1 last = curr nextResult += str(count) + str(last) result = nextResult return result
s = Solution() print s.countAndSay(1), '1' print s.countAndSay(2), '11' print s.countAndSay(3), '21' print s.countAndSay(4), '1211' print s.countAndSay(5), '111221'
spatial-computing/geotweets
data/tool/test/jsongener.py
Python
mit
2,441
0.003277
# Ramdomly generates data import json, random, copy data = { 'tweets': {}, 'events': {}, 'tweetsHeat': [], 'eventsHeat': [] } tweetGeo = { "type": "FeatureCollection", "features": [], "id": "tweetsyoulike.c22ab257" } tfeature = { "geometry": { "type": "Point", "coordin...
o['features'].append(tfea) coordi.append(tfea['properties']['importance']) data['tweetsHeat'].append(coordi) efea = copy.deepcopy(efeature) coordi = []
coordi.append(efeature['geometry']['coordinates'][1] + (random.random() - 0.5) * 10) coordi.append(efeature['geometry']['coordinates'][0] + (random.random() - 0.5) * 10) efea['geometry']['coordinates'][0] = coordi[1] efea['geometry']['coordinates'][1] = coordi[0] eventGeo['features'].append(efea) co...
bndl/bndl
bndl/__init__.py
Python
apache-2.0
1,142
0.000876
# 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 th...
or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging.config import os.path from bndl.util.conf import Config, String from bndl.util.log import instal
l_trace_logging from bndl.util.objects import LazyObject # Expose a global BNDL configuration conf = LazyObject(Config) # Configure Logging logging_conf = String('logging.conf') install_trace_logging() logging.captureWarnings(True) if os.path.exists(conf['bndl.logging_conf']): logging.config.fileConfig(conf[...
YoApp/yo-water-tracker
db.py
Python
mit
154
0.006494
# -*- c
oding: utf-8 -*- import pymongo from config import MONGO_STRING client = pymongo.MongoClient(MONGO_STRING, tz_aware=True) db = cl
ient['yo-water']
photoninger/ansible
test/units/modules/network/onyx/test_onyx_lldp.py
Python
gpl-3.0
2,404
0
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible 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. # # Ansible is d...
e.modules.network.onyx import onyx_lldp from units.modules.utils import set_module_args from .onyx_module import TestOnyxModule, load_fixture class TestOnyxInterfaceModule(TestOnyxModule): module = onyx_lldp def setUp(self):
super(TestOnyxInterfaceModule, self).setUp() self.mock_get_config = patch.object( onyx_lldp.OnyxLldpModule, "_get_lldp_config") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') ...