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
|
|---|---|---|---|---|---|---|---|
55a17b2ed3c506e240e35ae8bff432e08e588787
|
fix encoding error on *too* random bytes
|
pathod/language/websockets.py
|
pathod/language/websockets.py
|
import os
import netlib.websockets
import pyparsing as pp
from . import base, generators, actions, message
NESTED_LEADER = "pathod!"
class WF(base.CaselessLiteral):
TOK = "wf"
class OpCode(base.IntField):
names = {
"continue": netlib.websockets.OPCODE.CONTINUE,
"text": netlib.websockets.OPCODE.TEXT,
"binary": netlib.websockets.OPCODE.BINARY,
"close": netlib.websockets.OPCODE.CLOSE,
"ping": netlib.websockets.OPCODE.PING,
"pong": netlib.websockets.OPCODE.PONG,
}
max = 15
preamble = "c"
class Body(base.Value):
preamble = "b"
class RawBody(base.Value):
unique_name = "body"
preamble = "r"
class Fin(base.Boolean):
name = "fin"
class RSV1(base.Boolean):
name = "rsv1"
class RSV2(base.Boolean):
name = "rsv2"
class RSV3(base.Boolean):
name = "rsv3"
class Mask(base.Boolean):
name = "mask"
class Key(base.FixedLengthValue):
preamble = "k"
length = 4
class KeyNone(base.CaselessLiteral):
unique_name = "key"
TOK = "knone"
class Length(base.Integer):
bounds = (0, 1 << 64)
preamble = "l"
class Times(base.Integer):
preamble = "x"
COMPONENTS = (
OpCode,
Length,
# Bit flags
Fin,
RSV1,
RSV2,
RSV3,
Mask,
actions.PauseAt,
actions.DisconnectAt,
actions.InjectAt,
KeyNone,
Key,
Times,
Body,
RawBody,
)
class WebsocketFrame(message.Message):
components = COMPONENTS
logattrs = ["body"]
# Used for nested frames
unique_name = "body"
@property
def actions(self):
return self.toks(actions._Action)
@property
def body(self):
return self.tok(Body)
@property
def rawbody(self):
return self.tok(RawBody)
@property
def opcode(self):
return self.tok(OpCode)
@property
def fin(self):
return self.tok(Fin)
@property
def rsv1(self):
return self.tok(RSV1)
@property
def rsv2(self):
return self.tok(RSV2)
@property
def rsv3(self):
return self.tok(RSV3)
@property
def mask(self):
return self.tok(Mask)
@property
def key(self):
return self.tok(Key)
@property
def knone(self):
return self.tok(KeyNone)
@property
def times(self):
return self.tok(Times)
@property
def toklength(self):
return self.tok(Length)
@classmethod
def expr(cls):
parts = [i.expr() for i in cls.components]
atom = pp.MatchFirst(parts)
resp = pp.And(
[
WF.expr(),
base.Sep,
pp.ZeroOrMore(base.Sep + atom)
]
)
resp = resp.setParseAction(cls)
return resp
@property
def nested_frame(self):
return self.tok(NestedFrame)
def resolve(self, settings, msg=None):
tokens = self.tokens[:]
if not self.mask and settings.is_client:
tokens.append(
Mask(True)
)
if not self.knone and self.mask and self.mask.value and not self.key:
tokens.append(
Key(base.TokValueLiteral(os.urandom(4)))
)
return self.__class__(
[i.resolve(settings, self) for i in tokens]
)
def values(self, settings):
if self.body:
bodygen = self.body.value.get_generator(settings)
length = len(self.body.value.get_generator(settings))
elif self.rawbody:
bodygen = self.rawbody.value.get_generator(settings)
length = len(self.rawbody.value.get_generator(settings))
elif self.nested_frame:
bodygen = NESTED_LEADER + self.nested_frame.parsed.spec()
length = len(bodygen)
else:
bodygen = None
length = 0
if self.toklength:
length = int(self.toklength.value)
frameparts = dict(
payload_length=length
)
if self.mask and self.mask.value:
frameparts["mask"] = True
if self.knone:
frameparts["masking_key"] = None
elif self.key:
key = self.key.values(settings)[0][:]
frameparts["masking_key"] = key
for i in ["opcode", "fin", "rsv1", "rsv2", "rsv3", "mask"]:
v = getattr(self, i, None)
if v is not None:
frameparts[i] = v.value
frame = netlib.websockets.FrameHeader(**frameparts)
vals = [bytes(frame)]
if bodygen:
if frame.masking_key and not self.rawbody:
masker = netlib.websockets.Masker(frame.masking_key)
vals.append(
generators.TransformGenerator(
bodygen,
masker.mask
)
)
else:
vals.append(bodygen)
return vals
def spec(self):
return ":".join([i.spec() for i in self.tokens])
class NestedFrame(base.NestedMessage):
preamble = "f"
nest_type = WebsocketFrame
class WebsocketClientFrame(WebsocketFrame):
components = COMPONENTS + (
NestedFrame,
)
|
Python
| 0.999999
|
@@ -3,16 +3,44 @@
port os%0A
+import random%0Aimport string%0A
import n
@@ -3151,32 +3151,197 @@
d not self.key:%0A
+ allowed_chars = string.ascii_letters + string.digits%0A k = ''.join(%5Ballowed_chars%5Brandom.randrange(0, len(allowed_chars))%5D for i in range(4)%5D)%0A
toke
@@ -3396,21 +3396,9 @@
ral(
-os.urandom(4)
+k
))%0A
|
6f2e9362ac8925878e96d18f9b792ff440d83e83
|
819. Most Common Word
|
LeetCode/MostCommonWord.py
|
LeetCode/MostCommonWord.py
|
Python
| 0.999999
|
@@ -0,0 +1,449 @@
+from collections import Counter%0Afrom re import sub%0A%0Aclass Solution:%0A def mostCommonWord(self, paragraph, banned):%0A %22%22%22%0A :type paragraph: str%0A :type banned: List%5Bstr%5D%0A :rtype: str%0A %22%22%22%0A return Counter(%5Bp_word for p_word in %5Bre.sub(%22%5B%5Ea-zA-Z%5D+%22, %22%22, word.lower()) for word in paragraph.split()%5D if p_word not in banned%5D).most_common(1)%5B0%5D%5B0%5D # process words, then filter, then count and select most common%0A
|
|
c80fb5f4b391a76ead84d79b6701cf1a8013f1bc
|
Update Espressif platform // Resolve #245
|
platformio/builder/scripts/espressif.py
|
platformio/builder/scripts/espressif.py
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
"""
Builder for Espressif MCUs
"""
from os.path import join
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
def BeforeUpload(target, source, env): # pylint: disable=W0613,W0621
env.AutodetectUploadPort()
env = DefaultEnvironment()
env.Replace(
AR="xtensa-lx106-elf-ar",
AS="xtensa-lx106-elf-as",
CC="xtensa-lx106-elf-gcc",
CXX="xtensa-lx106-elf-g++",
OBJCOPY="xtensa-lx106-elf-objcopy",
RANLIB="xtensa-lx106-elf-ranlib",
SIZETOOL="xtensa-lx106-elf-size",
ARFLAGS=["rcs"],
ASPPFLAGS=["-x", "assembler-with-cpp"],
CFLAGS=[
"-std=c99",
"-Wpointer-arith",
"-Wno-implicit-function-declaration",
"-Wl,-EL",
"-fno-inline-functions",
"-nostdlib"
],
CPPFLAGS=[
"-Os", # optimize for size
"-mlongcalls",
"-mtext-section-literals",
"-falign-functions=4",
"-U__STRICT_ANSI__",
"-MMD" # output dependancy info
],
CXXFLAGS=[
"-fno-rtti",
"-fno-exceptions",
"-std=c++11"
],
CPPDEFINES=[
"F_CPU=$BOARD_F_CPU",
"__ets__",
"ICACHE_FLASH"
],
LINKFLAGS=[
"-nostdlib",
"-Wl,--no-check-sections",
"-u", "call_user_start",
"-Wl,-static"
],
SIZEPRINTCMD='"$SIZETOOL" -B -d $SOURCES',
UPLOADER=join("$PIOPACKAGES_DIR", "tool-esptool", "esptool"),
UPLOADERFLAGS=[
"-vv",
"-cd", "ck",
"-cb", "$UPLOAD_SPEED",
"-cp", "$UPLOAD_PORT",
"-ca", "0x00000",
"-cf", "${SOURCES[0]}",
"-ca", "0x10000",
"-cf", "${SOURCES[1]}"
],
UPLOADCMD='$UPLOADER $UPLOADERFLAGS'
)
env.Append(
BUILDERS=dict(
ElfToBin=Builder(
action=" ".join([
"$UPLOADER",
"-eo", "$SOURCES",
"-bo", "${TARGETS[0]}",
"-bm", "qio",
"-bf", "40",
"-bz", "512K",
"-bs", ".text",
"-bs", ".data",
"-bs", ".rodata",
"-bc", "-ec",
"-eo", "$SOURCES",
"-es", ".irom0.text", "${TARGETS[1]}",
"-ec", "-v"
]),
suffix=".bin"
)
)
)
#
# Configure SDK
#
if "FRAMEWORK" not in env:
env.Append(
CPPPATH=[
join("$PIOPACKAGES_DIR", "sdk-esp8266", "include"),
"$PROJECTSRC_DIR"
],
LIBPATH=[join("$PIOPACKAGES_DIR", "sdk-esp8266", "lib")]
)
env.Replace(
LDSCRIPT_PATH=join(
"$PIOPACKAGES_DIR", "sdk-esp8266", "ld", "eagle.app.v6.ld"),
LIBS=["c", "gcc", "phy", "pp", "net80211", "lwip", "wpa", "main",
"json", "upgrade", "smartconfig", "at", "ssl"]
)
#
# Target: Build executable and linkable firmware
#
target_elf = env.BuildFirmware()
#
# Target: Build the .hex
#
if "uploadlazy" in COMMAND_LINE_TARGETS:
target_firm = join("$BUILD_DIR", "firmware.bin")
else:
target_firm = env.ElfToBin(
[join("$BUILD_DIR", "firmware_00000"),
join("$BUILD_DIR", "firmware_10000")], target_elf)
#
# Target: Print binary size
#
target_size = env.Alias("size", target_elf, "$SIZEPRINTCMD")
AlwaysBuild(target_size)
#
# Target: Upload firmware
#
upload = env.Alias(["upload", "uploadlazy"], target_firm,
[BeforeUpload, "$UPLOADCMD"])
AlwaysBuild(upload)
#
# Target: Define targets
#
Default([target_firm, target_size])
|
Python
| 0
|
@@ -1741,24 +1741,65 @@
%22-ca%22,
+ %220x40000%22 if %22FRAMEWORK%22 not in env else
%220x10000%22,%0A
@@ -3325,15 +3325,77 @@
are_
+%25s%22 %25%0A (%2240000%22 if %22FRAMEWORK%22 not in env else %22
10000%22)
+)
%5D, t
|
c4e42c88fe6ec09df573f4d379512c516966526b
|
Fix Espressif "uploadlazy" target for @SmartAnthill Project
|
platformio/builder/scripts/espressif.py
|
platformio/builder/scripts/espressif.py
|
# Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
"""
Builder for Espressif MCUs
"""
from os.path import join
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
def BeforeUpload(target, source, env): # pylint: disable=W0613,W0621
env.AutodetectUploadPort()
env = DefaultEnvironment()
env.Replace(
AR="xtensa-lx106-elf-ar",
AS="xtensa-lx106-elf-as",
CC="xtensa-lx106-elf-gcc",
CXX="xtensa-lx106-elf-g++",
OBJCOPY="xtensa-lx106-elf-objcopy",
RANLIB="xtensa-lx106-elf-ranlib",
SIZETOOL="xtensa-lx106-elf-size",
ARFLAGS=["rcs"],
ASPPFLAGS=["-x", "assembler-with-cpp"],
CFLAGS=[
"-std=c99",
"-Wpointer-arith",
"-Wno-implicit-function-declaration",
"-Wl,-EL",
"-fno-inline-functions",
"-nostdlib"
],
CPPFLAGS=[
"-Os", # optimize for size
"-mlongcalls",
"-mtext-section-literals",
"-falign-functions=4",
"-U__STRICT_ANSI__",
"-MMD" # output dependancy info
],
CXXFLAGS=[
"-fno-rtti",
"-fno-exceptions",
"-std=c++11"
],
CPPDEFINES=[
"F_CPU=$BOARD_F_CPU",
"__ets__",
"ICACHE_FLASH"
],
LINKFLAGS=[
"-nostdlib",
"-Wl,--no-check-sections",
"-u", "call_user_start",
"-Wl,-static"
],
SIZEPRINTCMD='"$SIZETOOL" -B -d $SOURCES',
UPLOADER=join("$PIOPACKAGES_DIR", "tool-esptool", "esptool"),
UPLOADERFLAGS=[
"-vv",
"-cd", "ck",
"-cb", "$UPLOAD_SPEED",
"-cp", "$UPLOAD_PORT",
"-ca", "0x00000",
"-cf", "${SOURCES[0]}",
"-ca", "0x40000" if "FRAMEWORK" not in env else "0x10000",
"-cf", "${SOURCES[1]}"
],
UPLOADCMD='$UPLOADER $UPLOADERFLAGS'
)
env.Append(
BUILDERS=dict(
ElfToBin=Builder(
action=" ".join([
"$UPLOADER",
"-eo", "$SOURCES",
"-bo", "${TARGETS[0]}",
"-bm", "qio",
"-bf", "40",
"-bz", "512K",
"-bs", ".text",
"-bs", ".data",
"-bs", ".rodata",
"-bc", "-ec",
"-eo", "$SOURCES",
"-es", ".irom0.text", "${TARGETS[1]}",
"-ec", "-v"
]),
suffix=".bin"
)
)
)
#
# Configure SDK
#
if "FRAMEWORK" not in env:
env.Append(
CPPPATH=[
join("$PIOPACKAGES_DIR", "sdk-esp8266", "include"),
"$PROJECTSRC_DIR"
],
LIBPATH=[join("$PIOPACKAGES_DIR", "sdk-esp8266", "lib")]
)
env.Replace(
LDSCRIPT_PATH=join(
"$PIOPACKAGES_DIR", "sdk-esp8266", "ld", "eagle.app.v6.ld"),
LIBS=["c", "gcc", "phy", "pp", "net80211", "lwip", "wpa", "main",
"json", "upgrade", "smartconfig", "at", "ssl"]
)
#
# Target: Build executable and linkable firmware
#
target_elf = env.BuildFirmware()
#
# Target: Build the .hex
#
if "uploadlazy" in COMMAND_LINE_TARGETS:
target_firm = join("$BUILD_DIR", "firmware.bin")
else:
target_firm = env.ElfToBin(
[join("$BUILD_DIR", "firmware_00000"),
join("$BUILD_DIR", "firmware_%s" %
("40000" if "FRAMEWORK" not in env else "10000"))], target_elf)
#
# Target: Print binary size
#
target_size = env.Alias("size", target_elf, "$SIZEPRINTCMD")
AlwaysBuild(target_size)
#
# Target: Upload firmware
#
upload = env.Alias(["upload", "uploadlazy"], target_firm,
[BeforeUpload, "$UPLOADCMD"])
AlwaysBuild(upload)
#
# Target: Define targets
#
Default([target_firm, target_size])
|
Python
| 0
|
@@ -3162,16 +3162,26 @@
t_firm =
+ %5B%0A
join(%22$
@@ -3205,14 +3205,137 @@
ware
-.bin%22)
+_00000.bin%22),%0A join(%22$BUILD_DIR%22, %22firmware_%25s.bin%22 %25%0A (%2240000%22 if %22FRAMEWORK%22 not in env else %2210000%22))%0A %5D
%0Aels
|
7c1a1ee17b83a39d7dfb37b595090ccb7bc23532
|
create default group for ODIN users (if necessary)
|
promort/odin/migrations/0001_initial.py
|
promort/odin/migrations/0001_initial.py
|
Python
| 0
|
@@ -0,0 +1,790 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.3 on 2017-08-01 08:00%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0Afrom promort import settings as pms%0A%0Aimport logging%0Alogger = logging.getLogger('promort')%0A%0A%0Adef create_odin_group(apps, schema_editor):%0A logger.info('Creating default group for Odin users (if needed)')%0A Group = apps.get_model('auth', 'Group')%0A group_name = pms.DEFAULT_GROUPS%5B'odin_members'%5D%5B'name'%5D%0A group, created = Group.objects.get_or_create(name=group_name)%0A logger.info('Group %22%25s%22 --- Created %25s', group.name, created)%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('worklist_manager', '0002_auto_20170328_0652'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(create_odin_group),%0A %5D%0A
|
|
b1ef2e8c130debb8c43c6453ba1d99d0f33543b5
|
Use -j option for parallel testing
|
astropy_helpers/test_helpers.py
|
astropy_helpers/test_helpers.py
|
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import shutil
import subprocess
import sys
import tempfile
from distutils.core import Command
from .compat import _fix_user_options
PY3 = sys.version_info[0] == 3
class AstropyTest(Command, object):
description = 'Run the tests for this package'
user_options = [
('package=', 'P',
"The name of a specific package to test, e.g. 'io.fits' or 'utils'. "
"If nothing is specified, all default tests are run."),
('test-path=', 't',
'Specify a test location by path. If a relative path to a '
'.py file, it is relative to the built package. If a relative '
'path to a .rst file, it is relative to the docs directory '
'(see --docs-path). May also be an absolute path.'),
('verbose-results', 'V',
'Turn on verbose output from pytest.'),
('plugins=', 'p',
'Plugins to enable when running pytest.'),
('pastebin=', 'b',
"Enable pytest pastebin output. Either 'all' or 'failed'."),
('args=', 'a',
'Additional arguments to be passed to pytest.'),
('remote-data', 'R', 'Run tests that download remote data.'),
('pep8', '8',
'Enable PEP8 checking and disable regular tests. '
'Requires the pytest-pep8 plugin.'),
('pdb', 'd',
'Start the interactive Python debugger on errors.'),
('coverage', 'c',
'Create a coverage report. Requires the coverage package.'),
('open-files', 'o', 'Fail if any tests leave files open.'),
('parallel=', 'n',
'Run the tests in parallel on the specified number of '
'CPUs. If negative, all the cores on the machine will be '
'used. Requires the pytest-xdist plugin.'),
('docs-path=', None,
'The path to the documentation .rst files. If not provided, and '
'the current directory contains a directory called "docs", that '
'will be used.'),
('skip-docs', None,
"Don't test the documentation .rst files.")
]
user_options = _fix_user_options(user_options)
package_name = ''
def initialize_options(self):
self.package = None
self.test_path = None
self.verbose_results = False
self.plugins = None
self.pastebin = None
self.args = None
self.remote_data = False
self.pep8 = False
self.pdb = False
self.coverage = False
self.open_files = False
self.parallel = 0
self.docs_path = None
self.skip_docs = False
def finalize_options(self):
# Normally we would validate the options here, but that's handled in
# run_tests
pass
def run(self):
try:
import astropy
except ImportError:
raise ImportError(
"The 'test' command requires the astropy package to be "
"installed and importable.")
self.reinitialize_command('build', inplace=False)
self.run_command('build')
build_cmd = self.get_finalized_command('build')
new_path = os.path.abspath(build_cmd.build_lib)
if self.docs_path is None:
if os.path.exists('docs'):
self.docs_path = os.path.abspath('docs')
# Copy the build to a temporary directory for the purposes of testing
# - this avoids creating pyc and __pycache__ directories inside the
# build directory
tmp_dir = tempfile.mkdtemp(prefix=self.package_name + '-test-')
testing_path = os.path.join(tmp_dir, os.path.basename(new_path))
shutil.copytree(new_path, testing_path)
shutil.copy('setup.cfg', testing_path)
cmd_pre = ''
cmd_post = ''
try:
if self.coverage:
if self.parallel != 0:
raise ValueError(
"--coverage can not be used with --parallel")
try:
import coverage
except ImportError:
raise ImportError(
"--coverage requires that the coverage package is "
"installed.")
# Don't use get_pkg_data_filename here, because it
# requires importing astropy.config and thus screwing
# up coverage results for those packages.
coveragerc = os.path.join(
testing_path, self.package_name, 'tests', 'coveragerc')
# We create a coveragerc that is specific to the version
# of Python we're running, so that we can mark branches
# as being specifically for Python 2 or Python 3
with open(coveragerc, 'r') as fd:
coveragerc_content = fd.read()
if PY3:
ignore_python_version = '2'
else:
ignore_python_version = '3'
coveragerc_content = coveragerc_content.replace(
"{ignore_python_version}", ignore_python_version).replace(
"{packagename}", self.package_name)
tmp_coveragerc = os.path.join(tmp_dir, 'coveragerc')
with open(tmp_coveragerc, 'wb') as tmp:
tmp.write(coveragerc_content.encode('utf-8'))
cmd_pre = (
'import coverage; '
'cov = coverage.coverage(data_file="{0}", config_file="{1}"); '
'cov.start();'.format(
os.path.abspath(".coverage"), tmp_coveragerc))
cmd_post = (
'cov.stop(); '
'from astropy.tests.helper import _save_coverage; '
'_save_coverage(cov, result, "{0}", "{1}");'.format(
os.path.abspath('.'), testing_path))
if PY3:
set_flag = "import builtins; builtins._ASTROPY_TEST_ = True"
else:
set_flag = "import __builtin__; __builtin__._ASTROPY_TEST_ = True"
cmd = ('{cmd_pre}{0}; import {1.package_name}, sys; result = ('
'{1.package_name}.test('
'package={1.package!r}, '
'test_path={1.test_path!r}, '
'args={1.args!r}, '
'plugins={1.plugins!r}, '
'verbose={1.verbose_results!r}, '
'pastebin={1.pastebin!r}, '
'remote_data={1.remote_data!r}, '
'pep8={1.pep8!r}, '
'pdb={1.pdb!r}, '
'open_files={1.open_files!r}, '
'parallel={1.parallel!r}, '
'docs_path={1.docs_path!r}, '
'skip_docs={1.skip_docs!r})); '
'{cmd_post}'
'sys.exit(result)')
cmd = cmd.format(set_flag, self, cmd_pre=cmd_pre, cmd_post=cmd_post)
# Run the tests in a subprocess--this is necessary since
# new extension modules may have appeared, and this is the
# easiest way to set up a new environment
# Remove temporary directory
# On Python 3.x prior to 3.3, the creation of .pyc files
# is not atomic. py.test jumps through some hoops to make
# this work by parsing import statements and carefully
# importing files atomically. However, it can't detect
# when __import__ is used, so its carefulness still fails.
# The solution here (admittedly a bit of a hack), is to
# turn off the generation of .pyc files altogether by
# passing the `-B` switch to `python`. This does mean
# that each core will have to compile .py file to bytecode
# itself, rather than getting lucky and borrowing the work
# already done by another core. Compilation is an
# insignificant fraction of total testing time, though, so
# it's probably not worth worrying about.
retcode = subprocess.call([sys.executable, '-B', '-c', cmd],
cwd=testing_path, close_fds=False)
finally:
shutil.rmtree(tmp_dir)
raise SystemExit(retcode)
|
Python
| 0
|
@@ -1672,17 +1672,17 @@
lel=', '
-n
+j
',%0A
|
bf979d2c32d84c4011a7363489798056d3cc6a58
|
add TestBEventsWithFile
|
tests/unit/Events/test_BEventsWithFile.py
|
tests/unit/Events/test_BEventsWithFile.py
|
Python
| 0.000001
|
@@ -0,0 +1,1637 @@
+from AlphaTwirl.Events import BEvents as Events%0Afrom AlphaTwirl.Events import Branch%0Aimport unittest%0Aimport ROOT%0A%0A##____________________________________________________________________________%7C%7C%0AinputPath = '/Users/sakuma/work/cms/c150130_RA1_data/c150130_01_PHYS14/20150331_SingleMu/TTJets/treeProducerSusyAlphaT/tree.root'%0AtreeName = 'tree'%0A%0A##____________________________________________________________________________%7C%7C%0A@unittest.skip(%22skip TestBEventsWithFile%22)%0Aclass TestBEventsWithFile(unittest.TestCase):%0A%0A def test_branch(self):%0A inputFile = ROOT.TFile.Open(inputPath)%0A tree = inputFile.Get(treeName)%0A events = Events(tree)%0A%0A jet_pt = events.jet_pt%0A met_pt = events.met_pt%0A self.assertIsInstance(jet_pt, Branch)%0A self.assertIsInstance(met_pt, Branch)%0A%0A self.assertEqual(0, len(jet_pt))%0A self.assertEqual(1, len(met_pt))%0A self.assertEqual(0.0, met_pt%5B0%5D)%0A%0A tree.GetEntry(0)%0A self.assertEqual(2, len(jet_pt))%0A self.assertEqual(1, len(met_pt))%0A self.assertEqual(124.55626678466797, jet_pt%5B0%5D)%0A self.assertEqual(86.90544128417969, jet_pt%5B1%5D)%0A self.assertAlmostEqual(43.783382415771484, met_pt%5B0%5D)%0A%0A tree.GetEntry(1)%0A self.assertEqual(3, len(jet_pt))%0A self.assertEqual(1, len(met_pt))%0A self.assertEqual(112.48554992675781, jet_pt%5B0%5D)%0A self.assertEqual(52.32780075073242, jet_pt%5B1%5D)%0A self.assertEqual(48.861289978027344, jet_pt%5B2%5D)%0A self.assertAlmostEqual(20.483951568603516, met_pt%5B0%5D)%0A%0A##____________________________________________________________________________%7C%7C%0A
|
|
0782e8786272fcd6e3e1a41d31bea253865c468b
|
Add SolveTimer - print number of iterations and elapsed time to console while running ml.solve() - see docstring for usage
|
pastas/timer.py
|
pastas/timer.py
|
Python
| 0
|
@@ -0,0 +1,1016 @@
+try:%0A from tqdm.auto import tqdm%0Aexcept ModuleNotFoundError:%0A raise ModuleNotFoundError(%22SolveTimer requires 'tqdm' to be installed.%22)%0A%0A%0Aclass SolveTimer(tqdm):%0A %22%22%22Progress indicator for model optimization.%0A%0A Usage%0A ----- %0A Print timer and number of iterations in console while running%0A %60ml.solve()%60::%0A%0A %3E%3E%3E with SolveTimer() as t:%0A ml.solve(callback=t.update)%0A%0A This prints the following to the console, for example::%0A%0A Optimization progress: 73it %5B00:01, 67.68it/s%5D%0A%0A Note%0A ----%0A If the logger is also printing messages to the console the timer will not%0A be updated quite as nicely.%0A %22%22%22%0A%0A def __init__(self, *args, **kwargs):%0A if %22total%22 not in kwargs:%0A kwargs%5B'total'%5D = None%0A if %22desc%22 not in kwargs:%0A kwargs%5B%22desc%22%5D = %22Optimization progress%22%0A super(SolveTimer, self).__init__(*args, **kwargs)%0A%0A def update(self, _, n=1):%0A displayed = super(SolveTimer, self).update(n)%0A return displayed%0A
|
|
0d12fe35e0c7a31987d83737d22bfc9f54e72709
|
Add Binary
|
add-binary.py
|
add-binary.py
|
Python
| 0.999982
|
@@ -0,0 +1,508 @@
+# author: Fei Gao%0A#%0A# Add Binary%0A#%0A# Given two binary strings, return their sum (also a binary string).%0A# For example,%0A# a = %2211%22%0A# b = %221%22%0A# Return %22100%22.%0A%0A%0Aclass Solution:%0A # @param a, a string%0A # @param b, a string%0A # @return a string%0A def addBinary(self, a, b):%0A ai = int(a, base=2)%0A bi = int(b, base=2)%0A return '%7B:b%7D'.format(ai + bi)%0A%0A%0Adef main():%0A solver = Solution()%0A print(solver.addBinary('101', '1'))%0A pass%0A%0A%0Aif __name__ == '__main__':%0A main()%0A pass%0A
|
|
dd30bed54205eb3639e8af0e2cf879e7cf319701
|
add solution for Symmetric Tree
|
src/symmetricTree.py
|
src/symmetricTree.py
|
Python
| 0.000001
|
@@ -0,0 +1,622 @@
+# Definition for a binary tree node%0A# class TreeNode:%0A# def __init__(self, x):%0A# self.val = x%0A# self.left = None%0A# self.right = None%0A%0A%0Aclass Solution:%0A # @param root, a tree node%0A # @return a boolean%0A%0A def isSymmetric(self, root):%0A if not root:%0A return True%0A return self.check(root.left, root.right)%0A%0A def check(self, left, right):%0A if left is None or right is None:%0A return left is right%0A return (left.val == right.val and%0A self.check(left.left, right.right) and%0A self.check(left.right, right.left))%0A
|
|
6ece957e5317a9f54499714f9a7cb9bca221d4e5
|
Add a simple script that runs the pipeline for the single specified user
|
bin/debug/intake_single_user.py
|
bin/debug/intake_single_user.py
|
Python
| 0
|
@@ -0,0 +1,659 @@
+import json%0Aimport logging%0Aimport argparse%0Aimport numpy as np%0Aimport uuid%0A%0Aimport emission.pipeline.intake_stage as epi%0Aimport emission.core.wrapper.user as ecwu%0A%0Aif __name__ == '__main__':%0A np.random.seed(61297777)%0A%0A parser = argparse.ArgumentParser(prog=%22intake_single_user%22)%0A group = parser.add_mutually_exclusive_group(required=True)%0A group.add_argument(%22-e%22, %22--user_email%22)%0A group.add_argument(%22-u%22, %22--user_uuid%22)%0A%0A args = parser.parse_args()%0A%0A if args.user_uuid:%0A sel_uuid = uuid.UUID(args.user_uuid)%0A else:%0A sel_uuid = ecwu.User.fromEmail(args.user_email).uuid%0A%0A epi.run_intake_pipeline(%22single%22, %5Bsel_uuid%5D)%0A
|
|
4c5f750801cef0424fd93432b688fb74b079f4c5
|
Add migration to backfill recipient counts
|
temba/msgs/migrations/0037_backfill_recipient_counts.py
|
temba/msgs/migrations/0037_backfill_recipient_counts.py
|
Python
| 0
|
@@ -0,0 +1,854 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('msgs', '0036_auto_20151103_1014'),%0A %5D%0A%0A def backfill_recipient_counts(apps, schema):%0A Broadcast = apps.get_model('msgs', 'Broadcast')%0A Msg = apps.get_model('msgs', 'Msg')%0A%0A # get all broadcasts with 0 recipients%0A for broadcast in Broadcast.objects.filter(recipient_count=0):%0A # set to # of msgs%0A broadcast.recipient_count = Msg.objects.filter(broadcast=broadcast).count()%0A if recipient_count %3E 0:%0A broadcast.save()%0A print %22Updated %25d to %25d recipients%22 %25 (broadcast.id, broadcast.recipient_count)%0A%0A operations = %5B%0A migrations.RunPython(backfill_recipient_counts)%0A %5D%0A
|
|
b44f13bfa1ac8b3c1bd24e528fc7874a06df0121
|
Add script that creates a filtered list of required packages
|
dev_tools/src/d1_dev/update-requirements-txt.py
|
dev_tools/src/d1_dev/update-requirements-txt.py
|
Python
| 0.000001
|
@@ -0,0 +1,1647 @@
+#!/usr/bin/env python%0A%0Aimport shutil%0Aimport d1_dev.util%0Aimport os%0Aimport pip._internal.utils.misc%0Aimport re%0A%0A%0AREQUIREMENTS_FILENAME = 'requirements.txt'%0A%0A%0A# Modules in my dev environment that are not required by the stack%0A%0AMODULE_FILTER_REGEX_LIST = %7B%0A 'beautifulsoup',%0A 'black',%0A 'bs4',%0A 'dataone.*',%0A 'ete3',%0A 'Flask',%0A 'logging-tree',%0A 'PyQt.*',%0A 'pyqt5',%0A 'python-magic',%0A 'redbaron',%0A%7D%0A%0Adef main():%0A repo_dir = d1_dev.util.find_repo_root()%0A req_path = os.path.join(repo_dir, REQUIREMENTS_FILENAME)%0A req_backup_path = req_path + %22.bak%22%0A try:%0A os.remove(req_backup_path)%0A except FileNotFoundError:%0A pass%0A shutil.move(req_path, req_backup_path)%0A req_list = sorted(get_reqs())%0A write_reqs(req_path, req_list)%0A%0A%0Adef get_reqs():%0A req_list = %5B%5D%0A # noinspection PyProtectedMember%0A for package_dist in pip._internal.utils.misc.get_installed_distributions(local_only=True):%0A if not is_filtered_package(package_dist.project_name):%0A req_str = str(package_dist.as_requirement())%0A req_list.append(req_str)%0A return req_list%0A%0Adef is_filtered_package(project_name):%0A for filter_rx in MODULE_FILTER_REGEX_LIST:%0A if re.match(filter_rx, project_name, re.IGNORECASE):%0A print('Filtered: %7B%7D'.format(project_name, filter_rx))%0A return True%0A print('Included: %7B%7D'.format(project_name))%0A return False%0A%0A%0Adef write_reqs(req_path, req_list):%0A %22%22%22%0A Args:%0A req_path:%0A req_list:%0A %22%22%22%0A with open(req_path, 'w') as f:%0A f.write('%5Cn'.join(req_list) + %22%5Cn%22)%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
869e0d41a498698b3c785af7c86dc2bc831e0791
|
Create three-words.py
|
CheckiO/three-words.py
|
CheckiO/three-words.py
|
Python
| 0.99997
|
@@ -0,0 +1,100 @@
+def checkio(words):%0A return '111' in ''.join('1' if w.isalpha() else '0' for w in words.split())%0A
|
|
2521df36a3decb2824ef1207420a9b288b544fee
|
1512. Number of Good Pairs
|
LeetCode/NumberOfGoodPairs.py
|
LeetCode/NumberOfGoodPairs.py
|
Python
| 0.999999
|
@@ -0,0 +1,388 @@
+# don't need to show the pairs, so the order doesn't matter%0A# just need to find how many times each number appears and count the pairs%0A%0Afrom collections import Counter%0A%0Aclass Solution:%0A def numIdenticalPairs(self, nums: List%5Bint%5D) -%3E int:%0A counts = Counter(nums)%0A return sum(count * (count - 1) // 2 for count in counts.values()) # n*(n-1)/2 = number of pairs in n items%0A
|
|
f7d95d4df21bc442261723298f9889bd093feb97
|
add spaceapi module
|
py3status/modules/spaceapi.py
|
py3status/modules/spaceapi.py
|
Python
| 0.000001
|
@@ -0,0 +1,2336 @@
+# -*- coding: utf-8 -*-%0A%22%22%22%0AThis module shows if your favorite hackerspace is open or not%0A%0ALast modified: 2015-02-01%0AAuthor: @timmszigat%0ALicense: WTFPL http://www.wtfpl.net/txt/copying/%0A%22%22%22%0A%0Afrom time import time%0Aimport datetime%0Aimport json%0Aimport urllib.request%0Aimport codecs%0A%0Aclass Py3status:%0A %22%22%22%0A Configuration Parameters:%0A - cache_timeout: Set timeout between calls in seconds%0A - url: URL to SpaceAPI json file of your space%0A - open_text: text if space is open, strftime parmeters will be translated%0A - open_color: color if space is open%0A - closed_text: text if space is closed, strftime parameters will be translated%0A - closed_color: color if space is closed%0A %22%22%22%0A cache_timeout = 60%0A url = 'http://status.chaospott.de/status.json'%0A open_text = 'open since %25H:%25M'%0A open_color = None%0A closed_text = 'closed since %25H:%25M'%0A closed_color = None%0A%0A def __init__(self):%0A pass%0A%0A def check(self, i3s_output_list, i3s_config):%0A%0A response = %7B%0A 'name': 'spaceapi',%0A 'cached_until': time() + self.cache_timeout%0A %7D%0A%0A try:%0A if not self.open_color:%0A self.open_color = i3s_config%5B'color_good'%5D%0A%0A if not self.closed_color:%0A self.closed_color = ''%0A%0A json_file=urllib.request.urlopen(self.url)%0A%0A reader = codecs.getreader(%22utf-8%22)%0A data = json.load(reader(json_file))%0A json_file.close()%0A%0A %0A if(data%5B'state'%5D%5B'open'%5D == True):%0A response%5B'full_text'%5D = self.open_text%0A response%5B'short_text'%5D = '%25H:%25M'%0A if self.open_color:%0A response%5B'color'%5D = self.open_color%0A else:%0A response%5B'full_text'%5D = self.closed_text%0A response%5B'short_test'%5D = ''%0A if self.closed_color:%0A response%5B'color'%5D = self.closed_color%0A%0A%0A dt = datetime.datetime.fromtimestamp(data%5B'state'%5D%5B'lastchange'%5D)%0A response%5B'full_text'%5D = dt.strftime(response%5B'full_text'%5D)%0A%0A except:%0A response%5B'full_text'%5D = '';%0A%0A%0A return response%0Aif __name__ == %22__main__%22:%0A %22%22%22%0A Test this module by calling it directly.%0A %22%22%22%0A from time import sleep%0A x = Py3status()%0A while True:%0A print(x.check(%5B%5D, %7B%7D))%0A sleep(1)%0A
|
|
651c44b51a26733dde22e82a80b0668302e5df52
|
implement a base class for backends
|
merfi/backends/base.py
|
merfi/backends/base.py
|
Python
| 0
|
@@ -0,0 +1,471 @@
+from merfi import base, util%0Afrom tambo import Transport%0A%0A%0Aclass BaseBackend(base.BaseCommand):%0A%0A options = %5B%5D%0A parser = None%0A%0A def parse_args(self):%0A self.parser = Transport(self.argv, options=self.options)%0A self.parser.catch_help = self.help()%0A self.parser.parse_args()%0A self.path = util.infer_path(self.parser.unkown_commands)%0A self.check_dependency()%0A self.sign()%0A%0A def sign(self):%0A raise NotImplemented()%0A
|
|
7086ce47e4a2b6611596d177cc5adb166b382f48
|
Create cryptography.py
|
cryptography.py
|
cryptography.py
|
Python
| 0.999878
|
@@ -0,0 +1,4 @@
+%22%22%22%0A
|
|
2eb5ba178e3bed422a2cb7437362b30df717103e
|
remove dbcred file from staging interface
|
dataactvalidator/interfaces/validatorStagingInterface.py
|
dataactvalidator/interfaces/validatorStagingInterface.py
|
from sqlalchemy.exc import ResourceClosedError
from dataactcore.models.baseInterface import BaseInterface
class ValidatorStagingInterface(BaseInterface):
""" Manages all interaction with the staging database """
dbName = "staging"
credFileName = "dbCred.json"
Session = None
engine = None
session = None
def __init__(self):
self.dbConfigFile = self.getCredFilePath()
super(ValidatorStagingInterface,self).__init__()
@staticmethod
def getDbName():
""" Return database name"""
return ValidatorStagingInterface.dbName
def dropTable(self,table):
"""
Args:
table: Table to be dropped
Returns:
True if successful
"""
self.runStatement("".join(["DROP TABLE ",table]))
self.session.commit()
def tableExists(self,table):
""" True if table exists, false otherwise """
return self.engine.dialect.has_table(self.engine.connect(),table)
def countRows(self,table):
""" Returns number of rows in the specified table """
if(self.tableExists(table)):
response = (self.runStatement("".join(["SELECT COUNT(*) FROM ",table]))).fetchone()[0]
# Try to prevent blocking
self.session.close()
return response
else:
return 0
@staticmethod
def getTableName(jobId):
""" Get the staging table name based on the job ID """
return "".join(["job",str(jobId)])
|
Python
| 0
|
@@ -1,51 +1,4 @@
-from sqlalchemy.exc import ResourceClosedError%0A
from
@@ -51,16 +51,57 @@
nterface
+%0Afrom dataactcore.config import CONFIG_DB
%0A%0Aclass
@@ -222,50 +222,36 @@
e =
-%22staging%22%0A credFileName = %22dbCred.json%22
+CONFIG_DB%5B'staging_db_name'%5D
%0A
@@ -304,16 +304,16 @@
= None%0A%0A
+
def
@@ -332,59 +332,8 @@
f):%0A
- self.dbConfigFile = self.getCredFilePath()%0A
|
6f2529d1891b5c256394b9c8aa991b25a029b5f1
|
Add a migration to load users and buckets
|
migrations/004_load_seed_file.py
|
migrations/004_load_seed_file.py
|
Python
| 0
|
@@ -0,0 +1,501 @@
+%22%22%22%0ALoad initial user and bucket data from seed files.%0A%22%22%22%0Aimport logging%0Aimport os%0Aimport subprocess%0Aimport sys%0A%0Alog = logging.getLogger(__name__)%0A%0A%0Adef up(db):%0A names = db.collection_names()%0A%0A if %22users%22 in names:%0A log.info(%22users collection already created%22)%0A return%0A%0A if %22buckets%22 in names:%0A log.info(%22buckets collection already created%22)%0A return%0A%0A invoke = os.path.join(os.path.dirname(sys.executable), %22invoke%22)%0A subprocess.call(%5Binvoke, %22load_seed%22%5D)%0A
|
|
3dbe5ce617d882dc74a1b95e830634dc0d0f800c
|
Add examples from the ORM tutorial
|
python/sqlalchemy/tutorial.py
|
python/sqlalchemy/tutorial.py
|
Python
| 0
|
@@ -0,0 +1,1615 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A#%0A# Examples from the ORM tutorial%0A#%0A%0Afrom __future__ import print_function, division%0A%0Afrom sqlalchemy import Column, Integer, String, Sequence, ForeignKey%0Afrom sqlalchemy.ext.declarative import declarative_base%0Afrom sqlalchemy.orm import relationship, backref%0A%0ABase = declarative_base()%0A%0Aclass User(Base):%0A __tablename__ = 'user'%0A%0A id = Column(Integer, Sequence('user_id_seq'), primary_key=True)%0A name = Column(String(50))%0A fullname = Column(String(50))%0A password = Column(String(12))%0A%0A def __repr__(self):%0A return %22%3CUser(name='%25s', fullname='%25s', password='%25s')%3E%22 %25 (self.name,%0A self.fullname, self.password)%0A%0Aclass Address(Base):%0A __tablename__ = 'address'%0A%0A id = Column(Integer, Sequence('address_id_seq'), primary_key=True)%0A email_address = Column(String(50))%0A user_id = Column(Integer, ForeignKey('user.id'))%0A%0A user = relationship('User', backref=backref('addresses', order_by=id))%0A%0A def __repr__(self):%0A return %22%3CAddress(email_address='%25s')%3E%22 %25 self.email_address%0A%0Aif __name__ == '__main__':%0A from sqlalchemy import create_engine%0A from sqlalchemy.orm import sessionmaker%0A%0A engine = create_engine('sqlite:///tutorial.db')%0A # Create the tables if not exist%0A Base.metadata.create_all(engine)%0A # Create a session, do some insert and query%0A Session = sessionmaker()%0A session = Session(bind=engine)%0A ed = User(name='ed', fullname='Ed Jacson', password='edpass')%0A session.add(ed)%0A session.commit()%0A # Query%0A for row in session.query(User).all():%0A print(row)%0A
|
|
e3eaa56e95719957c72106640d574e6ec28a76b8
|
fix problem with high fluxes at edges which include occluded porosity
|
autotest/src/solution_reader.py
|
autotest/src/solution_reader.py
|
### ====================================================================
### Python-file
### author: Ethan T. Coon
### filename: solution_reader.py
### version:
### created: 25 January 2011
### on: 10:53:33 MST
### last modified: 14 February 2011
### at: 15:29:10 MST
### URL: http://www.ldeo.columbia.edu/~ecoon/
### email: ecoon _at_ lanl.gov
###
### ====================================================================
import os
import numpy as np
import pyvtk
def generate_commandline(filename):
infile = open(filename, 'r')
args = [line[:-1] for line in infile if not line.strip().startswith('#')]
infile.close()
if any('use_old_options_style' in line for line in args):
raise NotImplementedError("Old style options can't be used here... generate a PETSc-style options file and try again")
else:
import petsc4py
petsc4py.init(' '.join(args))
from petsc4py import PETSc
return
class SolutionReader(object):
def __init__( self, prefix ):
from petsc4py import PETSc
self._prefix = prefix
self._opts = PETSc.Options(prefix)
self._size = (self._opts.getInt('NX'), self._opts.getInt('NY'),
self._opts.getInt('NZ'))
self._s = self._opts.getInt('s',default=2)
lsize = list(self._size)
lsize.reverse()
self._size_r = tuple(lsize)
self._file_prefix = self._opts.getString('output_file_prefix', default='test_solution/')
self._vecs = dict()
self._scalefactor = self._opts.getReal('velocity_scalefactor', default=1.0)
def loadVec( self, name, ndofs=1 ):
from petsc4py import PETSc
length = np.array(self._size).prod()
print 'loading', self._file_prefix+name
vec = PETSc.Vec().createSeq(length*ndofs)
vec.setBlockSize(ndofs)
viewer = PETSc.Viewer().createBinary(self._file_prefix+name, PETSc.Viewer.Mode.R)
vec.load(viewer)
npvec = vec[...].reshape(self._size_r+(ndofs,)).transpose((2,1,0,3))[:]
viewer.destroy()
vec.destroy()
del viewer
del vec
return npvec
def loadVecToVTK( self, name, ndofs=1 ):
from petsc4py import PETSc
length = np.array(self._size).prod()
print 'loading', self._file_prefix+name
vec = PETSc.Vec().createSeq(length*ndofs)
viewer = PETSc.Viewer().createBinary(self._file_prefix+name, PETSc.Viewer.Mode.R)
vec.load(viewer)
if self._size[2] == 1:
length = 2*length
npvec = vec[...].reshape((self._size_r+(ndofs,)))[:]
npvec = np.repeat(npvec,2,axis=0)
npvec = npvec.reshape((length,ndofs))
else:
npvec = vec[...].reshape((length,ndofs))[:]
# scale
if name.startswith('u'):
npvec = npvec*self._scalefactor
if ndofs == 1:
data = pyvtk.Scalars(npvec, self._prefix.strip('_')+' '+name[:-7], 'default')
else:
data = pyvtk.Vectors([tuple(npvec[i,:]) for i in range(length)], self._prefix.strip('_')+' '+name[:-7])
viewer.destroy()
vec.destroy()
del viewer
del vec
return data
def solnToVTK( self ):
done = False
lcv = 0
coords = self.loadVec('coords.dat', 3)
dims = list(coords.shape[:-1])
try:
dx = coords[1,1,1]-coords[0,0,0]
except IndexError:
try:
dx = coords[0,1,1] - coords[0,0,0]
except IndexError:
try:
dx = coords[1,0,1] - coords[0,0,0]
except IndexError:
dx = coords[1,1,0] - coords[0,0,0]
dx = np.where(dx==0., 0.1, dx)
if dims[2] == 1:
dims[2] = 2
dims = tuple(dims)
print dims
dx = tuple(dx)
vtkgrid = pyvtk.StructuredPoints(dims, coords[0,0,0], dx)
while not done:
try:
if not os.path.exists(self._file_prefix+'prs%03d.dat'%lcv):
raise IOError('Nonexistent file')
except IOError:
done = True
print 'Read %d timesteps'%lcv
else:
prs_data = self.loadVecToVTK('prs%03d.dat'%lcv, 1)
vel_data = self.loadVecToVTK('u%03d.dat'%lcv, 3)
wall_data = self.loadVecToVTK('walls%03d.dat'%lcv, 1)
pointdata = pyvtk.PointData(prs_data, vel_data, wall_data)
data = pyvtk.VtkData(vtkgrid, self._prefix.strip('_')+' step %d'%lcv, pointdata)
data.tofile(self._file_prefix+'soln_%03d.vtk'%lcv)
lcv += 1
return
|
Python
| 0
|
@@ -297,17 +297,17 @@
ied: 1
-4
+6
Februar
@@ -343,14 +343,14 @@
1
-5:29:1
+0:38:2
0 MS
@@ -2975,16 +2975,169 @@
efactor%0A
+ print np.where(np.abs(npvec)/np.abs(npvec).mean() %3E 1e2)%5B0%5D%0A npvec = np.where(np.abs(npvec)/np.abs(npvec).mean() %3E 1e2, 0., npvec)
%0A%0A
|
b9da5732579dce0f25a413cbfe4936b8ac024aa5
|
move gzip classes into gzip
|
bamboo_crawler/gzip/__init__.py
|
bamboo_crawler/gzip/__init__.py
|
Python
| 0.000002
|
@@ -0,0 +1,387 @@
+import gzip%0A%0Afrom ..interfaces.deserializer import Deserializer%0Afrom ..interfaces.serializer import Serializer%0A%0A%0Aclass GzipSerializer(Serializer%5Bbytes, bytes%5D):%0A def serialize(self, value: bytes) -%3E bytes:%0A return gzip.compress(value)%0A%0A%0Aclass GzipDeserializer(Deserializer%5Bbytes, bytes%5D):%0A def deserialize(self, value: bytes) -%3E bytes:%0A return gzip.decompress(value)%0A
|
|
99282d42a3948b9ed45b02df657c344667ec0cf2
|
Add a migration for directive_sections -> relationships
|
src/ggrc/migrations/versions/20150521125008_324d461206_migrate_directive_sections_to_.py
|
src/ggrc/migrations/versions/20150521125008_324d461206_migrate_directive_sections_to_.py
|
Python
| 0
|
@@ -0,0 +1,1557 @@
+# Copyright (C) 2015 Google Inc., authors, and contributors %3Csee AUTHORS file%3E%0A# Licensed under http://www.apache.org/licenses/LICENSE-2.0 %3Csee LICENSE file%3E%0A# Created By: anze@reciprocitylabs.com%0A# Maintained By: anze@reciprocitylabs.com%0A%0A%22%22%22Migrate directive_sections to relationships%0A%0ARevision ID: 324d461206%0ARevises: a2fc29a71f3%0ACreate Date: 2015-05-21 12:50:08.987209%0A%0A%22%22%22%0A%0Afrom alembic import op%0A%0A# revision identifiers, used by Alembic.%0Arevision = '324d461206'%0Adown_revision = 'a2fc29a71f3'%0A%0Adef upgrade():%0A sql = %22%22%22%0A REPLACE INTO relationships (%0A modified_by_id, created_at, updated_at, source_id,%0A source_type, destination_id, destination_type, context_id%0A )%0A SELECT dc.modified_by_id, dc.created_at, dc.updated_at,%0A dc.section_id as source_id, 'Clause' as source_type,%0A dc.directive_id as destination_id,%0A IFNULL(d.kind, %22Policy%22) as destination_type,%0A dc.context_id%0A FROM directive_sections as dc JOIN directives as d ON dc.directive_id = d.id;%0A %22%22%22%0A op.execute(sql)%0A op.drop_constraint(%0A 'directive_sections_ibfk_2',%0A 'directive_sections',%0A type_='foreignkey')%0A op.drop_constraint(%0A 'directive_sections_ibfk_3',%0A 'directive_sections',%0A type_='foreignkey')%0A%0A%0Adef downgrade():%0A op.create_foreign_key(%0A 'directive_sections_ibfk_2',%0A 'directive_sections',%0A 'sections',%0A %5B'section_id'%5D,%0A %5B'id'%5D)%0A op.create_foreign_key(%0A 'directive_sections_ibfk_3',%0A 'directive_sections',%0A 'directives',%0A %5B'directive_id'%5D,%0A %5B'id'%5D)%0A
|
|
5b9d9f531e3544f6d3dfe0a2e48dcaaebf132921
|
Test case for RPC HTTP handler.
|
test/services/appmanager/test_http.py
|
test/services/appmanager/test_http.py
|
Python
| 0
|
@@ -0,0 +1,2080 @@
+import time%0A%0Aimport requests%0Afrom weavelib.messaging import Receiver%0Afrom weavelib.rpc import RPCServer, ServerAPI%0Afrom weavelib.services import BaseService%0A%0Afrom weaveserver.core.services import ServiceManager%0Afrom weaveserver.services.appmanager import ApplicationService%0A%0A%0AAUTH = %7B%0A %22auth1%22: %7B%0A %22type%22: %22SYSTEM%22,%0A %22appid%22: %22appmgr%22%0A %7D,%0A %22auth2%22: %7B%0A %22appid%22: %22appid2%22,%0A %22package%22: %22p%22%0A %7D%0A%7D%0A%0A%0Aclass DummyService(BaseService):%0A def __init__(self, token):%0A super(DummyService, self).__init__(token)%0A self.rpc_server = RPCServer(%22name%22, %22desc%22, %5B%0A ServerAPI(%22api1%22, %22desc2%22, %5B%5D, self.api1),%0A %5D, self)%0A%0A def api1(self):%0A return %22OK%22%0A%0A def on_service_start(self):%0A self.rpc_server.start()%0A%0A def on_service_stop(self):%0A self.rpc_server.stop()%0A%0A%0Aclass TestApplicationService(object):%0A def setup_class(cls):%0A cls.service_manager = ServiceManager()%0A cls.service_manager.apps = AUTH%0A cls.service_manager.start_services(%5B%22messaging%22%5D)%0A cls.appmgr = ApplicationService(%22auth1%22, %7B%22apps%22: AUTH%7D)%0A cls.appmgr.exited.set()%0A cls.appmgr.on_service_start()%0A%0A # Wait till it starts.%0A receiver = Receiver(%22/_system/root_rpc/request%22)%0A while True:%0A try:%0A receiver.start()%0A break%0A except:%0A time.sleep(1)%0A%0A def teardown_class(cls):%0A cls.service_manager.stop()%0A cls.appmgr.on_service_stop()%0A%0A def setup_method(self):%0A self.dummy_service = DummyService(%22auth2%22)%0A self.dummy_service.service_start()%0A%0A def teardown_method(self):%0A self.dummy_service.service_stop()%0A%0A def test_http_rpc(self):%0A obj = %7B%0A %22package_name%22: %22p%22,%0A %22rpc_name%22: %22name%22,%0A %22api_name%22: %22api1%22,%0A %22args%22: %5B%5D,%0A %22kwargs%22: %7B%7D%0A %7D%0A url = %22http://localhost:5000/api/rpc%22%0A for _ in range(1):%0A res = requests.post(url, json=obj).json()%0A assert res == %22OK%22%0A%0A
|
|
42ff16cade98512d0e80c1d467b01df1f4c33428
|
use new style str formatting
|
examples/ensemble/plot_gradient_boosting_oob.py
|
examples/ensemble/plot_gradient_boosting_oob.py
|
"""
======================================
Gradient Boosting Out-of-Bag estimates
======================================
Out-of-bag (OOB) estimates can be a useful heuristic to estimate
the "optimal" number of boosting iterations.
OOB estimates are almost identical to cross-validation estimates but
they can be computed on-the-fly without the need for repeated model
fitting.
OOB estimates are only available for Stochastic Gradient Boosting
(i.e. ``subsample < 1.0``), the estimates are derived from the improvement
in loss based on the out-of-bag examples.
The OOB estimator is a pessimistic estimator of the true
test loss, but remains a fairly good approximation for a small number of trees.
The figure shows the cumulative sum of the negative OOB improvements
as a function of the boosting iteration. As you can see, it tracks the test
loss for the first hundred iterations but then diverges in a
pessimistic way.
The figure also shows the performance of 3-fold cross validation which
usually gives a better estimate but is computationally more demanding.
"""
print(__doc__)
# Author: Peter Prettenhofer <peter.prettenhofer@gmail.com>
#
# License: BSD 3 clause
import numpy as np
import pylab as pl
from sklearn import ensemble
from sklearn.cross_validation import KFold
from sklearn.cross_validation import train_test_split
# Generate data (adapted from G. Ridgeway's gbm example)
n_samples = 1000
random_state = np.random.RandomState(13)
x1 = random_state.uniform(size=n_samples)
x2 = random_state.uniform(size=n_samples)
x3 = random_state.randint(0, 4, size=n_samples)
p = 1 / (1.0 + np.exp(-(np.sin(3 * x1) - 4 * x2 + x3)))
y = random_state.binomial(1, p, size=n_samples)
X = np.c_[x1, x2, x3]
X = X.astype(np.float32)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5,
random_state=9)
# Fit classifier with out-of-bag estimates
params = {'n_estimators': 1200, 'max_depth': 3, 'subsample': 0.5,
'learning_rate': 0.01, 'min_samples_leaf': 1, 'random_state': 3}
clf = ensemble.GradientBoostingClassifier(**params)
clf.fit(X_train, y_train)
acc = clf.score(X_test, y_test)
print("ACC: %.4f" % acc)
n_estimators = params['n_estimators']
x = np.arange(n_estimators) + 1
def heldout_score(clf, X_test, y_test):
"""compute deviance scores on ``X_test`` and ``y_test``. """
score = np.zeros((n_estimators,), dtype=np.float64)
for i, y_pred in enumerate(clf.staged_decision_function(X_test)):
score[i] = clf.loss_(y_test, y_pred)
return score
def cv_estimate(n_folds=3):
cv = KFold(n=X_train.shape[0], n_folds=n_folds)
cv_clf = ensemble.GradientBoostingClassifier(**params)
val_scores = np.zeros((n_estimators,), dtype=np.float64)
for train, test in cv:
cv_clf.fit(X_train[train], y_train[train])
val_scores += heldout_score(cv_clf, X_train[test], y_train[test])
val_scores /= n_folds
return val_scores
# Estimate best n_estimator using cross-validation
cv_score = cv_estimate(3)
# Compute best n_estimator for test data
test_score = heldout_score(clf, X_test, y_test)
# negative cumulative sum of oob improvements
cumsum = -np.cumsum(clf.oob_improvement_)
# min loss according to OOB
oob_best_iter = x[np.argmin(cumsum)]
# min loss according to test (normalize such that first loss is 0)
test_score -= test_score[0]
test_best_iter = x[np.argmin(test_score)]
# min loss according to cv (normalize such that first loss is 0)
cv_score -= cv_score[0]
cv_best_iter = x[np.argmin(cv_score)]
# color brew for the three curves
oob_color = map(lambda x: x / 256.0, (190, 174, 212))
test_color = map(lambda x: x / 256.0, (127, 201, 127))
cv_color = map(lambda x: x / 256.0, (253, 192, 134))
# plot curves and vertical lines for best iterations
pl.plot(x, cumsum, label='OOB loss', color=oob_color)
pl.plot(x, test_score, label='Test loss', color=test_color)
pl.plot(x, cv_score, label='CV loss', color=cv_color)
pl.axvline(x=oob_best_iter, color=oob_color)
pl.axvline(x=test_best_iter, color=test_color)
pl.axvline(x=cv_best_iter, color=cv_color)
# add three vertical lines to xticks
xticks = pl.xticks()
xticks_pos = np.array(xticks[0].tolist() +
[oob_best_iter, cv_best_iter, test_best_iter])
xticks_label = np.array(map(lambda t: int(t), xticks[0]) +
['OOB', 'CV', 'Test'])
ind = np.argsort(xticks_pos)
xticks_pos = xticks_pos[ind]
xticks_label = xticks_label[ind]
pl.xticks(xticks_pos, xticks_label)
pl.legend(loc='upper right')
pl.ylabel('normalized loss')
pl.xlabel('number of iterations')
pl.show()
|
Python
| 0
|
@@ -2185,20 +2185,28 @@
CC:
-%25.4f%22 %25
+%7B:.4f%7D%22.format(
acc)
+)
%0A%0An_
|
8ba5b29200520d853791943341d41798ff80a248
|
Change meta option for Github
|
src/repository/migrations/0003_auto_20170524_1503.py
|
src/repository/migrations/0003_auto_20170524_1503.py
|
Python
| 0.000001
|
@@ -0,0 +1,467 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.5 on 2017-05-24 15:03%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('repository', '0002_auto_20170522_2021'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterModelOptions(%0A name='github',%0A options=%7B'verbose_name': 'github project', 'verbose_name_plural': 'github projects'%7D,%0A ),%0A %5D%0A
|
|
811c1ed7324075970f0009d691866d1d47de43a2
|
add a setup.py to make this a nice official package
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,334 @@
+#!/usr/bin/python2.4%0A#%0A# Copyright 2006 Google Inc. All Rights Reserved.%0A%0Afrom distutils.core import setup%0A%0Asetup(name=%22google-mysql-tools%22,%0A description=%22Google MySQL Tools%22,%0A url=%22http://code.google.com/p/google-mysql-tools%22,%0A version=%220.1%22,%0A packages=%5B%22gmt%22%5D,%0A scripts=%5B%22mypgrep.py%22, %22compact_innodb.py%22%5D)%0A
|
|
193aa3ff7ef4219fd29a0ea40a8c0d2e5467de75
|
Add setup.py script
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,568 @@
+#!/usr/bin/env python%0A%0Afrom distutils.core import setup%0A%0Asetup(name = %22MutatorMath%22,%0A version = %221.8%22,%0A description = %22Python for piecewise linear interpolation in multiple dimensions with multiple, arbitrarily placed, masters.%22,%0A author = %22Erik van Blokland%22,%0A author_email = %22erik@letterror.com%22,%0A url = %22https://github.com/LettError/MutatorMath%22,%0A license = %22BSD 3 Clause%22,%0A packages = %5B%0A %22mutatorMath%22,%0A %22mutatorMath.objects%22,%0A %22mutatorMath.ufo%22,%0A %5D,%0A package_dir = %7B%22%22:%22Lib%22%7D,%0A)%0A
|
|
21a0948eb1d25e9126e2940cbc7d0496181d6a93
|
Add Django version trove classifiers.
|
setup.py
|
setup.py
|
import os
from setuptools import setup, find_packages
NAME = 'djangae'
PACKAGES = find_packages()
DESCRIPTION = 'Django integration with Google App Engine'
URL = "https://github.com/potatolondon/djangae"
LONG_DESCRIPTION = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
AUTHOR = 'Potato London Ltd.'
EXTRAS = {
"test": ["webtest"],
}
setup(
name=NAME,
version='0.9.1',
packages=PACKAGES,
# metadata for upload to PyPI
author=AUTHOR,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
keywords=["django", "Google App Engine", "GAE"],
url=URL,
classifiers=[
'Development Status :: 3 - Alpha',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
include_package_data=True,
# dependencies
extras_require=EXTRAS,
tests_require=EXTRAS['test'],
)
|
Python
| 0
|
@@ -700,16 +700,92 @@
jango',%0A
+ 'Framework :: Django :: 1.7',%0A 'Framework :: Django :: 1.8',%0A
|
f1ae87bd9df2c3d70db980ea5e721223b545da5f
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,345 @@
+#!/usr/bin/env python%0A%0Afrom distutils.core import setup%0A%0Asetup(name='Djheroku',%0A version='0.1',%0A description='Some helper functionality for binding Heroku configuration to Django',%0A author='Ferrix Hovi',%0A author_email='ferrix+git@ferrix.fi',%0A url='http://github.com/ferrix/djheroku/',%0A packages=%5B'djheroku'%5D%0A )%0A
|
|
6f57426a6a3881816506868f8278e252e5b0e5cd
|
Add setup.py file.
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,1811 @@
+try:%0A from setuptools import setup%0Aexcept ImportError:%0A from distutils.core import setup%0A%0A%0Aconfig = %7B%0A 'description': 'A set of tools to plan astronomical observations.',%0A 'author': 'iastro-pt',%0A 'url': 'https://github.com/iastro-pt/ObservationTools',%0A 'download_url': 'https://github.com/iastro-pt/ObservationTools',%0A 'author_email': 'daniel.andreasen@astro.up.pt',%0A 'version': '0.1',%0A 'license': 'MIT',%0A 'setup_requires': %5B'pytest-runner'%5D,%0A 'tests_require': %5B'pytest', 'hypothesis'%5D,%0A # %22PyAstronomy%22 when issue fixed.%0A 'install_requires': %5B%22numpy%22, %22astropy%22, %22scipy%22, %22matplotlib%22,%0A %22astropy%22, %22argparse%22, %22ephem%22%5D,%0A 'extras_require': %7B%0A 'dev': %5B'check-manifest'%5D,%0A 'tests': %5B'pytest', 'coverage', 'pytest-cov', 'python-coveralls', 'hypothesis'%5D,%0A 'docs': %5B'sphinx %3E= 1.4'%5D,%0A %7D,%0A 'packages': %5B%5D,%0A 'package_data': %7B%0A # Inlcude the data files:%0A '': %5B'data/*'%5D%7D,%0A 'scripts': %5B%22visibility.py%22, %22rv.py%22%5D,%0A 'name': 'ObservationTools',%0A # See https://pypi.python.org/pypi?%253Aaction=list_classifiers%0A %22classifiers%22: %5B%0A # How mature is this project? Common values are%0A # 3 - Alpha%0A # 4 - Beta%0A # 5 - Production/Stable%0A 'Development Status :: 3 - Alpha',%0A 'Intended Audience :: Science/Research',%0A 'Topic :: Scientific/Engineering :: Astronomy',%0A 'License :: OSI Approved :: MIT License',%0A 'Programming Language :: Python :: 2',%0A 'Programming Language :: Python :: 3',%0A 'Programming Language :: Python :: 3.5',%0A 'Programming Language :: Python :: 3.6',%0A 'Natural Language :: English',%0A %5D,%0A # What does your project relate to?%0A %22keywords%22: %5B'Astronomy', 'Observation'%5D,%0A%7D%0A%0Asetup(**config)%0A
|
|
50e9d1f1f66c6fc4e549fa7084f0189e0805d58e
|
Add first version of setup.py
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,978 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aif sys.version_info %3C (3,5):%0A sys.exit(%22doctr requires Python 3.5 or newer%22)%0A%0Afrom setuptools import setup%0Aimport versioneer%0A%0Asetup(%0A name='doctr',%0A version=versioneer.get_version(),%0A cmdclass=versioneer.get_cmdclass(),%0A description='''Deploy docs from Travis to GitHub pages.''',%0A author='Aaron Meurer and Gil Forsyth',%0A author_email='asmeurer@gmail.com',%0A url='https://github.com/gforsyth/doctr',%0A packages=%5B'doctr'%5D,%0A long_description=%22%22%22%0Adoctr%0A%0ADeploy docs from Travis to GitHub pages.%0A%0ALicense: MIT%0A%0A%22%22%22,%0A entry_points=%7B'console_scripts': %5B 'doctr = doctr.__main__:main'%5D%7D,%0A install_requires=%5B%0A 'requests',%0A 'cryptography',%0A %5D,%0A license=%22MIT%22,%0A classifiers=%5B%0A 'Programming Language :: Python :: 3',%0A 'Programming Language :: Python :: 3.5',%0A 'Topic :: Documentation',%0A 'Topic :: Software Development :: Documentation',%0A %5D,%0A zip_safe=False,%0A)%0A
|
|
d9bfa5d255a9a2a3ab278f94f338d2147dcdd1db
|
Fix setup
|
setup.py
|
setup.py
|
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='scikit-optimize',
version='0.1',
description='Sequential model-based optimization toolbox.',
long_description=('Scikit-Optimize, or skopt, is a simple and efficient'
' library for sequential model-based optimization,'
' accessible to everybody and reusable in various'
' contexts.'),
url='https://scikit-optimize.github.io/',
license='BSD',
author='The scikit-optimize contributors',
packages=['skopt', 'skopt.learning'],
install_requires=["numpy", "scipy", "scikit-learn>=0.18dev", "cython",
"matplotlib"]
)
|
Python
| 0.000001
|
@@ -634,16 +634,35 @@
earning'
+, 'skopt.optimizer'
%5D,%0A
|
e1d4cbbeab04e6c04b822073937ef19d7ec8e34a
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,607 @@
+#!/usr/bin/env python%0A%0Afrom setuptools import setup, find_packages%0A%0Asetup(name='raspberryturk',%0A version='0.0.1',%0A description='Python package powering the Raspberry Turk chess-playing robot.',%0A author='Joey Meyer',%0A author_email='jmeyer41@gmail.com',%0A url='https://bitbucket.com/joeymeyer/raspberryturk',%0A packages=find_packages(),%0A classifiers=%5B%0A 'Development Status :: 2 - Pre-Alpha',%0A 'Intended Audience :: Developers',%0A 'Topic :: Scientific/Engineering :: Artificial Intelligence',%0A 'Programming Language :: Python :: 2.7'%0A %5D%0A )
|
|
a4f05ca4022a542dac45114a832991c6bfc93e4a
|
Remove setuptools dependence.
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from setuptools import setup
description = """
"""
setup(
name = "sse",
url = "https://github.com/niwibe/sse",
author = "Andrei Antoukh",
author_email = "niwi@niwi.be",
version="1.0",
description = "Server Sent Events protocol implemetation.",
install_requires=['distribute'],
zip_safe=False,
py_modules = ['sse'],
classifiers = [
"Development Status :: 5 - Production/Stable",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: Implementation :: PyPy",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Environment :: Web Environment",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
],
)
|
Python
| 0
|
@@ -27,94 +27,35 @@
rom
-__future__ import unicode_literals%0Afrom setuptools import setup%0A%0Adescription = %22%22%22%0A%22%22%22
+distutils.core import setup
%0A%0Ase
@@ -205,9 +205,9 @@
=%221.
-0
+1
%22,%0A
@@ -230,17 +230,17 @@
%22Server
-
+-
Sent Eve
@@ -273,65 +273,8 @@
.%22,%0A
- install_requires=%5B'distribute'%5D,%0A zip_safe=False,%0A
|
b30e1c560ecde7b2c949de42eceddf5c49c9ba01
|
add setup.py file
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,128 @@
+from setuptools import setup%0A%0Asetup(%0A%09name=%22localFoodLearner%22,%0A%09version=%220.0.1%22,%0A%09install_requires=%5B%0A%09%09%22pandas%22,%0A%09%09%22numpy%22,%0A%09%5D%0A)
|
|
7036801e6931c480a3eec611ed87f13e29a181bf
|
Bump version to 0.7.9
|
setup.py
|
setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
here = lambda *a: os.path.join(os.path.dirname(__file__), *a)
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
readme = open(here('README.rst')).read()
history = open(here('HISTORY.rst')).read().replace('.. :changelog:', '')
requirements = [x.strip() for x in open(here('requirements.txt')).readlines()]
setup(
name='ouimeaux',
version='0.8dev',
description='Open source control for Belkin WeMo devices',
long_description=readme + '\n\n' + history,
author='Ian McCracken',
author_email='ian.mccracken@gmail.com',
url='https://github.com/iancmcc/ouimeaux',
packages=[
'ouimeaux',
],
package_dir={'ouimeaux': 'ouimeaux'},
include_package_data=True,
install_requires=requirements,
license="BSD",
zip_safe=False,
keywords='ouimeaux',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Topic :: Home Automation',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
],
entry_points={
'console_scripts': [
'wemo = ouimeaux.cli:wemo'
]
},
test_suite='tests',
)
|
Python
| 0
|
@@ -555,12 +555,11 @@
='0.
-8dev
+7.9
',%0A
|
1cbe793a5260fcfe8e16462e224bcfc19125063c
|
add a setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,1073 @@
+import os%0Afrom setuptools import setup%0A%0AREADME = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()%0A%0A# allow setup.py to be run from any path%0Aos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))%0A%0Asetup(%0A name='django-admin-resumable-js',%0A version='0.1',%0A packages=%5B'admin_resumable'%5D,%0A include_package_data=True,%0A license='MIT License',%0A description='A Django app for the uploading of large files from the django admin site.',%0A long_description=README,%0A url='https://github.com/jonatron/django-admin-resumable-js',%0A author='Your Name',%0A author_email='jon4tron@gmail.com',%0A classifiers=%5B%0A 'Environment :: Web Environment',%0A 'Framework :: Django',%0A 'Intended Audience :: Developers',%0A 'License :: OSI Approved :: MIT License',%0A 'Operating System :: OS Independent',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.7',%0A 'Topic :: Internet :: WWW/HTTP',%0A 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',%0A %5D,%0A)
|
|
2af222aed53f4cf799824b564ecd7e633d6356b8
|
add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,420 @@
+from setuptools import setup%0Asetup(%0A name = %22datatank_py%22,%0A version = %220.1%22,%0A packages = %5B %22datatank_py%22 %5D,%0A %0A install_requires = %5B'numpy%3E1.0'%5D,%0A # package_data = %7B%0A # %22%22 : %5B %22*.tank%22, %22*.markdown%22, %22*.txt%22 %5D%0A # %7D,%0A %0A author = %22Adam R. Maxwell%22,%0A author_email = %22amaxwell@mac.com%22,%0A description = %22Python modules for creating and modifying DataTank files%22,%0A license = %22BSD%22,%0A)%0A
|
|
a8b809a8f0f13bda454c2c78c08b35127bed16d6
|
Bump the patch version to 1.0.1.
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name="django-redis-cache",
url="http://github.com/sebleier/django-redis-cache/",
author="Sean Bleier",
author_email="sebleier@gmail.com",
version="1.0.0",
packages=["redis_cache", "redis_cache.backends"],
description="Redis Cache Backend for Django",
install_requires=['redis>=2.4.5'],
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Operating System :: OS Independent",
"Topic :: Software Development :: Libraries",
"Topic :: Utilities",
"Environment :: Web Environment",
"Framework :: Django",
],
)
|
Python
| 0
|
@@ -201,17 +201,17 @@
on=%221.0.
-0
+1
%22,%0A p
|
2dc04229247f28c8c098f8e3e00341419a1ead1c
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,765 @@
+# -*- coding:utf-8 -*-%0Afrom setuptools import setup%0Afrom setuptools.command.test import test as TestCommand%0A%0Aclass PyTest(TestCommand):%0A def finalize_options(self):%0A TestCommand.finalize_options(self)%0A self.test_args = %5B%5D%0A self.test_suite = True%0A%0A def run_tests(self):%0A import pytest%0A pytest.main(self.test_args)%0A%0Asetup(%0A name = %22openliveq%22,%0A packages = %5B%22openliveq%22%5D,%0A version = %220.0.1%22,%0A description = %22Package for NTCIR-13 OpenLiveQ%22,%0A author = %22Makoto P. Kato%22,%0A author_email = %22kato@dl.kuis.kyoto-u.ac.jp%22,%0A license = %22MIT License%22,%0A url = %22https://github.com/mpkato/openliveq%22,%0A install_requires = %5B%0A 'numpy'%0A %5D,%0A tests_require=%5B'pytest'%5D,%0A cmdclass = %7B'test': PyTest%7D%0A)%0A
|
|
926beaa12c0e17e949c362487014a6ec7521d654
|
Add distutils - setup.py
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,527 @@
+#!/usr/bin/env python%0A%0Afrom sslyze import SSLYZE_VERSION, PROJECT_URL%0Afrom distutils.core import setup%0A%0Asetup(name='SSLyze',%0A version=SSLYZE_VERSION,%0A description='Fast and full-featured SSL scanner',%0A long_description=open('README.md').read(),%0A author_email='sslyze@isecpartners.com',%0A url=PROJECT_URL,%0A scripts=%5B'sslyze.py'%5D,%0A packages=%5B'plugins', 'utils', 'utils.ctSSL'%5D,%0A package_data=%7B'plugins': %5B'data/mozilla_cacert.pem','data/mozilla_ev_oids.py'%5D%7D,%0A license=open('LICENSE.txt').read(),%0A )%0A
|
|
81ed734de508cb9dff61d2bc2703e54bda02067a
|
remove netifaces from package dependencies
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name='vent',
version='v0.4.3.dev',
packages=['vent', 'vent.core', 'vent.core.file_drop',
'vent.core.rq_worker', 'vent.core.rq_dashboard', 'vent.menus',
'vent.core.rmq_es_connector', 'vent.helpers', 'vent.api'],
install_requires=['docker', 'netifaces', 'npyscreen'],
scripts=['bin/vent'],
license='Apache License 2.0',
author='arpit',
author_email='',
maintainer='Charlie Lewis',
maintainer_email='clewis@iqt.org',
description=('A library that includes a CLI designed to serve as a'
' platform to collect and analyze data across a flexible set'
' of tools and technologies.'),
keywords='docker containers platform collection analysis tools devops',
url='https://github.com/CyberReboot/vent',
)
|
Python
| 0
|
@@ -316,21 +316,8 @@
er',
- 'netifaces',
'np
|
5262ff764e09b7d8e20cce848a288968014e648e
|
Add setup.py
|
setup.py
|
setup.py
|
Python
| 0.000001
|
@@ -0,0 +1,994 @@
+from setuptools import setup%0A%0Asetup(%0A name='iron',%0A version='0.0.1',%0A author='Alexander Schepanovski',%0A author_email='suor.web@gmail.com',%0A%0A description='Iron out your python code.',%0A long_description=open('README.rst').read(),%0A url='http://github.com/Suor/iron',%0A license='BSD',%0A%0A py_modules=%5B'iron', 'astpp'%5D,%0A install_requires=%5B%0A 'funcy%3E=1.1',%0A %5D,%0A entry_points = %7B%0A 'console_scripts': %5B%0A 'iron = iron:main',%0A %5D,%0A %7D,%0A%0A classifiers=%5B%0A 'Development Status :: 2 - Pre-Alpha',%0A 'License :: OSI Approved :: BSD License',%0A 'Operating System :: OS Independent',%0A 'Environment :: Console',%0A 'Programming Language :: Python',%0A 'Programming Language :: Python :: 2.7',%0A%0A 'Intended Audience :: Developers',%0A 'Topic :: Software Development :: Quality Assurance',%0A 'Topic :: Utilities',%0A 'Topic :: Software Development :: Libraries :: Python Modules',%0A %5D%0A)%0A
|
|
8dea7c6cc036e228c6a963413195d45f03a55850
|
add setup
|
setup.py
|
setup.py
|
Python
| 0
|
@@ -0,0 +1,61 @@
+from setuptools import setup%0Asetup(scripts=%5B'pip-check.py'%5D)%0A
|
|
4fe0efd61c848aa55e900031e5ae27bc3eb4b149
|
Add caffe profile tool.
|
tools/profiling/py_caffe_profiling.py
|
tools/profiling/py_caffe_profiling.py
|
Python
| 0
|
@@ -0,0 +1,1567 @@
+#!/usr/bin/env python%0A%0Aimport sys%0Aimport os%0Aimport argparse%0Aimport time%0Aimport numpy as np%0A%0Aif __name__ == '__main__':%0A parser = argparse.ArgumentParser('Time profiling of certain Caffe code.')%0A parser.add_argument('--caffe',%0A help='Path to caffe repository.')%0A parser.add_argument('--gpu', type=int, default=0,%0A help='GPU id. %5B0%5D')%0A parser.add_argument('--model',%0A help='Model prototxt.')%0A parser.add_argument('--weights',%0A help='Model parameter file (.caffemodel).')%0A parser.add_argument('--iterations', type=int, default=50,%0A help='Number of iterations. %5B50%5D')%0A parser.add_argument('--size', type=int, default=700,%0A help='Image size. %5B700%5D')%0A parser.add_argument('--num_roi', type=int, default=128,%0A help='Number of ROIs. %5B128%5D')%0A args = parser.parse_args()%0A%0A # import caffe%0A sys.path.insert(0, os.path.join(args.caffe, 'python'))%0A print %22Using caffe from %7B%7D%22.format(args.caffe)%0A try:%0A import caffe%0A except ImportError:%0A print %22ImportError: %7B%7D seems not a caffe repository.%22.format(args.caffe)%0A sys.exit()%0A%0A caffe.set_mode_gpu()%0A caffe.set_device(args.gpu)%0A net = caffe.Net(args.model, args.weights, caffe.TEST)%0A for i in xrange(args.iterations):%0A st = time.time()%0A size = args.size%0A num_roi = args.num_roi%0A net.blobs%5B'data'%5D.reshape(1, 3, size, size)%0A net.blobs%5B'rois'%5D.reshape(num_roi, 5)%0A net.forward()%0A print %22Iter %7B%7D: %7B:.02f%7D s for forward.%22.format(%0A i+1, time.time() - st)%0A%0A
|
|
185851cfb4614ebe97f38a43c5e2eb9503ce5c6c
|
Add tests for model render methods
|
masterfirefoxos/base/tests.py
|
masterfirefoxos/base/tests.py
|
Python
| 0
|
@@ -0,0 +1,1246 @@
+from django.test import SimpleTestCase%0A%0Afrom feincms.module.medialibrary.models import MediaFile%0A%0Afrom . import models%0A%0A%0Aclass TestYouTubeParagraphEntry(SimpleTestCase):%0A def test_render(self):%0A test_data = %7B'title': 'Test Title', 'text': 'test text',%0A 'youtube_id': 'test youtube id'%7D%0A rendered = models.YouTubeParagraphEntry(**test_data).render()%0A for value in test_data.values():%0A self.assertTrue(value in rendered)%0A%0A%0Aclass TestMediaParagraphEntry(SimpleTestCase):%0A def test_render(self):%0A test_data = %7B'title': 'Test Title', 'text': 'test text'%7D%0A entry = models.MediaParagraphEntry(**test_data)%0A entry.mediafile = MediaFile()%0A entry.mediafile.get_absolute_url = lambda: 'test mediafile url'%0A rendered = entry.render()%0A self.assertTrue('test mediafile url' in rendered)%0A for value in test_data.values():%0A self.assertTrue(value in rendered)%0A%0A%0Aclass TestFAQEntry(SimpleTestCase):%0A def test_render(self):%0A test_data = %7B'question': 'test question', 'answer': 'test answer'%7D%0A rendered = models.FAQEntry(**test_data).render()%0A for value in test_data.values():%0A self.assertTrue(value in rendered)%0A
|
|
a8e3570e373409cb442605218f1a6c936c518c5a
|
Add spotify liquid tag
|
liquid_tags/spotify.py
|
liquid_tags/spotify.py
|
Python
| 0.000008
|
@@ -0,0 +1,1314 @@
+%22%22%22%0ASpotify Tag%0A---------%0AThis implements a Liquid-style spotify tag for Pelican,%0Abased on the jekyll / octopress youtube tag %5B1%5D_%0A%0ASyntax%0A------%0A%7B%25 spotify id %25%7D%0A%0AExample%0A-------%0A%7B%25 spotify 1HNZcRFlIKwHAJD3LxvX4d %25%7D%0A%0AOutput%0A------%0A%3Ciframe src='https://embed.spotify.com/?uri=spotify:track:1HNZcRFlIKwHAJD3LxvX4d' width='300' height='380' frameborder='0' allowtransparency='true'%3E%3C/iframe%3E%0A%22%22%22%0Aimport os%0Aimport re%0Afrom .mdx_liquid_tags import LiquidTags%0A%0ASYNTAX = %22%7B%25 spotify id %25%7D%22%0A%0ASPOTIFY = re.compile(r'(%5Cw+)(%5Cs+(%5Cd+)%5Cs(%5Cd+))?')%0A%0A@LiquidTags.register('spotify')%0Adef spotify(preprocessor, tag, markup):%0A spotify_id = None%0A%0A match = SPOTIFY.search(markup)%0A if match:%0A groups = match.groups()%0A spotify_id = groups%5B0%5D%0A%0A if spotify_id:%0A spotify_out = %22%22%22%0A %3Ciframe src='https://embed.spotify.com/?uri=spotify:track:%7B%7D'%0A width='300'%0A height='380'%0A frameborder='0'%0A allowtransparency='true'%3E%3C/iframe%3E%22%22%22.format(spotify_id).strip()%0A else:%0A raise ValueError(%22Error processing input, %22%0A %22expected syntax: %7B0%7D%22.format(SYNTAX))%0A%0A return spotify_out%0A%0A%0A#----------------------------------------------------------------------%0A# This import allows image tag to be a Pelican plugin%0Afrom liquid_tags import register%0A
|
|
958abe5b298f255df5e4aef94b12d647f1319650
|
Create new package (#6811)
|
var/spack/repos/builtin/packages/py-pyani/package.py
|
var/spack/repos/builtin/packages/py-pyani/package.py
|
Python
| 0
|
@@ -0,0 +1,2432 @@
+##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass PyPyani(PythonPackage):%0A %22%22%22pyani is a Python3 module that provides support for calculating%0A average nucleotide identity (ANI) and related measures for whole genome%0A comparisons, and rendering relevant graphical summary output. Where%0A available, it takes advantage of multicore systems, and can integrate%0A with SGE/OGE-type job schedulers for the sequence comparisons.%22%22%22%0A%0A homepage = %22http://widdowquinn.github.io/pyani%22%0A url = %22https://pypi.io/packages/source/p/pyani/pyani-0.2.7.tar.gz%22%0A%0A version('0.2.7', '239ba630d375a81c35b7c60fb9bec6fa')%0A version('0.2.6', 'd5524b9a3c62c36063ed474ea95785c9')%0A%0A depends_on('python@3.5:')%0A depends_on('py-setuptools', type='build')%0A depends_on('py-matplotlib', type=('build', 'run'))%0A depends_on('py-seaborn', type=('build', 'run'))%0A%0A # Required for ANI analysis%0A depends_on('py-biopython', type=('build', 'run'))%0A depends_on('py-pandas', type=('build', 'run'))%0A depends_on('py-scipy', type=('build', 'run'))%0A%0A # Required for ANIb analysis%0A depends_on('blast-plus~python', type='run')%0A%0A # Required for ANIm analysis%0A depends_on('mummer', type='run')%0A
|
|
04ddb34d3dd312294bdc61f694f1db862091cf57
|
Create beta_move_zeroes.py
|
Solutions/beta_move_zeroes.py
|
Solutions/beta_move_zeroes.py
|
Python
| 0.000002
|
@@ -0,0 +1,164 @@
+def move_zeroes(*args):%0A return sum(%5B%5Bx%5D*args.count(x) for x in range(min(args), max(args)+1) if x!=0%5D, %5B%5D) + %5C%0A %5B0%5D*args.count(0) if args else %5B%5D%0A
|
|
c45ccd0f258fcbb152ffa9597ceb1bacd472f73b
|
Add test for email backend coverage
|
web/impact/impact/tests/test_impact_email_backend.py
|
web/impact/impact/tests/test_impact_email_backend.py
|
Python
| 0
|
@@ -0,0 +1,1509 @@
+from mock import patch%0Afrom django.core import mail%0Afrom django.test import TestCase%0Afrom django.urls import reverse%0A%0Afrom impact.minimal_email_handler import MinimalEmailHandler%0A%0Aclass TestEmailBackend(TestCase):%0A%0A @patch(%22impact.impact_email_backend.ImpactEmailBackend._add_logging_headers%22)%0A @patch(%22django.core.mail.backends.smtp.EmailBackend.send_messages%22)%0A def test_email_contains_header_if_ses_config_set(%0A self,%0A mocked_backend,%0A mock_add_logging_headers%0A ):%0A with self.settings(%0A SES_CONFIGURATION_SET=%22test%22,%0A EMAIL_BACKEND='mc.email_backends.AccelerateEmailBackend'):%0A MinimalEmailHandler(%5B%22a@example.com%22%5D,%0A %22subject%22,%0A %22body%22).send()%0A self.assertTrue(mock_add_logging_headers.called)%0A%0A @patch(%22impact.impact_email_backend.ImpactEmailBackend._add_logging_headers%22)%0A @patch(%22django.core.mail.backends.smtp.EmailBackend.send_messages%22)%0A def test_email_does_not_contain_header_if_ses_config_not_set(%0A self,%0A mocked_backend,%0A mock_add_logging_headers%0A ):%0A with self.settings(%0A SES_CONFIGURATION_SET=%22%22,%0A EMAIL_BACKEND='mc.email_backends.AccelerateEmailBackend'):%0A MinimalEmailHandler(%5B%22a@example.com%22%5D,%0A %22subject%22,%0A %22body%22).send()%0A self.assertFalse(mock_add_logging_headers.called)%0A%0A %0A
|
|
33aa9e79d2fe331f88574c02ad297072455be86a
|
add command to create scripts with the shell env
|
cerbero/commands/gensdkshell.py
|
cerbero/commands/gensdkshell.py
|
Python
| 0
|
@@ -0,0 +1,2901 @@
+# cerbero - a multi-platform build system for Open Source software%0A# Copyright (C) 2012 Andoni Morales Alastruey %3Cylatuya@gmail.com%3E%0A#%0A# This library is free software; you can redistribute it and/or%0A# modify it under the terms of the GNU Library General Public%0A# License as published by the Free Software Foundation; either%0A# version 2 of the License, or (at your option) any later version.%0A#%0A# This library 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 GNU%0A# Library General Public License for more details.%0A#%0A# You should have received a copy of the GNU Library General Public%0A# License along with this library; if not, write to the%0A# Free Software Foundation, Inc., 59 Temple Place - Suite 330,%0A# Boston, MA 02111-1307, USA.%0A%0Aimport os%0A%0Afrom cerbero.commands import Command, register_command%0Afrom cerbero.errors import FatalError%0Afrom cerbero.utils import _, N_, ArgparseArgument, shell%0A%0A%0ASCRIPT_TPL = '''%5C%0A#!/bin/bash%0A%0A%25s%0A%0A%25s%0A'''%0A%0A%0Aclass GenSdkShell(Command):%0A doc = N_('Create a script with the shell environment for the SDK')%0A name = 'gensdkshell'%0A%0A DEFAULT_CMD = 'exec %22$@%22'%0A%0A def __init__(self):%0A Command.__init__(self,%0A %5BArgparseArgument('name', nargs=1, default='sdk-shell',%0A help=_('name of the scrips')),%0A ArgparseArgument('-o', '--output-dir', default='.',%0A help=_('output directory')),%0A ArgparseArgument('-p', '--prefix',%0A help=_('prefix of the SDK')),%0A ArgparseArgument('--cmd', default=self.DEFAULT_CMD,%0A help=_('command to run in the script')),%0A %5D)%0A%0A def run(self, config, args):%0A name = args.name%5B0%5D%0A prefix = args.prefix and args.prefix or config.prefix%0A libdir = os.path.join(prefix, 'lib')%0A py_prefix = config.py_prefix%0A output_dir = args.output_dir%0A cmd = args.cmd%0A self.runargs(config, name, output_dir, prefix, libdir, py_prefix, cmd)%0A%0A def runargs(self, config, name, output_dir, prefix, libdir,%0A py_prefix, cmd=None):%0A cmd = cmd or self.DEFAULT_CMD%0A env = config.get_env(prefix, libdir, py_prefix)%0A env%5B'PATH'%5D = '%25s/bin:$PATH' %25 prefix%0A env%5B'LDFLAGS'%5D = '-L%25s' %25 libdir%0A envstr = ''%0A for e, v in env.iteritems():%0A v = v.replace(config.prefix, prefix)%0A envstr += '%25s=%22%25s%22%5Cn' %25 (e, v)%0A try:%0A filepath = os.path.join(output_dir, name)%0A with open(filepath, 'w+') as f:%0A f.write(SCRIPT_TPL %25 (envstr, cmd))%0A shell.call(%22chmod +x %25s%22 %25 filepath)%0A except IOError, ex:%0A raise FatalError(_(%22Error creating script: %25s%22, ex))%0A%0A%0Aregister_command(GenSdkShell)%0A
|
|
a8c3bbc363a319cd2e5748b1265b6e00563d510a
|
add udp.py
|
Foundations.of.Python.Network.Programming.369p/udp.py
|
Foundations.of.Python.Network.Programming.369p/udp.py
|
Python
| 0.000113
|
@@ -0,0 +1,1418 @@
+import argparse, socket%0Afrom datetime import datetime%0AMAX_BYTES = 65535%0Adef server(port):%0A sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)%0A sock.bind(('127.0.0.1', port))%0A print('Listening at %7B%7D'.format(sock.getsockname()))%0A while True:%0A data, address = sock.recvfrom(MAX_BYTES)%0A text = data.decode('ascii')%0A print('The client at %7B%7D says %7B!r%7D'.format(address, text))%0A text = 'Your data was %7B%7D bytes long'.format(len(data))%0A data = text.encode('ascii')%0A sock.sendto(data, address)%0Adef client(port):%0A sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)%0A text = 'The time is %7B%7D'.format(datetime.now())%0A data = text.encode('ascii')%0A sock.sendto(data, ('127.0.0.1', port))%0A print('The OS assigned me the address %7B%7D'.format(sock.getsockname()))%0A data, address = sock.recvfrom(MAX_BYTES) # Danger!%0A text = data.decode('ascii')%0A print('The server %7B%7D replied %7B!r%7D'.format(address, text))%0A%0Aif __name__ == '__main__':%0A choices = %7B'client': client, 'server': server%7D%0A parser = argparse.ArgumentParser(description='Send and receive UDP locally')%0A parser.add_argument('role', choices=choices, help='which role to play')%0A parser.add_argument('-p', metavar='PORT', type=int, default=1060,%0A help='UDP port (default 1060)')%0A args = parser.parse_args()%0A function = choices%5Bargs.role%5D%0A function(args.p)%0A
|
|
b1c0b9afacb12e8255681db25a01b94f25fed89e
|
add http tps test
|
test/test_http.py
|
test/test_http.py
|
Python
| 0
|
@@ -0,0 +1,1206 @@
+#!/usr/bin/env python3%0A%22%22%22 Vpp HTTP tests %22%22%22%0A%0Aimport unittest%0Aimport os%0Aimport subprocess%0Aimport http.client%0Afrom framework import VppTestCase, VppTestRunner, Worker%0Afrom vpp_devices import VppTAPInterface%0A%0A%0A@unittest.skip(%22Requires root%22)%0Aclass TestHttpTps(VppTestCase):%0A %22%22%22 HTTP test class %22%22%22%0A%0A @classmethod%0A def setUpClass(cls):%0A super(TestHttpTps, cls).setUpClass()%0A%0A @classmethod%0A def tearDownClass(cls):%0A super(TestHttpTps, cls).tearDownClass()%0A%0A def setUp(self):%0A self.client_ip4 = '172.0.0.2'%0A self.server_ip4 = '172.0.0.1'%0A self.vapi.cli(f'create tap id 0 host-ip4-addr %7Bself.client_ip4%7D/24')%0A self.vapi.cli(f'set int ip addr tap0 %7Bself.server_ip4%7D/24')%0A self.vapi.cli('set int state tap0 up')%0A self.vapi.session_enable_disable(is_enable=1)%0A%0A def test_http_tps(self):%0A fname = 'test_file_1M'%0A self.vapi.cli('http tps uri tcp://0.0.0.0/8080')%0A con = http.client.HTTPConnection(f%22%7Bself.server_ip4%7D%22, 8080)%0A con.request('GET', f'/%7Bfname%7D')%0A r = con.getresponse()%0A self.assertEqual(len(r.read()), 1 %3C%3C 20)%0A%0A%0Aif __name__ == '__main__':%0A unittest.main(testRunner=VppTestRunner)%0A
|
|
51b90afe8388b0425810bc1560cffe2e5a02fca8
|
Add boolean matrix generator - from mocogenomics
|
code/generate_boolean_matrix.py
|
code/generate_boolean_matrix.py
|
Python
| 0.000001
|
@@ -0,0 +1,1608 @@
+import itertools%0A%0Aletters = %5B'A','R','N','D','C','E','Q','G','H','I','L','K','M','F','P','S','T','W','Y','V'%5D%0A%0A# generates a matrix from all peptides and saves to CSV%0Adef generateBooleanMatrix(peptides):%0A%09# generate header ------%0A%09peptide_length = 9%0A%09aa_list = %5B'A','R','N','D','C','E','Q','G','H','I','L','K','M','F','P','S','T','W','Y','V'%5D%0A%0A%09positions = %5B%5D%0A%09for i in xrange(1, peptide_length + 1):%0A%09%09positions.append(%22Pos%25(i)s%22 %25 vars())%0A%0A%09tuples = %5Be for e in itertools.product(positions, ''.join(aa_list))%5D%0A%0A%09header = %5B'peptide'%5D%0A%09for i in xrange(len(tuples)):%0A%09%09header.append(''.join(tuples%5Bi%5D))%0A%0A%09# initialize master matrix and add header as a row%09%0A%09matrix = %5B%5D%0A%09matrix.append(header)%0A%0A%09# generate array for each peptide and concatenate -----%0A%09for peptide in peptides:%0A%09%09print 'Peptide:'%09# for testing%0A%09%09print peptide %09%09# for testing%0A%09%09amino_acids = list(peptide)%0A%0A%09%09peptide_positions = %5Bpeptide%5D%0A%09%09# create subarray for each position and concatenate%0A%09%09for i in xrange(len(peptide)):%0A%09%09%09subarr = %5B%5D%0A%09%09%09%0A%09%09%09# create subarray with boolean values for amino acid presence based on order of aa_list array%0A%09%09%09for j in xrange(len(aa_list)):%0A%09%09%09%09if peptide%5Bi%5D == aa_list%5Bj%5D:%0A%09%09%09%09%09subarr += %5B1%5D%0A%09%09%09%09else:%0A%09%09%09%09%09subarr += %5B0%5D%0A%0A%09%09%09# add extra zeroes if peptide length %3C maximum peptide length%0A%09%09%09if len(amino_acids) %3C peptide_length:%0A%09%09%09%09for k in xrange(peptide_length - len(aa_list), max_length):%0A%09%09%09%09%09subarr += %5B0%5D%0A%0A%09%09%09# concatenate booleans for one position to list%0A%09%09%09peptide_positions += subarr%0A%09%09# add peptide row to master matrix%0A%09%09matrix.append(peptide_positions)%0A%0A%09return matrix%0A%09%0A%09# save to CSV -------
|
|
7de5d0df0b726c629724d931766ede629a451d18
|
Add logging tests.
|
tests/logutils.py
|
tests/logutils.py
|
Python
| 0
|
@@ -0,0 +1,236 @@
+%22%22%22%0A.. moduleauthor:: Adam Gagorik %3Cadam.gagorik@gmail.com%3E%0A%22%22%22%0Aimport unittest%0Aimport pydarkstar.logutils%0A%0Apydarkstar.logutils.setDebug()%0A%0Aclass TestLogutils(unittest.TestCase):%0A pass%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
7a7c8c1f735982ca8403aec05861430ba70aca7f
|
add a test that checks _mssql whilst being run in threads
|
tests/threaded.py
|
tests/threaded.py
|
Python
| 0
|
@@ -0,0 +1,973 @@
+import _mssql%0Aimport unittest%0Aimport threading%0Afrom mssqltests import server, username, password, database%0A%0Aclass TestingThread(threading.Thread):%0A%0A def run(self):%0A self.running = True%0A mssql = _mssql.connect(server, username, password)%0A mssql.select_db(database)%0A for i in xrange(0, 100):%0A mssql.execute_query('SELECT %25d', (i,))%0A for row in mssql:%0A assert row%5B0%5D == i%0A mssql.close()%0A self.running = True%0A%0A%0Aclass ThreadedTests(unittest.TestCase):%0A %0A def testThreadedUse(self):%0A threads = %5B%5D%0A for i in xrange(0, 5):%0A thread = TestingThread()%0A thread.start()%0A threads.append(thread)%0A%0A running = True%0A while running:%0A running = False%0A for thread in threads:%0A if thread.is_alive():%0A running = True%0A break%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
8a332dc133d27f02bac126528e576fb2b787438d
|
Converting the font image to a convenient format
|
tool/font_conv.py
|
tool/font_conv.py
|
Python
| 0.99999
|
@@ -0,0 +1,728 @@
+# -*- coding: utf-8 -*-%0A%0Aimport sys, os, argparse%0Aimport Image, struct, shutil%0A%0A__version__ = %220.1.0%22%0A%0Adef main (argv):%0A parser = argparse.ArgumentParser(description=%22Generates a bmf file from a BMFont fnt file.%22)%0A parser.add_argument(%22bmf_file%22)%0A parser.add_argument(%22fnt_file%22)%0A opts = parser.parse_args()%0A%0A with open(opts.bmf_file, %22wb%22) as out:%0A img_file = os.path.splitext(opts.fnt_file)%5B0%5D + '_0.png'%0A img_original = Image.open(img_file)%0A img_mono = img_original.convert('L')%0A%0A (w, h) = img_mono.size%0A out.write(struct.pack('%3EHHH', w, h, w*h))%0A%0A for b in img_mono.getdata():%0A out.write(struct.pack('B', b))%0A%0Aif __name__ == '__main__':%0A main(sys.argv)%0A
|
|
d16b48d49f23bbf2f3ca0f6bc82d961b5b3ce50b
|
Add user_data parameter for Notify.add_action
|
udiskie/notify.py
|
udiskie/notify.py
|
"""
Notification utility.
"""
import logging
import sys
from udiskie.dbus import DBusException
__all__ = ['Notify']
class Notify(object):
"""
Notification tool.
Can be connected to udisks daemon in order to automatically issue
notifications when system status has changed.
NOTE: the action buttons in the notifications don't work with all
notification services.
"""
def __init__(self, notify, mounter, timeout=None):
"""
Initialize notifier and connect to service.
:param notify: notification service module (pynotify or notify2)
:param mounter: Mounter object
:param dict timeout: timeouts
"""
self._notify = notify
self._mounter = mounter
self._timeout = timeout or {}
self._default = self._timeout.get('timeout', -1)
self._log = logging.getLogger(__name__)
self._notifications = []
# Subscribe all enabled events to the daemon:
udisks = mounter.udisks
for event in ['device_mounted', 'device_unmounted',
'device_locked', 'device_unlocked',
'device_added', 'device_removed',
'job_failed']:
if self._enabled(event):
udisks.connect(event, getattr(self, event))
# event handlers:
def device_mounted(self, device):
"""
Show 'Device mounted' notification with 'Browse directory' button.
:param device: device object
"""
label = device.id_label
mount_path = device.mount_paths[0]
browse_action = ('browse', 'Browse directory',
self._mounter.browse, device)
self._show_notification(
'device_mounted',
'Device mounted',
'%s mounted on %s' % (label, mount_path),
'drive-removable-media',
self._mounter._browser and browse_action)
def device_unmounted(self, device):
"""
Show 'Device unmounted' notification.
:param device: device object
"""
label = device.id_label
self._show_notification(
'device_unmounted',
'Device unmounted',
'%s unmounted' % (label,),
'drive-removable-media')
def device_locked(self, device):
"""
Show 'Device locked' notification.
:param device: device object
"""
device_file = device.device_presentation
self._show_notification(
'device_locked',
'Device locked',
'%s locked' % (device_file,),
'drive-removable-media')
def device_unlocked(self, device):
"""
Show 'Device unlocked' notification.
:param device: device object
"""
device_file = device.device_presentation
self._show_notification(
'device_unlocked',
'Device unlocked',
'%s unlocked' % (device_file,),
'drive-removable-media')
def device_added(self, device):
"""
Show 'Device added' notification.
:param device: device object
"""
device_file = device.device_presentation
if (device.is_drive or device.is_toplevel) and device_file:
self._show_notification(
'device_added',
'Device added',
'device appeared on %s' % (device_file,),
'drive-removable-media')
def device_removed(self, device):
"""
Show 'Device removed' notification.
:param device: device object
"""
device_file = device.device_presentation
if (device.is_drive or device.is_toplevel) and device_file:
self._show_notification(
'device_removed',
'Device removed',
'device disappeared on %s' % (device_file,),
'drive-removable-media')
def job_failed(self, device, action, message):
"""
Show 'Job failed' notification with 'Retry' button.
:param device: device object
"""
device_file = device.device_presentation or device.object_path
if message:
text = 'failed to %s %s:\n%s' % (action, device_file, message)
else:
text = 'failed to %s device %s.' % (action, device_file,)
try:
retry = getattr(self._mounter, action)
except AttributeError:
retry_action = None
else:
retry_action = ('retry', 'Retry', retry, device)
self._show_notification(
'job_failed',
'Job failed', text,
'drive-removable-media',
retry_action)
def _show_notification(self,
event, summary, message, icon,
action=None):
"""
Show a notification.
:param str event: event name
:param str summary: notification title
:param str message: notification body
:param str icon: icon name
:param dict action: parameters to :meth:`_add_action`
"""
notification = self._notify(summary, message, icon)
timeout = self._get_timeout(event)
if timeout != -1:
notification.set_timeout(int(timeout * 1000))
if action:
self._add_action(notification, *action)
try:
notification.show()
except DBusException:
# Catch and log the exception. Starting udiskie with notifications
# enabled while not having a notification service installed is a
# mistake too easy to be made, but it shoud not render the rest of
# udiskie's logic useless by raising an exception before the
# automount handler gets invoked.
exc = sys.exc_info()[1]
self._log.error("Failed to show notification: {0}"
.format(exc.message))
def _add_action(self, notification, action, label, callback, *args):
"""
Show an action button button in mount notifications.
Note, this only works with some libnotify services.
"""
def on_action_click(notification, action):
callback(*args)
notification.add_action(action, label, on_action_click)
# pynotify does not store hard references to the notification
# objects. When a signal is received and the notification does not
# exist anymore, no handller will be called. Therefore, we need to
# prevent these notifications from being destroyed by storing
# references (note, notify2 doesn't need this):
notification.connect('closed', self._notifications.remove)
self._notifications.append(notification)
def _enabled(self, event):
"""
Check if the notification for an event is enabled.
:param str event: event name
:returns: if the event notification is enabled
:rtype: bool
"""
return self._get_timeout(event) not in (None, False)
def _get_timeout(self, event):
"""
Get the timeout for an event from the config.
:param str event: event name
:returns: timeout in seconds
:rtype: int, float or NoneType
"""
return self._timeout.get(event, self._default)
|
Python
| 0.000006
|
@@ -6338,16 +6338,22 @@
on_click
+, None
)%0A
|
9f7fc07dbe48494b19826dfe06a1e1a4cf5469c5
|
Add in a few global options. Feel free to rename them, they're just the first thing that came to mind.
|
src/python/m5/__init__.py
|
src/python/m5/__init__.py
|
# Copyright (c) 2005 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Nathan Binkert
# Steve Reinhardt
import sys, os, time, atexit, optparse
# import the SWIG-wrapped main C++ functions
import main
# import a few SWIG-wrapped items (those that are likely to be used
# directly by user scripts) completely into this module for
# convenience
from main import simulate, SimLoopExitEvent
# import the m5 compile options
import defines
# define this here so we can use it right away if necessary
def panic(string):
print >>sys.stderr, 'panic:', string
sys.exit(1)
# Prepend given directory to system module search path. We may not
# need this anymore if we can structure our config library more like a
# Python package.
def AddToPath(path):
# if it's a relative path and we know what directory the current
# python script is in, make the path relative to that directory.
if not os.path.isabs(path) and sys.path[0]:
path = os.path.join(sys.path[0], path)
path = os.path.realpath(path)
# sys.path[0] should always refer to the current script's directory,
# so place the new dir right after that.
sys.path.insert(1, path)
# Callback to set trace flags. Not necessarily the best way to do
# things in the long run (particularly if we change how these global
# options are handled).
def setTraceFlags(option, opt_str, value, parser):
objects.Trace.flags = value
# Standard optparse options. Need to be explicitly included by the
# user script when it calls optparse.OptionParser().
standardOptions = [
optparse.make_option("--traceflags", type="string", action="callback",
callback=setTraceFlags)
]
# make a SmartDict out of the build options for our local use
import smartdict
build_env = smartdict.SmartDict()
build_env.update(defines.m5_build_env)
# make a SmartDict out of the OS environment too
env = smartdict.SmartDict()
env.update(os.environ)
# The final hook to generate .ini files. Called from the user script
# once the config is built.
def instantiate(root):
config.ticks_per_sec = float(root.clock.frequency)
# ugly temporary hack to get output to config.ini
sys.stdout = file('config.ini', 'w')
root.print_ini()
sys.stdout.close() # close config.ini
sys.stdout = sys.__stdout__ # restore to original
main.initialize() # load config.ini into C++ and process it
noDot = True # temporary until we fix dot
if not noDot:
dot = pydot.Dot()
instance.outputDot(dot)
dot.orientation = "portrait"
dot.size = "8.5,11"
dot.ranksep="equally"
dot.rank="samerank"
dot.write("config.dot")
dot.write_ps("config.ps")
# Export curTick to user script.
def curTick():
return main.cvar.curTick
# register our C++ exit callback function with Python
atexit.register(main.doExitCleanup)
# This import allows user scripts to reference 'm5.objects.Foo' after
# just doing an 'import m5' (without an 'import m5.objects'). May not
# matter since most scripts will probably 'from m5.objects import *'.
import objects
|
Python
| 0.000001
|
@@ -2907,271 +2907,1357 @@
ue%0A%0A
-# Standard optparse options. Need to be explicitly included by the%0A# user script when it calls optparse.OptionParser().%0AstandardOptions = %5B%0A optparse.make_option(%22--traceflags%22, type=%22string%22, action=%22callback%22,%0A callback=setTraceFlags
+def setTraceStart(option, opt_str, value, parser):%0A objects.Trace.start = value%0A%0Adef clearPCSymbol(option, opt_str, value, parser):%0A objects.ExecutionTrace.pc_symbol = False%0A%0Adef clearPrintCycle(option, opt_str, value, parser):%0A objects.ExecutionTrace.print_cycle = False%0A%0Adef statsTextFile(option, opt_str, value, parser):%0A objects.Statistics.text_file = value%0A%0A# Standard optparse options. Need to be explicitly included by the%0A# user script when it calls optparse.OptionParser().%0AstandardOptions = %5B%0A optparse.make_option(%22--traceflags%22, type=%22string%22, action=%22callback%22,%0A callback=setTraceFlags),%0A optparse.make_option(%22--tracestart%22, type=%22int%22, action=%22callback%22,%0A callback=setTraceStart),%0A optparse.make_option(%22--nopcsymbol%22, action=%22callback%22,%0A callback=clearPCSymbol,%0A help=%22Turn off printing PC symbols in trace output%22),%0A optparse.make_option(%22--noprintcycle%22, action=%22callback%22,%0A callback=clearPrintCycle,%0A help=%22Turn off printing cycles in trace output%22),%0A optparse.make_option(%22--statsfile%22, type=%22string%22, action=%22callback%22,%0A callback=statsTextFile, metavar=%22FILE%22,%0A help=%22Sets the output file for the statistics%22
)%0A
|
d3c6845e83514f59f421d042cab9cf8fa817e33c
|
Add tests for common.signal.SignalCompare
|
tests/test_signal.py
|
tests/test_signal.py
|
Python
| 0
|
@@ -0,0 +1,1364 @@
+# Copyright 2015-2015 ARM Limited%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#%0A%0Aimport pandas as pd%0Aimport trappy%0Afrom utils_tests import TestBART%0Afrom bart.common.signal import SignalCompare%0A%0A%0Aclass TestSignalCompare(TestBART):%0A%0A def __init__(self, *args, **kwargs):%0A super(TestSignalCompare, self).__init__(*args, **kwargs)%0A%0A def test_conditional_compare(self):%0A %22%22%22Test conditional_compare%22%22%22%0A%0A A = %5B0, 0, 0, 3, 3, 0, 0, 0%5D%0A B = %5B0, 0, 2, 2, 2, 2, 1, 1%5D%0A%0A run = trappy.Run(%22.%22, events=%5B%22event%22%5D)%0A df = pd.DataFrame(%7B%22A%22: A, %22B%22: B%7D)%0A run.event.data_frame = df%0A%0A s = SignalCompare(run, %22event:A%22, %22event:B%22)%0A expected = (1.5, 2.0 / 7)%0A self.assertEqual(%0A s.conditional_compare(%0A %22event:A %3E event:B%22,%0A method=%22rect%22),%0A expected)%0A
|
|
f91d32d25bc84a795d53f2f7698b77862d08f690
|
Add a test_traits file
|
tests/test_traits.py
|
tests/test_traits.py
|
Python
| 0.000003
|
@@ -0,0 +1,900 @@
+# -*- coding: utf-8 -*-%0Afrom dynmen import common%0Aimport unittest%0A%0Aclass TestFlag(unittest.TestCase):%0A @classmethod%0A def setUpClass(cls):%0A class TFlag(object):%0A dflt_t = common.Flag('dflt_t', default=True, flag='-dt')%0A dflt_f = common.Flag('dflt_f', default=False, flag='-df')%0A cls.TFlag = TFlag%0A%0A def setUp(self):%0A self.tflag = self.TFlag()%0A%0A def test_dflt_true(self):%0A self.assertEqual(self.tflag.dflt_t, '-dt')%0A self.tflag.dflt_t = False%0A self.assertFalse('')%0A%0A def test_dflt_false(self):%0A self.assertEqual(self.tflag.dflt_f, '')%0A self.tflag.dflt_f = True%0A self.assertEqual(self.tflag.dflt_f, '-df')%0A%0A def test_validation(self):%0A with self.assertRaises(TypeError):%0A self.tflag.dflt_f = 37%0A with self.assertRaises(TypeError):%0A self.tflag.dflt_t = 'asdfasdf'%0A%0A
|
|
34b7d99becd1664c1a5881da178fb4ae8b871bee
|
Add new package: mahout (#18048)
|
var/spack/repos/builtin/packages/mahout/package.py
|
var/spack/repos/builtin/packages/mahout/package.py
|
Python
| 0
|
@@ -0,0 +1,1230 @@
+# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass Mahout(Package):%0A %22%22%22The Apache Mahout project's goal is to build an environment for%0A quickly creating scalable performant machine learning applications.%22%22%22%0A%0A homepage = %22https://mahout.apache.org/%22%0A url = %22https://archive.apache.org/dist/mahout/0.13.0/apache-mahout-distribution-0.13.0-src.tar.gz%22%0A list_url = %22https://archive.apache.org/dist/mahout%22%0A list_depth = 1%0A%0A version('0.13.0', sha256='bbe5a584fa83eb4ea3e0c146256e3e913c225426434759458d1423508da7c519')%0A version('0.12.2', sha256='cac9a3fd4f11b2cb850b86d1bd23aec90e960cfae91850c49056c2eaae71afba')%0A version('0.12.1', sha256='32e334115e4b2bfa21ba58e888fc47cdde2ca32c915d1694ed6761bda3b05dbb')%0A version('0.12.0', sha256='65f340072131b1178b7bf4da115782254bdb20d6abd9789f10fc6dfe1ea7e7ad')%0A%0A depends_on('maven', type='build')%0A depends_on('java@8', type=('build', 'run'))%0A%0A def install(self, spec, prefix):%0A mvn = which('mvn')%0A mvn('package', '-DskipTests')%0A install_tree('.', prefix)%0A
|
|
3867db9e3c2107deae0c2b3e7f8ba3461bb550b2
|
Add test case to check invalid time_start (#558)
|
monitoring/prober/scd/test_subscription_query_time.py
|
monitoring/prober/scd/test_subscription_query_time.py
|
Python
| 0
|
@@ -0,0 +1,1412 @@
+%22%22%22Strategic conflict detection Subscription put query tests:%0A%0A - query with different time formats.%0A%22%22%22%0A%0Aimport datetime%0A%0Afrom monitoring.monitorlib.infrastructure import default_scope%0Afrom monitoring.monitorlib import scd%0Afrom monitoring.monitorlib.scd import SCOPE_SC%0Afrom monitoring.prober.infrastructure import for_api_versions%0A%0A%0ABASE_URL = 'https://example.com/uss'%0A%0ASUB_ID = '00000088-b268-481c-a32d-6be442000000'%0Adef _make_sub_req(time_start, time_end, alt_start, alt_end, radius, scd_api):%0A req = %7B%0A %22extents%22: scd.make_vol4(time_start, time_end, alt_start, alt_end, scd.make_circle(-56, 178, radius)),%0A %22old_version%22: 0,%0A %22uss_base_url%22: BASE_URL,%0A %0A %22notify_for_constraints%22: False%0A %7D%0A if scd_api == scd.API_0_3_5:%0A req%5B%22notify_for_operations%22%5D = True%0A elif scd_api == scd.API_0_3_15:%0A req%5B%22notify_for_operational_intents%22%5D = True%0A return req%0A%0A%0A@for_api_versions(scd.API_0_3_5, scd.API_0_3_15)%0A@default_scope(SCOPE_SC)%0Adef test_subscription_with_invalid_start_time(scd_api, scd_session):%0A if scd_session is None:%0A return%0A%0A time_start = datetime.datetime.utcnow()%0A time_end = time_start + datetime.timedelta(hours=2.5)%0A req = _make_sub_req(time_start, time_end, 200, 1000, 500, scd_api)%0A req%5B'extents'%5D%5B'time_start'%5D%5B'value'%5D = 'something-invalid'%0A%0A resp = scd_session.put('/subscriptions/%7B%7D'.format(SUB_ID), json=req)%0A assert resp.status_code == 400, resp.content%0A
|
|
32fb5d7d98c112bf9a358339931f2708114fd56b
|
fix commentary of DimensionKey in questions.models in API for sphinx
|
msgvis/apps/questions/models.py
|
msgvis/apps/questions/models.py
|
from django.db import models
from msgvis.apps.dimensions import registry
from django.db.models import Q
class Article(models.Model):
"""
A published research article.
"""
year = models.PositiveIntegerField(null=True, default=None, blank=True)
"""The publication year for the article."""
authors = models.CharField(max_length=250, default=None, blank=True)
"""A plain-text author list."""
link = models.CharField(max_length=250, default=None, blank=True)
"""A url to the article."""
title = models.CharField(max_length=250, default=None, blank=True)
"""The title of the article."""
venue = models.CharField(max_length=250, default=None, blank=True)
"""The venue where the article was published."""
class Question(models.Model):
"""
A research question from an :class:`Article`.
May be associated with a number of :class:`.Dimension` objects.
"""
source = models.ForeignKey(Article, null=True, default=None)
"""The source article for the question."""
text = models.TextField()
"""The text of the question."""
dimensions = models.ManyToManyField("dimensions.DimensionKey")
"""A set of dimensions related to the question."""
@staticmethod
def get_dimension_key_model(key):
return registry.get_dimension(key).get_key_model()
def add_dimension(self, key):
self.dimensions.add(self.get_dimension_key_model(key))
def get_sample_questions(dimension_list):
"""
Given dimensions, return sample research questions.
"""
questions = Question.objects.all()
for dimension in dimension_list:
questions = questions.filter(dimensions__key=dimension)
if questions.count() == 0:
questions = Question.objects.all()
"""Consider the case that no dimension in the existing questions matches"""
#TODO: may need a better way to handle this
return questions[:10]
|
Python
| 0
|
@@ -897,16 +897,19 @@
imension
+Key
%60 object
|
f1b8216408f26094a70789297198d2a63b0db0dd
|
Add pframe test.
|
tests/pframe_test.py
|
tests/pframe_test.py
|
Python
| 0
|
@@ -0,0 +1,1806 @@
+%22%22%22Tests for scripts/pframe.py.%22%22%22%0Aimport re%0Aimport unittest%0A%0Afrom test_utils import import_utils%0Aimport_utils.prepare_lldb_import_or_exit()%0A%0Aimport lldb%0A%0Aimport_utils.prepare_for_scripts_imports()%0A%0Afrom scripts import pframe%0A%0Aclass PFrameTest(unittest.TestCase):%0A def __init__(self, *args, **kwargs):%0A super(PFrameTest, self).__init__(*args, **kwargs)%0A self.debugger = None%0A self.target = None%0A%0A def tearDown(self):%0A if self.debugger and self.target:%0A self.debugger.DeleteTarget(self.target)%0A%0A def testPFrame(self):%0A %22%22%22Tests the expected output of the %7Cpframe %3Cinstance%3E%7C command.%22%22%22%0A self.debugger = lldb.SBDebugger.Create()%0A self.debugger.SetAsync(False)%0A self.target = self.debugger.CreateTarget('')%0A error = lldb.SBError()%0A process = self.target.AttachToProcessWithName(self.debugger.GetListener(),%0A 'TestApp', False, error)%0A if not process:%0A self.assertTrue(False, 'Could not attach to process %22TestApp%22')%0A self.debugger.SetSelectedTarget(self.target)%0A result = lldb.SBCommandReturnObject()%0A%0A # Get the test view, which has an abitrary tag of 19.%0A self.debugger.GetCommandInterpreter().HandleCommand(%0A 'po %5B%5BUIWindow keyWindow%5D viewWithTag:19%5D', result)%0A self.assertTrue(result.Succeeded())%0A output = result.GetOutput()%0A start_index = output.find('0x')%0A self.assertTrue(start_index != -1)%0A end_index = output.find(';')%0A self.assertTrue(end_index != -1)%0A view = output%5Bstart_index:end_index%5D%0A%0A pframe.pframe(self.debugger, view, result, None)%0A self.assertTrue(result.Succeeded())%0A expected_output_regex = r'%5C(origin = %5C(x = 0, y = 0%5C), size = %5C(width = 100, height = 100%5C)%5C)'%0A self.assertTrue(re.search(expected_output_regex, result.GetOutput(), re.M))%0A
|
|
9524f44838df21f386b56d047e4a45e2aba9ad4e
|
Create Valid_Palindrome.py
|
Array/Valid_Palindrome.py
|
Array/Valid_Palindrome.py
|
Python
| 0.000001
|
@@ -0,0 +1,1602 @@
+Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.%0A%0AFor example,%0A%22A man, a plan, a canal: Panama%22 is a palindrome.%0A%22race a car%22 is not a palindrome.%0A%0ANote:%0AHave you consider that the string might be empty? This is a good question to ask during an interview.%0A%0AFor the purpose of this problem, we define empty string as valid palindrome.%0A%0A # 1. isalnum()%0A # 2. lower()%0A # 3. no need to check len at the begining%0A%0Aclass Solution:%0A # @param s, a string%0A # @return a boolean%0A def isPalindrome_1(self, s):%0A if len(s) == 0:%0A return True %0A characters = 'abcdefghijklmnopqrstuvwxyz1234567890' %0A left = 0; right = len(s)-1%0A %0A s = s.lower()%0A #while left %3C len(s)-1 and right %3E-1 and left %3C= right:%0A while left %3C right:%0A if s%5Bleft%5D not in characters:%0A left += 1%0A elif s%5Bright%5D not in characters:%0A right -=1%0A elif s%5Bleft%5D == s%5Bright%5D:%0A left += 1%0A right -= 1%0A elif s%5Bleft%5D != s%5Bright%5D:%0A return False %0A return True %0A %0A def isPalindrome(self, s):%0A start = 0%0A end = len(s) - 1%0A while start %3C end:%0A while start %3C end and not s%5Bstart%5D.isalnum():%0A start += 1%0A while start %3C end and not s%5Bend%5D.isalnum():%0A end -= 1%0A if s%5Bstart%5D.lower() != s%5Bend%5D.lower():%0A return False%0A start += 1%0A end -= 1%0A return True%0A %0A
|
|
bffa61da4576c088c081daea3833142af58fef1d
|
Add in some tests for cities
|
tests/test_cities.py
|
tests/test_cities.py
|
Python
| 0.000019
|
@@ -0,0 +1,204 @@
+import testtools%0A%0Aimport cities%0A%0A%0Aclass TestCities(testtools.TestCase):%0A def test_largest(self):%0A largest = 'Sydney'%0A self.assertEqual(largest, cities.largest(cities.get_cities()).name)%0A%0A
|
|
102a1c57763c646962eb62569e1f7b57793142f3
|
fix test_step test
|
tests/test_client.py
|
tests/test_client.py
|
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
import pytest
from mock import patch, Mock
from plaid.client import Client, require_access_token
def test_require_access_token_decorator():
class TestClass(object):
access_token = 'foo'
@require_access_token
def some_func(self):
return True
obj = TestClass()
obj.some_func()
def test_require_access_token_decorator_raises():
class TestClass(object):
access_token = None
@require_access_token
def some_func(self):
return True
obj = TestClass()
with pytest.raises(Exception):
obj.some_func()
def test_connect():
with patch('requests.post') as mock_requests_post:
mock_response = Mock()
mock_response.content = '{}'
mock_requests_post.return_value = mock_response
client = Client('myclientid', 'mysecret')
account_type = 'bofa'
username = 'foo'
password = 'bar'
email = 'foo@bar.com'
response = client.connect(account_type, username, password, email)
assert mock_response == response
def test_step():
with patch('requests.post') as mock_requests_post:
client = Client('myclientid', 'mysecret', 'token')
client.step('bofa', 'foo')
assert mock_requests_post.called
def test_step_requires_access_token():
client = Client('myclientid', 'mysecret')
with pytest.raises(Exception):
client.step('bofa', 'foo')
def test_delete_user():
with patch('requests.delete') as mock_requests_delete:
client = Client('myclientid', 'mysecret', 'token')
client.delete_user()
assert mock_requests_delete.called
def test_delete_user_requires_access_token():
client = Client('myclientid', 'mysecret')
with pytest.raises(Exception):
client.delete_user('bofa', 'foo')
def test_transactions():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret', 'token')
ret = client.transactions()
assert mock_requests_get.called
assert ret is not None
def test_transactions_requires_access_token():
client = Client('myclientid', 'mysecret')
with pytest.raises(Exception):
client.transactions()
def test_balance():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret', 'token')
ret = client.balance()
assert mock_requests_get.called
assert ret is not None
def test_balance_requires_access_token():
client = Client('myclientid', 'mysecret')
with pytest.raises(Exception):
client.balance()
def test_entity():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret')
client.entity(1)
assert mock_requests_get.called
def test_categories():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret')
client.categories()
assert mock_requests_get.called
def test_category():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret')
client.category(1)
assert mock_requests_get.called
def test_categories_by_mapping():
with patch('requests.get') as mock_requests_get:
client = Client('myclientid', 'mysecret')
client.categories_by_mapping('Food > Spanish Restaurant', 'plaid')
assert mock_requests_get.called
|
Python
| 0.000005
|
@@ -1178,24 +1178,29 @@
%0A%0A%0Adef test_
+auth_
step():%0A
@@ -1316,32 +1316,262 @@
%0A client.
+auth_step('bofa', 'foo')%0A assert mock_requests_post.called%0A%0A%0Adef test_connect_step():%0A with patch('requests.post') as mock_requests_post:%0A client = Client('myclientid', 'mysecret', 'token')%0A client.connect_
step('bofa', 'fo
|
91d24f62505462e5009cd5e0fb1176824d7c57d9
|
Test config
|
tests/test_config.py
|
tests/test_config.py
|
Python
| 0.000001
|
@@ -0,0 +1,1061 @@
+from changes import config%0Afrom . import BaseTestCase%0A%0A%0Aclass ConfigTestCase(BaseTestCase):%0A arguments = %7B%0A '--debug': True,%0A '--dry-run': False,%0A '--help': False,%0A '--major': False,%0A '--minor': False,%0A '--new-version': '0.0.1',%0A 'new_version': '0.0.1',%0A '--noinput': True,%0A '--patch': True,%0A '--pypi': None,%0A '--skip-changelog': False,%0A '--test-command': None,%0A '--tox': False,%0A '--version-prefix': None,%0A '%3Capp_name%3E': 'changes',%0A 'bump_version': False,%0A 'changelog': True,%0A 'install': False,%0A 'pypi': False,%0A 'release': False,%0A 'tag': False,%0A 'test': False,%0A 'upload': False%0A %7D%0A%0A def setUp(self):%0A config.arguments = self.arguments%0A%0A def test_common_arguments(self):%0A expected_arguments = (%0A 'changes',%0A False,%0A '0.0.1',%0A )%0A self.assertEquals(%0A expected_arguments,%0A config.common_arguments()%0A )%0A
|
|
71fda989816e1848c99b801c133171216abe0df5
|
Add test for setting scheduler parameters
|
tests/test_domain.py
|
tests/test_domain.py
|
Python
| 0
|
@@ -0,0 +1,525 @@
+%0Aimport unittest%0Aimport libvirt%0A%0Aclass TestLibvirtDomain(unittest.TestCase):%0A def setUp(self):%0A self.conn = libvirt.open(%22test:///default%22)%0A self.dom = self.conn.lookupByName(%22test%22)%0A%0A def tearDown(self):%0A self.dom = None%0A self.conn = None%0A%0A def testDomainSchedParams(self):%0A params = self.dom.schedulerParameters()%0A self.assertEquals(len(params), 1)%0A self.assertTrue(%22weight%22 in params)%0A params%5B%22weight%22%5D = 100%0A self.dom.setSchedulerParameters(params)%0A
|
|
726ae01462c8945df1b7d3f32d56fc54ed9b6fa2
|
Write hub initialization tests
|
tests/test_bicycle_wheel.py
|
tests/test_bicycle_wheel.py
|
Python
| 0.000001
|
@@ -0,0 +1,1986 @@
+import pytest%0Afrom bikewheelcalc import BicycleWheel, Rim, Hub%0A%0A%0A# -------------------------------------------------------------------------------%0A# Test fixtures%0A#------------------------------------------------------------------------------%0A@pytest.fixture%0Adef std_radial():%0A 'Return a Standard Bicycle Wheel with radial spokes'%0A%0A w = BicycleWheel()%0A w.hub = Hub(diam1=0.050, width1=0.025)%0A w.rim = Rim(radius=0.3, area=100e-6,%0A I11=25., I22=200., I33=100., Iw=0.0,%0A young_mod=69e9, shear_mod=26e9)%0A%0A w.lace_radial(n_spokes=36, diameter=1.8e-3, young_mod=210e9, offset=0.)%0A%0A@pytest.fixture%0Adef std_3cross():%0A 'Return a Standard Bicycle Wheel with 3-cross spokes'%0A%0A w = BicycleWheel()%0A w.hub = Hub(diam1=0.050, width1=0.025)%0A w.rim = Rim(radius=0.3, area=100e-6,%0A I11=25., I22=200., I33=100., Iw=0.0,%0A young_mod=69e9, shear_mod=26e9)%0A%0A w.lace_cross(n_spokes=36, n_cross=3, diameter=1.8e-3, young_mod=210e9, offset=0.)%0A%0A%0A# -----------------------------------------------------------------------------%0A# Hub tests%0A# -----------------------------------------------------------------------------%0Adef test_hub_symm():%0A 'Initialize a symmetric hub using flange diameter and width'%0A%0A h = Hub(diameter=0.05, width=0.05)%0A%0A assert h.width_left == 0.025%0A assert h.width_right == 0.025%0A assert h.diameter_left == 0.05%0A assert h.diameter_right == 0.05%0A%0Adef test_hub_asymm():%0A 'Initialize an asymmetric hub using two explicit diameters and widths'%0A%0A h = Hub(diameter_left=0.04, diameter_right=0.06, width_left=0.03, width_right=0.02)%0A%0A assert h.width_left == 0.03%0A assert h.width_right == 0.02%0A assert h.diameter_left == 0.04%0A assert h.diameter_right == 0.06%0A%0Adef test_hub_asymm_offset():%0A 'Initialize an asymmetric hub using a width and an offset'%0A%0A h = Hub(diameter=0.05, width=0.05, offset=0.01)%0A%0A assert h.width_left == 0.035%0A assert h.widtH_right == 0.015%0A
|
|
d05a2a7504bf8e6adf6d5d94d0b810060f66a9ec
|
Create test_it_all.py
|
tests/test_it_all.py
|
tests/test_it_all.py
|
Python
| 0.000009
|
@@ -0,0 +1,9 @@
+#soon TM%0A
|
|
afe2cac782f2578e610137891566d862f62375c6
|
Create uds18.py
|
uds18.py
|
uds18.py
|
Python
| 0.000002
|
@@ -0,0 +1,85 @@
+%22%22%22%0ACustom fits for the lens in UDS-18%0A%22%22%22%0Aimport unicorn%0Aimport pyfits%0Aimport emcee%0A
|
|
df26dc408dc629e4802716ace5d0b3879c2b110b
|
Create factories.py
|
trendpy/factories.py
|
trendpy/factories.py
|
Python
| 0.000001
|
@@ -0,0 +1,1495 @@
+# factory.py%0A%0A# MIT License%0A%0A# Copyright (c) 2017 Rene Jean Corneille%0A%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A%0A# The above copyright notice and this permission notice shall be included in all%0A# copies or substantial portions of the Software.%0A%0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, 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 IN THE%0A# SOFTWARE.%0A%0Afrom trendpy.strategies import *%0A%0Aclass StrategyFactory:%0A%09factories = %7B%7D%0A%0A%09@staticmethod%0A%09def add(id,factory):%0A%09%09StrategyFactory.factories.put%5Bid%5D = factory%0A%0A%09@staticmethod%0A%09def create(id,*args,**kwargs):%0A%09%09if not id in StrategyFactory.factories:%0A%09%09%09StrategyFactory.factories%5Bid%5D = eval('%25s.Factory()' %25 id)%0A%09%09return StrategyFactory.factories%5Bid%5D.create(*args,**kwargs)%0A
|
|
df7cf8ef2bdba9f50e21f4a7fc96904122fde311
|
Add gunicorn config file
|
gunicorn_cfg.py
|
gunicorn_cfg.py
|
Python
| 0
|
@@ -0,0 +1,724 @@
+%22%22%22%0AThis file contains gunicorn settings.%0ATo run sqmpy with gunicorn run the following command:%0A%0A gunicorn -c gunicorn_cfg.py run:app%0A%0AIn order to daemonize gunicorn add -D flag:%0A%0A gunicorn -c gunicorn_cfg.py run:app -D%0A%0A%22%22%22%0Aimport multiprocessing%0A%0A%0A# Gunicorn will listen on the given host:port%0Abind = '0.0.0.0:3000'%0A%0A# The only tested worker class is gevent%0Aworker_class = 'gevent'%0A%0A# Set number of workers based on CPU count%0Aworkers = multiprocessing.cpu_count() * 2 + 1%0A%0A# Uncomment for development%0A# reload = True%0A%0A# Daemonize the application%0Adaemon = False%0A%0A# Comment only for development. Use your own certificates here.%0Akeyfile = 'server.key'%0Acertfile = 'server.crt'%0A%0A# Application loglevel%0Aloglevel = 'debug'%0A
|
|
cb875f2043a1c3a9ec5201336d1b577655612279
|
move utility methods into their own module as functions, clean up type lookup
|
utils.py
|
utils.py
|
Python
| 0
|
@@ -0,0 +1,327 @@
+def bytes_to_unicode(data):%0A return data.decode(%22UTF-8%22)%0A%0A%0Adef unicode_to_bytes(data):%0A return data.encode(%22UTF-8%22)%0A%0A%0Adef pretty_print(self, user, msg_type, destination, message):%0A if isinstance(message, list):%0A message = %22 %22.join(message)%0A print(%22%25s %25s %25s :%25s%22 %25 (user, msg_type, destination, message))%0A
|
|
568fe1ff8c4ef27f93751f53a27707f045f19037
|
update core api module
|
simphony_paraview/core/api.py
|
simphony_paraview/core/api.py
|
from .iterators import iter_cells, iter_grid_cells
from .cuba_data_accumulator import CUBADataAccumulator
from .cuba_utils import (
supported_cuba, cuba_value_types, default_cuba_value, VALUETYPES)
from .constants import points2edge, points2face, points2cell, dataset2writer
from .paraview_utils import write_to_file, loaded_in_paraview
from .cuds2vtk import cuds2vtk
__all__ = [
'iter_cells',
'iter_grid_cells',
'CUBADataAccumulator',
'supported_cuba',
'default_cuba_value',
'cuba_value_types',
'VALUETYPES',
'points2edge',
'points2face',
'points2cell',
'dataset2writer',
'write_to_file',
'loaded_in_paraview',
'cuds2vtk']
|
Python
| 0
|
@@ -300,16 +300,22 @@
import
+(%0A
write_to
@@ -339,16 +339,45 @@
paraview
+, typical_distance, set_data)
%0A%0Afrom .
@@ -713,10 +713,50 @@
uds2vtk'
+,%0A 'typical_distance',%0A 'set_data'
%5D%0A
|
f418e9e68d1f2a7f6a0ad5060a1ed5a7ed74664f
|
Add YCM configuration
|
_vim/ycm_global_extra_conf.py
|
_vim/ycm_global_extra_conf.py
|
Python
| 0
|
@@ -0,0 +1,2560 @@
+# Copied from https://gist.github.com/micbou/f8ed3f8bd6bd24e9f89bef286437306b. Kudos to micbou%0A%0Aimport os%0Aimport ycm_core%0A%0A%0ASOURCE_EXTENSIONS = %5B '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' %5D%0A%0A%0Adef IsHeaderFile( filename ):%0A extension = os.path.splitext( filename )%5B 1 %5D%0A return extension in %5B '.h', '.hxx', '.hpp', '.hh' %5D%0A%0A%0Adef GetCompilationInfoForFile( database, filename ):%0A # The compilation_commands.json file generated by CMake does not have entries%0A # for header files. So we do our best by asking the db for flags for a%0A # corresponding source file, if any. If one exists, the flags for that file%0A # should be good enough.%0A if IsHeaderFile( filename ):%0A basename = os.path.splitext( filename )%5B 0 %5D%0A for extension in SOURCE_EXTENSIONS:%0A replacement_file = basename + extension%0A if os.path.exists( replacement_file ):%0A compilation_info = database.GetCompilationInfoForFile(%0A replacement_file )%0A if compilation_info.compiler_flags_:%0A return compilation_info%0A return None%0A return database.GetCompilationInfoForFile( filename )%0A%0A%0Adef PathsToAllParentFolders( path ):%0A folder = os.path.normpath( path )%0A if os.path.isdir( folder ):%0A yield folder%0A while True:%0A parent = os.path.dirname( folder )%0A if parent == folder:%0A break%0A folder = parent%0A yield folder%0A%0A%0Adef FindCompilationDatabase( filename, compilation_database_folder):%0A if os.path.exists(os.path.abspath( compilation_database_folder )):%0A return compilation_database_folder%0A%0A for folder in PathsToAllParentFolders( filename ):%0A compile_commands = os.path.join( folder, compilation_database_folder,%0A 'compile_commands.json' )%0A if os.path.exists( compile_commands ):%0A return os.path.dirname( compile_commands )%0A return None%0A%0A%0Adef FlagsForFile( filename, **kwargs ):%0A compilation_database_folder = kwargs%5B 'client_data' %5D.get(%0A 'g:ycm_compilation_database_folder' )%0A if not compilation_database_folder:%0A return %7B%7D%0A %0A compilation_database_folder = FindCompilationDatabase(%0A filename, compilation_database_folder )%0A if not compilation_database_folder:%0A return %7B%7D%0A%0A database = ycm_core.CompilationDatabase( compilation_database_folder )%0A if not database.DatabaseSuccessfullyLoaded():%0A return %7B%7D%0A%0A compilation_info = GetCompilationInfoForFile( database, filename )%0A if not compilation_info:%0A return %7B%7D%0A %0A return %7B%0A 'flags': compilation_info.compiler_flags_,%0A 'include_paths_relative_to_dir': compilation_info.compiler_working_dir_%0A %7D%0A
|
|
be4374fd50d0c1148e3a734cc53391e15d4bbdc4
|
Create wksp5.py
|
wksp5.py
|
wksp5.py
|
Python
| 0.000003
|
@@ -0,0 +1,699 @@
+%22%22%22Rx Workshop: Event Processing.%0APart 2 - Grouping.%0AUsage:%0A python wksp5.py%0A%22%22%22%0Afrom __future__ import print_function%0Aimport rx%0A%0A%0Aclass Program:%0A %0A @staticmethod%0A def main():%0A src = rx.Observable.from_iterable(get_input(),%0A rx.concurrency.Scheduler.new_thread)%0A res = src.group_by(lambda s: len(s)).to_blocking()%0A res.for_each(lambda g: print(%22New group with length = %22 + str(g.key))%0A and g.subscribe(lambda x: print%0A (%22 %22 + str(x) + %22 member of %22 + g.key)))%0A%0A%0Adef get_input():%0A while True:%0A yield raw_input()%0A%0A%0Aif __name__ == '__main__':%0A Program.main()%0A
|
|
e789579c77d2d96d098f4b46f1dfec4d54c843e5
|
move AbstractProductCategory and AbstractNestedProductCategory
|
eca_catalogue/categorization/abstract_models.py
|
eca_catalogue/categorization/abstract_models.py
|
Python
| 0.000006
|
@@ -0,0 +1,801 @@
+from django.db import models%0Afrom django.utils.translation import ugettext_lazy as _%0A%0Afrom treebeard.mp_tree import MP_Node%0A%0A%0Aclass AbstractProductCategory(models.Model):%0A name = models.CharField(_(%22Name%22), max_length=128, unique=True)%0A description = models.TextField(_(%22Description%22), blank=True, null=True)%0A%0A class Meta:%0A abstract = True%0A verbose_name = _(%22Product category%22)%0A verbose_name_plural = _(%22Product categories%22)%0A ordering = %5B'name'%5D%0A%0A def __unicode__(self):%0A return self.name%0A%0A%0Aclass AbstractNestedProductCategory(AbstractProductCategory, MP_Node):%0A class Meta:%0A abstract = True%0A%0A def __unicode__(self):%0A if not self.is_root():%0A return unicode(self.get_parent()) + %22 -%3E %22 + self.name%0A return self.name%0A%0A
|
|
3bbaf37193fe147f66b17d848f646f4400aa6278
|
Fix lights issue #8098 (#8101)
|
homeassistant/components/light/vera.py
|
homeassistant/components/light/vera.py
|
"""
Support for Vera lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.vera/
"""
import logging
from homeassistant.components.light import (
ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ENTITY_ID_FORMAT,
SUPPORT_BRIGHTNESS, SUPPORT_RGB_COLOR, Light)
from homeassistant.components.vera import (
VERA_CONTROLLER, VERA_DEVICES, VeraDevice)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['vera']
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Vera lights."""
add_devices(
VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light'])
class VeraLight(VeraDevice, Light):
"""Representation of a Vera Light, including dimmable."""
def __init__(self, vera_device, controller):
"""Initialize the light."""
self._state = False
self._color = None
self._brightness = None
VeraDevice.__init__(self, vera_device, controller)
self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id)
@property
def brightness(self):
"""Return the brightness of the light."""
return self._brightness
@property
def rgb_color(self):
"""Return the color of the light."""
return self._color
@property
def supported_features(self):
"""Flag supported features."""
if self._color:
return SUPPORT_BRIGHTNESS | SUPPORT_RGB_COLOR
else:
return SUPPORT_BRIGHTNESS
def turn_on(self, **kwargs):
"""Turn the light on."""
if ATTR_RGB_COLOR in kwargs and self._color:
self.vera_device.set_color(kwargs[ATTR_RGB_COLOR])
elif ATTR_BRIGHTNESS in kwargs and self.vera_device.is_dimmable:
self.vera_device.set_brightness(kwargs[ATTR_BRIGHTNESS])
else:
self.vera_device.switch_on()
self._state = True
self.schedule_update_ha_state(True)
def turn_off(self, **kwargs):
"""Turn the light off."""
self.vera_device.switch_off()
self._state = False
self.schedule_update_ha_state()
@property
def is_on(self):
"""Return true if device is on."""
return self._state
def update(self):
"""Call to update state."""
self._state = self.vera_device.is_switched_on()
self._brightness = self.vera_device.get_brightness()
self._color = self.vera_device.get_color()
|
Python
| 0
|
@@ -2407,16 +2407,182 @@
ed_on()%0A
+ if self.vera_device.is_dimmable:%0A # If it is dimmable, both functions exist. In case color%0A # is not supported, it will return None%0A
@@ -2634,16 +2634,20 @@
tness()%0A
+
|
000239e4f838f6514f6e902510d70fdc41b196d5
|
Add wordpress_post
|
wordpress_post.py
|
wordpress_post.py
|
Python
| 0.000006
|
@@ -0,0 +1,2271 @@
+import os %0D%0Aimport time%0D%0Afrom base64 import b64encode%0D%0Aimport json%0D%0Aimport requests%0D%0Afrom wordpresspushmedia import *%0D%0A%0D%0A#%0D%0A# publish the image as a media in wordpress, and return the HTML to include into the post%0D%0A#%0D%0Adef wordpress_publish_image(blogid,title,imageurl,bearer_key):%0D%0A url = %22https://public-api.wordpress.com/rest/v1/sites/%22 + blogid + %22/media/new%22%0D%0A headers = %7B%22Authorization%22: %22bearer %22 + bearer_key %7D%0D%0A postdata = %7B 'media_urls' : %5Bimageurl%5D %7D%0D%0A response = requests.post(url, data=json.dumps(postdata), headers=headers)%0D%0A jresponse = response.json()%0D%0A%0D%0A media = jresponse%5B'media'%5D%5B0%5D;%0D%0A general_link = media%5B'link'%5D;%0D%0A linkdir = %22/%22.join(general_link.split(%22/%22)%5B:-1%5D)%0D%0A%0D%0A metadata = media%5B'metadata'%5D;%0D%0A if 'large' in metadata%5B'sizes'%5D:%0D%0A filebig = metadata%5B'sizes'%5D%5B'large'%5D%5B'file'%5D;%0D%0A src = linkdir + %22/%22 + filebig;%0D%0A width = metadata%5B'sizes'%5D%5B'large'%5D%5B'width'%5D;%0D%0A height = metadata%5B'sizes'%5D%5B'large'%5D%5B'height'%5D;%0D%0A sizetype = %22size-large%22;%0D%0A else:%0D%0A src = media%5B'link'%5D;%0D%0A width = metadata%5B'width'%5D;%0D%0A height = metadata%5B'height'%5D;%0D%0A sizetype = %22size-full%22;%0D%0A WPID = media%5B'id'%5D%0D%0A%0D%0A SRC = src;%0D%0A TITLE = title;%0D%0A WIDTH = str(width);%0D%0A HEIGHT = str(height);%0D%0A ID = str(WPID);%0D%0A%0D%0A HTML = %22%3Cimg src=%5C%22%22 + SRC + %22%5C%22 alt=%5C%22%22 + TITLE + %22%5C%22 width=%5C%22%22 + WIDTH + %22%5C%22 height=%5C%22%22 + HEIGHT + %22%5C%22 class=%5C%22alignnone %22 + sizetype + %22 wp-image-%22 + ID + %22%5C%22 /%3E%22%0D%0A return HTML%0D%0A%0D%0A#%0D%0A# post a wordpress post with image%0D%0A#%0D%0Adef wordpress_post(status,description,title,categories,tags,imageurl,wordpress_blogid,wordpress_bearer_key):%0D%0A html = wordpress_publish_image(wordpress_blogid,title,imageurl, wordpress_bearer_key)%0D%0A content = html + %22%5Cn%22 + description%0D%0A headers = %7B%22Authorization%22: %22bearer %22 + wordpress_bearer_key %7D%0D%0A data = %7B 'content': content, %22status%22:status, %22title%22:title, %22categories%22:categories, %22tags%22:tags %7D%0D%0A try: %0D%0A response = requests.post(%22https://public-api.wordpress.com/rest/v1/sites/%22 + wordpress_blogid + %22/posts/new%22, data=data, headers=headers)%0D%0A result = response.json()%0D%0A except:%0D%0A print %22wordpress post catch exception%22%0D%0A result = %22%22%0D%0A return result%0D%0A
|
|
2fdbd208ee6db593df6f8b7c171a716ea3716920
|
Add a checks module
|
doc8/checks.py
|
doc8/checks.py
|
Python
| 0
|
@@ -0,0 +1,1826 @@
+# -*- coding: utf-8 -*-%0A%0A# Copyright (C) 2014 Ivan Melnikov %3Civ at altlinux dot org%3E%0A#%0A# Author: Joshua Harlow %3Charlowja@yahoo-inc.com%3E%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# 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, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Aimport abc%0Aimport re%0A%0Aimport six%0A%0A%0A@six.add_metaclass(abc.ABCMeta)%0Aclass ContentCheck(object):%0A @abc.abstractmethod%0A def report_iter(self, parsed_file):%0A pass%0A%0A%0A@six.add_metaclass(abc.ABCMeta)%0Aclass LineCheck(object):%0A @abc.abstractmethod%0A def report_iter(self, line):%0A pass%0A%0A%0Aclass CheckTrailingWhitespace(LineCheck):%0A _TRAILING_WHITESPACE_REGEX = re.compile('%5Cs$')%0A REPORTS = frozenset(%5B%22D002%22%5D)%0A%0A def report_iter(self, line):%0A if self._TRAILING_WHITESPACE_REGEX.search(line):%0A yield ('D002', 'Trailing whitespace')%0A%0A%0Aclass CheckIndentationNoTab(LineCheck):%0A _STARTING_WHITESPACE_REGEX = re.compile('%5E(%5Cs+)')%0A REPORTS = frozenset(%5B%22D003%22%5D)%0A%0A def report_iter(self, line):%0A match = self._STARTING_WHITESPACE_REGEX.search(line)%0A if match:%0A spaces = match.group(1)%0A if '%5Ct' in spaces:%0A yield ('D003', 'Tabulation used for indentation')%0A%0A%0Aclass CheckCarriageReturn(LineCheck):%0A REPORTS = frozenset(%5B%22D004%22%5D)%0A%0A def report_iter(self, line):%0A if %22%5Cr%22 in line:%0A yield ('D004', 'Found literal carriage return')%0A%0A%0A
|
|
35de07472674c01c4816214123bf786599c239fb
|
Update source exe_17
|
Exe_17.py
|
Exe_17.py
|
# File. Input/Output
#name = input("What is your name? ")
#print("Your name is", name)
# ============ OPENING and CLOSING Files =============
# Syntax (opening_
# file object = open(file_name [, access_mode][, buffering])
#
# Here are parameter details:
# file_name: The file_name argument is a string value that contains the name
# of the file that you want to access.
# access_mode: The access_mode determines the mode in which the file has
# to be opened, i.e., read, write, append, etc. A complete list
# of possible values is given in the filemode table. This is optional
# parameter and the default file access mode is read (r).
# buffering: If the buffering value is set to 0, no buffering takes place.
# If the buffering value is 1, line buffering is performed while
# accessing a file. If you specify the buffering value as an integer
# greater than 1, then buffering action is performed with the
# indicated buffer size. If negative, the buffer size is the
# system default (default behavior).
fo = open("temp/foo.txt", "w")
print("Name of the file: ", fo.name)
print("Closed or not : ", fo.closed)
print("Opening mode : ", fo.mode)
# print("Softspace flag : ", fo.softspace)
fo.write("Python is a great language.\nYeah its great!!\n")
fo.close() # Close opened file
# ====== The read() method ======
# [Note] Python strings can have binary data, apart from text data.
#
# +++ Syntax: fileObject.read([count])
#
# Here, passed parameter is the number of bytes to be read from the opened file.
# This method starts reading from the beginning of the file and if count is missing,
# then it tries to read as much as possible, maybe until the end of file.
fo = open("temp/foo.txt", "r+")
str = fo.read(10)
print("Reading string is: '", str, "'")
# Check current position
position = fo.tell();
print("Current file position : ", position)
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print("Again read String is : ", str)
# Close opened file
fo.close()
# ======= EDIT Files =======
# 1. Rename(): os.rename(current_file_name, new_file_name)
# 2. Remove(): os.remove(file_name)
# 3. mkdir(): os.mkdir("newdir") -- make new directory
# 4. chdir(): os.chdir("newdir") -- change current directory
# 5. getcwd(): os.getcwd() -- display the current working directory
# 6. rmdir(): os.rmdir('dirname') -- delete the directory
import os # Required
os.mkdir("test-dir")
print(os.getcwd())
os.chdir("test-dir")
print(os.getcwd())
fo = open("foo.txt", "w")
fo.close()
os.rename("foo.txt", "refoo.txt")
print(os.getcwd())
os.remove("refoo.txt")
os.chdir(".\..")
os.rmdir('test-dir')
print(os.getcwd())
# File/Directory methods
fo = open("temp/123", "w+")
print("File Descriptor: ", fo.fileno())
print("Connection to a tty(-like) device status:", fo.isatty())
fo.write("This is 1st line\n")
fo.write("This is 2nd line\n")
fo.write("This is 3rd line\n")
fo.write("This is 4th line\n")
fo.write("This is 5th line\n")
fo.close()
fo = open("temp/123", "w+") # reopen working file
line = fo.readline()
print("Read line:", line)
line = fo.readline(5)
print("Read line:", line)
# Again set the pointer to the beginning
fo.seek(0, 0)
# Get the current position of the file
print("Current position:", fo.tell())
# Now truncate remaining file
print(fo.truncate())
# Try to read file now
line = fo.readline()
print("Read line:", line)
# Back to the beginning
fo.seek(0, 0)
# Read file, using the next() method
for index in range(5):
line = fo.next()
print("Line No", index, "-", line)
fo.close()
# The writelines() method
fo = open("temp/123", "w+")
print("Name of the file: ", fo.name)
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print("Line No", index, "-", line)
fo.close()
# Remove file
os.remove("temp/123")
|
Python
| 0
|
@@ -15,17 +15,16 @@
Output%0A%0A
-#
name = i
@@ -52,17 +52,16 @@
me? %22)%0A%0A
-#
print(%22Y
@@ -1288,18 +1288,16 @@
o.mode)%0A
-#
print(%22S
|
6c21cab0bc08fcce83b35b4f51a2d7f369af3af6
|
Build RequestContext in webhook middleware
|
senlin/api/middleware/webhook.py
|
senlin/api/middleware/webhook.py
|
# 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 oslo_log import log as logging
from senlin.common import context
from senlin.common import exception
from senlin.common.i18n import _
from senlin.common import utils
from senlin.common import wsgi
from senlin.drivers.openstack import sdk
from senlin.webhooks import webhooks
LOG = logging.getLogger(__name__)
class WebhookMiddleware(wsgi.Middleware):
'''Middleware to do authentication for webhook triggering
This middleware gets authentication for request to a webhook
based on information embedded inside url and then rebuild the
request header.
'''
def process_request(self, req):
self._authenticate(req)
def _authenticate(self, req):
LOG.debug("Checking credentials of webhook request")
credential = self._get_credential(req)
if not credential:
return
# Get a valid token based on credential
# and fill into the request header
token_id = self._get_token(credential)
req.headers['X-Auth-Token'] = token_id
def _get_credential(self, req):
try:
url_bottom = req.url.rsplit('webhooks')[1]
webhook_id = url_bottom.rsplit('/')[1]
trigger = url_bottom.rsplit('/')[2].startswith('trigger')
if trigger is not True or 'key' not in req.params:
raise Exception()
except Exception:
LOG.debug(_("%(url)s is not a webhook trigger url,"
" pass."), {'url': req.url})
return
if req.method != 'POST':
LOG.debug(_("Not a post request to webhook trigger url"
" %(url)s, pass."), {'url': req.url})
return
# This is a webhook triggering, we need to fill in valid
# credential info into the http headers to ensure this
# request can pass keystone auth_token validation.
#
# Get the credential stored in DB based on webhook ID.
# TODO(Anyone): Use Barbican to store these credential.
LOG.debug(_("Get credential of webhook %(id)s"), webhook_id)
senlin_context = context.get_service_context()
webhook_obj = webhooks.Webhook.load(senlin_context, webhook_id)
credential = webhook_obj.credential
credential['webhook_id'] = webhook_id
if 'auth_url' not in credential:
# If no auth_url is provided in credential, use
# auth_url of senlin service context
credential['auth_url'] = senlin_context['auth_url']
# Decrypt the credential password with key embedded in req params
try:
password = utils.decrypt(credential['password'],
req.params['key'])
credential['password'] = password
except Exception:
msg = 'Invalid key for webhook(%s) credential decryption' % \
webhook_id
LOG.error(msg)
raise exception.SenlinBadRequest(msg=msg)
return credential
def _get_token(self, credential):
'''Get a valid token based on credential'''
try:
access_info = sdk.authenticate(**credential)
token_id = access_info.auth_token
except Exception as ex:
msg = 'Webhook get token failed: %s' % ex.message
LOG.error(msg)
raise exception.WebhookCredentialInvalid(
webhook=credential['webhook_id'])
# Get token successfully!
return token_id
|
Python
| 0.000207
|
@@ -2662,16 +2662,31 @@
context.
+RequestContext.
get_serv
@@ -2699,16 +2699,297 @@
ntext()%0A
+ # Build a RequestContext from senlin_context since DB API%0A # needs the session parameter.%0A # TODO(Anyone): This converting is not needed any more after%0A # the context redesign is finally complete.%0A ctx = context.RequestContext(**senlin_context)%0A
@@ -3024,30 +3024,19 @@
ok.load(
-senlin_context
+ctx
, webhoo
|
dbcaa9f2cda37269cd5dfca1166394f71bb3adfc
|
Create Example5.py
|
Example5.py
|
Example5.py
|
Python
| 0
|
@@ -0,0 +1,1560 @@
+# Carlos Pedro Gon%C3%A7alves (2015), Game Theory with Python%0A# Game Theory and Applied A.I. Classes%0A# Instituto Superior de Ci%C3%AAncias Sociais e Pol%C3%ADticas (ISCSP)%0A# University of Lisbon%0A# cgoncalves@iscsp.ulisboa.pt%0A#%0A# New Entrant vs Market Leader (payoffs correspond to strategic value)%0A#%0A# For more details see the user manual that comes with the package:%0A# Gon%C3%A7alves, C.P. (2015) %22Game Player User Manual - A Game Theory Analyzer With Python%22,%0A# https://sites.google.com/site/autonomouscomputingsystems/game-player%0A%0Aimport gamep # import the game player main module%0A%0Atree = %5B%5D # setup the game tree%0A%0A# design the tree in accordance with the problem:%0A# the %22No move%22 is added at a given level whenever the player has no alternative choice%0A# this allows us to deal with a tree with different branch lengths%0Agamep.createPath(%5B%22Enter%22,%22Propose partnership%22,%22Accept partnership%22,%22No move%22%5D, %5B5,3%5D,tree)%0Agamep.createPath(%5B%22Enter%22,%22Propose partnership%22,%22Reject partnership%22,%22Fight%22%5D, %5B-2,3.5%5D,tree)%0Agamep.createPath(%5B%22Enter%22,%22Propose partnership%22,%22Reject partnership%22,%22Do not fight%22%5D, %5B4,2%5D,tree)%0Agamep.createPath(%5B%22Enter%22,%22Do not propose partnership%22,%22Fight%22,%22No move%22%5D, %5B-1,3%5D,tree)%0Agamep.createPath(%5B%22Enter%22,%22Do not propose partnership%22,%22Do not fight%22,%22No move%22%5D, %5B4,2%5D,tree)%0Agamep.createPath(%5B%22Do not enter%22,%22No move%22,%22No move%22,%22No move%22%5D,%5B0,5%5D,tree)%0Agamep.showTree(tree)%0A%0A# play sequence New Entrant plays in the first two levels then the Market Leader plays%0A# in the next two levels %0Aplays = %5B0,0,1,1%5D%0A%0Agamep.evaluateTree(tree,plays) # evaluate the game tree%0A
|
|
f0e1fc1751b20019e87cc50085c1350806b02f9f
|
Add missing visualizer module
|
thinc/extra/visualizer.py
|
thinc/extra/visualizer.py
|
Python
| 0.000001
|
@@ -0,0 +1,945 @@
+''' A visualizer module for Thinc '''%0Aimport seaborn%0Aimport matplotlib.pyplot as plt%0A%0A%0Adef visualize_attention(x, y, weights, layer='Encoder', self_attn=True):%0A '''%0A Visualize self/outer attention%0A Args:%0A x: sentence%0A y: sentence%0A weights: (nH, nL, nL)%0A '''%0A def heatmap(x, y, data, ax):%0A seaborn.heatmap(data, square=True, xticklabels=y, yticklabels=x, vmin=0.0, vmax=1.0,%0A cbar_kws = dict(use_gridspec=False, location=%22top%22),%0A ax=ax)%0A num = min(weights.shape%5B0%5D, 4)%0A fig, axs = plt.subplots(1, num)%0A attn_type = 'self attention' if self_attn else 'outer attention'%0A fig.suptitle('%7B%7D %7B%7D for all the heads'.format(layer, attn_type))%0A if len(weights.shape) == 3:%0A for i in range(num):%0A heatmap(x, y, weights%5Bi%5D, axs%5Bi%5D)%0A else:%0A raise ValueError(%22Wrong input weights dimensions%22)%0A plt.show()%0A
|
|
0a23dddae52c861ef8f359affc71c082e970c9a5
|
Create WhatsApp.py
|
WhatsApp.py
|
WhatsApp.py
|
Python
| 0.000003
|
@@ -0,0 +1,1034 @@
+from selenium import webdriver%0Afrom selenium.webdriver.support.ui import WebDriverWait%0Afrom selenium.webdriver.support import expected_conditions as EC%0Afrom selenium.webdriver.common.keys import Keys%0Afrom selenium.webdriver.common.by import By%0Aimport time%0A %0A# Replace below path with the absolute path%0A# to chromedriver in your computer%0Adriver = webdriver.Chrome('/home/saket/Downloads/chromedriver')%0A %0Adriver.get(%22https://web.whatsapp.com/%22)%0Await = WebDriverWait(driver, 600)%0A %0A# Replace 'Friend's Name' with the name of your friend %0A# or the name of a group %0Atarget = '%22Friend%5C's Name%22'%0A %0A# Replace the below string with your own message%0Astring = %22Message sent using Python!!!%22%0A %0Aarg = '//span%5Bcontains(@title,' + target + ')%5D'%0Agroup = wait.until(EC.presence_of_element_located((%0A By.XPATH, arg)))%0Agroup.click()%0Ainp = '//div%5B@class=%22input%22%5D%5B@dir=%22auto%22%5D%5B@data-tab=%221%22%5D'%0Ainput = wait.until(EC.presence_of_element_located((%0A By.XPATH, inp_xpath)))%0Afor i in range(100):%0A input.send_keys(string + Keys.ENTER)%0A time.sleep(1)%0A
|
|
927c9bcb0beab4f8fd6c2003573316906ad9dee3
|
add init file
|
__init__.py
|
__init__.py
|
Python
| 0.000002
|
@@ -0,0 +1,22 @@
+#!-*- coding:utf-8 -*-
|
|
1ab69075e39ad52674ffa52b86f64839f24d9016
|
Update merge person tool
|
project/apps/api/management/commands/merge_persons.py
|
project/apps/api/management/commands/merge_persons.py
|
Python
| 0.000001
|
@@ -0,0 +1,2331 @@
+from optparse import make_option%0A%0Afrom django.core.management.base import (%0A BaseCommand,%0A CommandError,%0A)%0A%0Afrom apps.api.models import (%0A Person,%0A Singer,%0A Director,%0A Arranger,%0A)%0A%0A%0Aclass Command(BaseCommand):%0A help = %22Merge selected singers by name%22%0A option_list = BaseCommand.option_list + (%0A make_option(%0A %22-o%22,%0A %22--old%22,%0A dest=%22old%22,%0A help=%22specify old name%22,%0A ),%0A )%0A option_list = option_list + (%0A make_option(%0A %22-n%22,%0A %22--new%22,%0A dest=%22new%22,%0A help=%22specify new name%22,%0A ),%0A )%0A%0A def handle(self, *args, **options):%0A # make sure file option is present%0A if options%5B'old'%5D is None:%0A raise CommandError(%22Option %60--old=...%60 must be specified.%22)%0A%0A if options%5B'new'%5D is None:%0A raise CommandError(%22Option %60--new=...%60 must be specified.%22)%0A%0A # make sure both singers exist%0A try:%0A new_person = Person.objects.get(%0A name__iexact=options%5B'new'%5D,%0A )%0A except Person.DoesNotExist:%0A raise CommandError(%22New person does not exist.%22)%0A try:%0A old_person = Person.objects.get(%0A name__iexact=options%5B'old'%5D,%0A )%0A except Singer.DoesNotExist:%0A raise CommandError(%22Old person does not exist.%22)%0A%0A # Move related records%0A for director in old_person.choruses.all():%0A Director.objects.create(%0A person=new_person,%0A contestant=director.contestant,%0A part=director.part,%0A )%0A for singer in old_person.quartets.all():%0A Singer.objects.create(%0A person=new_person,%0A contestant=singer.contestant,%0A part=singer.part,%0A )%0A%0A for arranger in old_person.arrangements.all():%0A Arranger.objects.create(%0A person=new_person,%0A chart=arranger.chart,%0A part=arranger.part,%0A )%0A%0A # remove redundant singer%0A try:%0A old_person.delete()%0A except Exception as e:%0A raise CommandError(%22Error deleted old singer: %7B0%7D%22.format(e))%0A%0A return %22Merged %7B0%7D into %7B1%7D%22.format(old_person, new_person)%0A
|
|
0bcc7fa0b5ab0b59cdc5fdfeeae8ffa39ead72bc
|
Refactor PatternMachine to use private variables
|
nupic/data/pattern_machine.py
|
nupic/data/pattern_machine.py
|
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Utilities for generating and manipulating patterns, for use in
experimentation and tests.
"""
import random
class PatternMachine(object):
"""
Base pattern machine class.
"""
def __init__(self,
n,
w,
num=100,
seed=42):
"""
@param n (int) Number of available bits in pattern
@param w (int/list) Number of on bits in pattern
If list, each pattern will have a `w` randomly
selected from the list.
@param num (int) Number of available patterns
"""
# Save member variables
self.n = n
self._w = w
self.num = num
# Initialize member variables
random.seed(seed)
self.patterns = dict()
self._generate()
def get(self, number):
"""
Return a pattern for a number.
@param number (int) Number of pattern
@return (set) Indices of on bits
"""
if not number in self.patterns:
raise IndexError("Invalid number")
return self.patterns[number]
def numbersForBit(self, bit):
"""
Return the set of pattern numbers that match a bit.
@param bit (int) Index of bit
@return (set) Indices of numbers
"""
if bit >= self.n:
raise IndexError("Invalid bit")
numbers = set()
for index, pattern in self.patterns.iteritems():
if bit in pattern:
numbers.add(index)
return numbers
def numberMapForBits(self, bits):
"""
Return a map from number to matching on bits,
for all numbers that match a set of bits.
@param bits (set) Indices of bits
@return (dict) Mapping from number => on bits.
"""
numberMap = dict()
for bit in bits:
numbers = self.numbersForBit(bit)
for number in numbers:
if not number in numberMap:
numberMap[number] = set()
numberMap[number].add(bit)
return numberMap
def prettyPrintPattern(self, bits, verbosity=1):
"""
Pretty print a pattern.
@param bits (set) Indices of on bits
@param verbosity (int) Verbosity level
@return (string) Pretty-printed text
"""
numberMap = self.numberMapForBits(bits)
text = ""
numberList = []
numberItems = sorted(numberMap.iteritems(),
key=lambda (number, bits): len(bits),
reverse=True)
for number, bits in numberItems:
if verbosity > 2:
strBits = [str(n) for n in bits]
numberText = "{0} (bits: {1})".format(number, ",".join(strBits))
elif verbosity > 1:
numberText = "{0} ({1} bits)".format(number, len(bits))
else:
numberText = str(number)
numberList.append(numberText)
text += "[{0}]".format(", ".join(numberList))
return text
def _generate(self):
"""
Generates set of random patterns.
"""
for i in xrange(self.num):
pattern = random.sample(xrange(self.n), self._getW())
self.patterns[i] = set(pattern)
def _getW(self):
"""
Gets a value of `w` for use in generating a pattern.
"""
w = self._w
if type(w) is list:
return random.choice(w)
else:
return w
class ConsecutivePatternMachine(PatternMachine):
"""
Pattern machine class that generates patterns with non-overlapping,
consecutive on bits.
"""
def _generate(self):
"""
Generates set of consecutive patterns.
"""
n = self.n
w = self._w
assert type(w) is int, "List for w not supported"
for i in xrange(n / w):
pattern = set(xrange(i * w, (i+1) * w))
self.patterns[i] = pattern
|
Python
| 0
|
@@ -1620,14 +1620,15 @@
elf.
+_
n = n%0A
-
@@ -1648,16 +1648,17 @@
self.
+_
num = nu
@@ -1717,32 +1717,33 @@
(seed)%0A self.
+_
patterns = dict(
@@ -1943,32 +1943,33 @@
number in self.
+_
patterns:%0A
@@ -2016,24 +2016,25 @@
return self.
+_
patterns%5Bnum
@@ -2236,16 +2236,17 @@
%3E= self.
+_
n:%0A
@@ -2296,24 +2296,24 @@
rs = set()%0A%0A
-
for inde
@@ -2327,24 +2327,25 @@
ern in self.
+_
patterns.ite
@@ -3891,16 +3891,17 @@
ge(self.
+_
num):%0A
@@ -3940,16 +3940,17 @@
ge(self.
+_
n), self
@@ -3962,32 +3962,33 @@
W())%0A self.
+_
patterns%5Bi%5D = se
@@ -4441,16 +4441,17 @@
= self.
+_
n%0A w
@@ -4601,16 +4601,17 @@
self.
+_
patterns
|
fee0bf6ab2fdeab8e81ca3f0381cdcc76454ee28
|
Add openai environment viewer
|
openai/environments_viewer.py
|
openai/environments_viewer.py
|
Python
| 0
|
@@ -0,0 +1,428 @@
+import gym%0A%0A# LunarLanderContinuous-v2%0A# BipedalWalker-v2%0A%0Aenv = gym.make('BipedalWalker-v2')%0A%0An_epsiodes = 20%0An_timesteps = 100%0Afor i_episode in range(n_epsiodes):%0A%09observation = env.reset()%0A%09for t in range(n_timesteps):%0A%09%09env.render()%0A%09%09print(observation)%0A%09%09action = env.action_space.sample()%0A%09%09observation, reward, done, info = env.step(action)%0A%09%09if done:%0A%09%09%09print(%22Episode finished after %7B%7D timesteps%22.format(t+1))%0A%09%09%09break%0A
|
|
17173e7688c7a544678086eb5081051e90b3510b
|
Make gui.util a package.
|
Cura/gui/util/__init__.py
|
Cura/gui/util/__init__.py
|
Python
| 0
|
@@ -0,0 +1,15 @@
+# coding=utf-8%0A
|
|
c2b75140bf01b8c8e57a4a835f7cae017b15a939
|
Fix config validation import to make things more readable
|
homeassistant/components/sensor/wunderground.py
|
homeassistant/components/sensor/wunderground.py
|
"""
Support for Weather Underground weather service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.wunderground/
"""
from datetime import timedelta
import logging
import requests
import voluptuous as vol
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.config_validation import (ensure_list, string)
from homeassistant.util import Throttle
from homeassistant.const import (CONF_PLATFORM, CONF_MONITORED_CONDITIONS,
CONF_API_KEY, TEMP_FAHRENHEIT, TEMP_CELSIUS,
STATE_UNKNOWN)
CONF_PWS_ID = 'pws_id'
_RESOURCE = 'http://api.wunderground.com/api/{}/conditions/q/'
_LOGGER = logging.getLogger(__name__)
# Return cached results if last scan was less then this time ago.
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=300)
# Sensor types are defined like: Name, units
SENSOR_TYPES = {
'weather': ['Weather Summary', None],
'station_id': ['Station ID', None],
'feelslike_c': ['Feels Like (°C)', TEMP_CELSIUS],
'feelslike_f': ['Feels Like (°F)', TEMP_FAHRENHEIT],
'feelslike_string': ['Feels Like', None],
'heat_index_c': ['Dewpoint (°C)', TEMP_CELSIUS],
'heat_index_f': ['Dewpoint (°F)', TEMP_FAHRENHEIT],
'heat_index_string': ['Heat Index Summary', None],
'dewpoint_c': ['Dewpoint (°C)', TEMP_CELSIUS],
'dewpoint_f': ['Dewpoint (°F)', TEMP_FAHRENHEIT],
'dewpoint_string': ['Dewpoint Summary', None],
'wind_kph': ['Wind Speed', 'kpH'],
'wind_mph': ['Wind Speed', 'mpH'],
'UV': ['UV', None],
'pressure_in': ['Pressure', 'in'],
'pressure_mb': ['Pressure', 'mbar'],
'wind_dir': ['Wind Direction', None],
'wind_string': ['Wind Summary', None],
'temp_c': ['Temperature (°C)', TEMP_CELSIUS],
'temp_f': ['Temperature (°F)', TEMP_FAHRENHEIT],
'relative_humidity': ['Relative Humidity', '%'],
'visibility_mi': ['Visibility (miles)', 'mi'],
'visibility_km': ['Visibility (km)', 'km'],
'precip_today_in': ['Precipation Today', 'in'],
'precip_today_metric': ['Precipitation Today', 'mm'],
'precip_today_string': ['Precipitation today', None],
'solarradiation': ['Solar Radiation', None]
}
PLATFORM_SCHEMA = vol.Schema({
vol.Required(CONF_PLATFORM): "wunderground",
vol.Required(CONF_API_KEY): string,
vol.Optional(CONF_PWS_ID): string,
vol.Required(CONF_MONITORED_CONDITIONS,
default=[]): vol.All(ensure_list, [vol.In(SENSOR_TYPES)]),
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Wunderground sensor."""
rest = WUndergroundData(hass,
config.get(CONF_API_KEY),
config.get(CONF_PWS_ID, None))
sensors = []
for variable in config[CONF_MONITORED_CONDITIONS]:
sensors.append(WUndergroundSensor(rest, variable))
try:
rest.update()
except ValueError as err:
_LOGGER.error("Received error from WUnderground: %s", err)
return False
add_devices(sensors)
return True
class WUndergroundSensor(Entity):
"""Implementing the Wunderground sensor."""
def __init__(self, rest, condition):
"""Initialize the sensor."""
self.rest = rest
self._condition = condition
@property
def name(self):
"""Return the name of the sensor."""
return "PWS_" + self._condition
@property
def state(self):
"""Return the state of the sensor."""
if self.rest.data and self._condition in self.rest.data:
return self.rest.data[self._condition]
else:
return STATE_UNKNOWN
@property
def entity_picture(self):
"""Return the entity picture."""
if self._condition == 'weather':
return self.rest.data['icon_url']
@property
def unit_of_measurement(self):
"""Return the units of measurement."""
return SENSOR_TYPES[self._condition][1]
def update(self):
"""Update current conditions."""
self.rest.update()
# pylint: disable=too-few-public-methods
class WUndergroundData(object):
"""Get data from Wundeground."""
def __init__(self, hass, api_key, pws_id=None):
"""Initialize the data object."""
self._hass = hass
self._api_key = api_key
self._pws_id = pws_id
self._latitude = hass.config.latitude
self._longitude = hass.config.longitude
self.data = None
def _build_url(self):
url = _RESOURCE.format(self._api_key)
if self._pws_id:
url = url + 'pws:' + self._pws_id
else:
url = url + '{},{}'.format(self._latitude, self._longitude)
return url + '.json'
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
"""Get the latest data from wunderground."""
try:
result = requests.get(self._build_url(), timeout=10).json()
if "error" in result['response']:
raise ValueError(result['response']["error"]
["description"])
else:
self.data = result["current_observation"]
except ValueError as err:
_LOGGER.error("Check Wunderground API %s", err.args)
self.data = None
raise
|
Python
| 0.000001
|
@@ -321,20 +321,22 @@
Entity%0A
-from
+import
homeass
@@ -372,36 +372,13 @@
ion
-import (ensure_list, string)
+as cv
%0Afro
@@ -2332,16 +2332,19 @@
I_KEY):
+cv.
string,%0A
@@ -2374,16 +2374,19 @@
WS_ID):
+cv.
string,%0A
@@ -2467,16 +2467,19 @@
vol.All(
+cv.
ensure_l
|
fd03d3c8a032e06ff2a84af48f6d23e3b3365695
|
Integrate LLVM at llvm/llvm-project@f011d32c3a62
|
third_party/llvm/workspace.bzl
|
third_party/llvm/workspace.bzl
|
"""Provides the repository macro to import LLVM."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo(name):
"""Imports LLVM."""
LLVM_COMMIT = "3cd5696a33095fe41c8c63f933d239f2c0dbb36e"
LLVM_SHA256 = "5d6e9211f9886586b20fc4c88e9c72833fa686212df82957f3d0b67a5c090d23"
tf_http_archive(
name = name,
sha256 = LLVM_SHA256,
strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
"https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
],
build_file = "//third_party/llvm:llvm.BUILD",
patch_file = [
"//third_party/llvm:infer_type.patch", # TODO(b/231285230): remove once resolved
"//third_party/llvm:build.patch",
"//third_party/llvm:macos_build_fix.patch",
],
link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
)
|
Python
| 0.000001
|
@@ -160,133 +160,133 @@
= %22
-3cd5696a33095fe41c8c63f933d239f2c0dbb36e%22%0A LLVM_SHA256 = %225d6e9211f9886586b20fc4c88e9c72833fa686212df82957f3d0b67a5c090d23
+f011d32c3a625eb86d1e33a70100b0a031f5fcd4%22%0A LLVM_SHA256 = %22b3ec1a2253da80c473df9addacc6ff5b7cfc3a788043a1c59480a93fd0d6fe0e
%22%0A%0A
|
8d473ee89ea43e5004b78314c0ca49cde0049980
|
Integrate LLVM at llvm/llvm-project@961fd77687d2
|
third_party/llvm/workspace.bzl
|
third_party/llvm/workspace.bzl
|
"""Provides the repository macro to import LLVM."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo(name):
"""Imports LLVM."""
LLVM_COMMIT = "4004fb6453d9cee1fc0160d6ebac62fa8e898131"
LLVM_SHA256 = "faec068929d9f039b3f65d8f074bfbee4d9bdc0829b50f7848b110f2bf7c3383"
tf_http_archive(
name = name,
sha256 = LLVM_SHA256,
strip_prefix = "llvm-project-{commit}".format(commit = LLVM_COMMIT),
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
"https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
],
build_file = "//third_party/llvm:llvm.BUILD",
patch_file = [
"//third_party/llvm:infer_type.patch", # TODO(b/231285230): remove once resolved
"//third_party/llvm:build.patch",
"//third_party/llvm:toolchains.patch",
"//third_party/llvm:temporary.patch", # Cherry-picks and temporary reverts. Do not remove even if temporary.patch is empty.
],
link_files = {"//third_party/llvm:run_lit.sh": "mlir/run_lit.sh"},
)
|
Python
| 0.000001
|
@@ -160,133 +160,133 @@
= %22
-4004fb6453d9cee1fc0160d6ebac62fa8e898131%22%0A LLVM_SHA256 = %22faec068929d9f039b3f65d8f074bfbee4d9bdc0829b50f7848b110f2bf7c3383
+961fd77687d27089acf0a09ea29a87fb8ccd7522%22%0A LLVM_SHA256 = %227c225e465ae120daa639ca68339fe7f43796ab08ff0ea893579a067b8f875078
%22%0A%0A
|
0869a26cc061b86b31e7e5144bf90c276fa8c786
|
Add numpy_checkwiki.py
|
numpy_checkwiki.py
|
numpy_checkwiki.py
|
Python
| 0.000427
|
@@ -0,0 +1,664 @@
+#!/usr/bin/env python%0Aimport subprocess%0Aimport os, shutil, tempfile%0Afrom numpy_towiki import *%0A%0APATCH = os.path.join(DIR, 'wiki.patch')%0A%0Adef main():%0A regenerate_base_xml()%0A os.chdir(DIR)%0A%0A new_xml = tempfile.NamedTemporaryFile()%0A %0A if not os.path.isdir(SITE_PTH):%0A raise RuntimeError(%22directory %25s not found%22 %25 SITE_PTH)%0A%0A exec_cmd(%5BPYDOCMOIN, 'moin-collect-local', '-o', new_xml.name, WIKI_CONF%5D)%0A exec_cmd(%5BPYDOCMOIN, 'patch', '-s', SITE_PTH,%0A BASEXML, new_xml.name, '-o', PATCH%5D, echo=True)%0A %0A print %22Check in %25s for what has been changed%22 %25 PATCH%0A%0Aif __name__ == %22__main__%22: main()%0A%0A# vim:sw=4 expandtab smarttab%0A
|
|
728c4db461bdf22a668436ac25ca1cb9afb80e81
|
add argparse01.py
|
trypython/stdlib/argparse01.py
|
trypython/stdlib/argparse01.py
|
Python
| 0.004268
|
@@ -0,0 +1,1015 @@
+%22%22%22%0Aargparse %E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AE%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E3%81%A7%E3%81%99%E3%80%82%0A%E5%9F%BA%E6%9C%AC%E7%9A%84%E3%81%AA%E4%BD%BF%E3%81%84%E6%96%B9%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E3%80%82%0A%0A%E5%8F%82%E8%80%83%EF%BC%9A http://bit.ly/2UXDCIG%0A%22%22%22%0Aimport argparse%0Aimport sys%0A%0Afrom common.commoncls import SampleBase%0Afrom common.commonfunc import pr%0A%0A%0Aclass Sample(SampleBase):%0A def exec(self):%0A #%0A # argparse %E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%82%92%E4%BD%BF%E3%81%86%E5%A0%B4%E5%90%88%E3%81%AE%E5%9F%BA%E6%9C%AC%E3%81%AF%E4%BB%A5%E4%B8%8B%E3%81%AE%E6%89%8B%E9%A0%86%0A #%0A # (1) argparse.ArgumentParser %E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88%E7%94%9F%E6%88%90%0A # (2) parser %E3%81%AB add_argument %E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%A7%E5%BC%95%E6%95%B0%E6%83%85%E5%A0%B1%E3%82%92%E8%BF%BD%E5%8A%A0%0A # (3) parser.parse_args %E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E5%91%BC%E3%81%B3%E5%87%BA%E3%81%97%0A # (4) args %E3%81%8B%E3%82%89 %E5%BC%95%E6%95%B0%E6%83%85%E5%A0%B1 %E3%82%92%E5%8F%96%E5%BE%97%0A #%0A parser = argparse.ArgumentParser(description='argparse sample01')%0A%0A parser.add_argument('indir', type=str, help='input directory')%0A parser.add_argument('outdir', type=str, help='output directory')%0A%0A args = parser.parse_args()%0A%0A pr('type(parser)', type(parser))%0A pr('type(args)', type(args))%0A pr('args.indir', args.indir)%0A pr('args.outdir', args.outdir)%0A%0A%0Adef go():%0A sys.argv.append('~/indir')%0A sys.argv.append('~/outdir')%0A%0A obj = Sample()%0A obj.exec()%0A%0A%0Aif __name__ == '__main__':%0A go()%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.