commit
stringlengths 40
40
| subject
stringlengths 1
3.25k
| old_file
stringlengths 4
311
| new_file
stringlengths 4
311
| old_contents
stringlengths 0
26.3k
| lang
stringclasses 3
values | proba
float64 0
1
| diff
stringlengths 0
7.82k
|
---|---|---|---|---|---|---|---|
7bace5ca301124f03d7ff98669ac08c0c32da55f | Add example OOP python script | labs/lab-5/oop.py | labs/lab-5/oop.py | Python | 0.000005 | @@ -0,0 +1,1134 @@
+#!/usr/bin/python%0A#%0A# Copyright 2016 BMC Software, Inc.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A#%0Aclass Animal(object):%0A%0A def __init__(self):%0A self.voice = %22???%22%0A%0A def speak(self):%0A print('A %7B0%7D says %22%7B1%7D%22'.format(self.__class__.__name__, self.voice))%0A%0Aclass Cat(Animal):%0A%0A def __init__(self):%0A super(Cat, self).__init__()%0A self.voice = 'Meow!'%0A%0Aclass Dog(Animal):%0A%0A def __init__(self):%0A super(Dog, self).__init__()%0A self.voice = 'Woof!'%0A%0A%0Aif __name__ == '__main__':%0A animal = Animal()%0A animal.speak()%0A%0A cat = Cat()%0A cat.speak()%0A%0A dog = Dog()%0A dog.speak()%0A
|
|
5f2533e090e181d84c3e5567131447aa4326773a | Add libx11 package | libx11/conanfile.py | libx11/conanfile.py | Python | 0.000001 | @@ -0,0 +1,1347 @@
+from conans import ConanFile, AutoToolsBuildEnvironment, tools%0Aimport os%0A%0A%0Aclass Libx11Conan(ConanFile):%0A name = %22libx11%22%0A version = %221.6.5%22%0A license = %22Custom https://cgit.freedesktop.org/xorg/lib/libX11/tree/COPYING%22%0A url = %22https://github.com/trigger-happy/conan-packages%22%0A description = %22X11 client-side library%22%0A settings = %22os%22, %22compiler%22, %22build_type%22, %22arch%22%0A options = %7B%22shared%22: %5BTrue, False%5D%7D%0A default_options = %22shared=False%22%0A generators = %22cmake%22%0A%0A def source(self):%0A pkgLink = 'https://xorg.freedesktop.org/releases/individual/lib/libX11-%7Bversion%7D.tar.bz2'.format(version=self.version)%0A self.run(%22curl -JOL %22 + pkgLink)%0A self.run(%22tar xf libX11-%7Bversion%7D.tar.bz2%22.format(version=self.version))%0A%0A def build(self):%0A envBuild = AutoToolsBuildEnvironment(self)%0A installPrefix=os.getcwd()%0A with tools.chdir(%22libX11-%7Bversion%7D%22.format(version=self.version)):%0A with tools.environment_append(envBuild.vars):%0A self.run(%22./configure --prefix=%7B0%7D --disable-xf86bigfont%22.format(installPrefix))%0A self.run(%22make install%22)%0A%0A def package(self):%0A self.copy(%22lib/*%22, dst=%22.%22, keep_path=True)%0A self.copy(%22include/*%22, dst=%22.%22, keep_path=True)%0A%0A def package_info(self):%0A self.cpp_info.libs = %5B%22X11%22, %22X11-xcb%22%5D%0A
|
|
e972bb5127b231bfbdf021597f5c9a32bb6e21c8 | Create gametesting.py | gametesting.py | gametesting.py | Python | 0 | @@ -0,0 +1 @@
+%0A
|
|
a83a48f6c9276b86c3cc13aeb000611036a6e3c4 | Make all end-points accepting post | jedihttp/handlers.py | jedihttp/handlers.py | import bottle
from bottle import response, request
import json
import jedi
import logging
app = bottle.Bottle( __name__ )
logger = logging.getLogger( __name__ )
@app.get( '/healthy' )
def healthy():
return _Json({})
@app.get( '/ready' )
def ready():
return _Json({})
@app.post( '/completions' )
def completion():
logger.info( 'received /completions request' )
script = _GetJediScript( request.json )
return _Json(
{
'completions': [ {
'name': completion.name,
'description': completion.description,
'docstring': completion.docstring(),
'module_path': completion.module_path,
'line': completion.line,
'column': completion.column
} for completion in script.completions() ]
} )
def _GetJediScript( request_data ):
source = request_data[ 'source' ]
line = request_data[ 'line' ]
col = request_data[ 'col' ]
path = request_data[ 'path' ]
return jedi.Script( source, line, col, path )
def _Json( data ):
response.content_type = 'application/json'
return json.dumps( data )
| Python | 0.000318 | @@ -159,26 +159,27 @@
__ )%0A%0A%0A@app.
-ge
+pos
t( '/healthy
@@ -223,18 +223,19 @@
%0A%0A%0A@app.
-ge
+pos
t( '/rea
|
64e91bf4a7fb8dae8ae49db64396bdfed12bec63 | Add deploy script for pypi. | deploy.py | deploy.py | Python | 0 | @@ -0,0 +1,919 @@
+%22%22%22%0ADeploy this package to PyPi.%0A%0AIf the package is already uploaded (by --version) then this will do nothing.%0AReqires Python3.%0A%22%22%22%0A%0Aimport http.client%0Aimport json%0Aimport subprocess%0A%0A%0Adef setup(*args):%0A o = subprocess.check_output('python3 ./setup.py %25s' %25 ' '.join(args),%0A shell=True)%0A return o.decode().rstrip()%0A%0Aname = setup('--name')%0Aversion = setup('--version')%0A%0Aprint(%22Package:%22, name)%0Aprint(%22Version:%22, version)%0A%0Aprint(%22Checking PyPi...%22)%0Apiconn = http.client.HTTPSConnection('pypi.python.org')%0Apiconn.request(%22GET%22, '/pypi/%25s/json' %25 name)%0Apiresp = piconn.getresponse()%0Aif piresp.status != 200:%0A exit('PyPi Service Error: %25s' %25 piresp.reason)%0Apiinfo = json.loads(piresp.read().decode())%0A%0Adeployed_versions = list(piinfo%5B'releases'%5D.keys())%0Aif version in deployed_versions:%0A print(%22PyPi is already up-to-date for:%22, version)%0A exit()%0A%0Aprint(setup('sdist', 'upload'))%0A
|
|
77a7873221fdbf2a83be99b6d05c5bb6bef65552 | Fix silly logic from last commit. | flexget/plugins/services/pogcal_acquired.py | flexget/plugins/services/pogcal_acquired.py | from __future__ import unicode_literals, division, absolute_import
import logging
import re
from datetime import datetime
from sqlalchemy import Column, Unicode, Integer
from flexget import validator
from flexget.plugin import register_plugin
from flexget.utils import requests
from flexget.utils.soup import get_soup
from flexget.schema import versioned_base
log = logging.getLogger('pogcal_acquired')
Base = versioned_base('pogcal_acquired', 0)
session = requests.Session()
class PogcalShow(Base):
__tablename__ = 'pogcal_shows'
id = Column(Integer, primary_key=True, autoincrement=False, nullable=False)
name = Column(Unicode)
class PogcalAcquired(object):
def validator(self):
root = validator.factory('dict')
root.accept('text', key='username', required=True)
root.accept('text', key='password', required=True)
return root
def on_task_exit(self, task, config):
if not task.accepted and not task.manager.options.test:
return
try:
result = session.post('http://www.pogdesign.co.uk/cat/',
data={'username': config['username'],
'password': config['password'],
'sub_login': 'Account Login'})
except requests.RequestException as e:
log.error('Error logging in to pog calendar: %s' % e)
return
if 'logout' not in result.text:
log.error('Username/password for pogdesign calendar appear to be incorrect.')
return
for entry in task.accepted:
if not entry.get('series_name') and entry.get('series_id_type') == 'ep':
continue
show_id = self.find_show_id(entry['series_name'], task.session)
if not show_id:
log.debug('Could not find pogdesign calendar id for `%s`' % entry['series_name'])
continue
if task.manager.options.test:
log.verbose('Would mark %s %s in pogdesign calenadar.' % (entry['series_name'], entry['series_id']))
continue
else:
log.verbose('Marking %s %s in pogdesign calenadar.' % (entry['series_name'], entry['series_id']))
shid = '%s-%s-%s/%s-%s' % (show_id, entry['series_season'], entry['series_episode'],
datetime.now().month, datetime.now().year)
try:
session.post('http://www.pogdesign.co.uk/cat/watchhandle',
data={'watched': 'adding', 'shid': shid})
except requests.RequestException as e:
log.error('Error marking %s %s in pogdesign calendar: %s' %
(entry['series_name'], entry['series_id'], e))
def find_show_id(self, show_name, db_sess):
# Check if we have this show id cached
show_name = show_name.lower()
db_show = db_sess.query(PogcalShow).filter(PogcalShow.name == show_name).first()
if db_show:
return db_show.id
# Try to look up the id from pogdesign
show_re = self.show_re(show_name)
try:
page = session.get('http://www.pogdesign.co.uk/cat/showselect.php')
except requests.RequestException as e:
log.error('Error looking up show `%s` from pogdesign calendar: %s' % (show_re, e))
return
soup = get_soup(page.content)
search = re.compile(show_re, flags=re.I)
show = soup.find(text=search)
if show:
id = int(show.previous['value'])
db_sess.add(PogcalShow(id=id, name=show_name))
return id
else:
log.verbose('Could not find pogdesign calendar id for show `%s`' % show_re)
def show_re(self, show_name):
# Normalize and format show name
show_re = re.sub(r'\s+\((.*)\)$', r'( \(\1\))?', show_name)
if show_re.startswith('the'):
show_re = show_re[3:].strip() + r' \[the\]'
return show_re
register_plugin(PogcalAcquired, 'pogcal_acquired', api_ver=2)
| Python | 0.999999 | @@ -1679,19 +1679,22 @@
_name')
-and
+or not
entry.g
|
2dfa0dd815061497f89f9ca5e09fa62ea4dc23bf | fix issue #956 | launcher/start.py | launcher/start.py | #!/usr/bin/env python
# coding:utf-8
import os, sys
import time
import atexit
import webbrowser
import launcher_log
current_path = os.path.dirname(os.path.abspath(__file__))
python_path = os.path.abspath( os.path.join(current_path, os.pardir, 'python27', '1.0'))
noarch_lib = os.path.abspath( os.path.join(python_path, 'lib', 'noarch'))
sys.path.append(noarch_lib)
has_desktop = True
if sys.platform.startswith("linux"):
def X_is_running():
try:
from subprocess import Popen, PIPE
p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
p.communicate()
return p.returncode == 0
except:
return False
if X_is_running():
from gtk_tray import sys_tray
else:
from non_tray import sys_tray
has_desktop = False
elif sys.platform == "win32":
win32_lib = os.path.join(python_path, 'lib', 'win32')
sys.path.append(win32_lib)
from win_tray import sys_tray
elif sys.platform == "darwin":
darwin_lib = os.path.abspath( os.path.join(python_path, 'lib', 'darwin'))
sys.path.append(darwin_lib)
extra_lib = "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjc"
sys.path.append(extra_lib)
try:
import mac_tray as sys_tray
except:
from non_tray import sys_tray
else:
print("detect platform fail:%s" % sys.platform)
from non_tray import sys_tray
has_desktop = False
import config
import web_control
import module_init
import update
import setup_win_python
def exit_handler():
print 'Stopping all modules before exit!'
module_init.stop_all()
web_control.stop()
atexit.register(exit_handler)
def main():
# change path to launcher
global __file__
__file__ = os.path.abspath(__file__)
if os.path.islink(__file__):
__file__ = getattr(os, 'readlink', lambda x: x)(__file__)
os.chdir(os.path.dirname(os.path.abspath(__file__)))
web_control.confirm_xxnet_exit()
setup_win_python.check_setup()
module_init.start_all_auto()
web_control.start()
if has_desktop and config.get(["modules", "launcher", "popup_webui"], 1) == 1:
webbrowser.open("http://127.0.0.1:8085/")
update.start()
if config.get(["modules", "launcher", "show_systray"], 1):
sys_tray.serve_forever()
else:
while True:
time.sleep(100)
module_init.stop_all()
sys.exit()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt: # Ctrl + C on console
module_init.stop_all()
sys.exit
| Python | 0 | @@ -564,16 +564,28 @@
err=PIPE
+, shell=True
)%0A
|
03137f65202f5423ea705db601aaea7f18c590f9 | add the main file | lexos/__main__.py | lexos/__main__.py | Python | 0.000001 | @@ -0,0 +1,100 @@
+%22%22%22Module allowing for %60%60python -m lexos ...%60%60.%22%22%22%0Afrom lexos import application%0A%0Aapplication.run()%0A
|
|
370f5a87ac8d26245b5919fc98b24019861f4dde | Add missing test | tests/test_fetch_site_logs_from_ftp_sites.py | tests/test_fetch_site_logs_from_ftp_sites.py | Python | 0.000383 | @@ -0,0 +1,242 @@
+import pytest%0Aimport os%0A%0Afrom fetch_site_logs_from_ftp_sites import gws_list_site_logs%0A%0Adef test_get_gws_site_logs():%0A os.environ%5B'gws_url'%5D = 'https://testgeodesy-webservices.geodesy.ga.gov.au'%0A assert len(gws_list_site_logs()) %3E 1000%0A
|
|
65a639fafbe88b4867ff474b0884ebc2cc7c29d8 | fix libjpeg_turbo in valid names | third_party/systemlibs/syslibs_configure.bzl | third_party/systemlibs/syslibs_configure.bzl | # -*- Python -*-
"""Repository rule for system library autoconfiguration.
`syslibs_configure` depends on the following environment variables:
* `TF_SYSTEM_LIBS`: list of third party dependencies that should use
the system version instead
"""
_TF_SYSTEM_LIBS = "TF_SYSTEM_LIBS"
VALID_LIBS = [
"absl_py",
"astor_archive",
"boringssl",
"com_github_googleapis_googleapis",
"com_github_googlecloudplatform_google_cloud_cpp",
"com_googlesource_code_re2",
"curl",
"cython",
"double_conversion",
"flatbuffers",
"gast_archive",
"gif_archive",
"grpc",
"jpeg",
"jsoncpp_git",
"lmdb",
"nasm",
"nsync",
"org_sqlite",
"pcre",
"png_archive",
"six_archive",
"snappy",
"swig",
"termcolor_archive",
"zlib_archive",
]
def auto_configure_fail(msg):
"""Output failure message when syslibs configuration fails."""
red = "\033[0;31m"
no_color = "\033[0m"
fail("\n%sSystem Library Configuration Error:%s %s\n" % (red, no_color, msg))
def _is_windows(repository_ctx):
"""Returns true if the host operating system is windows."""
os_name = repository_ctx.os.name.lower()
if os_name.find("windows") != -1:
return True
return False
def _enable_syslibs(repository_ctx):
s = repository_ctx.os.environ.get(_TF_SYSTEM_LIBS, "").strip()
if not _is_windows(repository_ctx) and s != None and s != "":
return True
return False
def _get_system_lib_list(repository_ctx):
"""Gets the list of deps that should use the system lib.
Args:
repository_ctx: The repository context.
Returns:
A string version of a python list
"""
if _TF_SYSTEM_LIBS not in repository_ctx.os.environ:
return []
libenv = repository_ctx.os.environ[_TF_SYSTEM_LIBS].strip()
libs = []
for lib in list(libenv.split(",")):
lib = lib.strip()
if lib == "":
continue
if lib not in VALID_LIBS:
auto_configure_fail("Invalid system lib set: %s" % lib)
return []
libs.append(lib)
return libs
def _format_system_lib_list(repository_ctx):
"""Formats the list of deps that should use the system lib.
Args:
repository_ctx: The repository context.
Returns:
A list of the names of deps that should use the system lib.
"""
libs = _get_system_lib_list(repository_ctx)
ret = ""
for lib in libs:
ret += "'%s',\n" % lib
return ret
def _tpl(repository_ctx, tpl, substitutions = {}, out = None):
if not out:
out = tpl.replace(":", "")
repository_ctx.template(
out,
Label("//third_party/systemlibs%s.tpl" % tpl),
substitutions,
False,
)
def _create_dummy_repository(repository_ctx):
"""Creates the dummy repository to build with all bundled libraries."""
_tpl(repository_ctx, ":BUILD")
_tpl(
repository_ctx,
":build_defs.bzl",
{
"%{syslibs_enabled}": "False",
"%{syslibs_list}": "",
},
)
def _create_local_repository(repository_ctx):
"""Creates the repository to build with system libraries."""
_tpl(repository_ctx, ":BUILD")
_tpl(
repository_ctx,
":build_defs.bzl",
{
"%{syslibs_enabled}": "True",
"%{syslibs_list}": _format_system_lib_list(repository_ctx),
},
)
def _syslibs_autoconf_impl(repository_ctx):
"""Implementation of the syslibs_configure repository rule."""
if not _enable_syslibs(repository_ctx):
_create_dummy_repository(repository_ctx)
else:
_create_local_repository(repository_ctx)
syslibs_configure = repository_rule(
implementation = _syslibs_autoconf_impl,
environ = [
_TF_SYSTEM_LIBS,
],
)
"""Configures the build to link to system libraries
instead of using bundled versions.
Add the following to your WORKSPACE FILE:
```python
syslibs_configure(name = "local_config_syslibs")
```
Args:
name: A unique name for this workspace rule.
"""
| Python | 0.000561 | @@ -606,12 +606,21 @@
%22
+lib
jpeg
+_turbo
%22,%0A
|
0774413ae3623c28a8aaf77727d0c355f6a5bd7c | Add deezer_complete core plugin #146 | timeside/plugins/provider/deezer_complete.py | timeside/plugins/provider/deezer_complete.py | Python | 0 | @@ -0,0 +1,920 @@
+from timeside.core import implements, interfacedoc%0Afrom timeside.core.provider import Provider%0Afrom timeside.core.api import IProvider%0Afrom timeside.core.tools.utils import slugify%0A%0Aimport os%0Afrom requests import get%0A%0A%0Aclass DeezerComplete(Provider):%0A %22%22%22%0A Represents Deezer Provider while loading results%0A computed on complete tracks on Deezer's infrastructure%0A %22%22%22%0A implements(IProvider)%0A %0A @staticmethod%0A @interfacedoc%0A def id():%0A return 'deezer_complete'%0A%0A @staticmethod%0A @interfacedoc%0A def name():%0A return %22Deezer Complete%22%0A%0A @staticmethod%0A @interfacedoc%0A def ressource_access():%0A return False%0A%0A def get_source_from_id(self, external_id, path, download=False):%0A return ''%0A %0A def get_source_from_url(self, url, path, download=False):%0A return ''%0A%0A def get_id_from_url(self, url):%0A return url.split(%22/%22)%5B-1:%5D%5B0%5D%0A
|
|
fa8032792f208e2693f8f6a4693ba9af084de935 | use path | src/robotide/spec/librarymanager.py | src/robotide/spec/librarymanager.py | # Copyright 2008-2012 Nokia Siemens Networks Oyj
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from Queue import Queue
from threading import Thread
from robotide.spec.librarydatabase import LibraryDatabase
from robotide.spec.libraryfetcher import _get_import_result_from_process
from robotide.spec.xmlreaders import _init_from_spec
class LibraryManager(Thread):
def __init__(self, database_name):
self._database_name = database_name
self._messages = Queue()
Thread.__init__(self)
self.setDaemon(True)
def run(self):
self._initiate_database_connection()
while True:
if not self._handle_message():
break
self._database.close()
def _initiate_database_connection(self):
self._database = LibraryDatabase(self._database_name)
def _handle_message(self):
message = self._messages.get()
if not message:
return False
type = message[0]
if type == 'fetch':
self._handle_fetch_keywords_message(message)
return True
def _handle_fetch_keywords_message(self, message):
_, library_name, library_args, callback = message
try:
keywords = _get_import_result_from_process(library_name, library_args)
except ImportError:
keywords = _init_from_spec(library_name)
self._update_database_and_call_callback_if_needed((library_name, library_args), keywords, callback)
def _update_database_and_call_callback_if_needed(self, library_key, keywords, callback):
db_keywords = self._database.fetch_library_keywords(*library_key)
if not db_keywords or self._keywords_differ(keywords, db_keywords):
self._database.insert_library_keywords(library_key[0], library_key[1], keywords)
self._call(callback, keywords)
else:
self._database.update_library_timestamp(*library_key)
def _call(self, callback, *args):
try:
callback(*args)
except Exception:
pass
def fetch_keywords(self, library_name, library_args, callback):
self._messages.put(('fetch', library_name, library_args, callback))
def stop(self):
self._messages.put(False)
def _keywords_differ(self, keywords1, keywords2):
if keywords1 != keywords2 and None in (keywords1, keywords2):
return True
if len(keywords1) != len(keywords2):
return True
for k1, k2 in zip(keywords1, keywords2):
if k1.name != k2.name:
return True
if k1.doc != k2.doc:
return True
if k1.arguments != k2.arguments:
return True
if k1.source != k2.source:
return True
return False
| Python | 0.000005 | @@ -622,16 +622,26 @@
t Queue%0A
+import os%0A
from thr
@@ -844,16 +844,27 @@
rom_spec
+, _get_path
%0A%0Aclass
@@ -1722,32 +1722,117 @@
ge%0A try:%0A
+ path =_get_path(library_name.replace('/', os.sep), os.path.abspath('.'))%0A
keyw
@@ -1870,28 +1870,20 @@
process(
-library_name
+path
, librar
|
02c06a544b1b6e4230a9b658540b360cc60c0bb5 | add cmstat.py | gist/cmstat.py | gist/cmstat.py | Python | 0.000101 | @@ -0,0 +1,1771 @@
+from __future__ import print_function%0Aimport sh%0Afrom collections import namedtuple%0Aimport os%0Aimport itertools%0Agit = sh.git.bake()%0A%0A%0ANumStat = namedtuple('NumStat', %5B'insert', 'delete', 'filename'%5D)%0A%0A%0Adef getCommit(commit):%0A %22%22%22get commit message%0A --no-pager: stop pager which block stdout%0A -n 1: only show one commit%0A (not use %5E.. style, this will fail when not have prior commit)%0A --color=never: not colorful output%0A %22%22%22%0A opt = ('--numstat', '-n 1', '--color=never', '--pretty=%25H')%0A return git('--no-pager', 'log', commit, *opt)%0A%0A%0Adef parseNumStat(cm):%0A l = cm.split('%5Cn%5Cn')%0A ret = %5B%5D%0A if len(l) %3C 2:%0A return ret%0A for line in l%5B1%5D.split('%5Cn'):%0A line = line.split()%0A if len(line) %3C 3:%0A continue%0A if line%5B0%5D == '-' or line%5B1%5D == '-':%0A continue%0A n = NumStat(int(line%5B0%5D), int(line%5B1%5D), line%5B2%5D)%0A ret.append(n)%0A return ret%0A%0A%0Adef getStatLst():%0A cmlst = git('rev-list', 'HEAD', '--after=2014-01-01', '--author=liuyang')%0A shalst = cmlst.split()%0A stlst = %5B%5D%0A for sha in shalst:%0A cm = getCommit(sha)%0A ret = parseNumStat(cm)%0A stlst.extend(ret)%0A return stlst%0A%0A%0Adef groupFileExt(numst):%0A fn = numst.filename%0A ret = os.path.splitext(fn)%0A if ret%5B1%5D == %22%22:%0A return ret%5B0%5D%0A else:%0A return ret%5B1%5D%0A%0A%0Adef main():%0A stlst = getStatLst()%0A a = sum(%5Bst.insert for st in stlst%5D)%0A b = sum(%5Bst.delete for st in stlst%5D)%0A print(a, b, a + b)%0A stlst = sorted(stlst, key=groupFileExt)%0A for ext, g in itertools.groupby(stlst, groupFileExt):%0A g = list(g)%0A aa = sum(%5Bst.insert for st in g%5D)%0A bb = sum(%5Bst.delete for st in g%5D)%0A print(ext, aa, bb, aa + bb)%0A%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
e29a2107cd08e6b40b99e3682d783887107a5e77 | Add a loader to load several yaml files | populous/loader.py | populous/loader.py | Python | 0 | @@ -0,0 +1,1859 @@
+import collections%0A%0Aimport yaml%0A%0A%0Adef load_yaml(*filenames):%0A %22%22%22%0A Parse the given files as if they were a single YAML file.%0A %22%22%22%0A with ChainedFileObject(*filenames) as f:%0A return yaml.load(f)%0A%0A%0Aclass ChainedFileObject(object):%0A %22%22%22%0A A file-like object behaving like if all the given filenames were a single%0A file.%0A%0A Note that you never get content from several files during a single call to%0A %60%60read%60%60, even if the length of the requested buffer if longer that the%0A remaining bytes in the current file. You have to call %60%60read%60%60 again in%0A order to get content from the next file.%0A%0A Can be used as a context manager (in a %60%60with%60%60 statement).%0A%0A Example::%0A %3E%3E%3E f = ChainedFileObject('foo.txt', 'bar.txt')%0A %3E%3E%3E f.read()%0A %22I'm the content of foo.txt%22%0A %3E%3E%3E f.read(1024)%0A %22I'm the content of bar.txt%22%0A %3E%3E%3E f.read()%0A ''%0A %3E%3E%3E f.close()%0A %22%22%22%0A%0A def __init__(self, *filenames):%0A self.filenames = collections.deque(filenames)%0A self.current = None%0A%0A self.nextfile()%0A%0A def __enter__(self):%0A return self%0A%0A def __exit__(self, *args):%0A return self.close()%0A%0A def nextfile(self):%0A current = self.current%0A self.current = None%0A%0A try:%0A if current:%0A current.close()%0A finally:%0A try:%0A self.current = open(self.filenames.popleft())%0A except IndexError:%0A self.current = None%0A%0A def read(self, n=None):%0A if not self.current:%0A return ''%0A%0A output = self.current.read()%0A%0A if not output:%0A self.nextfile()%0A return self.read()%0A%0A return output%0A%0A def close(self):%0A current = self.current%0A self.current = None%0A%0A if current:%0A current.close()%0A
|
|
555cedf76d5f569b8a99691ed7dba672e578bb42 | Add admin integration for positions | positions/admin.py | positions/admin.py | Python | 0 | @@ -0,0 +1,263 @@
+from django.contrib import admin%0Afrom .models import Position%0A%0Aclass PositionAdminIndex(admin.ModelAdmin):%0A list_display = %5B'title', 'date'%5D%0A%0A list_filter = %5B'date'%5D%0A%0A search_fields = %5B'title', 'content'%5D%0Aadmin.site.register(Position, PositionAdminIndex)
|
|
9dc39f6492d9ece3964d5cb733cc146acee7cf66 | Create w3_1.py | w3_1.py | w3_1.py | Python | 0.000482 | @@ -0,0 +1,15 @@
+print(%22hello%22)%0A
|
|
31fcd83585905ca28245e42163c77af38f0c83cf | Create w3_1.py | w3_1.py | w3_1.py | Python | 0.000482 | @@ -0,0 +1,14 @@
+print(%22test%22)%0A
|
|
d35f2d7310c277625ea6e2e15b887ac9620696a7 | Add unit test for glacier vault | tests/unit/glacier/test_vault.py | tests/unit/glacier/test_vault.py | Python | 0 | @@ -0,0 +1,2219 @@
+#!/usr/bin/env python%0A# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved%0A#%0A# Permission is hereby granted, free of charge, to any person obtaining a%0A# copy of this software and associated documentation files (the%0A# %22Software%22), to deal in the Software without restriction, including%0A# without limitation the rights to use, copy, modify, merge, publish, dis-%0A# tribute, sublicense, and/or sell copies of the Software, and to permit%0A# persons to whom the Software is furnished to do so, subject to the fol-%0A# lowing conditions:%0A#%0A# The above copyright notice and this permission notice shall be included%0A# in all copies or substantial portions of the Software.%0A#%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS%0A# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-%0A# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT%0A# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,%0A# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS%0A# IN THE SOFTWARE.%0A#%0Aimport unittest%0Afrom cStringIO import StringIO%0A%0Aimport mock%0Afrom mock import ANY%0A%0Afrom boto.glacier import vault%0A%0A%0Aclass TestVault(unittest.TestCase):%0A def setUp(self):%0A self.size_patch = mock.patch('os.path.getsize')%0A self.getsize = self.size_patch.start()%0A%0A def tearDown(self):%0A self.size_patch.stop()%0A%0A def test_upload_archive_small_file(self):%0A api = mock.Mock()%0A v = vault.Vault(api, None)%0A v.name = 'myvault'%0A self.getsize.return_value = 1%0A stringio = StringIO('content')%0A m = mock.mock_open()%0A m.return_value.read = stringio.read%0A%0A api.upload_archive.return_value = %7B'ArchiveId': 'archive_id'%7D%0A with mock.patch('boto.glacier.vault.open', m, create=True):%0A archive_id = v.upload_archive('filename', 'my description')%0A self.assertEqual(archive_id, 'archive_id')%0A api.upload_archive.assert_called_with('myvault', m.return_value, ANY,%0A ANY, 'my description')%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
d44f12ca4395c0001bbaf0cf0d5436a84484569c | Create fasta2nexus.py | biokit/converters/fasta2nexus.py | biokit/converters/fasta2nexus.py | Python | 0.000001 | @@ -0,0 +1,510 @@
+from Bio import AlignIO%0A%0A%0Aclass Fasta2Nexus(object):%0A %22%22%22%0A %22%22%22%0A def __init__(self, infile, outfile, *args, **kwargs):%0A %22%22%22%0A %22%22%22%0A self.infile = infile%0A self.outfile = outfile%0A%0A def __call__(self):%0A%0A input_handle = open(self.infile, %22rU%22)%0A output_handle = open(self.outfile, %22w%22)%0A%0A alignments = AlignIO.parse(input_handle, %22fasta%22)%0A AlignIO.write(alignments, output_handle, %22nexus%22)%0A%0A output_handle.close()%0A input_handle.close()%0A%0A
|
|
e8cd41a2151e5907aeaac685f5c78300a010ce7e | add sensu plugin to check eventanomaly | plugins/bongo/check-eventanomaly.py | plugins/bongo/check-eventanomaly.py | Python | 0 | @@ -0,0 +1,2257 @@
+#!/usr/bin/env python%0A%0Afrom optparse import OptionParser%0Aimport socket%0Aimport sys%0Aimport httplib%0Aimport json%0A%0APASS = 0%0AFAIL = 1%0A%0Adef get_bongo_host(server, app):%0A try:%0A con = httplib.HTTPConnection(server, timeout=45)%0A con.request(%22GET%22,%22/v2/apps/%22 + app)%0A data = con.getresponse()%0A if data.status %3E= 300:%0A print %22get_bongo_host: Recieved non-2xx response= %25s%22 %25 (data.status)%0A sys.exit(FAIL)%0A json_data = json.loads(data.read())%0A host = %22%25s:%25s%22 %25 (json_data%5B'app'%5D%5B'tasks'%5D%5B0%5D%5B'host'%5D,json_data%5B'app'%5D%5B'tasks'%5D%5B0%5D%5B'ports'%5D%5B0%5D)%0A con.close()%0A return host%0A except Exception, e:%0A print %22get_bongo_host: %25s :exception caught%22 %25 (e)%0A sys.exit(FAIL)%0A%0Adef get_status(host, group, time):%0A try:%0A con = httplib.HTTPConnection(host,timeout=45)%0A con.request(%22GET%22,%22/v1/eventdrop/%22 + group + %22/%22 + time)%0A data = con.getresponse()%0A if data.status %3E= 300:%0A print %22get_status: Recieved non-2xx response= %25s%22 %25 (data.status)%0A sys.exit(FAIL)%0A json_data = json.loads(data.read())%0A con.close()%0A%0A print %22get_status: %25s%22 %25 (json_data%5B'msg'%5D)%0A sys.exit(json_data%5B'status'%5D)%0A%0A #if json_data%5B'status'%5D == 1:%0A # print %22get_status: %25s%22 %25 (json_data%5B'msg'%5D)%0A # sys.exit(FAIL)%0A #else:%0A # print %22%25s is fine%22 %25group%0A # sys.exit(PASS)%0A except Exception, e:%0A print %22get_status: %25s :exception caught%22 %25 (e)%0A sys.exit(FAIL)%0A%0Aif __name__==%22__main__%22:%0A parser = OptionParser()%0A parser.add_option(%22-s%22, dest=%22server%22, action=%22store%22, default=%22localhost:8080%22, help=%22Marathon Cluster address with port no%22)%0A parser.add_option(%22-a%22, dest=%22app%22, action=%22store%22, default=%22bongo.useast.prod%22, help=%22App Id to retrieve the slave address%22)%0A parser.add_option(%22-g%22, dest=%22group%22, action=%22store%22, default=%22pmi%22, help=%22The group of event pmi or adevents%22)%0A parser.add_option(%22-t%22, dest=%22time%22, action=%22store%22, default=%2210min%22, help=%22The time gap for which the difference is to be calculated%22)%0A (options, args) = parser.parse_args()%0A host = get_bongo_host(options.server, options.app)%0A get_status(host, options.group, options.time)%0A
|
|
6a95f7aa987994cdd173dc52d5de2754e449ebbb | Add a Python script that controls the user list in my own Twitter lists. | listmanager.py | listmanager.py | Python | 0 | @@ -0,0 +1,2037 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%22%22%22This script manages your own Twitter lists.%0A%0AExamples:%0A You can add users to a list by the %22add%22 command::%0A%0A $ python listmanager.py add your_screen_name your_list_name user1 %5Buser2 ...%5D%0A%0A Likewise, you can also remove users by the %22remove%22 command.%0A%22%22%22%0A%0Afrom secret import twitter_instance%0Afrom argparse import ArgumentParser%0A%0A__version__ = '1.0.0'%0A%0Adef configure():%0A %22%22%22Parse the command line parameters.%0A%0A Returns:%0A An instance of argparse.ArgumentParser that stores the command line%0A parameters.%0A %22%22%22%0A%0A parser = ArgumentParser(description='Twitter List Manager')%0A parser.add_argument('--version', action='version', version=__version__)%0A%0A # Positional arguments%0A parser.add_argument(%0A 'command',%0A choices=%5B'add', 'remove',%5D,%0A help='Either %22add%22 or %22remove%22.')%0A%0A parser.add_argument(%0A 'owner_screen_name',%0A help='The screen name of the user who owns the list being requested by a slug.')%0A%0A parser.add_argument(%0A 'slug',%0A help='The slug of the list.')%0A%0A parser.add_argument(%0A 'screen_names',%0A nargs='+',%0A help='A comma separated list of screen names, up to 100 are allowed in a single request.')%0A%0A return parser%0A%0Adef main(args):%0A %22%22%22The main function.%0A%0A Args:%0A args: An instance of argparse.ArgumentParser parsed in the configure%0A function.%0A%0A Returns:%0A None.%0A %22%22%22%0A%0A tw = twitter_instance()%0A%0A # Few commands are available so far.%0A if args.command == 'add':%0A tw.lists.members.create_all(%0A owner_screen_name=args.owner_screen_name,%0A slug=args.slug,%0A screen_name=','.join(args.screen_names))%0A elif args.command == 'remove':%0A tw.lists.members.destroy_all(%0A owner_screen_name=args.owner_screen_name,%0A slug=args.slug,%0A screen_name=','.join(args.screen_names))%0A%0Aif __name__ == '__main__':%0A parser = configure()%0A main(parser.parse_args())%0A
|
|
489c77d3bbd3a9e0e14578f4371870042e2d04d1 | Add another debug script | debug1.py | debug1.py | Python | 0.000001 | @@ -0,0 +1,512 @@
+import logging%0Aimport threading%0Afrom cornbread.xorg import *%0A%0Aif __name__ == '__main__':%0A logging.warning('Creating FW')%0A w = FocusedWindow()%0A%0A logging.warning('Creating FW thread')%0A t = threading.Thread(target=FocusedWindowWatcher, args=(w,))%0A%0A logging.warning('Starting thread')%0A t.start()%0A%0A try:%0A logging.warning('Joining FW thread')%0A t.join(4)%0A%0A except KeyboardInterrupt as e:%0A logging.warning('Keyboard interrupt')%0A w._exit_watch = True%0A t.join(4)%0A
|
|
b6b65f0ca7253af5325eafc6b19e7cfecda231b3 | Add solution for exercise 2b of hw3 | hw3/hw3_2b.py | hw3/hw3_2b.py | Python | 0.000071 | @@ -0,0 +1,496 @@
+import sympy%0A%0Ax1, x2 = sympy.symbols('x1 x2')%0Af = 8*x1 + 12*x2 + x1**2 -2*x2**2%0A%0Adf_dx1 = sympy.diff(f,x1)%0Adf_dx2 = sympy.diff(f,x2)%0AH = sympy.hessian(f, (x1, x2))%0A%0Axs = sympy.solve(%5Bdf_dx1, df_dx2%5D, %5Bx1, x2%5D)%0A%0AH_xs = H.subs(%5B(x1,xs%5Bx1%5D), (x2,xs%5Bx2%5D)%5D)%0Alambda_xs = H_xs.eigenvals()%0A%0Acount = 0%0Afor i in lambda_xs.keys():%0A if i.evalf() %3C= 0:%0A count += 1%0A%0Aif count == 0:%0A print 'Local minima'%0Aelif count == len(lambda_xs.keys()):%0A print 'Lacal maxima'%0Aelse:%0A print 'Saddle point'%0A
|
|
8649fef1ddea18525fd0f6c5f8aa42e18b0726f8 | rename plot to visualizer | lib/visualizer.py | lib/visualizer.py | Python | 0.000874 | @@ -0,0 +1,2232 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport matplotlib.pyplot as plt%0Afrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas%0Aimport datetime%0Aimport time%0Afrom utils import slugify%0Afrom scipy.cluster.hierarchy import dendrogram%0A%0Adef create_bar_graph(_x,_y,_title,_disp):%0A%0A print %22Creating bar graph...%22%0A # VARIABLES %0A bar_color='#CCCCCC'%0A bar_width=.35%0A%0A images_path=%22/home/clemsos/Dev/mitras/out/%22%0A%0A w=len(_x) # width of the canvas%0A h=len(_y) # height of the canvas%0A%0A # Create a figure with size 6 _x 6 inches.%0A fig = plt.figure(figsize=(w,h))%0A%0A # Create a canvas and add the figure to it.%0A canvas = FigureCanvas(fig)%0A%0A # bar plot for volume of%0A bars = fig.add_subplot(111)%0A%0A # Display Grid%0A bars.grid(True,linestyle='-',color='0.75')%0A%0A # Display Bars%0A bars.bar(_x, _y, facecolor=bar_color, %0A align='center', ecolor='black')%0A%0A # This sets the ticks on the x axis to be exactly where we put the center of the bars.%0A # bars.set_xticks(_x)%0A%0A # Create a y label%0A bars.set_ylabel('Counts')%0A%0A # Create a title, in italics%0A bars.set_title(_title,fontstyle='italic')%0A%0A # Generate the Scatter Plot.%0A # bars.scatter(_x,_y,s=20,color='tomato');%0A%0A # Auto-adjust and beautify the labels%0A fig.autofmt_xdate()%0A%0A # Save the generated Scatter Plot to a PNG file.%0A fn=images_path+slugify(_title)%0A canvas.print_figure(fn,dpi=200)%0A fig.savefig(fn+%22.pdf%22)%0A %0A print %22 graph file has been at %25s.png%22%25fn%0A print %22 graph file has been at %25s.pdf%22%25fn%0A%0A # Show us everything%0A if _disp is True :%0A plt.show() %0A%0Adef plot_sparcity():%0A # should use matplotlib spy : http://matplotlib.org/examples/pylab_examples/spy_demos.html%0A pass%0A%0Adef augmented_dendrogram(*args, **kwargs):%0A ddata = dendrogram(*args, **kwargs)%0A%0A if not kwargs.get('no_plot', False):%0A for i, d in zip(ddata%5B'icoord'%5D, ddata%5B'dcoord'%5D):%0A x = 0.5 * sum(i%5B1:3%5D)%0A y = d%5B1%5D%0A plt.plot(x, y, 'ro')%0A plt.annotate(%22%25.3g%22 %25 y, (x, y), xytext=(0, -8),%0A textcoords='offset points',%0A va='top', ha='center')%0A%0A%0A# VIZ lib%0A# http://bokeh.pydata.org/
|
|
71b0af732e6d151a22cc0d0b28b55020780af8b6 | Add memoize function for python 2.x | ftools.py | ftools.py | Python | 0.000018 | @@ -0,0 +1,515 @@
+from functools import wraps%0A%0A%0Adef memoize(obj):%0A # This is taken from the Python Decorator Library on the official Python%0A # wiki. https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize%0A # Unfortunately we're using Python 2.x here and lru_cache isn't available%0A%0A cache = obj.cache = %7B%7D%0A%0A @wraps(obj)%0A def memoizer(*args, **kwargs):%0A key = str(args) + str(kwargs)%0A if key not in cache:%0A cache%5Bkey%5D = obj(*args, **kwargs)%0A return cache%5Bkey%5D%0A return memoizer%0A
|
|
1967db2a9b6e3b4420a1ebc5fe5fe157d61c6314 | Initialise entry and do a proper 404 if it could not be found. | kindlefeed.py | kindlefeed.py | # KindleFeed Controller
# =====================
#
# This file is part of KindleFeed.
#
# KindleFeed is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# KindleFeed is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with KindleFeed. If not, see <http://www.gnu.org/licenses/>.
import feedparser, flask, urllib
app = flask.Flask(__name__)
@app.template_filter('quote_plus')
def urlencode(s):
return urllib.quote_plus(s)
@app.route('/')
def index():
feeds = (('Mashable', 'http://feeds.mashable.com/Mashable'), ('TechCrunch', 'http://feeds.feedburner.com/techcrunch'))
return flask.render_template('index.html', feeds=feeds)
@app.route('/feed')
def feed():
url = flask.request.args.get('url')
feed = feedparser.parse(url)
return flask.render_template('feed.html', url=url, feed=feed)
@app.route('/entry')
def entry():
feed_url = flask.request.args.get('feed')
entry_id = flask.request.args.get('entry')
feed = feedparser.parse(feed_url)
for i in feed.entries:
if i.id == entry_id:
entry = i
return flask.render_template('entry.html', feed_url=feed_url, feed=feed, entry=entry)
def main():
app.debug = True
app.run(host='0.0.0.0', port=80)
if __name__ == '__main__':
main()
| Python | 0 | @@ -1402,16 +1402,30 @@
eed_url)
+%0A%09entry = None
%0A%0A%09for i
@@ -1477,16 +1477,56 @@
ntry = i
+%0A%09%0A%09if entry == None:%0A%09%09flask.abort(404)
%0A%0A%09retur
|
7b05d0a9d8017477cd6ddfac6ba56898affcdf37 | Revert "start reactor in separate thread" | king/tking.py | king/tking.py | import exceptions, sys
from twisted.internet import reactor
from twisted.names import dns as twisted_dns
from twisted.names import server
from datetime import datetime
from random import randrange
from threading import Thread
from time import sleep
from datetime import datetime
import dns.query, dns.rdatatype, dns.exception
import socket
import rpyc
myHostName = socket.gethostname().replace('.', '-')
myIP = socket.gethostbyname(socket.gethostname()).replace('.', '-')
myAddr = '%s-%s.nbapuns.com' % (myIP, myHostName)
# target1 = '8.8.8.8'
# target2 = 'ns1.google.com'
# target2_ip = '216.239.32.10'
###############
# RPC Service #
###############
class TurboKingService(rpyc.Service):
def on_connect(self):
pass
def on_disconnect(self):
pass
def exposed_test(self):
return 1
# TODO: Figure out if old reactors are using memory
def exposed_get_latency(self, t1, ip1, t2, ip2):
query_id = randrange(0, sys.maxint)
# Setup DNS Server
factory = DNSServerFactory(query_id, t2, ip2)
protocol = twisted_dns.DNSDatagramProtocol(factory)
udpPort = reactor.listenUDP(53, protocol)
tcpPort = reactor.listenTCP(53, factory)
# Start DNS Client
t=DNSClient(query_id, t1, ip1)
t.run()
udpPort.stopListening()
tcpPort.stopListening()
if factory.start_time:
return t.end_time - factory.start_time
else:
return None
##########
# Client #
##########
class DNSClient(Thread):
def __init__(self, query_id, target1, target1_ip):
Thread.__init__(self)
self.query_id = query_id
self.target1 = target1
self.target1_ip = target1_ip
self.end_time = None
def run(self):
sleep(1) # Wait for DNS Server to Start
addr = "final.%i.%s" % (self.query_id, myAddr)
query = dns.message.make_query(addr, dns.rdatatype.A)
try:
response = dns.query.udp(query, self.target1_ip, timeout=5)
self.end_time = datetime.now()
print "Recieved Response:"
print response
except dns.exception.Timeout, e:
print e
##############
# DNS Server #
##############
class DNSServerFactory(server.DNSServerFactory):
def __init__(self, query_id, t2, ip2, authorities=None, caches=None, clients=None, verbose=0):
server.DNSServerFactory.__init__(self,authorities,caches,clients,verbose)
self.query_id = query_id
self.target2 = t2
self.target2_ip = ip2
self.start_time = None
#TODO: Stop Handling of Queries after seeing a valid one
def handleQuery(self, message, protocol, address):
print "Recieved Query"
print address
print message
global start_time, query_id
try:
query = message.queries[0]
target = query.name.name
print target
dummy, id, origin = target.split('.')[0:3]
if int(id) != self.query_id:
print "Query ID Doesn't Match"
raise Exception
else:
self.start_time = datetime.now()
NS = twisted_dns.RRHeader(name=target, type=twisted_dns.NS, cls=twisted_dns.IN, ttl=0, auth=True,
payload=twisted_dns.Record_NS(name=self.target2, ttl=0))
A = twisted_dns.RRHeader(name=self.target2, type=twisted_dns.A, cls=twisted_dns.IN, ttl=0,
payload=twisted_dns.Record_A(address=self.target2_ip, ttl=None))
ans = []
auth = [NS]
add = [A]
args = (self, (ans, auth, add), protocol, message, address)
return server.DNSServerFactory.gotResolverResponse(*args)
except Exception, e:
print "Bad Request", e
if __name__ == "__main__":
# Start DNS Server
Thread(target=reactor.run, args=(False,), kwargs={'installSignalHandlers' : 0}).start()
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(TurboKingService, port = 18861)
t.start()
| Python | 0 | @@ -1130,18 +1130,8 @@
- udpPort =
rea
@@ -1170,18 +1170,8 @@
- tcpPort =
rea
@@ -1275,19 +1275,21 @@
t.
-run
+start
()%0A%0A
@@ -1296,62 +1296,70 @@
-udpPort.stopListening()%0A tcpPort.stopListening(
+# Start DNS Server%0A reactor.run(installSignalHandlers=0
)%0A%0A
@@ -2191,16 +2191,93 @@
print e%0A
+ reactor.callFromThread(reactor.stop)%0A print %22Stopped Reactor%22%0A
%0A%0A######
@@ -3951,123 +3951,8 @@
_%22:%0A
- # Start DNS Server%0A Thread(target=reactor.run, args=(False,), kwargs=%7B'installSignalHandlers' : 0%7D).start()%0A
|
4bc2c46e605b7bffb6e7e8206fdb6bb168864c45 | test random user fulfilling the specifications | listRandomUser.py | listRandomUser.py | Python | 0 | @@ -0,0 +1,1445 @@
+import random%0Aclass list_random:%0A%0A def __init__(self, n):%0A self.n=n%0A self.count=n/2%0A self.l_tuple=%5B%5D%0A for i in range(n):%0A for j in range(i+1,n):%0A self.l_tuple.append(%5Bi,j,0%5D)%0A # 0 no usado%0A # 1 invalido%0A # 2 usado%0A%0A def _valido(self,i,lista):%0A if self.l_tuple%5Bi%5D%5B2%5D==0:%0A for j in lista:%0A if (j%5B0%5D==self.l_tuple%5Bi%5D%5B0%5D or%5C%0A j%5B0%5D==self.l_tuple%5Bi%5D%5B1%5D or%5C%0A j%5B1%5D==self.l_tuple%5Bi%5D%5B0%5D or%5C%0A j%5B1%5D==self.l_tuple%5Bi%5D%5B1%5D): %0A self.l_tuple%5Bi%5D%5B2%5D==1%0A return False%0A self.l_tuple%5Bi%5D%5B2%5D==2%0A lista.append((self.l_tuple%5Bi%5D%5B0%5D,self.l_tuple%5Bi%5D%5B1%5D))%0A return True%0A return False%0A%0A def list1(self):%0A lista=%5B%5D%0A k = self.count%0A while (k%3E0):%0A i = random.randrange(len(self.l_tuple))%0A if self._valido(i,lista):%0A pass%0A else:%0A last = len(self.l_tuple)-1%0A for j in range(len(self.l_tuple)):%0A if self._valido((i+j+1) %25 len(self.l_tuple),lista):%0A break%0A if j == last:%0A # no encontrada solucion%0A raise %22solucion no encontrada%22%0A k=k-1%0A print %22UNO MENOS%22, k%0A return lista%0A%0A%0A
|
|
c2f1717c53042f8ff3a7ba169a2db365aa8bc8ba | ADd gff2togff3.py | gff2togff3.py | gff2togff3.py | Python | 0.001224 | @@ -0,0 +1,361 @@
+%22%22%22Change attribute string from GFF2 format GGF3 format.%22%22%22%0A%0Aimport csv%0Aimport sys%0A%0Afor row in csv.reader(open(sys.argv%5B1%5D), delimiter=%22%5Ct%22):%0A if not row%5B0%5D.startswith(%22#%22):%0A row%5B8%5D = %22;%22.join(%0A %5B%22%25s=%25s%22 %25 (attribute.split()%5B0%5D, %22 %22.join(attribute.split()%5B1:%5D))%0A for attribute in row%5B8%5D.split(%22 ; %22)%5D)%0A print(%22%5Ct%22.join(row))%0A
|
|
a18e1b9fde1b86c4cfee2c202fcebe0d1fd640e9 | debug mode off! | lib/Artist.py | lib/Artist.py | from flask import Flask
from flask import render_template
from flask import jsonify
from flask import session
from flask import redirect
from flask import request
from multiprocessing import Process
from time import sleep
from time import time
class Artist(object):
def __init__(self, diary, config_opts):
self.diary = diary
app = Flask(
__name__,
template_folder='../assets/templates',
static_folder='../assets/static',
static_url_path=''
)
app.diary = diary
app.secret_key = "Alice touches herself."
app.debug = True
if config_opts.has_option('overall', 'password'):
app.password = config_opts.get('overall', 'password')
@app.before_request
def check_auth():
if request.endpoint not in ('check_password', 'static'):
if 'is_logged_in' not in session:
return redirect('/password')
else:
app.password = None
# See if configured to bind to specific address/port
if config_opts.has_option('overall', 'bind'):
bind_opt = config_opts.get('overall', 'bind')
if ':' in bind_opt:
# e.g bind = 127.0.0.1:4567
app.bind_addr, app.bind_port = bind_opt.split(':')
app.bind_port = int(app.bind_port)
else:
# eg. bind = 127.0.0.1
app.bind_addr = bind_opt
app.bind_port = 5000
else:
app.bind_addr = '127.0.0.1'
app.bind_port = 5000
app.enabled_probes = config_opts.options('probes')
# I can split too!
# Since I can't do an "IF osx.LoadAVG OR linux.LoadAvg in Jinja
# I had to come up with this, remove their OS-prefixs
app.enabled_probes = [x.split('.')[1] for x in app.enabled_probes]
@app.route('/')
def index():
return render_template(
'index.html',
enabled_probes=app.enabled_probes,
password=app.password
)
@app.route('/api/load/<path:mode>')
def api_load(mode):
load_record = app.diary.read('LoadAvg', mode, how_many = 200)
return jsonify({
'load': load_record,
})
@app.route('/api/heavy_process_stat')
def api_heavy_process_stat():
heavy_process_stat = app.diary.read(
'HeavyProcessStat','live', how_many=1)[0]
return jsonify(heavy_process_stat)
@app.route('/api/mem_info/<int:how_many>')
def api_mem_info(how_many=40):
mem_info_record = app.diary.read('MemInfo', 'live', how_many)
return jsonify({
'mem_info': mem_info_record,
})
@app.route('/api/apache')
def api_apache():
apache_activity = app.diary.read('Apache2', 'live', how_many = 50)
return jsonify({
'apache_activity': apache_activity
})
@app.route('/api/apache_geocache')
def api_apache_geocache():
apache_ips = app.diary.read('Apache2', 'live', how_many=1)[0]
return jsonify({
'apache_ips': {
"ips": apache_ips["ips"]
}
})
@app.route('/api/postgres/<int:how_many>')
def api_postgres(how_many=30):
postgres_stats = app.diary.read('Postgres', 'live', how_many)
return jsonify({
'postgres_stats': postgres_stats,
})
@app.route('/api/mysql')
def api_mysql():
mysql_stats = app.diary.read('MySQL', 'live', how_many = 50)
return jsonify({
'mysql_stats': mysql_stats,
})
@app.route('/api/nginx/<int:how_many>')
def api_nginx(how_many=30):
nginx_stats = app.diary.read('Nginx','live', how_many)
return jsonify({
'nginx_stats': nginx_stats,
})
@app.route('/api/nginx_geocache')
def api_nginx_geocache():
nginx_ips = app.diary.read('Nginx','live', how_many=1)[0]
return jsonify({
'nginx_ips': {
"ips": nginx_ips.get("ips", [])
}
})
@app.route('/password', methods=['GET', 'POST'])
def check_password():
if request.method == 'POST':
if request.form['password'] == app.password:
session['is_logged_in'] = 'uh-uh!'
return redirect('/')
else:
return render_template('password.html', message="Nope, that's not it.")
else:
return render_template('password.html')
@app.route('/logout')
def logout():
session.clear()
return redirect('/password')
# Assign to self, so other methods can interact with it.
self.app = app
def start(self):
self.flask_ps = Process(
target=self.app.run,
kwargs={'host': self.app.bind_addr, 'port': self.app.bind_port}
)
self.flask_ps.start()
def stop(self):
print "Stop called @", time()
sleep(1)
print "[!] Telling the artist to pack his things.."
self.flask_ps.terminate()
| Python | 0 | @@ -592,16 +592,17 @@
rself.%22%0A
+#
|
ac89ec64ab619bfa778d0961aeaefc8967d971a3 | Add errors.py to move away from Python errors | errors.py | errors.py | Python | 0.000001 | @@ -0,0 +1,293 @@
+# Kimi language interpreter in Python 3%0A# Anjana Vakil%0A# http://www.github.com/vakila/kimi%0A%0Adef complain_and_die(message):%0A print(message)%0A quit()%0A%0Adef assert_or_complain(assertion, message):%0A try:%0A assert assertion%0A except AssertionError:%0A complain_and_die(message)%0A
|
|
5cb726d5139537cbe7c03bc5ed540b9cdb7c7e21 | Add bzero simprocedure I have had lying around forever | angr/procedures/posix/bzero.py | angr/procedures/posix/bzero.py | Python | 0 | @@ -0,0 +1,173 @@
+from ..libc import memset%0A%0Aclass bzero(memset.memset):%0A def run(self, addr, size):%0A return super().run(addr, self.state.solver.BVV(0, self.arch.byte_width), size)%0A
|
|
551f78f32665b1397120ada10036c1d9c09daddc | Create flip-bits.py | lulu/flip-bits.py | lulu/flip-bits.py | Python | 0.000004 | @@ -0,0 +1,448 @@
+class Solution:%0A %22%22%22%0A @param a, b: Two integer%0A return: An integer%0A %22%22%22%0A def bitSwapRequired(self, a, b):%0A # write your code here%0A return self.countOnes(a%5Eb)%0A %0A def countOnes(self, num):%0A # write your code here%0A counter = 0%0A a = 1%0A for i in range(0, 32):%0A digit = num & a%0A if digit != 0:%0A counter += 1%0A a *= 2%0A return counter%0A
|
|
b62b3b26f2ae6525a53b211c7f291aa7be51d377 | Monitor all sensor types by default to rtorrent (#17894) | homeassistant/components/sensor/rtorrent.py | homeassistant/components/sensor/rtorrent.py | """Support for monitoring the rtorrent BitTorrent client API."""
import logging
import xmlrpc.client
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_URL, CONF_NAME,
CONF_MONITORED_VARIABLES, STATE_IDLE)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
from homeassistant.exceptions import PlatformNotReady
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPE_CURRENT_STATUS = 'current_status'
SENSOR_TYPE_DOWNLOAD_SPEED = 'download_speed'
SENSOR_TYPE_UPLOAD_SPEED = 'upload_speed'
DEFAULT_NAME = 'rtorrent'
SENSOR_TYPES = {
SENSOR_TYPE_CURRENT_STATUS: ['Status', None],
SENSOR_TYPE_DOWNLOAD_SPEED: ['Down Speed', 'kB/s'],
SENSOR_TYPE_UPLOAD_SPEED: ['Up Speed', 'kB/s'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_URL): cv.url,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_MONITORED_VARIABLES, default=[]): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the rtorrent sensors."""
url = config[CONF_URL]
name = config[CONF_NAME]
try:
rtorrent = xmlrpc.client.ServerProxy(url)
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent daemon failed")
raise PlatformNotReady
dev = []
for variable in config[CONF_MONITORED_VARIABLES]:
dev.append(RTorrentSensor(variable, rtorrent, name))
add_entities(dev)
def format_speed(speed):
"""Return a bytes/s measurement as a human readable string."""
kb_spd = float(speed) / 1024
return round(kb_spd, 2 if kb_spd < 0.1 else 1)
class RTorrentSensor(Entity):
"""Representation of an rtorrent sensor."""
def __init__(self, sensor_type, rtorrent_client, client_name):
"""Initialize the sensor."""
self._name = SENSOR_TYPES[sensor_type][0]
self.client = rtorrent_client
self.type = sensor_type
self.client_name = client_name
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.data = None
self._available = False
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self.client_name, self._name)
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def available(self):
"""Return true if device is available."""
return self._available
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement
def update(self):
"""Get the latest data from rtorrent and updates the state."""
multicall = xmlrpc.client.MultiCall(self.client)
multicall.throttle.global_up.rate()
multicall.throttle.global_down.rate()
try:
self.data = multicall()
self._available = True
except (xmlrpc.client.ProtocolError, ConnectionRefusedError):
_LOGGER.error("Connection to rtorrent lost")
self._available = False
return
upload = self.data[0]
download = self.data[1]
if self.type == SENSOR_TYPE_CURRENT_STATUS:
if self.data:
if upload > 0 and download > 0:
self._state = 'Up/Down'
elif upload > 0 and download == 0:
self._state = 'Seeding'
elif upload == 0 and download > 0:
self._state = 'Downloading'
else:
self._state = STATE_IDLE
else:
self._state = None
if self.data:
if self.type == SENSOR_TYPE_DOWNLOAD_SPEED:
self._state = format_speed(download)
elif self.type == SENSOR_TYPE_UPLOAD_SPEED:
self._state = format_speed(upload)
| Python | 0 | @@ -1012,21 +1012,28 @@
ult=
-%5B%5D): vol.All(
+list(SENSOR_TYPES)):
%0A
@@ -1037,16 +1037,24 @@
+vol.All(
cv.ensur
|
75437fc5607b41763f8c81813ba12dbe1c414c5f | combine the sequence names from various headers and then concatonate the sam entries | iron/utilities/combine_sam.py | iron/utilities/combine_sam.py | Python | 0.000001 | @@ -0,0 +1,1050 @@
+#!/usr/bin/python%0Aimport sys, argparse, re%0A%0Adef main():%0A parser = argparse.ArgumentParser(description = 'Combine sam files')%0A parser.add_argument('sam_files',nargs='+',help='FILENAME for sam files')%0A args = parser.parse_args()%0A header = False%0A seqs = set()%0A tagorder = %5B%5D%0A tagseen = %7B%7D%0A for file in args.sam_files:%0A with open(file) as inf:%0A for line in inf:%0A line = line.rstrip()%0A f = line.split(%22%5Ct%22)%0A m = re.match('%5E(@%5CS%5CS)%5Cs',line)%0A if not m or len(f) %3E 10: break%0A if m.group(1) == '@SQ':%0A seqs.add(line)%0A if m.group(1) not in tagseen:%0A tagorder.append(m.group(1))%0A tagseen%5Bm.group(1)%5D = line%0A #now print the header%0A for tag in tagorder:%0A if tag != '@SQ':%0A print tagseen%5Btag%5D%0A else:%0A for seq in sorted(seqs):%0A print seq %0A #now go back through and do the sam data%0A for file in args.samfiles:%0A with open(file) as inf:%0A for line in inf:%0A f = line.rstrip().split(%22%5Ct%22)%0A if len(f) %3E 10:%0A print line%0Amain()%0A
|
|
e3c493847ead7352ecad1e92a739a1b79549a70c | Add dodo tape command | dodo_commands/extra/webdev_commands/tape.py | dodo_commands/extra/webdev_commands/tape.py | Python | 0.000004 | @@ -0,0 +1,722 @@
+# noqa%0Aimport argparse%0Afrom dodo_commands.extra.standard_commands import DodoCommand%0A%0A%0Aclass Command(DodoCommand): # noqa%0A help = %22%22%0A decorators = %5B%22docker%22%5D%0A docker_options = %5B%0A '--name=tape',%0A %5D%0A%0A def add_arguments_imp(self, parser): # noqa%0A parser.add_argument(%0A 'tape_args',%0A nargs=argparse.REMAINDER%0A )%0A%0A def handle_imp(self, tape_args, **kwargs): # noqa%0A tape_args = tape_args%5B1:%5D if tape_args%5B:1%5D == %5B'-'%5D else tape_args%0A%0A self.runcmd(%0A %5B%0A self.get_config(%22/TAPE/tape%22, %22tape%22),%0A self.get_config(%22/TAPE/glob%22)%0A %5D + tape_args,%0A cwd=self.get_config(%22/TAPE/src_dir%22)%0A )%0A
|
|
0f13cc95eeeed58c770e60b74a37f99ca24a28f0 | add tests for views | api/tests/test_views.py | api/tests/test_views.py | Python | 0 | @@ -0,0 +1,1508 @@
+from django.test import TestCase%0Afrom rest_framework.test import APIClient%0Afrom rest_framework import status%0Afrom django.core.urlresolvers import reverse%0A%0Aclass ViewsTestCase(TestCase):%0A %22%22%22Test suite for views.%22%22%22%0A%0A def setUp(self):%0A %22%22%22setup variables%22%22%22%0A self.client = APIClient()%0A%0A def create_file(self, filepath):%0A %22%22%22Create a file for testing.%22%22%22%0A f = open(filepath, 'w')%0A f.write('this is a good file%5Cn')%0A f.close()%0A f = open(filepath, 'rb')%0A return %7B'_file': f%7D%0A%0A def test_file_upload(self):%0A data = self.create_file('/tmp/file')%0A response = self.client.post(%0A reverse('api.upload'), data, format='multipart')%0A self.assertEqual(response.status_code, status.HTTP_201_CREATED)%0A%0A def test_getting_all_files(self):%0A response = self.client.get(reverse('file_get'))%0A%0A def test_getting_specific_file(self):%0A pass%0A%0A def test_deleting_a_file(self):%0A %22%22%22Ensure an existing file can be deleted.%22%22%22%0A data = self.create_file('/tmp/file')%0A response = self.client.post(%0A reverse('api.upload'), data, format='multipart')%0A self.assertEqual(response.status_code, status.HTTP_201_CREATED)%0A # get the file that's just been uploaded%0A new_file = File.objects.get()%0A res = self.client.delete(%0A reverse('api.delete'), kwargs=%7B'pk': new_file.id%7D, follow=True)%0A self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)%0A%0A
|
|
27788308891d9cd82da7782d62b5920ea7a54f80 | Add custom command to daily check scores | employees/management/commands/dailycheck.py | employees/management/commands/dailycheck.py | Python | 0 | @@ -0,0 +1,3028 @@
+from constance import config%0Afrom datetime import datetime%0Afrom django.core.management.base import BaseCommand%0Afrom django.core.mail import EmailMessage%0Afrom django.shortcuts import get_list_or_404%0Afrom employees.models import Employee%0A%0A%0Aclass Command(BaseCommand):%0A help = %22Update scores daily.%22%0A%0A def change_day(self):%0A employees = get_list_or_404(Employee)%0A for employee in employees:%0A employee.yesterday_given = employee.today_given%0A employee.yesterday_received = employee.today_received%0A employee.today_given = 0%0A employee.today_received = 0%0A employee.save()%0A%0A def change_month(self):%0A employees = get_list_or_404(Employee)%0A for employee in employees:%0A employee.last_month_given = employee.current_month_given%0A employee.last_month_score = employee.current_month_score%0A employee.current_month_given = 0%0A employee.current_month_score = 0%0A employee.save()%0A%0A def change_year(self):%0A employees = get_list_or_404(Employee)%0A for employee in employees:%0A employee.last_year_given = employee.current_year_given%0A employee.last_year_score = employee.current_year_score%0A employee.current_year_given = 0%0A employee.current_year_score = 0%0A employee.save()%0A%0A def send_daily_email(self):%0A subject = config.DAILY_EXECUTION_CONFIRMATION_SUBJECT%0A message = config.DAILY_EXECUTION_CONFIRMATION_MESSAGE%0A email = EmailMessage(subject, message, to=%5Bconfig.DAILY_EXECUTION_CONFIRMATION_EMAIL%5D)%0A email.send()%0A%0A def send_blocked_notification_email(self, employee):%0A subject = config.USER_BLOCKED_NOTIFICATION_SUBJECT%0A message = config.USER_BLOCKED_NOTIFICATION_MESSAGE %25 employee.username%0A email = EmailMessage(subject, message, to=%5Bemployee.email%5D)%0A email.send()%0A%0A def evaluate_block_users(self):%0A employees = get_list_or_404(Employee)%0A for employee in employees:%0A if employee.yesterday_given %3E config.MAX_STARS_GIVEN_DAY:%0A employee.is_blocked = True%0A if employee.yesterday_received %3E config.MAX_STARS_RECEIVED_DAY:%0A employee.is_blocked = True%0A if employee.current_month_given %3E config.MAX_STARS_GIVEN_MONTHLY:%0A employee.is_blocked = True%0A if employee.current_month_score %3E config.MAX_STARS_RECEIVED_MONTHLY:%0A employee.is_blocked = True%0A employee.save()%0A%0A try:%0A if employee.is_blocked:%0A self.send_blocked_notification_email()%0A except Exception as e:%0A print e%0A%0A def handle(self, *args, **options):%0A today = datetime.now()%0A self.change_day()%0A self.evaluate_block_users()%0A self.send_daily_email()%0A%0A if today.day == 1:%0A self.change_month()%0A if (today.day == 1 and today.month == 1):%0A self.change_year()%0A
|
|
8aac73fdc26fd838c3f91ffa9bc58e25777a5179 | Add tests for mach angle | properties/tests/test_mach_angle.py | properties/tests/test_mach_angle.py | Python | 0 | @@ -0,0 +1,540 @@
+#!/usr/bin/env python%0A%0A%22%22%22Test Mach angle functions.%0A%0ATest data is obtained from http://www.grc.nasa.gov/WWW/k-12/airplane/machang.html.%0A%22%22%22%0A%0A%0Aimport nose%0Aimport nose.tools as nt%0A%0Afrom properties.prandtl_meyer_function import mu_in_deg%0A%0A%[email protected](ValueError)%0Adef test_mach_lesser_than_one():%0A m = 0.1%0A mu_in_deg(m)%0A%0A%0Adef test_normal_mach():%0A m1 = 1.5%0A nt.assert_almost_equal(mu_in_deg(m1), 41.762, places=3)%0A%0A m2 = 2.6%0A nt.assert_almost_equal(mu_in_deg(m2), 22.594, places=3)%0A%0A%0Aif __name__ == '__main__':%0A nose.main()
|
|
49dfd690abe794e3b393b8bcac3e0ab1427c41b3 | Define riot_open. | riot/app.py | riot/app.py | Python | 0.000913 | @@ -0,0 +1,185 @@
+# -*- coding: utf-8 -*-%0A%0Aimport urwid%0A%0Adef run_tag(tag, *args, **kwargs):%0A loop = urwid.MainLoop(tag, *args, **kwargs)%0A loop.run()%0A%0Adef quit_app():%0A raise urwid.ExitMainLoop()%0A
|
|
f1cc40c716f1e4f598e0a9230cd188fc897ac117 | add config | moon/config.py | moon/config.py | Python | 0.000002 | @@ -0,0 +1,1197 @@
+# -*- coding: utf-8 -*-%0A%22%22%22 %E8%BF%99%E9%87%8C%E6%98%AF%E4%B8%80%E4%BA%9B%E5%B7%A5%E5%85%B7, %E7%94%A8%E6%9D%A5%E5%AE%9E%E7%8E%B0%E7%AE%80%E5%8D%95%E7%9A%84%E9%A1%B9%E7%9B%AE%E9%85%8D%E7%BD%AE%E7%B3%BB%E7%BB%9F %22%22%22%0Aimport logging%0A%0A_confdata = %7B%7D%0A%0A%0Adef setconf(prjname, confile, confdict=%7B%7D):%0A _confdata%5Bprjname%5D = (confile, confdict)%0A%0A%0Adef exportconf(prjname, globals):%0A %22%22%22 %E4%BB%8E%E6%96%87%E4%BB%B6%E5%92%8C%E5%AD%97%E5%85%B8%E4%B8%AD%E5%AF%BC%E5%87%BA%E9%85%8D%E7%BD%AE%0A %3E%3E%3E open(%22/tmp/testmoonconf.py%22, %22w%22).write(%22OSOS = 10%22)%0A %3E%3E%3E setconf(%22hongbo%22, %22/tmp/testmoonconf.py%22, %7B%22OSOSOS%22: 321%7D)%0A %3E%3E%3E d = %7B%7D%0A %3E%3E%3E exportconf(%22hongbo%22, d)%0A %3E%3E%3E print d%5B%22OSOS%22%5D%0A 10%0A %3E%3E%3E print d%5B%22OSOSOS%22%5D%0A 321%0A %22%22%22%0A try:%0A filename, confdict = _confdata%5Bprjname%5D%0A except KeyError as e:%0A e.strerror = %22Unable to find confdata for '%25s', %22 %5C%0A %22you must %60setconf%60 first%22 %25 prjname%0A raise%0A try:%0A with open(filename) as config_file:%0A exec(compile(config_file.read(), filename, %22exec%22), globals)%0A logging.info(%22Load config from %25s%22, filename)%0A except IOError as e:%0A e.strerror = 'Unable to load configuration file (%25s)' %25 e.strerror%0A raise%0A if confdict:%0A globals.update(confdict)%0A%0A%0Aif __name__ == %22__main__%22:%0A import sys, os%0A sys.path.remove(os.path.abspath(os.path.dirname(__file__)))%0A import doctest%0A doctest.testmod()%0A
|
|
106a339561f5b79e0cd9508246d2f8da227c4fdc | move file to folder | move_hmdb51.py | move_hmdb51.py | Python | 0.000003 | @@ -0,0 +1,1139 @@
+import argparse%0Aimport os%0Aimport sys%0Aimport math%0Aimport cv2%0Aimport numpy as np%0Aimport multiprocessing%0Aimport re%0Aimport shutil%0A%0A%0A%0Aparser = argparse.ArgumentParser()%0Aparser.add_argument('--data_dir', type=str, help=%22video image list%22,%0A%09%09%09%09%09default='/media/llj/storage/tvcj/hmdbcnn3_test')%0Aparser.add_argument('--origin_file_dir', type=str, default='/media/llj/storage/hmdb51')%0A%0Aargs = parser.parse_args()%0A%0Atxt_files = %5B%5D%0Afor root, folders, filenames in os.walk(args.data_dir):%0A for filename in filenames:%0A txt_files.append(str(filename))%0Aprint ' 1 ', txt_files%5B0%5D%0A%0A%0Aclass_name = os.listdir(args.origin_file_dir)%0Afor name in class_name:%0A if not os.path.exists(args.data_dir + '/' + name):%0A os.makedirs(args.data_dir + '/' + name)%0A%0Afor root, folders, filename in os.walk(args.origin_file_dir):%0A for folder in folders:%0A folder_dir = os.path.join(root,folder)%0A avi_files = os.listdir(folder_dir)%0A #print ' avi 1', avi_files%5B0%5D%0A for txt in txt_files:%0A if txt%5B:-4%5D in str(avi_files):%0A shutil.move(args.data_dir + '/' + txt , args.data_dir + '/' + folder+'/'+txt)%0A %0A
|
|
6349d8acfd76fc893dfdb6a7c12aebfe9ec1bac9 | add plexpy/Plex.tv | Contents/Libraries/Shared/subzero/lib/auth.py | Contents/Libraries/Shared/subzero/lib/auth.py | Python | 0 | @@ -0,0 +1,2120 @@
+# coding=utf-8%0A%0A%0A# thanks, https://github.com/drzoidberg33/plexpy/blob/master/plexpy/plextv.py%0A%0Aclass PlexTV(object):%0A %22%22%22%0A Plex.tv authentication%0A %22%22%22%0A%0A def __init__(self, username=None, password=None):%0A self.protocol = 'HTTPS'%0A self.username = username%0A self.password = password%0A self.ssl_verify = plexpy.CONFIG.VERIFY_SSL_CERT%0A%0A self.request_handler = http_handler.HTTPHandler(host='plex.tv',%0A port=443,%0A token=plexpy.CONFIG.PMS_TOKEN,%0A ssl_verify=self.ssl_verify)%0A%0A def get_plex_auth(self, output_format='raw'):%0A uri = '/users/sign_in.xml'%0A base64string = base64.encodestring('%25s:%25s' %25 (self.username, self.password)).replace('%5Cn', '')%0A headers = %7B'Content-Type': 'application/xml; charset=utf-8',%0A 'Content-Length': '0',%0A 'X-Plex-Device-Name': 'PlexPy',%0A 'X-Plex-Product': 'PlexPy',%0A 'X-Plex-Version': 'v0.1 dev',%0A 'X-Plex-Client-Identifier': plexpy.CONFIG.PMS_UUID,%0A 'Authorization': 'Basic %25s' %25 base64string + %22:%22%0A %7D%0A%0A request = self.request_handler.make_request(uri=uri,%0A proto=self.protocol,%0A request_type='POST',%0A headers=headers,%0A output_format=output_format)%0A%0A return request%0A%0A def get_token(self):%0A plextv_response = self.get_plex_auth(output_format='xml')%0A%0A if plextv_response:%0A xml_head = plextv_response.getElementsByTagName('user')%0A if not xml_head:%0A logger.warn(%22Error parsing XML for Plex.tv token%22)%0A return %5B%5D%0A%0A auth_token = xml_head%5B0%5D.getAttribute('authenticationToken')%0A%0A return auth_token%0A else:%0A return %5B%5D
|
|
d0c2ee2e0d848a586cc03ba5ac5da697b333ef32 | Create list of random num | Misc/listOfRandomNum.py | Misc/listOfRandomNum.py | Python | 0.00002 | @@ -0,0 +1,176 @@
+#List of randoms%0A%0Aimport random%0Aimport math%0A%0AnumList = %5B%5D%0A%0Afor i in range(10):%0A numList.append(random.randrange(1, 20))%0A%0Afor i in numList:%0A print(%22Rand num = %22 + str(i))%0A
|
|
9f508a429949d59f9969cc1e17a9094fa7c2441d | Create routines.py | routines.py | routines.py | Python | 0.000003 | @@ -0,0 +1 @@
+%0A
|
|
85abbe29c7c764deac75b6e7b95e1ccec645d84b | Add icmp_ping ansible module | ansible-tests/validations/library/icmp_ping.py | ansible-tests/validations/library/icmp_ping.py | Python | 0 | @@ -0,0 +1,971 @@
+#!/usr/bin/env python%0A%0ADOCUMENTATION = '''%0A---%0Amodule: icmp_ping%0Ashort_description: ICMP ping remote hosts%0Arequirements: %5B ping %5D%0Adescription:%0A - Check host connectivity with ICMP ping.%0Aoptions:%0A host:%0A required: true%0A description:%0A - IP address or hostname of host to ping%0A type: str%0Aauthor: %22Martin Andre (@mandre)%22%0A'''%0A%0AEXAMPLES = '''%0A# Ping host:%0A- icmp: name=somegroup state=present%0A- hosts: webservers%0A tasks:%0A - name: Check Internet connectivity%0A ping: host=%22www.ansible.com%22%0A'''%0A%0A%0Adef main():%0A module = AnsibleModule(%0A argument_spec = dict(%0A host = dict(required=True, type='str'),%0A )%0A )%0A%0A failed = False%0A%0A host = module.params.pop('host')%0A result = module.run_command('ping -c 1 %7B%7D'.format(host))%5B0%5D%0A if result != 0:%0A failed = True%0A%0A module.exit_json(failed=failed, changed=False)%0A%0A%0Afrom ansible.module_utils.basic import *%0Aif __name__ == '__main__':%0A main()%0A
|
|
24cf3ca775e8f42fa73217e29d3662a32627f9ea | Use a more reliable method to get the commit SHA for a tag. | buedafab/notify.py | buedafab/notify.py | """Deploy notification hooks for third party services like Campfire and Hoptoad.
"""
from fabric.api import env, require, local
from fabric.decorators import runs_once
import os
from buedafab import utils
@runs_once
def hoptoad_deploy(deployed=False):
"""Notify Hoptoad of the time and commit SHA of an app deploy.
Requires the hoppy Python package and the env keys:
hoptoad_api_key - as it sounds.
deployment_type - app environment
release - the commit SHA or git tag of the deployed version
scm - path to the remote git repository
"""
require('hoptoad_api_key')
require('deployment_type')
require('release')
require('scm')
if deployed and env.hoptoad_api_key:
commit = local('git rev-parse --short %(release)s' % env,
capture=True)
import hoppy.deploy
hoppy.api_key = env.hoptoad_api_key
try:
hoppy.deploy.Deploy().deploy(
env=env.deployment_type,
scm_revision=commit,
scm_repository=env.scm,
local_username=os.getlogin())
except Exception, e:
print ("Couldn't notify Hoptoad of the deploy, but continuing "
"anyway: %s" % e)
else:
print ('Hoptoad notified of deploy of %s@%s to %s environment by %s'
% (env.scm, commit, env.deployment_type, os.getlogin()))
@runs_once
def campfire_notify(deployed=False):
"""Hop in Campfire and notify your developers of the time and commit SHA of
an app deploy.
Requires the pinder Python package and the env keys:
deployment_type - app environment
release - the commit SHA or git tag of the deployed version
scm_http_url - path to an HTTP view of the remote git repository
campfire_subdomain - subdomain of your Campfire account
campfire_token - API token for Campfire
campfire_room - the room to join and notify (the string name, e.g.
"Developers")
"""
require('deployment_type')
require('release')
if (deployed and env.campfire_subdomain and env.campfire_token
and env.campfire_room):
from pinder import Campfire
deploying = local('git rev-parse --short %(release)s' % env,
capture=True)
branch = utils.branch(env.release)
if env.tagged:
require('release')
branch = env.release
name = env.unit
deployer = os.getlogin()
deployed = env.deployed_version
target = env.deployment_type.lower()
source_repo_url = env.scm_http_url
compare_url = ('%s/compare/%s...%s' % (source_repo_url, deployed,
deploying))
campfire = Campfire(env.campfire_subdomain, env.campfire_token,
ssl=True)
room = campfire.find_room_by_name(env.campfire_room)
room.join()
if deployed:
message = ('%s is deploying %s %s (%s..%s) to %s %s'
% (deployer, name, branch, deployed, deploying, target,
compare_url))
else:
message = ('%s is deploying %s %s to %s' % (deployer, name,
branch, target))
room.speak(message)
print 'Campfire notified that %s' % message
| Python | 0 | @@ -2281,41 +2281,46 @@
rev-
-parse --short %25(release)s' %25 env,
+list --abbrev-commit %25s %7C head -n 1' %25
%0A
@@ -2323,32 +2323,45 @@
%0A
+ env.release,
capture=True)%0A
|
d3937b803baf036d5bd96dfcb1e10e51b29bab1e | Create migration | fellowms/migrations/0023_event_ad_status.py | fellowms/migrations/0023_event_ad_status.py | Python | 0.000001 | @@ -0,0 +1,540 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.7 on 2016-06-06 13:00%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('fellowms', '0022_fellow_user'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='event',%0A name='ad_status',%0A field=models.CharField(choices=%5B('U', 'Unprocessed'), ('V', 'Visible'), ('H', 'Hide'), ('A', 'Archived')%5D, default='U', max_length=1),%0A ),%0A %5D%0A
|
|
db465ffe58a425b651930eaf1778ef179ed42d2a | Rename res_dict to result and add comment. | redash/query_runner/dynamodb_sql.py | redash/query_runner/dynamodb_sql.py | import json
import logging
import sys
from redash.query_runner import *
from redash.utils import JSONEncoder
logger = logging.getLogger(__name__)
try:
from dql import Engine, FragmentEngine
from pyparsing import ParseException
enabled = True
except ImportError, e:
enabled = False
types_map = {
'UNICODE': TYPE_INTEGER,
'TINYINT': TYPE_INTEGER,
'SMALLINT': TYPE_INTEGER,
'INT': TYPE_INTEGER,
'DOUBLE': TYPE_FLOAT,
'DECIMAL': TYPE_FLOAT,
'FLOAT': TYPE_FLOAT,
'REAL': TYPE_FLOAT,
'BOOLEAN': TYPE_BOOLEAN,
'TIMESTAMP': TYPE_DATETIME,
'DATE': TYPE_DATETIME,
'CHAR': TYPE_STRING,
'STRING': TYPE_STRING,
'VARCHAR': TYPE_STRING
}
class DynamoDBSQL(BaseSQLQueryRunner):
@classmethod
def configuration_schema(cls):
return {
"type": "object",
"properties": {
"region": {
"type": "string",
"default": "us-east-1"
},
"access_key": {
"type": "string",
},
"secret_key": {
"type": "string",
}
},
"required": ["access_key", "secret_key"],
"secret": ["secret_key"]
}
def test_connection(self):
engine = self._connect()
list(engine.connection.list_tables())
@classmethod
def annotate_query(cls):
return False
@classmethod
def type(cls):
return "dynamodb_sql"
@classmethod
def name(cls):
return "DynamoDB (with DQL)"
def __init__(self, configuration):
super(DynamoDBSQL, self).__init__(configuration)
def _connect(self):
engine = FragmentEngine()
config = self.configuration.to_dict()
if not config.get('region'):
config['region'] = 'us-east-1'
if config.get('host') == '':
config['host'] = None
engine.connect(**config)
return engine
def _get_tables(self, schema):
engine = self._connect()
for table in engine.describe_all():
schema[table.name] = {'name': table.name, 'columns': table.attrs.keys()}
def run_query(self, query, user):
engine = None
try:
engine = self._connect()
res_dict = engine.execute(query if str(query).endswith(';') else str(query)+';')
columns = []
rows = []
if isinstance(result, basestring):
result = [{"value": result}]
for item in res_dict:
if not columns:
for k, v in item.iteritems():
columns.append({
'name': k,
'friendly_name': k,
'type': types_map.get(str(type(v)).upper(), None)
})
rows.append(item)
data = {'columns': columns, 'rows': rows}
json_data = json.dumps(data, cls=JSONEncoder)
error = None
except ParseException as e:
error = u"Error parsing query at line {} (column {}):\n{}".format(e.lineno, e.column, e.line)
json_data = None
except (SyntaxError, RuntimeError) as e:
error = e.message
json_data = None
except KeyboardInterrupt:
if engine and engine.connection:
engine.connection.cancel()
error = "Query cancelled by user."
json_data = None
except Exception as e:
raise sys.exc_info()[1], None, sys.exc_info()[2]
return json_data, error
register(DynamoDBSQL)
| Python | 0 | @@ -32,17 +32,16 @@
rt sys%0A%0A
-%0A
from red
@@ -2339,20 +2339,18 @@
res
-_dic
+ul
t = engi
@@ -2458,24 +2458,197 @@
rows = %5B%5D
+%0A%0A # When running a count query it returns the value as a string, in which case%0A # we transform it into a dictionary to be the same as regular queries.
%0A
@@ -2728,16 +2728,17 @@
esult%7D%5D%0A
+%0A
@@ -2760,16 +2760,13 @@
res
-_dic
+ul
t:%0A
-%0A
|
0781070ee0c17a34a3cc9521e8a6b67c401aa692 | Add WGAN Tests | models/wgan_test.py | models/wgan_test.py | Python | 0 | @@ -0,0 +1,870 @@
+# Lint as: python3%0A%22%22%22Tests for WGAN model.%22%22%22%0A%0Afrom __future__ import absolute_import%0Afrom __future__ import division%0Afrom __future__ import print_function%0A%0Aimport tensorflow as tf%0Aimport numpy as np%0Aimport os%0A%0Aimport wgan%0A%0A%0Aclass SpectralTest(tf.test.TestCase):%0A%0A def test_interpolation_2d(self):%0A x1 = np.random.normal(size=(10, 256))%0A x2 = np.random.normal(size=(10, 256))%0A %0A interpolation = wgan._get_interpolation(x1, x2)%0A self.assertShapeEqual(x1, interpolation)%0A %0A def test_interpolation_3d(self):%0A x1 = np.random.normal(size=(10, 256, 32))%0A x2 = np.random.normal(size=(10, 256, 32))%0A %0A interpolation = wgan._get_interpolation(x1, x2)%0A self.assertShapeEqual(x1, interpolation)%0A%0A %0A%0A%0Aif __name__ == '__main__':%0A os.environ%5B%22CUDA_VISIBLE_DEVICES%22%5D = ''%0A tf.test.main()%0A
|
|
e90d12802ff62738cbe4094e8db079f6519f47a5 | Create BDayGift.py | Probability/BDayGift.py | Probability/BDayGift.py | Python | 0 | @@ -0,0 +1,120 @@
+import sys;%0A%0An = int(sys.stdin.readline());%0AS = 0%0Afor i in range(n):%0A S += int(sys.stdin.readline());%0A %0Aprint(S/2.0);%0A
|
|
45f91a92fd3ae08dd7403707f3981f306122eb6c | test task creation | freelancefinder/remotes/tests/test_tasks.py | freelancefinder/remotes/tests/test_tasks.py | Python | 0.000322 | @@ -0,0 +1,425 @@
+%22%22%22Tests related to the remotes.tasks functions.%22%22%22%0A%0Afrom django_celery_beat.models import IntervalSchedule, PeriodicTask%0A%0Afrom ..tasks import setup_periodic_tasks%0A%0A%0Adef test_make_tasks():%0A %22%22%22Ensure that setup makes some tasks/schedules.%22%22%22%0A setup_periodic_tasks(None)%0A intervals = IntervalSchedule.objects.all().count()%0A tasks = PeriodicTask.objects.all().count()%0A%0A assert intervals %3E 0%0A assert tasks %3E 0%0A
|
|
9edce7cb1704aa1d06b74b661725d54b465e54da | Add SQLALCHEMY_ECHO support in heroku.py (when debugging) | heroku.py | heroku.py | #!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ZKillmail
from evesrp.transformers import ShipTransformer, PilotTransformer
from evesrp.auth.testauth import TestAuth
from evesrp.auth.bravecore import BraveCore
from os import environ as env
from binascii import unhexlify
from ecdsa import SigningKey, VerifyingKey, NIST256p
from hashlib import sha256
class TestZKillboard(ZKillmail):
def __init__(self, *args, **kwargs):
super(TestZKillboard, self).__init__(*args, **kwargs)
if self.domain not in ('zkb.pleaseignore.com', 'kb.pleaseignore.com'):
raise ValueError("This killmail is from the wrong killboard")
@property
def value(self):
return 0
def hex2key(hex_key):
key_bytes = unhexlify(hex_key)
if len(hex_key) == 64:
return SigningKey.from_string(key_bytes, curve=NIST256p,
hashfunc=sha256)
elif len(hex_key) == 128:
return VerifyingKey.from_string(key_bytes, curve=NIST256p,
hashfunc=sha256)
else:
raise ValueError("Key in hex form is of the wrong length.")
def configure_app(app, config):
app.config['USER_AGENT_EMAIL'] = '[email protected]'
app.config['SQLALCHEMY_DATABASE_URI'] = config.get('DATABASE_URL',
'sqlite:///')
app.config['AUTH_METHODS'] = [TestAuth(admins=['paxswill',]), ]
app.config['KILLMAIL_SOURCES'] = [
EveWikiZKillmail,
EveWikiCRESTMail
]
# Configure Brave Core if all the needed things are there
try:
core_private_key = hex2key(config['CORE_AUTH_PRIVATE_KEY'])
core_public_key = hex2key(config['CORE_AUTH_PUBLIC_KEY'])
core_identifier = config['CORE_AUTH_IDENTIFIER']
except KeyError:
pass
else:
app.config['AUTH_METHODS'].append(BraveCore(core_private_key,
core_public_key, core_identifier))
if config.get('DEBUG') is not None:
app.debug = True
secret_key = config.get('SECRET_KEY')
if secret_key is not None:
app.config['SECRET_KEY'] = unhexlify(secret_key)
app = create_app()
configure_app(app, env)
if __name__ == '__main__':
# So we get the database tables for these
from evesrp.auth.testauth import TestUser, TestGroup
from evesrp.auth.bravecore import CoreUser, CoreGroup
print("Creating databases...")
app.extensions['sqlalchemy'].db.create_all(app=app)
| Python | 0 | @@ -1980,16 +1980,119 @@
g = True
+%0A if config.get('SQLALCHEMY_ECHO') is not None:%0A app.config%5B'SQLALCHEMY_ECHO'%5D = True
%0A%0A se
|
cd3f59026b9026d62537b38d4e9d70a740e88018 | Add tests for java mode | tests/test_java_mode.py | tests/test_java_mode.py | Python | 0.000001 | @@ -0,0 +1,2195 @@
+import editor_manager%0Aimport editor_common%0Aimport curses%0Aimport curses.ascii%0Aimport keytab%0Afrom ped_test_util import read_str,validate_screen,editor_test_suite,play_macro,screen_size,match_attr%0A%0Adef test_java_mode(testdir,capsys):%0A with capsys.disabled():%0A def main(stdscr):%0A lines_to_test = %5B%0A '// This is a simple Java program.',%0A '// FileName : %22HelloWorld.java%22',%0A 'class HelloWorld',%0A '%7B',%0A ' // Your program begins with a call to main()',%0A ' // Prints %22Hello, World%22 to the terminal window',%0A ' public static void main(String args%5B%5D)',%0A ' %7B',%0A ' System.out.println(%22Hello, World%22);',%0A ' %7D',%0A '%7D'%0A %5D%0A args = %7B %22java_test%22:%22%5Cn%22.join(lines_to_test)%7D%0A testfile = testdir.makefile(%22.java%22, **args)%0A%0A green = curses.color_pair(1)%0A red = curses.color_pair(2)%0A cyan = curses.color_pair(3)%0A white = curses.color_pair(4)%0A%0A ed = editor_common.Editor(stdscr,None,str(testfile))%0A ed.setWin(stdscr.subwin(ed.max_y,ed.max_x,0,0))%0A ed.main(False)%0A ed.main(False)%0A validate_screen(ed)%0A assert(ed.mode and ed.mode.name() == %22java_mode%22)%0A match_list = %5B(0,0,32,red),(2,0,5,cyan),(4,4,44,red),(8,27,14,green)%5D%0A for line,pos,width,attr in match_list:%0A assert(match_attr(ed.scr,line+1,pos,1,width,attr))%0A ed.goto(7,5)%0A ed.endln()%0A ed.main(False,10)%0A assert(ed.getLine() == 8 and ed.getPos() == 4)%0A ed.insert('if (20 %3E 18) %7B')%0A ed.main(False,10)%0A ed.insert('System.out.println(%2220 greater than 18%22);')%0A ed.main(False,10)%0A ed.insert('%7D')%0A ed.main(False,10)%0A ed.main(False)%0A ed.main(False)%0A assert(match_attr(ed.scr,9,4,1,2,cyan))%0A assert(match_attr(ed.scr,10,27,1,20,green))%0A assert(ed.getLine() == 11 and ed.getPos() == 4)%0A%0A curses.wrapper(main)%0A
|
|
f03f976696077db4146ea78e0d0b1ef5767f00ca | Add high level signing capabilities | tests/unit/test_sign.py | tests/unit/test_sign.py | Python | 0 | @@ -0,0 +1,554 @@
+# Import libnacl libs%0Aimport libnacl.sign%0A%0A# Import pythonlibs%0Aimport unittest%0A%0A%0Aclass TestSigning(unittest.TestCase):%0A '''%0A '''%0A def test_sign(self):%0A msg = ('Well, that%5C's no ordinary rabbit. That%5C's the most foul, '%0A 'cruel, and bad-tempered rodent you ever set eyes on.')%0A signer = libnacl.sign.Signer()%0A signed = signer.sign(msg)%0A self.assertNotEqual(msg, signed)%0A veri = libnacl.sign.Verifier(signer.hex_vk())%0A verified = veri.verify(signed)%0A self.assertEqual(verified, msg)%0A
|
|
f6609763f832cd5672e40d1dfe8f7dc7c58ca7c5 | Create diarygui.py | _src/om2py2w/2wex0/diarygui.py | _src/om2py2w/2wex0/diarygui.py | Python | 0 | @@ -0,0 +1,1052 @@
+# -*- coding: utf-8 -*- %0A# ------------2w task:simple diary GUI-----------%0A# --------------created by bambooom-------------- %0A%0A%0Afrom Tkinter import * # import Tkinter module%0Afrom ScrolledText import * # ScrolledText module = Text Widget + scrollbar%0A%0Aglobal newlog%0A%0Aclass Application(Frame): # %E5%9F%BA%E6%9C%AC%E6%A1%86%E6%9E%B6%0A%0A def __init__(self, master=None):%0A Frame.__init__(self, master)%0A self.pack()%0A self.createWidgets()%0A%0A def createWidgets(self): # %E7%BB%84%E4%BB%B6%0A newlog = StringVar()%0A%0A l = Label(self, text = %22Input here: %22) # Label Widget %E6%8F%90%E7%A4%BA%E8%BE%93%E5%85%A5%0A l.grid(row = 0, column = 0, sticky = W)%0A%0A e = Entry(self,textvariable=newlog,width=80) # Entry box %E8%BE%93%E5%85%A5%E6%A1%86%0A e.grid(row = 0, column = 1, sticky = W)%0A%0A t = ScrolledText(self) # ScrolledText %E6%89%93%E5%8D%B0%E5%87%BA%E6%96%87%E6%A1%A3%E7%9A%84%E6%A1%86%0A t.grid(columnspan = 2, sticky = W)%0A%0A b = Button(self, text=%22QUIT%22, fg=%22red%22, command=self.quit) # %E9%80%80%E5%87%BA%E7%9A%84button%0A b.grid(row = 2, column = 0, sticky = W)%0A%0A%0Aroot = Tk()%0Aroot.title('MyDiary Application')%0Aapp = Application(root)%0A%0A# %E4%B8%BB%E6%B6%88%E6%81%AF%E5%BE%AA%E7%8E%AF:%0Aapp.mainloop()%0A
|
|
c43c7d523ddbb5b914748a20d55971fbf1c12496 | Create oauth2token.py | oauth2token.py | oauth2token.py | Python | 0.000016 | @@ -0,0 +1,1204 @@
+#!/usr/bin/python%0A%0A'''%0A This script will attempt to open your webbrowser,%0A perform OAuth 2 authentication and print your access token.%0A%0A It depends on two libraries: oauth2client and gflags.%0A%0A To install dependencies from PyPI:%0A%0A $ pip install python-gflags oauth2client%0A%0A Then run this script:%0A%0A $ python get_oauth2_token.py%0A %0A This is a combination of snippets from:%0A https://developers.google.com/api-client-library/python/guide/aaa_oauth%0A'''%0Aimport sys%0Asys.path.append('/usr/lib/python2.7/dist-packages')%0Afrom oauth2client.client import OAuth2WebServerFlow%0Afrom oauth2client.tools import run%0Afrom oauth2client.file import Storage%0A%0A%0ACLIENT_ID = '411103951529-nf611s2285n12mmqrkigq3ckgkac1gmv.apps.googleusercontent.com'%0A%0ACLIENT_SECRET = 'uDKCenlmvo1desQfylHIUnYr'%0A%0A%0Aflow = OAuth2WebServerFlow(client_id=CLIENT_ID,%0A client_secret=CLIENT_SECRET,%0A scope='https://spreadsheets.google.com/feeds https://docs.google.com/feeds',%0A redirect_uri='http://example.com/auth_return')%0A%0Astorage = Storage('creds.data')%0A%0Acredentials = run(flow, storage)%0A%0Aprint (%22access_token: %25s%22) %25 credentials.access_token%0A%0A
|
|
31cdb65a8d370c6f309ad610aa3b969d5bfb8706 | Add follow_bot.py | follow_bot.py | follow_bot.py | Python | 0.00002 | @@ -0,0 +1,1530 @@
+%22%22%22Follow bot, to follow some followers from an account%0A%22%22%22%0A__date__ = '08/01/2014'%0A__author__ = '@ismailsunni'%0A%0Aimport tweepy%0Aimport constants%0A%0A# constants%0Aconsumer_key = constants.consumer_key%0Aconsumer_secret = constants.consumer_secret%0Aaccess_key = constants.access_key%0Aaccess_secret = constants.access_secret%0A%0Adef need_to_follow(user):%0A statuses_count = user.statuses_count%0A followers_count = user.followers_count%0A friends_count = user.friends_count%0A created_at = user.created_at%0A # last_status_time = user.status.created_at%0A%0A if followers_count %3E friends_count:%0A return True%0A else:%0A return False%0A%0A%0Adef main():%0A auth = tweepy.OAuthHandler(consumer_key, consumer_secret)%0A auth.set_access_token(access_key, access_secret)%0A api = tweepy.API(auth)%0A # accounts = %5B'sarapanhaticom'%5D%0A accounts = %5B'rischanmafrur'%5D%0A for account in accounts:%0A followers = api.followers(account)%0A print followers%0A for follower in followers:%0A if need_to_follow(follower):%0A print follower.screen_name%0A try:%0A friend = api.create_friendship(follower.screen_name)%0A if friend.screen_name == follower.screen_name:%0A print 'Follow ' + follower.name + ' success'%0A else:%0A print 'Follow ' + follower.name + ' failed'%0A except tweepy.TweepError, e:%0A print e%0A%0A print 'benar'%0A%0Aif __name__ == '__main__':%0A main()
|
|
e26be1cdee6b40896e7ee5c2a894fba05fc58480 | Add traceview directory. | traceview/__init__.py | traceview/__init__.py | Python | 0 | @@ -0,0 +1,233 @@
+# -*- coding: utf-8 -*-%0A%0A%22%22%22%0ATraceView API library%0A%0A:copyright: (c) 2014 by Daniel Riti.%0A:license: MIT, see LICENSE for more details.%0A%0A%22%22%22%0A%0A__title__ = 'traceview'%0A__version__ = '0.1.0'%0A__author__ = 'Daniel Riti'%0A__license__ = 'MIT'%0A
|
|
b28d2933ac1b5c6375f9dd5142f467a06bd69463 | add a simple plot script to visualize the distribution | Utils/py/BallDetection/Evaluation/plot_csv.py | Utils/py/BallDetection/Evaluation/plot_csv.py | Python | 0 | @@ -0,0 +1,221 @@
+import matplotlib.pyplot as plt%0Aimport sys%0Aimport numpy as np%0A%0Ascores = np.genfromtxt(sys.argv%5B1%5D, usecols=(1), skip_header=1, delimiter=%22,%22)%0A%0Ascores = np.sort(scores)%0A%0Aplt.style.use('seaborn')%0Aplt.plot(scores)%0Aplt.show()
|
|
6d910181758008d05de3917fdac5b35b34188a8e | add RebootNodeWithPCU call. fails gracefully if dependencies are not met. | PLC/Methods/RebootNodeWithPCU.py | PLC/Methods/RebootNodeWithPCU.py | Python | 0 | @@ -0,0 +1,2270 @@
+import socket%0A%0Afrom PLC.Faults import *%0Afrom PLC.Method import Method%0Afrom PLC.Parameter import Parameter, Mixed%0Afrom PLC.Nodes import Node, Nodes%0Afrom PLC.NodeNetworks import NodeNetwork, NodeNetworks%0Afrom PLC.Auth import Auth%0Afrom PLC.POD import udp_pod%0A%0Atry:%0A%09from pcucontrol import reboot%0A%09external_dependency = True%0Aexcept:%0A%09external_dependency = False%0A%0Aclass RebootNodeWithPCU(Method):%0A %22%22%22%0A%09Uses the associated PCU to attempt to reboot the given Node.%0A%0A Admins can reboot any node. Techs and PIs can only reboot nodes at%0A their site.%0A%0A Returns 1 if the reboot proceeded without error (Note: this does not guarantee%0A%09that the reboot is successful).%0A%09Returns -1 if external dependencies for this call are not available.%0A%09Returns %22error string%22 if the reboot failed with a specific message.%0A %22%22%22%0A%0A roles = %5B'admin', 'pi', 'tech'%5D%0A%0A accepts = %5B%0A Auth(),%0A Mixed(Node.fields%5B'node_id'%5D,%0A Node.fields%5B'hostname'%5D)%0A %5D%0A%0A returns = Parameter(int, '1 if successful')%0A%0A def call(self, auth, node_id_or_hostname):%0A # Get account information%0A nodes = Nodes(self.api, %5Bnode_id_or_hostname%5D)%0A if not nodes:%0A raise PLCInvalidArgument, %22No such node%22%0A%0A node = nodes%5B0%5D%0A%0A # Authenticated function%0A assert self.caller is not None%0A%0A # If we are not an admin, make sure that the caller is a%0A # member of the site at which the node is located.%0A if 'admin' not in self.caller%5B'roles'%5D:%0A if node%5B'site_id'%5D not in self.caller%5B'site_ids'%5D:%0A raise PLCPermissionDenied, %22Not allowed to reboot nodes from specified site%22%0A%0A%09%09# Verify that the node has pcus associated with it.%0A%09%09pcus = PCUs(self.api, %7B'pcu_id' : node%5B'pcu_ids'%5D%7D )%0A if not pcus:%0A raise PLCInvalidArgument, %22No PCUs associated with Node%22%0A%0A%09%09pcu = pcus%5B0%5D%0A%0A%09%09if not external_dependency:%0A raise PLCNotImplemented, %22Could not load external module to attempt reboot%22%0A%0A%09%09# model, hostname, port, %0A%09%09# i = pcu%5B'node_ids'%5D.index(node%5B'node_id'%5D)%0A%09%09# p = pcu%5B'ports'%5D%5Bi%5D%0A%09%09ret = reboot.reboot_api(node, pcu)%0A%0A self.event_objects = %7B'Node': %5Bnode%5B'node_id'%5D%5D%7D%0A self.message = %22RebootNodeWithPCU called%22%0A%09 %0A return ret%0A
|
|
f75e1397735adcbd39dbc90a0446b9efd9532be4 | add initial python script to handle button events that trigger the node process | bin/selfie.py | bin/selfie.py | Python | 0 | @@ -0,0 +1,346 @@
+#!/usr/bin/python%0A%0Aimport RPi.GPIO as GPIO%0Aimport time%0Afrom subprocess import call%0A%0AGPIO.setmode(GPIO.BCM)%0A%0ABUTTON = 18;%0A%0AGPIO.setup(BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP)%0A%0Awhile True:%0A input_state = GPIO.input(BUTTON)%0A if input_state == False:%0A print('Button Pressed')%0A call(%5B%22node%22, %22./index.js%22%5D)%0A time.sleep(1)%0A
|
|
fb83969c6467e288ff16661aec2eafc174bdf124 | correct fieldsight form issue fix | onadata/apps/fsforms/management/commands/set_correct_fxf_in_finstance.py | onadata/apps/fsforms/management/commands/set_correct_fxf_in_finstance.py | Python | 0 | @@ -0,0 +1,1431 @@
+from django.db import transaction%0Afrom django.core.management.base import BaseCommand%0A%0Afrom onadata.apps.fieldsight.models import Site%0Afrom onadata.apps.fsforms.models import FieldSightXF, FInstance%0Afrom onadata.apps.viewer.models.parsed_instance import update_mongo_instance%0A%0A%0Aclass Command(BaseCommand):%0A help = 'Deploy Stages'%0A%0A def handle(self, *args, **options):%0A organization_id = 13%0A # project_id = 30%0A sites = Site.objects.filter(project__organization__id=organization_id).values_list('id', flat=True)%0A for site_id in sites:%0A # self.stdout.write('Operating in site '+str(site_id))%0A with transaction.atomic():%0A finstances = FInstance.objects.filter(site_id=site_id, site_fxf_id__isnull=False)%0A for fi in finstances:%0A site_fsxf = fi.site_fxf%0A if site_fsxf.site.id != site_id:%0A correct_form = FieldSightXF.objects.get(site__id=site_id, is_staged=True, fsform=fi.project_fxf)%0A fi.site_fxf = correct_form%0A fi.save()%0A parsed_instance = fi.instance.parsed_instance%0A d = parsed_instance.to_dict_for_mongo()%0A d.update(%7B'fs_uuid': correct_form.id%7D)%0A update_mongo_instance(d)%0A self.stdout.write('Successfully corrected form')%0A
|
|
0f76875400ea1a03a23a4b266eb0ca9bf574922d | implement 9 (9) 各行を2コラム目,1コラム目の優先順位で辞書の逆順ソートしたもの(注意: 各行の内容は変更せずに並び替えよ).確認にはsortコマンドを用いよ(この問題は結果が合わなくてもよい). | set01/09.py | set01/09.py | Python | 0.000001 | @@ -0,0 +1,381 @@
+# -*- coding: utf-8 -*-%0A# (9) %E5%90%84%E8%A1%8C%E3%82%92%EF%BC%92%E3%82%B3%E3%83%A9%E3%83%A0%E7%9B%AE%EF%BC%8C%EF%BC%91%E3%82%B3%E3%83%A9%E3%83%A0%E7%9B%AE%E3%81%AE%E5%84%AA%E5%85%88%E9%A0%86%E4%BD%8D%E3%81%A7%E8%BE%9E%E6%9B%B8%E3%81%AE%E9%80%86%E9%A0%86%E3%82%BD%E3%83%BC%E3%83%88%E3%81%97%E3%81%9F%E3%82%82%E3%81%AE%EF%BC%88%E6%B3%A8%E6%84%8F: %E5%90%84%E8%A1%8C%E3%81%AE%E5%86%85%E5%AE%B9%E3%81%AF%E5%A4%89%E6%9B%B4%E3%81%9B%E3%81%9A%E3%81%AB%E4%B8%A6%E3%81%B3%E6%9B%BF%E3%81%88%E3%82%88%EF%BC%89%EF%BC%8E%E7%A2%BA%E8%AA%8D%E3%81%AB%E3%81%AFsort%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%82%92%E7%94%A8%E3%81%84%E3%82%88%EF%BC%88%E3%81%93%E3%81%AE%E5%95%8F%E9%A1%8C%E3%81%AF%E7%B5%90%E6%9E%9C%E3%81%8C%E5%90%88%E3%82%8F%E3%81%AA%E3%81%8F%E3%81%A6%E3%82%82%E3%82%88%E3%81%84%EF%BC%89%EF%BC%8E%0A%0Aimport sys%0A%0Alines = %5Bline.decode('utf-8').rstrip(u'%5Cr%5Cn') for line in sys.stdin.readlines()%5D%0Alines = sorted(lines, key = lambda l: l.split(u'%5Ct')%5B0%5D)%0Alines = sorted(lines, key = lambda l: l.split(u'%5Ct')%5B1%5D)%0A%0Afor line in lines:%0A print line.encode('utf-8')%0A%0A
|
|
c24dc9072e1e8bddc3dbda09f1b98b51d91fc644 | fix fetching (#2921) | var/spack/repos/builtin/packages/oce/package.py | var/spack/repos/builtin/packages/oce/package.py | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# 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 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
import platform
class Oce(Package):
"""Open CASCADE Community Edition:
patches/improvements/experiments contributed by users over the official
Open CASCADE library.
"""
homepage = "https://github.com/tpaviot/oce"
url = "https://github.com/tpaviot/oce/archive/OCE-0.18.tar.gz"
version('0.18', '226e45e77c16a4a6e127c71fefcd171410703960ae75c7ecc7eb68895446a993')
version('0.17.2', 'bf2226be4cd192606af677cf178088e5')
version('0.17.1', '36c67b87093c675698b483454258af91')
version('0.17', 'f1a89395c4b0d199bea3db62b85f818d')
version('0.16.1', '4d591b240c9293e879f50d86a0cb2bb3')
version('0.16', '7a4b4df5a104d75a537e25e7dd387eca')
variant('tbb', default=True,
description='Build with Intel Threading Building Blocks')
depends_on('[email protected]:', type='build')
depends_on('tbb', when='+tbb')
# There is a bug in OCE which appears with Clang (version?) or GCC 6.0
# and has to do with compiler optimization, see
# https://github.com/tpaviot/oce/issues/576
# http://tracker.dev.opencascade.org/view.php?id=26042
# https://github.com/tpaviot/oce/issues/605
# https://github.com/tpaviot/oce/commit/61cb965b9ffeca419005bc15e635e67589c421dd.patch
patch('null.patch', when='@0.16:0.17.1')
# fix build with Xcode 8 "previous definition of CLOCK_REALTIME"
# reported 27 Sep 2016 https://github.com/tpaviot/oce/issues/643
if (platform.system() == "Darwin") and (
'.'.join(platform.mac_ver()[0].split('.')[:2]) == '10.12'):
patch('sierra.patch', when='@0.17.2:0.18')
def install(self, spec, prefix):
options = []
options.extend(std_cmake_args)
options.extend([
'-DOCE_INSTALL_PREFIX=%s' % prefix,
'-DOCE_BUILD_SHARED_LIB:BOOL=ON',
'-DCMAKE_BUILD_TYPE:STRING=Release',
'-DOCE_DATAEXCHANGE:BOOL=ON',
'-DOCE_DISABLE_X11:BOOL=ON',
'-DOCE_DRAW:BOOL=OFF',
'-DOCE_MODEL:BOOL=ON',
'-DOCE_MULTITHREAD_LIBRARY:STRING=%s' % (
'TBB' if '+tbb' in spec else 'NONE'),
'-DOCE_OCAF:BOOL=ON',
'-DOCE_USE_TCL_TEST_FRAMEWORK:BOOL=OFF',
'-DOCE_VISUALISATION:BOOL=OFF',
'-DOCE_WITH_FREEIMAGE:BOOL=OFF',
'-DOCE_WITH_GL2PS:BOOL=OFF',
'-DOCE_WITH_OPENCL:BOOL=OFF'
])
if platform.system() == 'Darwin':
options.extend([
'-DOCE_OSX_USE_COCOA:BOOL=ON',
])
if '.'.join(platform.mac_ver()[0].split('.')[:2]) == '10.12':
# use @rpath on Sierra due to limit of dynamic loader
options.append('-DCMAKE_MACOSX_RPATH=ON')
else:
options.append('-DCMAKE_INSTALL_NAME_DIR:PATH=%s/lib' % prefix)
cmake('.', *options)
make("install/strip")
if self.run_tests:
make("test")
| Python | 0.000002 | @@ -1473,80 +1473,8 @@
oce%22
-%0A url = %22https://github.com/tpaviot/oce/archive/OCE-0.18.tar.gz%22
%0A%0A
@@ -2031,24 +2031,167 @@
en='+tbb')%0A%0A
+ def url_for_version(self, version):%0A return 'https://github.com/tpaviot/oce/archive/OCE-%25s.tar.gz' %25 (%0A version.dotted)%0A%0A
# There
|
d654bf0fb0c5e3fc7a11029a216c109b5f04d37b | Add __init__ file | taxdata/cps/__init__.py | taxdata/cps/__init__.py | Python | 0.00026 | @@ -0,0 +1,458 @@
+# flake8: noqa%0Afrom taxdata.cps import benefits%0Afrom taxdata.cps import cps_meta%0Afrom taxdata.cps import cpsmar%0Afrom taxdata.cps.create import create%0Afrom taxdata.cps.finalprep import finalprep%0Afrom taxdata.cps import helpers%0Afrom taxdata.cps import impute%0Afrom taxdata.cps import pycps%0Afrom taxdata.cps import splitincome%0Afrom taxdata.cps import targeting%0Afrom taxdata.cps import taxunit%0Afrom taxdata.cps import validation%0Afrom taxdata.cps import constants%0A
|
|
1fddb845ad99bb65aa7b86155d899043a64ebdcf | Update app/views/main/views.py | app/views/main/views.py | app/views/main/views.py | Python | 0 | @@ -0,0 +1,1785 @@
+from flask import current_app as app%0Afrom flask import flash%0Afrom flask import redirect%0Afrom flask import render_template%0Afrom flask import url_for%0Afrom flask_login import current_user%0Afrom flask_login import login_required%0A%0Afrom . import main%0Afrom .forms import SearchForm%0A%0Afrom ..api.utils import _search%0A%0A%[email protected]('/', methods=%5B'GET', 'POST'%5D)%0Adef index():%0A return render_template('index.html')%0A%0A%[email protected]('/dashboard', methods=%5B'GET'%5D)%0A@login_required%0Adef dashboard():%0A bio = app.db.bios.count()%0A payroll = app.db.payrolls.count()%0A work = app.db.work_histories.count()%0A%0A context = %7B%0A 'counter': %7B%0A 'Bio': bio,%0A 'Payrolls': payroll,%0A 'Work Histories': work,%0A 'Mortgages': 0,%0A 'Rents': 0,%0A 'Utilities': 0,%0A 'Loans': 0,%0A 'Education Histories': 0%0A %7D,%0A 'total_records': bio + payroll + work%0A %7D%0A context.update(labels=list(context%5B'counter'%5D.keys()),%0A values=list(context%5B'counter'%5D.values()))%0A return render_template('main/dashboard.html', **context)%0A%0A%[email protected]('/search', methods=%5B'GET', 'POST'%5D)%0A@login_required%0Adef search():%0A context = %7B%7D%0A form = SearchForm()%0A%0A if form.validate_on_submit():%0A bvn = form.bvn.data%0A%0A context.update(bvn=form.bvn.data)%0A result = _search(bvn, app)%0A%0A if result.get('status') == 'error':%0A flash(result.get('message'), 'error')%0A context.update(enrollee=result)%0A else:%0A for error in form.errors.values():%0A if isinstance(error, list):%0A for e in error:%0A flash(e, 'error')%0A else:%0A flash(error, 'error')%0A return render_template('search/results.html', **context)%0A
|
|
938a9548b6503136b82fd248258df5f4e0523f8a | add sorting_algorithms.py | adv/sorting_algorithms.py | adv/sorting_algorithms.py | Python | 0.003966 | @@ -0,0 +1,2180 @@
+# Sorting Algorithms%0D%0A%0D%0Aimport random%0D%0Aimport time%0D%0A%0D%0Amy_list = range(10000)%0D%0A%0D%0Arandom.shuffle(my_list)%0D%0A%0D%0A#print sorted(my_list) #We have a way to sort information.%0D%0A%0D%0A# But how did it do that?%0D%0A%0D%0A###################################################################%0D%0A%0D%0A# What does %22efficiency%22 mean in terms of a program?%0D%0A%0D%0A# 1. Running time. Does it take a really long time to run?%0D%0A%0D%0A# 2. Resources. (Memory, Power)%0D%0A%0D%0A# 3. Lines of code%0D%0A%0D%0A# 4. Manpower%0D%0A%0D%0Adef is_sorted(lst):%0D%0A if len(lst) %3C= 1:%0D%0A return True%0D%0A else:%0D%0A return lst%5B0%5D %3C= lst%5B1%5D and is_sorted(lst%5B1:%5D)%0D%0A%0D%0Adef stupid_sort(lst):%0D%0A while not is_sorted(lst):%0D%0A random.shuffle(lst)%0D%0A return lst%0D%0A%0D%0Adef dumb_sort(lst):%0D%0A number_list= %5BNone%5D * 10000000%0D%0A for number in lst:%0D%0A number_list%5Bnumber%5D = number%0D%0A sorted_list = %5B%5D%0D%0A for thing in number_list:%0D%0A if thing:%0D%0A sorted_list.append(thing)%0D%0A return sorted_list%0D%0A%0D%0Adef insertion_sort(lst):%0D%0A new_list = %5Blst%5B0%5D%5D%0D%0A for element in lst%5B1:%5D:%0D%0A for index, new_element in enumerate(new_list):%0D%0A if element %3C= new_element:%0D%0A new_list.insert(index, element)%0D%0A found = True%0D%0A break%0D%0A else:%0D%0A new_list.append(element)%0D%0A return new_list%0D%0A%0D%0Adef selection_sort(lst):%0D%0A new_list = %5B%5D%0D%0A length = len(lst)%0D%0A while len(new_list) != length:%0D%0A element = min(lst)%0D%0A lst.remove(element)%0D%0A new_list.append(element)%0D%0A return new_list%0D%0A%0D%0Adef merge(left, right):%0D%0A new_list = %5B%5D%0D%0A while len(left) %3E 0 and len(right) %3E 0:%0D%0A if left%5B0%5D %3C= right%5B0%5D:%0D%0A new_list.append(left.pop(0))%0D%0A else:%0D%0A new_list.append(right.pop(0))%0D%0A return new_list + left + right%0D%0A%0D%0Adef merge_sort(lst):%0D%0A if len(lst) %3C= 1:%0D%0A return lst%0D%0A else:%0D%0A middle = len(lst) / 2%0D%0A return merge(merge_sort(lst%5B:middle%5D), merge_sort(lst%5Bmiddle:%5D))%0D%0A%0D%0A %0D%0Astart = time.time()%0D%0Aanswer = merge_sort(my_list)%0D%0Aend = time.time()%0D%0A%0D%0Aprint 'It took %7B%7D seconds!'.format(end-start)%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A%0D%0A
|
|
bb7031385af7931f9e12a8987375f929bcfb6b5a | Create script that checks for dev and docs dependencies. | scripts/devdeps.py | scripts/devdeps.py | Python | 0 | @@ -0,0 +1,1763 @@
+from __future__ import print_function%0A%0Aimport sys%0A%0Atry:%0A import colorama%0A def blue(text): return %22%25s%25s%25s%22 %25 (colorama.Fore.BLUE, text, colorama.Style.RESET_ALL)%0A def red(text): return %22%25s%25s%25s%22 %25 (colorama.Fore.RED, text, colorama.Style.RESET_ALL)%0Aexcept ImportError:%0A def blue(text) : return text%0A def red(text) : return text%0A%0Adef depend_check(deps_name, *args):%0A %22%22%22Check for missing dependencies%0A %22%22%22%0A found = True%0A missing = %5B%5D%0A%0A for dependency in args:%0A try:%0A __import__(dependency)%0A except ImportError as e:%0A missing.append(dependency)%0A found = False%0A%0A print('-'*80)%0A if not found:%0A print(red(%22You are missing the following %25s dependencies:%22) %25 deps_name)%0A%0A for dep in missing:%0A name = pkg_info_dict.get(dep, dep)%0A print(%22 * %22, name)%0A print()%0A return False%0A else:%0A print(blue(%22All %25s dependencies installed! You are good to go!%5Cn%22) %25 deps_name)%0A return True%0A%0Aif __name__ == '__main__':%0A%0A #Dictionary maps module names to package names%0A pkg_info_dict = %7B'bs4' : 'beautiful-soup',%0A 'websocket' : 'websocket-client',%0A 'sphinx_bootstrap_theme' : 'sphinx-bootstrap-theme',%0A 'sphinxcontrib.httpdomain' : 'sphinxcontrib-httpdomain',%0A 'pdiffer' : 'pdiff'%0A %7D%0A%0A dev_deps = %5B'bs4', 'colorama', 'pdiffer', 'boto', 'nose', 'mock', 'coverage',%0A 'websocket'%5D%0A depend_check('Dev', *dev_deps)%0A%0A docs_deps = %5B'graphviz', 'sphinx', 'pygments', 'sphinx_bootstrap_theme',%0A 'sphinxcontrib.httpdomain'%5D%0A depend_check('Docs', *docs_deps)%0A
|
|
a23e08275652f7356863edada51e7dee345a2dfc | Add functools from Python trunk r65615 | test-tools/functools.py | test-tools/functools.py | Python | 0 | @@ -0,0 +1,2162 @@
+%22%22%22functools.py - Tools for working with functions and callable objects%0A%22%22%22%0A# Python module wrapper for _functools C module%0A# to allow utilities written in Python to be added%0A# to the functools module.%0A# Written by Nick Coghlan %3Cncoghlan at gmail.com%3E%0A# Copyright (C) 2006 Python Software Foundation.%0A# See C source code for _functools credits/copyright%0A%0Afrom _functools import partial, reduce%0A%0A# update_wrapper() and wraps() are tools to help write%0A# wrapper functions that can handle naive introspection%0A%0AWRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')%0AWRAPPER_UPDATES = ('__dict__',)%0Adef update_wrapper(wrapper,%0A wrapped,%0A assigned = WRAPPER_ASSIGNMENTS,%0A updated = WRAPPER_UPDATES):%0A %22%22%22Update a wrapper function to look like the wrapped function%0A%0A wrapper is the function to be updated%0A wrapped is the original function%0A assigned is a tuple naming the attributes assigned directly%0A from the wrapped function to the wrapper function (defaults to%0A functools.WRAPPER_ASSIGNMENTS)%0A updated is a tuple naming the attributes of the wrapper that%0A are updated with the corresponding attribute from the wrapped%0A function (defaults to functools.WRAPPER_UPDATES)%0A %22%22%22%0A for attr in assigned:%0A setattr(wrapper, attr, getattr(wrapped, attr))%0A for attr in updated:%0A getattr(wrapper, attr).update(getattr(wrapped, attr, %7B%7D))%0A # Return the wrapper so this can be used as a decorator via partial()%0A return wrapper%0A%0Adef wraps(wrapped,%0A assigned = WRAPPER_ASSIGNMENTS,%0A updated = WRAPPER_UPDATES):%0A %22%22%22Decorator factory to apply update_wrapper() to a wrapper function%0A%0A Returns a decorator that invokes update_wrapper() with the decorated%0A function as the wrapper argument and the arguments to wraps() as the%0A remaining arguments. Default arguments are as for update_wrapper().%0A This is a convenience function to simplify applying partial() to%0A update_wrapper().%0A %22%22%22%0A return partial(update_wrapper, wrapped=wrapped,%0A assigned=assigned, updated=updated)%0A
|
|
d3a652111aa7df0a5ecc429db6aa639f9a667ff9 | Create imogen.py | imogen.py | imogen.py | Python | 0.000001 | @@ -0,0 +1 @@
+%0A
|
|
ca098b540b171460f41ea66c01d2b0d039feb073 | Add arrange combination algorithm | arrange_combination/arrange.py | arrange_combination/arrange.py | Python | 0.000036 | @@ -0,0 +1,450 @@
+#!/usr/bin/env python%0A%0Adef range(input_list, step):%0A%0A if step == 3:%0A print(input_list)%0A return%0A%0A for i in range(step, len(input_list)):%0A input_list%5Bstep%5D, input_list%5Bi%5D = input_list%5Bi%5D, input_list%5Bstep%5D%0A range(input_list, step+1)%0A input_list%5Bstep%5D, input_list%5Bi%5D = input_list%5Bi%5D, input_list%5Bstep%5D%0A%0A%0Adef main():%0A import ipdb;ipdb.set_trace()%0A input_list = %5B%22a%22, %22b%22, %22c%22%5D%0A range(input_list, 0)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
|
|
c28522ace1efc0d2c7545bbc742356f6f6428812 | Use argparse in the radare module. | modules/radare.py | modules/radare.py | # -*- coding: utf-8 -*-
# This file is part of Viper - https://github.com/botherder/viper
# See the file 'LICENSE' for copying permission.
import os
import sys
import getopt
from viper.common.out import *
from viper.common.abstracts import Module
from viper.core.session import __sessions__
ext = ".bin"
run_radare = {'linux2': 'r2', 'darwin': 'r2',
'win32': 'r2'}
class Radare(Module):
cmd = 'r2'
description = 'Start Radare2'
authors = ['dukebarman']
def __init__(self):
self.is_64b = False
self.ext = ''
self.server = ''
def open_radare(self, filename):
directory = filename + ".dir"
if not os.path.exists(directory):
os.makedirs(directory)
destination = directory + "/executable" + self.ext
if not os.path.lexists(destination):
os.link(filename, destination)
command_line = '{} {}{}'.format(run_radare[sys.platform], self.server, destination)
os.system(command_line)
def run(self):
if not __sessions__.is_set():
self.log('error', "No session opened")
return
def usage():
self.log('', "usage: r2 [-h] [-s]")
def help():
usage()
self.log('', "")
self.log('', "Options:")
self.log('', "\t--help (-h)\tShow this help message")
self.log('', "\t--webserver (-w)\tStart web-frontend for radare2")
self.log('', "")
try:
opts, argv = getopt.getopt(self.args[0:], 'hw', ['help', 'webserver'])
except getopt.GetoptError as e:
self.log('', e)
return
for opt, value in opts:
if opt in ('-h', '--help'):
help()
return
elif opt in ('-w', '--webserver'):
self.server = "-c=H "
filetype = __sessions__.current.file.type
if 'x86-64' in filetype:
self.is_64b = True
arch = '64' if self.is_64b else '32'
if 'DLL' in filetype:
self.ext = '.dll'
to_print = [arch, 'bit DLL (Windows)']
if "native" in filetype:
to_print.append('perhaps a driver (.sys)')
self.log('info', ' '.join(to_print))
elif 'PE32' in filetype:
self.ext = '.exe'
self.log('info', ' '.join([arch, 'bit executable (Windows)']))
elif 'shared object' in filetype:
self.ext = '.so'
self.log('info', ' '.join([arch, 'bit shared object (linux)']))
elif 'ELF' in filetype:
self.ext = ''
self.log('info', ' '.join([arch, 'bit executable (linux)']))
else:
self.log('error', "Unknown binary")
try:
self.open_radare(__sessions__.current.file.path)
except:
self.log('error', "Unable to start Radare2")
| Python | 0 | @@ -165,46 +165,32 @@
ort
-getopt%0A%0Afrom viper.common.out import *
+shlex%0Aimport subprocess%0A
%0Afro
@@ -344,16 +344,19 @@
+
'win32':
@@ -363,16 +363,17 @@
'r2'%7D%0A%0A
+%0A
class Ra
@@ -481,32 +481,185 @@
__init__(self):%0A
+ super(Radare, self).__init__()%0A self.parser.add_argument('-w', '--webserver', action='store_true', help='Start web-frontend for radare2')%0A
self.is_
@@ -1050,16 +1050,17 @@
= '%7B%7D %7B%7D
+
%7B%7D'.form
@@ -1126,17 +1126,26 @@
-os.system
+args = shlex.split
(com
@@ -1159,311 +1159,91 @@
ne)%0A
-%0A
-def run(self):%0A if not __sessions__.is_set():%0A self.log('error', %22No session opened%22)%0A return%0A%0A def usage():%0A self.log('', %22usage: r2 %5B-h%5D %5B-s%5D%22)%0A%0A def help():%0A usage()%0A self.log('', %22%22)%0A self.log('', %22Options:%22
+ subprocess.Popen(args)%0A%0A def run(self):%0A super(Radare, self).run(
)%0A
@@ -1252,457 +1252,146 @@
-
+if
self.
-log('', %22%5Ct--help (-h)%5CtShow this help message%22)%0A self.log('', %22%5Ct--webserver (-w)%5CtStart web-frontend for radare2%22)%0A self.log('', %22%22)%0A%0A try:%0A opts, argv = getopt.getopt(self.args%5B0:%5D, 'hw', %5B'help', 'webserver'%5D)%0A except getopt.GetoptError as e:%0A self.log('', e)%0A return%0A%0A for opt, value in opts:%0A if opt in ('-h', '--help'):%0A help()%0A
+parsed_args is None:%0A return%0A%0A if not __sessions__.is_set():%0A self.log('error', %22No session opened%22)%0A
@@ -1402,26 +1402,24 @@
-
return%0A
-
+%0A
el
@@ -1418,32 +1418,28 @@
- elif opt in ('-w', '--
+if self.parsed_args.
webs
@@ -1447,16 +1447,10 @@
rver
-'):%0A
+:%0A
@@ -1476,17 +1476,16 @@
= %22-c=H
-
%22%0A%0A
|
f0da1774514c839b4b97fa92d2202437932dc99a | Add a small driver for plotting skeletons. | analysis/plot-skeleton.py | analysis/plot-skeleton.py | Python | 0 | @@ -0,0 +1,474 @@
+#!/usr/bin/env python%0A%0Aimport climate%0A%0Aimport database%0Aimport plots%0A%0A%[email protected](%0A root='plot data rooted at this path',%0A pattern=('plot data from files matching this pattern', 'option'),%0A)%0Adef main(root, pattern='*/*block02/*trial00*.csv.gz'):%0A with plots.space() as ax:%0A for trial in database.Experiment(root).trials_matching(pattern):%0A plots.skeleton(ax, trial, 100)%0A break%0A%0A%0Aif __name__ == '__main__':%0A climate.call(main)%0A
|
|
060c8a4379aef14459929a47bf62a80a3e7eef67 | Create af_setJoints.py | af_scripts/tmp/af_setJoints.py | af_scripts/tmp/af_setJoints.py | Python | 0.000001 | @@ -0,0 +1,651 @@
+import pymel.core as pm%0A%0AcurSel = pm.ls(sl=True,type='transform')%5B0%5D%0A%0AbBox = pm.xform(curSel,ws=1,q=1,bb=1)%0AsizeX = abs(bBox%5B0%5D-bBox%5B3%5D)%0AsizeY = abs(bBox%5B1%5D-bBox%5B4%5D)%0AsizeZ = abs(bBox%5B2%5D-bBox%5B5%5D)%0AcurPvt = %5B(bBox%5B0%5D+sizeX/2),(bBox%5B1%5D+sizeY/2),(bBox%5B2%5D+sizeZ/2)%5D%0A%0AccUD = pm.circle(n='circle_rotUpDown',r=sizeY/2,nr=(1,0,0))%0Apm.move(ccUD%5B0%5D,curPvt)%0A%0AccLR = pm.circle(n='circle_rotLeftRight',r=sizeX/2,nr=(0,1,0))%0Apm.move(ccLR%5B0%5D,curPvt)%0A%0Apm.select(d=1)%0Apm.jointDisplayScale(0.1)%0Apm.joint(p=(0,bBox%5B1%5D,bBox%5B2%5D),n='joint_base')%0Apm.joint(p=(pm.xform(ccUD,ws=1,q=1,rp=1)),n='joint_rotUpDown')%0Apm.joint(p=(pm.xform(ccLR,ws=1,q=1,rp=1)),n='joint_rotLeftRight')%0A
|
|
bde8b61f419dd6e66a85cc92f3661de6aaadeb94 | ADD CHECK FOR YELLING | proselint/checks/misc/yelling.py | proselint/checks/misc/yelling.py | Python | 0 | @@ -0,0 +1,376 @@
+# -*- coding: utf-8 -*-%0A%22%22%22EES: Too much yelling..%0A%0A---%0Alayout: post%0Aerror_code: SCH%0Asource: ???%0Asource_url: ???%0Atitle: yelling%0Adate: 2014-06-10 12:31:19%0Acategories: writing%0A---%0A%0AToo much yelling.%0A%0A%22%22%22%0Afrom proselint.tools import blacklist%0A%0Aerr = %22MAU103%22%0Amsg = u%22Too much yelling.%22%0A%0Acheck = blacklist(%5B%22%5BA-Z%5D+ %5BA-Z%5D+ %5BA-Z%5D+%22%5D, err, msg, ignore_case=False)%0A
|
|
26e7e7b270bfd5e08cf871f7d89b5a92b07df230 | add migration file | contmon/scraper/migrations/0001_initial.py | contmon/scraper/migrations/0001_initial.py | Python | 0.000001 | @@ -0,0 +1,1669 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0Aimport django.utils.timezone%0Aimport model_utils.fields%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A replaces = %5B('scraper', '0001_initial'), ('scraper', '0002_auto_20150706_2105'), ('scraper', '0003_auto_20150706_2108'), ('scraper', '0004_auto_20150706_2110'), ('scraper', '0005_auto_20150706_2116')%5D%0A%0A dependencies = %5B%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name='WebsiteScraperConfig',%0A fields=%5B%0A ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),%0A ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),%0A ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),%0A ('domain', models.CharField(max_length=400, db_index=True)),%0A ('selector_style', models.CharField(blank=True, max_length=100, choices=%5B(b'css', b'css'), (b'xpath', b'xpath')%5D)),%0A ('name_selector', models.CharField(max_length=100, blank=True)),%0A ('image_selector', models.CharField(max_length=100, blank=True)),%0A ('content_selector', models.CharField(max_length=100)),%0A ('next_page_selector', models.CharField(max_length=100, blank=True)),%0A ('tabs_selector', models.CharField(max_length=100, blank=True)),%0A %5D,%0A options=%7B%0A 'abstract': False,%0A %7D,%0A ),%0A %5D%0A
|
|
2e7aa28131ce09143ef5f6b1b36eddbd112352b7 | Revert "get rid of sleep in setUp" | smart_open/tests/test_s3_version.py | smart_open/tests/test_s3_version.py | # -*- coding: utf-8 -*-
import logging
import os
import time
import unittest
import uuid
import boto3
import botocore.client
import moto
from smart_open import open
BUCKET_NAME = 'test-smartopen-{}'.format(uuid.uuid4().hex)
KEY_NAME = 'test-key'
DISABLE_MOCKS = os.environ.get('SO_DISABLE_MOCKS') == "1"
logger = logging.getLogger(__name__)
def maybe_mock_s3(func):
if DISABLE_MOCKS:
return func
else:
return moto.mock_s3(func)
@maybe_mock_s3
def setUpModule():
'''Called once by unittest when initializing this module. Sets up the
test S3 bucket.
'''
boto3.resource('s3').create_bucket(Bucket=BUCKET_NAME)
boto3.resource('s3').BucketVersioning(BUCKET_NAME).enable()
def put_to_bucket(contents, num_attempts=12, sleep_time=5):
# fake (or not) connection, bucket and key
logger.debug('%r', locals())
#
# In real life, it can take a few seconds for the bucket to become ready.
# If we try to write to the key while the bucket while it isn't ready, we
# will get a ClientError: NoSuchBucket.
#
for attempt in range(num_attempts):
try:
boto3.resource('s3').Object(BUCKET_NAME, KEY_NAME).put(Body=contents)
return
except botocore.exceptions.ClientError as err:
logger.error('caught %r, retrying', err)
time.sleep(sleep_time)
assert False, 'failed to create bucket %s after %d attempts' % (BUCKET_NAME, num_attempts)
def get_versions(bucket, key):
"""Return object versions in chronological order."""
return [
v.id
for v in sorted(
boto3.resource('s3').Bucket(bucket).object_versions.filter(Prefix=key),
key=lambda version: version.last_modified,
)
]
@maybe_mock_s3
class TestVersionId(unittest.TestCase):
def setUp(self):
#
# Each run of this test reuses the BUCKET_NAME, but works with a
# different key for isolation.
#
self.key = 'test-write-key-{}'.format(uuid.uuid4().hex)
self.url = "s3://%s/%s" % (BUCKET_NAME, self.key)
self.test_ver1 = u"String version 1.0".encode('utf8')
self.test_ver2 = u"String version 2.0".encode('utf8')
with open(self.url, 'wb') as fout:
fout.write(self.test_ver1)
logging.critical('versions after first write: %r', get_versions(BUCKET_NAME, self.key))
with open(self.url, 'wb') as fout:
fout.write(self.test_ver2)
self.versions = get_versions(BUCKET_NAME, self.key)
logging.critical('versions after second write: %r', get_versions(BUCKET_NAME, self.key))
def test_good_id(self):
"""Does passing the version_id parameter into the s3 submodule work correctly when reading?"""
params = {'version_id': self.versions[0]}
with open(self.url, mode='rb', transport_params=params) as fin:
actual = fin.read()
self.assertEqual(actual, self.test_ver1)
def test_bad_id(self):
"""Does passing an invalid version_id exception into the s3 submodule get handled correctly?"""
params = {'version_id': 'bad-version-does-not-exist'}
with self.assertRaises(IOError):
open(self.url, 'rb', transport_params=params)
def test_bad_mode(self):
"""Do we correctly handle non-None version when writing?"""
params = {'version_id': self.versions[0]}
with self.assertRaises(ValueError):
open(self.url, 'wb', transport_params=params)
def test_no_version(self):
"""Passing in no version at all gives the newest version of the file?"""
with open(self.url, 'rb') as fin:
actual = fin.read()
self.assertEqual(actual, self.test_ver2)
def test_newest_version(self):
"""Passing in the newest version explicitly gives the most recent content?"""
params = {'version_id': self.versions[1]}
with open(self.url, mode='rb', transport_params=params) as fin:
actual = fin.read()
self.assertEqual(actual, self.test_ver2)
def test_oldset_version(self):
"""Passing in the oldest version gives the oldest content?"""
params = {'version_id': self.versions[0]}
with open(self.url, mode='rb', transport_params=params) as fin:
actual = fin.read()
self.assertEqual(actual, self.test_ver1)
if __name__ == '__main__':
unittest.main()
| Python | 0 | @@ -2394,24 +2394,226 @@
self.key))%0A%0A
+ if DISABLE_MOCKS:%0A #%0A # I suspect there is a race condition that's messing up the%0A # order of the versions in the test.%0A #%0A time.sleep(5)%0A%0A
with
|
2c728b79856aee63aebaeaeb29ce119edd510331 | Update pattern string | axelrod/strategies/lookerup.py | axelrod/strategies/lookerup.py | from axelrod import Actions, Player, init_args
from itertools import product
C, D = Actions.C, Actions.D
class LookerUp(Player):
"""
A strategy that uses a lookup table to decide what to do based on a
combination of the last m turns and the opponent's opening n actions. If
there isn't enough history to do this (i.e. for the first m turns) then
cooperate.
The lookup table is implemented as a dict. The keys are 3-tuples giving the
opponents first n actions, self's last m actions, and opponents last m
actions, all as strings. The values are the actions to play on this round.
For example, in the case of m=n=1, if
- the opponent started by playing C
- my last action was a C the opponents
- last action was a D
then the corresponding key would be
('C', 'C', 'D')
and the value would contain the action to play on this turn.
Some well-known strategies can be expressed as special cases; for example
Cooperator is given by the dict:
{('', '', '') : C}
where m and n are both zero. Tit-For-Tat is given by:
{
('', 'C', 'D') : D,
('', 'D', 'D') : D,
('', 'C', 'C') : C,
('', 'D', 'C') : C,
}
where m=1 and n=0.
Lookup tables where the action depends on the opponent's first actions (as
opposed to most recent actions) will have a non-empty first string in the
tuple. For example, this fragment of a dict:
{
...
('C', 'C', 'C') : C.
('D', 'C', 'C') : D,
...
}
states that if self and opponent both cooperated on the previous turn, we
should cooperate this turn unless the opponent started by defecting, in
which case we should defect.
To denote lookup tables where the action depends on sequences of actions
(so m or n are greater than 1), simply concatenate the strings together.
Below is an incomplete example where m=3 and n=2.
{
...
('CC', 'CDD', 'CCC') : C.
('CD', 'CCD', 'CCC') : D,
...
}
"""
name = 'LookerUp'
classifier = {
'memory_depth': float('inf'),
'stochastic': False,
'inspects_source': False,
'manipulates_source': False,
'manipulates_state': False
}
@init_args
def __init__(self, lookup_table=None):
"""
If no lookup table is provided to the constructor, then use the TFT one.
"""
Player.__init__(self)
if not lookup_table:
lookup_table = {
('', 'C', 'D') : D,
('', 'D', 'D') : D,
('', 'C', 'C') : C,
('', 'D', 'C') : C,
}
self.lookup_table = lookup_table
# Rather than pass the number of previous turns (m) to consider in as a
# separate variable, figure it out. The number of turns is the length
# of the second element of any given key in the dict.
self.plays = len(list(self.lookup_table.keys())[0][1])
# The number of opponent starting actions is the length of the first
# element of any given key in the dict.
self.opponent_start_plays = len(list(self.lookup_table.keys())[0][0])
# If the table dictates to ignore the opening actions of the opponent
# then the memory classification is adjusted
if self.opponent_start_plays == 0:
self.classifier['memory_depth'] = self.plays
# Ensure that table is well-formed
for k, v in lookup_table.items():
if (len(k[1]) != self.plays) or (len(k[0]) != self.opponent_start_plays):
raise ValueError("All table elements must have the same size")
if len(v) > 1:
raise ValueError("Table values should be of length one, C or D")
def strategy(self, opponent):
# If there isn't enough history to lookup an action, cooperate.
if len(self.history) < max(self.plays, self.opponent_start_plays):
return C
# Count backward m turns to get my own recent history.
history_start = -1 * self.plays
my_history = ''.join(self.history[history_start:])
# Do the same for the opponent.
opponent_history = ''.join(opponent.history[history_start:])
# Get the opponents first n actions.
opponent_start = ''.join(opponent.history[:self.opponent_start_plays])
# Put these three strings together in a tuple.
key = (opponent_start, my_history, opponent_history)
# Look up the action associated with that tuple in the lookup table.
action = self.lookup_table[key]
return action
class EvolvedLookerUp(LookerUp):
"""
A LookerUp strategy that uses a lookup table generated using an evolutionary
algorithm.
"""
name = "EvolvedLookerUp"
def __init__(self):
plays = 2
opponent_start_plays = 2
# Generate the list of possible tuples, i.e. all possible combinations
# of m actions for me, m actions for opponent, and n starting actions
# for opponent.
self_histories = [''.join(x) for x in product('CD', repeat=plays)]
other_histories = [''.join(x) for x in product('CD', repeat=plays)]
opponent_starts = [''.join(x) for x in
product('CD', repeat=opponent_start_plays)]
lookup_table_keys = list(product(opponent_starts, self_histories,
other_histories))
# Pattern of values determed previously with an evolutionary algorithm.
pattern='CDCCDCCCDCDDDDDCCDCCCDDDCDDDDDDCDDDDCDDDDCCDDCDDCDDDCCCDCDCDDDDD'
# Zip together the keys and the action pattern to get the lookup table.
lookup_table = dict(zip(lookup_table_keys, pattern))
LookerUp.__init__(self, lookup_table=lookup_table)
| Python | 0 | @@ -5592,16 +5592,16 @@
CDCC
-CDDDCDDD
+DDDDDCDC
DDDC
@@ -5609,26 +5609,24 @@
DDDC
-DDDD
CCDDC
-DDCDDDCCC
+CDDDDDCDCDD
DCDC
@@ -5630,16 +5630,18 @@
CDCDDDDD
+DD
'%0A
|
872dd45173e889db06e9b16105492c241f7badae | Add an example for dynamic RPC lookup. | examples/rpc_dynamic.py | examples/rpc_dynamic.py | Python | 0 | @@ -0,0 +1,1157 @@
+import asyncio%0Aimport aiozmq%0Aimport aiozmq.rpc%0A%0A%0Aclass DynamicHandler(aiozmq.rpc.AttrHandler):%0A%0A def __init__(self, namespace=()):%0A self.namespace = namespace%0A%0A def __getitem__(self, key):%0A try:%0A return getattr(self, key)%0A except AttributeError:%0A return DynamicHandler(self.namespace + (key,))%0A%0A @aiozmq.rpc.method%0A def func(self):%0A return (self.namespace, 'val')%0A%0A%[email protected]%0Adef go():%0A server = yield from aiozmq.rpc.start_server(%0A DynamicHandler(), bind='tcp://*:*')%0A server_addr = next(iter(server.transport.bindings()))%0A%0A client = yield from aiozmq.rpc.open_client(%0A connect=server_addr)%0A%0A ret = yield from client.rpc.func()%0A assert ((), 'val') == ret, ret%0A%0A ret = yield from client.rpc.a.func()%0A assert (('a',), 'val') == ret, ret%0A%0A ret = yield from client.rpc.a.b.func()%0A assert (('a', 'b'), 'val') == ret, ret%0A%0A server.close()%0A client.close()%0A%0A%0Adef main():%0A asyncio.set_event_loop_policy(aiozmq.ZmqEventLoopPolicy())%0A asyncio.get_event_loop().run_until_complete(go())%0A print(%22DONE%22)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
e0b1bea00c56657ef9fb4456203a522920375cc2 | add testLCMSpy.py script | software/ddapp/src/python/tests/testLCMSpy.py | software/ddapp/src/python/tests/testLCMSpy.py | Python | 0.000001 | @@ -0,0 +1,2157 @@
+from ddapp.consoleapp import ConsoleApp%0Afrom ddapp import lcmspy%0Afrom ddapp import lcmUtils%0Afrom ddapp import simpletimer as st%0A%0Aapp = ConsoleApp()%0A%0Aapp.setupGlobals(globals())%0A%0Aif app.getTestingInteractiveEnabled():%0A app.showPythonConsole()%0A%0A%0Alcmspy.findLCMModulesInSysPath()%0A%0Atimer = st.SimpleTimer()%0Astats = %7B%7D%0A%0AchannelToMsg = %7B%7D%0Aitems = %7B%7D%0A%0Adef item(r, c):%0A rowDict = items.setdefault(r, %7B%7D)%0A try:%0A return rowDict%5Bc%5D%0A%0A except KeyError:%0A i = QtGui.QTableWidgetItem('')%0A table.setItem(r, c, i)%0A rowDict%5Bc%5D = i%0A return i%0A%0A%0Adef printStats():%0A print '%5Cn------------------------%5Cn'%0A%0A averages = %5B(channel, stat.getAverage()) for channel, stat in stats.iteritems()%5D%0A%0A averages.sort(key=lambda x: x%5B1%5D)%0A%0A table.setRowCount(len(averages))%0A i = 0%0A for channel, bytesPerSecond in reversed(averages):%0A print channel, '%25.3f kbps' %25 (bytesPerSecond/1024.0)%0A%0A item(i, 0).setText(channel)%0A item(i, 1).setText(channelToMsg%5Bchannel%5D)%0A item(i, 2).setText('%25.3f kbps' %25 (bytesPerSecond/1024.0))%0A i += 1%0A%0A%0Adef onMessage(messageData, channel):%0A%0A messageData = str(messageData)%0A msgType = lcmspy.getMessageClass(messageData)%0A%0A if not msgType:%0A #print 'failed decode:', channel%0A pass%0A else:%0A name = lcmspy.getMessageTypeFullName(msgType)%0A%0A stat = stats.get(channel)%0A if not stat:%0A stat = st.AverageComputer()%0A stats%5Bchannel%5D = stat%0A%0A stat.update(len(messageData))%0A%0A if channel not in channelToMsg:%0A channelToMsg%5Bchannel%5D = lcmspy.getMessageTypeFullName(msgType) if msgType else '%3Cunknown msg type%3E'%0A%0A if timer.elapsed() %3E 3:%0A printStats()%0A timer.reset()%0A%0A for stat in stats.values():%0A stat.reset()%0A%0A #msg = lcmspy.decodeMessage(messageData)%0A%0A%0Asub = lcmUtils.addSubscriber(channel='.+', callback=onMessage)%0Asub.setNotifyAllMessagesEnabled(True)%0A%0A%0Afrom PythonQt import QtGui, QtCore%0A%0Atable = QtGui.QTableWidget()%0Atable.setColumnCount(3)%0Atable.setHorizontalHeaderLabels(%5B'channel', 'type', 'bandwidth'%5D)%0Atable.verticalHeader().setVisible(False)%0A%0A%0Atable.show()%0A%0A%0A%0A%0Aapp.start()%0A
|
|
3c365bb964e5466eddd5623329c50bc14e03964a | version bump for 0.21.4.4. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.21.4.3'
| Python | 0 | @@ -16,8 +16,8 @@
1.4.
-3
+4
'%0A%0A
|
da5b5c1ab9a3af614ff7bcc42ce42f4a23a89324 | version bump for 0.23.4.1. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.23.4'
| Python | 0 | @@ -11,11 +11,13 @@
'0.23.4
+.1
'%0A%0A
|
9155555df340c4f845326326faf79c582df70394 | version bump for 0.28.1. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.28.0.2'
| Python | 0 | @@ -10,14 +10,12 @@
= '0.28.
-0.2
+1
'%0A%0A
|
632266d59f1eefafcb38747ea57686824f41b978 | version bump for 0.20.11.1. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.20.11'
| Python | 0 | @@ -12,11 +12,13 @@
'0.20.11
+.1
'%0A%0A
|
45367ebc4e54402082add655fa8c87885a50e6a4 | version bump for 0.21.2.2. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.21.2.1'
| Python | 0 | @@ -12,12 +12,12 @@
'0.21.2.
-1
+2
'%0A%0A
|
7cc3dd653351799d2513a424c6bedd499f28c1a1 | version bump for 0.20.10. | oneflow/__init__.py | oneflow/__init__.py |
VERSION = '0.20.9.15'
| Python | 0 | @@ -14,11 +14,9 @@
.20.
-9.15
+10
'%0A%0A
|
cb2cc713c29c20ba239a60b6151c5e5c001c8e0b | Add joinkb.py | joinkb.py | joinkb.py | Python | 0.000005 | @@ -0,0 +1,1235 @@
+from __future__ import print_function%0A%0A__module_name__ = 'Join Kickban'%0A__module_version__ = '0.1'%0A__module_description__ = 'Kickbans clients from specified channels on regex match against their nickname on join'%0A__author__ = 'Daniel A. J.'%0A%0Aimport hexchat%0Aimport re%0A%0Are = re.compile(r'%5Cbfoo%5Cb') # regex pattern to be matched against in user's nickname%0Acheck_channels = %5B'#test', '#fooness'%5D # channel(s) where script is active%0Anet = 'freenode' # network where script is active%0A%0Adef join_search(word, word_eol, userdata):%0A%0A channel = word%5B2%5D%0A user_nickname = ''.join(word%5B0%5D%5B1:word%5B0%5D.index('!')%5D)%0A user_host = ''.join(word%5B0%5D%5Bword%5B0%5D.index('@'):%5D)%0A %0A for x in check_channels:%0A if re.search(user_nickname) != None and channel == x and hexchat.get_info(%22network%22) == net:%0A hexchat.command(%22mode %25s +b *!*%25s%22 %25 (channel, user_host))%0A hexchat.command(%22kick %25s regex pattern detected%22 %25 user_nickname)%0A%0A return hexchat.EAT_ALL%0A %0Adef unload_joinkb(userdata):%0A print(__module_name__, 'version', __module_version__, 'unloaded.')%0A%0Ahexchat.hook_server(%22JOIN%22, join_search)%0Ahexchat.hook_unload(unload_joinkb)%0A%0Aprint(__module_name__, 'version', __module_version__, 'loaded.')%0A%0A
|
|
f6864179a2dc1c531afc2c3ba6be300006e01fab | Create consecZero.py | Codingame/Python/Clash/consecZero.py | Codingame/Python/Clash/consecZero.py | Python | 0.000001 | @@ -0,0 +1,380 @@
+import sys%0Aimport math%0A%0A# Auto-generated code below aims at helping you parse%0A# the standard input according to the problem statement.%0A%0An = input()%0A%0A# Write an action using print%0A# To debug: print(%22Debug messages...%22, file=sys.stderr)%0Ac = 0%0At = 0%0Afor x in n:%0A if x == '0':%0A t += 1%0A else:%0A if t %3E c:%0A c = t%0A t = 0%0Aif t %3E c:%0A c = t%0Aprint(c)%0A
|
|
6a4fb74befd22c2bc814dbe51a1fa884a077be9d | Create django_audit_snippets.py | example_code/django_audit_snippets.py | example_code/django_audit_snippets.py | Python | 0.000004 | @@ -0,0 +1,1299 @@
+from django.conf import settings%0Afrom urls import urlpatterns%0A%0A'''%0AAccess shell via%0A./manage.py shell %0A(or shell_plus if you have django-extensions)%0ADont forget you may need to set environment variables:%0A - DJANGO_SETTINGS_MODULE to the settings file (python module load syntax like settings.filename) and %0A - PYTHONPATH to include the path where the Django code sits%0A %0AInstall ipython and django-extensions to get a better shell (shell_plus)%0Apip install django-extensions%0A%0AThis also has show_urls command which will do something similar to get_urls_friendly below%0A%0Aurls will not contain urlpatterns in later django releases%0A'''%0A%0A%0A# all the configured apps settings are now in here%0Asettings%0A%0A# this prints out mapped urls and associated views%0Adef get_urls_friendly(raw_urls, nice_urls=%5B%5D, urlbase=''):%0A '''Recursively builds a list of all the urls in the current project and the name of their associated view'''%0A for entry in raw_urls:%0A fullurl = (urlbase + entry.regex.pattern).replace('%5E','')%0A if entry.callback: %0A viewname = entry.callback.func_name%0A nice_urls.append('%25s - %25s' %25(fullurl, viewname))%0A else: %0A get_urls_friendly(entry.url_patterns, nice_urls, fullurl)%0A nice_urls = sorted(list(set(nice_urls))) %0A return nice_urls%0A
|
|
73819cea7150e15212a014f9c3a42a69d0351ab8 | Create cutrope.py | cutrope.py | cutrope.py | Python | 0 | @@ -0,0 +1,969 @@
+# Author: Vikram Raman%0A# Date: 08-15-2015%0A%0Aimport time%0A%0A# Given a rope with length n, how to cut the rope into m parts with length n%5B0%5D, n%5B1%5D, ..., n%5Bm-1%5D,%0A# in order to get the maximal product of n%5B0%5D*n%5B1%5D* ... *n%5Bm-1%5D? %0A# We have to cut once at least. Additionally, the length of the whole length of the rope, %0A# as well as the length of each part, are in integer value.%0A%0A# For example, if the length of the rope is 8, %0A# the maximal product of the part lengths is 18. %0A# In order to get the maximal product, %0A# the rope is cut into three parts with lengths 2, 3, and 3 respectively.%0A%0A# immediate thoughts: this is a dynamic programming knapsack kind of problem%0A%0Adef cutrope(l):%0A d = %5B0, 1%5D%0A%0A for i in range(2, l+1):%0A maxVal = 0%0A for j in range(1, i):%0A maxVal = max(j * d%5Bi-j%5D, j * (i-j), maxVal)%0A d.append(maxVal)%0A print d%0A%0Al = 8%0Astart_time = time.clock()%0Acutrope(l)%0Aprint(%22--- %25s seconds ---%22 %25 (time.clock() - start_time))%0A
|
|
6b95af9822b9d94793eef503609b48d83066f594 | add test that causes KeyError for disabled text | test/test-text-diabled.py | test/test-text-diabled.py | Python | 0 | @@ -0,0 +1,224 @@
+from framework import *%0Aroot.title(%22Disabled text%22)%0A%0Acanv.create_text(200, 200,%0A%09text = %22Test disabled text%22,%0A%09font = (%22Times%22, 20),%0A%09state = DISABLED%0A)%0A%0Athread.start_new_thread(test, (canv, __file__, True))%0Aroot.mainloop()%0A
|
|
06efe8a8be913fb63f27016268d86f1ad0a5bcdf | Add test_engine_seed.py | tests/test_engine_seed.py | tests/test_engine_seed.py | Python | 0.000039 | @@ -0,0 +1,1151 @@
+# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2015-2016 MIT Probabilistic Computing Project%0A%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A%0A# http://www.apache.org/licenses/LICENSE-2.0%0A%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom cgpm.crosscat.engine import Engine%0Afrom cgpm.utils import general as gu%0A%0Adef test_engine_simulate_no_repeat():%0A %22%22%22Generate 3 samples from 2 states 10 times, and ensure uniqueness.%22%22%22%0A rng = gu.gen_rng(1)%0A engine = Engine(X=%5B%5B1%5D%5D, cctypes=%5B'normal'%5D, num_states=2, rng=rng)%0A samples_list = %5B%0A %5Bs%5B0%5D for s in engine.simulate(rowid=-i, query=%5B0%5D, N=3)%5B0%5D%5D%0A for i in xrange(10)%0A %5D%0A samples_set = set(%5Bfrozenset(s) for s in samples_list%5D)%0A assert len(samples_set) == len(samples_list)%0A
|
|
3de2b08133f6f721a3a30120a93b81be0eacefb6 | add tests for the scuba.filecleanup sub-module | tests/test_filecleanup.py | tests/test_filecleanup.py | Python | 0 | @@ -0,0 +1,1883 @@
+from __future__ import print_function%0A%0Afrom nose.tools import *%0Afrom unittest import TestCase%0Atry:%0A from unittest import mock%0Aexcept ImportError:%0A import mock%0A%0Afrom scuba.filecleanup import FileCleanup%0A%0Adef assert_set_equal(a, b):%0A assert_equal(set(a), set(b))%0A%0A%0Aclass TestFilecleanup(TestCase):%0A%0A @mock.patch('os.remove')%0A def test_files_tracked(self, os_remove_mock):%0A '''FileCleanup.files works'''%0A%0A fc = FileCleanup()%0A fc.register('foo.txt')%0A fc.register('bar.bin')%0A%0A assert_set_equal(fc.files, %5B'foo.txt', 'bar.bin'%5D)%0A %0A%0A @mock.patch('os.remove')%0A def test_basic_usage(self, os_remove_mock):%0A '''FileCleanup removes one file'''%0A%0A fc = FileCleanup()%0A fc.register('foo.txt')%0A fc.cleanup()%0A%0A os_remove_mock.assert_any_call('foo.txt') %0A%0A %0A @mock.patch('os.remove')%0A def test_multiple_files(self, os_remove_mock):%0A '''FileCleanup removes multiple files'''%0A%0A fc = FileCleanup()%0A fc.register('foo.txt')%0A fc.register('bar.bin')%0A fc.register('/something/snap.crackle')%0A fc.cleanup()%0A%0A os_remove_mock.assert_any_call('bar.bin') %0A os_remove_mock.assert_any_call('foo.txt') %0A os_remove_mock.assert_any_call('/something/snap.crackle')%0A%0A%0A @mock.patch('os.remove')%0A def test_multiple_files(self, os_remove_mock):%0A '''FileCleanup ignores os.remove() errors'''%0A%0A def os_remove_se(path):%0A if path == 'INVALID':%0A raise OSError('path not found')%0A%0A os_remove_mock.side_effect = os_remove_se%0A%0A fc = FileCleanup()%0A fc.register('foo.txt')%0A fc.register('bar.bin')%0A fc.register('INVALID')%0A fc.cleanup()%0A%0A os_remove_mock.assert_any_call('bar.bin') %0A os_remove_mock.assert_any_call('foo.txt') %0A%0A assert_set_equal(fc.files, %5B%5D)%0A
|
|
d41005d14239a93237fb839084f029208b94539d | Use the custom.js as served from the CDN for try | common/profile_default/ipython_notebook_config.py | common/profile_default/ipython_notebook_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Configuration file for ipython-notebook.
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Whether to trust or not X-Scheme/X-Forwarded-Proto and X-Real-Ip/X-Forwarded-
# For headerssent by the upstream reverse proxy. Necessary if the proxy handles
# SSL
c.NotebookApp.trust_xheaders = True
# Include our extra templates
c.NotebookApp.extra_template_paths = ['/srv/templates/']
# Supply overrides for the tornado.web.Application that the IPython notebook
# uses.
c.NotebookApp.tornado_settings = {
'headers': {
'Content-Security-Policy': "frame-ancestors 'self' https://*.jupyter.org https://jupyter.github.io https://*.tmpnb.org"
},
'static_url_prefix': 'https://cdn.jupyter.org/notebook/3.1.0/'
}
| Python | 0 | @@ -812,13 +812,11 @@
ook/
-3.1.0
+try
/'%0A%7D
|
2b380d501b80afad8c7c5ec27537bcc682ed2775 | Fix some scope mistakes. This fix was part of the reverted commit. | commands/handle.py | commands/handle.py | import commands.cmds as cmds
def handle(self, chat_raw):
self.logger.info("Handling command: " + chat_raw + " (for player" + self.fquid + ")")
_atmp1 = chat_raw.split(" ")
_atmp2 = list(_atmp1[0])
del _atmp2[0]
del _atmp1[0]
cmdobj = {
"base": _atmp2,
"args_raw": _atmp1,
"scope": self,
"chat_raw": chat_raw
}
commands.cmds.InvalidCommand.begin(self, cmdobj) if _atmp2 not in commands.cmds.baseList else commands.cmds.baseList[_atmp2].begin(self, cmdobj) | Python | 0 | @@ -368,25 +368,16 @@
%7D%0A
-commands.
cmds.Inv
@@ -425,25 +425,16 @@
not in
-commands.
cmds.bas
@@ -444,25 +444,16 @@
st else
-commands.
cmds.bas
|
b37f31b5adbdda3e5d40d2d8a9dde19b2e305c2c | Add tests for the controller module | ckanext/wirecloudview/tests/test_controller.py | ckanext/wirecloudview/tests/test_controller.py | Python | 0 | @@ -0,0 +1,2654 @@
+# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2018 Future Internet Consulting and Development Solutions S.L.%0A%0A# This file is part of CKAN WireCloud View Extension.%0A%0A# CKAN WireCloud View Extension is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as published by%0A# the Free Software Foundation, either version 3 of the License, or%0A# (at your option) any later version.%0A%0A# CKAN WireCloud View Extension is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A%0A# You should have received a copy of the GNU Affero General Public License%0A# along with CKAN WireCloud View Extension. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0A# This file is part of CKAN Data Requests Extension.%0A%0Aimport json%0Aimport unittest%0A%0Afrom mock import DEFAULT, patch%0A%0Afrom ckanext.wirecloudview.controller import WireCloudViewController%0A%0A%0Aclass WirecloudViewControllerTest(unittest.TestCase):%0A%0A @patch.multiple(%22ckanext.wirecloudview.controller%22, request=DEFAULT, get_plugin=DEFAULT, toolkit=DEFAULT, OAuth2Session=DEFAULT, response=DEFAULT)%0A def test_get_workspaces(self, request, get_plugin, toolkit, OAuth2Session, response):%0A self.controller = WireCloudViewController()%0A self.controller.client_id = %22aclientid%22%0A%0A request.params = %7B%0A 'incomplete': 'key words',%0A 'limit': '20',%0A %7D%0A get_plugin().wirecloud_url = %22https://dashboards.example.org%22%0A oauth = OAuth2Session()%0A OAuth2Session.reset_mock()%0A oauth.get().json.return_value = %7B%0A %22results%22: %5B%0A %7B%22owner%22: %22user1%22, %22name%22: %22dashboard1%22%7D,%0A %7B%22owner%22: %22user2%22, %22name%22: %22other-dashboard%22%7D,%0A %5D%0A %7D%0A oauth.get.reset_mock()%0A response.headers = %7B%7D%0A%0A result = self.controller.get_workspaces()%0A%0A self.assertEqual(%0A json.loads(result.decode('utf-8')),%0A %7B%0A %22ResultSet%22: %7B%0A %22Result%22: %5B%0A %7B%22Name%22: %22user1/dashboard1%22%7D,%0A %7B%22Name%22: %22user2/other-dashboard%22%7D,%0A %5D%0A %7D%0A %7D%0A )%0A self.assertEqual(response.headers%5Bb'Content-Type'%5D, b%22application/json%22)%0A OAuth2Session.assert_called_once_with(self.controller.client_id, token=toolkit.c.usertoken)%0A oauth.get.assert_called_once_with(%22https://dashboards.example.org/api/search?namespace=workspace&q=key+words&maxresults=20%22)%0A
|
|
d1d1892551d805b5a73aaef07932c65fd375e342 | Add Rules unit test | py/desisurvey/test/test_rules.py | py/desisurvey/test/test_rules.py | Python | 0 | @@ -0,0 +1,798 @@
+import unittest%0A%0Aimport numpy as np%0A%0Aimport desisurvey.tiles%0Afrom desisurvey.rules import Rules%0A%0A%0Aclass TestRules(unittest.TestCase):%0A%0A def setUp(self):%0A pass%0A%0A def test_rules(self):%0A rules = Rules()%0A tiles = desisurvey.tiles.get_tiles()%0A completed = np.ones(tiles.ntiles, bool)%0A rules.apply(completed)%0A completed%5B:%5D = False%0A rules.apply(completed)%0A gen = np.random.RandomState(123)%0A for i in range(10):%0A completed%5Bgen.choice(tiles.ntiles, tiles.ntiles // 10, replace=False)%5D = True%0A rules.apply(completed)%0A%0Adef test_suite():%0A %22%22%22Allows testing of only this module with the command::%0A%0A python setup.py test -m %3Cmodulename%3E%0A %22%22%22%0A return unittest.defaultTestLoader.loadTestsFromName(__name__)%0A
|
|
3efa20e0d93c922bec6ae0f41774fd406532257a | Allow manually graded code cells | nbgrader/preprocessors/checkcellmetadata.py | nbgrader/preprocessors/checkcellmetadata.py | from nbgrader import utils
from nbgrader.preprocessors import NbGraderPreprocessor
class CheckCellMetadata(NbGraderPreprocessor):
"""A preprocessor for checking that grade ids are unique."""
def preprocess(self, nb, resources):
resources['grade_ids'] = ids = []
nb, resources = super(CheckCellMetadata, self).preprocess(nb, resources)
id_set = set([])
for grade_id in ids:
if grade_id in id_set:
raise RuntimeError("Duplicate grade id: {}".format(grade_id))
id_set.add(grade_id)
return nb, resources
def preprocess_cell(self, cell, resources, cell_index):
if utils.is_grade(cell):
# check for blank grade ids
grade_id = cell.metadata.nbgrader.get("grade_id", "")
if grade_id == "":
raise RuntimeError("Blank grade id!")
resources['grade_ids'].append(grade_id)
# check for valid points
points = cell.metadata.nbgrader.get("points", "")
try:
points = float(points)
except ValueError:
raise RuntimeError(
"Point value for grade cell {} is invalid: {}".format(
grade_id, points))
# check that code cells are grade OR solution (not both)
if cell.cell_type == "code" and utils.is_grade(cell) and utils.is_solution(cell):
raise RuntimeError(
"Code grade cell '{}' is also marked as a solution cell".format(
grade_id))
# check that markdown cells are grade AND solution (not either/or)
if cell.cell_type == "markdown" and utils.is_grade(cell) and not utils.is_solution(cell):
raise RuntimeError(
"Markdown grade cell '{}' is not marked as a solution cell".format(
grade_id))
if cell.cell_type == "markdown" and not utils.is_grade(cell) and utils.is_solution(cell):
raise RuntimeError(
"Markdown solution cell (index {}) is not marked as a grade cell".format(
cell_index))
return cell, resources
| Python | 0 | @@ -1268,308 +1268,8 @@
))%0A%0A
- # check that code cells are grade OR solution (not both)%0A if cell.cell_type == %22code%22 and utils.is_grade(cell) and utils.is_solution(cell):%0A raise RuntimeError(%0A %22Code grade cell '%7B%7D' is also marked as a solution cell%22.format(%0A grade_id))%0A%0A
|
6f5e4b4a125883017c6349545cc2d141054bc662 | Fix super call with wrong class. | extra_views/formsets.py | extra_views/formsets.py | from django.views.generic.base import TemplateResponseMixin, View
from django.http import HttpResponseRedirect
from django.forms.formsets import formset_factory
from django.forms.models import modelformset_factory, inlineformset_factory
from django.views.generic.detail import SingleObjectMixin, SingleObjectTemplateResponseMixin
from django.views.generic.list import MultipleObjectMixin, MultipleObjectTemplateResponseMixin
from django.forms.models import BaseInlineFormSet
class BaseFormSetMixin(object):
"""
Base class for constructing a FormSet within a view
"""
initial = []
form_class = None
formset_class = None
success_url = None
extra = 2
max_num = None
can_order = False
can_delete = False
def construct_formset(self):
return self.get_formset()(initial=self.get_initial(), **self.get_formset_kwargs())
def get_initial(self):
return self.initial
def get_formset_class(self):
return self.formset_class
def get_form_class(self):
return self.form_class
def get_formset(self):
return formset_factory(self.get_form_class(), **self.get_factory_kwargs())
def get_formset_kwargs(self):
kwargs = {}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
def get_factory_kwargs(self):
kwargs = {
'extra': self.extra,
'max_num': self.max_num,
'can_order': self.can_order,
'can_delete': self.can_delete,
}
if self.get_formset_class():
kwargs['formset'] = self.get_formset_class()
return kwargs
class FormSetMixin(BaseFormSetMixin):
def get_context_data(self, **kwargs):
return kwargs
def get_success_url(self):
if self.success_url:
url = self.success_url
else:
# Default to returning to the same page
url = self.request.get_full_path()
return url
def formset_valid(self, formset):
return HttpResponseRedirect(self.get_success_url())
def formset_invalid(self, formset):
return self.render_to_response(self.get_context_data(formset=formset))
class ModelFormSetMixin(FormSetMixin, MultipleObjectMixin):
exclude = None
fields = None
formfield_callback = None
def get_context_data(self, **kwargs):
context = kwargs
if self.object_list:
context['object_list'] = self.object_list
context_object_name = self.get_context_object_name(self.get_queryset())
if context_object_name:
context[context_object_name] = self.object_list
return context
def construct_formset(self):
return self.get_formset()(queryset=self.get_queryset(), **self.get_formset_kwargs())
def get_factory_kwargs(self):
kwargs = super(ModelFormSetMixin, self).get_factory_kwargs()
kwargs.update({
'exclude': self.exclude,
'fields': self.fields,
'formfield_callback': self.formfield_callback,
})
if self.get_form_class():
kwargs['form'] = self.get_form_class()
if self.get_formset_class():
kwargs['formset'] = self.get_formset_class()
return kwargs
def get_formset(self):
return modelformset_factory(self.model, **self.get_factory_kwargs())
def formset_valid(self, formset):
self.object_list = formset.save()
return super(ModelFormSetMixin, self).formset_valid(formset)
class BaseInlineFormSetMixin(BaseFormSetMixin):
model = None
inline_model = None
fk_name = None
formset_class = BaseInlineFormSet
exclude = None
fields = None
formfield_callback = None
can_delete = True
def get_context_data(self, **kwargs):
context = kwargs
if self.object:
context['object'] = self.object
context_object_name = self.get_context_object_name(self.object)
if context_object_name:
context[context_object_name] = self.object
return context
def construct_formset(self):
return self.get_formset()(instance=self.object, **self.get_formset_kwargs())
def get_inline_model(self):
return self.inline_model
def get_factory_kwargs(self):
kwargs = super(BaseInlineFormSetMixin, self).get_factory_kwargs()
kwargs.update({
'exclude': self.exclude,
'fields': self.fields,
'formfield_callback': self.formfield_callback,
'fk_name': self.fk_name,
})
if self.get_form_class():
kwargs['form'] = self.get_form_class()
if self.get_formset_class():
kwargs['formset'] = self.get_formset_class()
return kwargs
def get_formset(self):
return inlineformset_factory(self.model, self.get_inline_model(), **self.get_factory_kwargs())
class InlineFormSetMixin(BaseInlineFormSetMixin, FormSetMixin, SingleObjectMixin):
def formset_valid(self, formset):
self.object_list = formset.save()
return super(BaseInlineFormSetMixin, self).formset_valid(formset)
class ProcessFormSetView(View):
"""
A mixin that processes a fomset on POST.
"""
def get(self, request, *args, **kwargs):
formset = self.construct_formset()
return self.render_to_response(self.get_context_data(formset=formset))
def post(self, request, *args, **kwargs):
formset = self.construct_formset()
if formset.is_valid():
return self.formset_valid(formset)
else:
return self.formset_invalid(formset)
def put(self, *args, **kwargs):
return self.post(*args, **kwargs)
class BaseFormSetView(FormSetMixin, ProcessFormSetView):
"""
A base view for displaying a formset
"""
class FormSetView(TemplateResponseMixin, BaseFormSetView):
"""
A view for displaying a formset, and rendering a template response
"""
class BaseModelFormSetView(ModelFormSetMixin, ProcessFormSetView):
"""
A base view for displaying a modelformset
"""
def get(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
return super(BaseModelFormSetView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object_list = self.get_queryset()
return super(BaseModelFormSetView, self).post(request, *args, **kwargs)
class ModelFormSetView(MultipleObjectTemplateResponseMixin, BaseModelFormSetView):
"""
A view for displaying a modelformset, and rendering a template response
"""
class BaseInlineFormSetView(InlineFormSetMixin, ProcessFormSetView):
"""
A base view for displaying a modelformset for a queryset belonging to a parent model
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseInlineFormSetView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseInlineFormSetView, self).post(request, *args, **kwargs)
class InlineFormSetView(SingleObjectTemplateResponseMixin, BaseInlineFormSetView):
"""
A view for displaying a modelformset for a queryset belonging to a parent model
"""
| Python | 0 | @@ -5224,36 +5224,32 @@
return super(
-Base
InlineFormSetMix
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.