commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
e8e7d188b45b06967a6f7ec210f91b1bbe4e494c
|
use pathlib
|
abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core
|
abilian/web/admin/panels/sysinfo.py
|
abilian/web/admin/panels/sysinfo.py
|
# coding=utf-8
"""
"""
from __future__ import absolute_import, print_function, division
import os
import sys
import pkg_resources
from pip.vcs import vcs
from pathlib import Path
from flask import render_template
from ..panel import AdminPanel
class SysinfoPanel(AdminPanel):
id = 'sysinfo'
label = 'System information'
icon = 'hdd'
def get(self):
uname = os.popen("uname -a").read()
python_version = sys.version.strip()
packages = []
for dist in pkg_resources.working_set:
package = dict(
name=dist.project_name,
key=dist.key,
version=dist.version if dist.has_version() else u'Unknown version',
vcs=None,
)
location = unicode(Path(dist.location).absolute())
vcs_name = vcs.get_backend_name(location)
if vcs_name:
vc = vcs.get_backend_from_location(location)()
url, revision = vc.get_info(location)
package['vcs'] = dict(name=vcs_name, url=url, revision=revision)
packages.append(package)
packages.sort(key=lambda d: d.get('key', None))
return render_template("admin/sysinfo.html",
python_version=python_version,
packages=packages,
uname=uname)
|
# coding=utf-8
"""
"""
from __future__ import absolute_import, print_function, division
import os
import sys
import pkg_resources
from pip.vcs import vcs
from flask import render_template
from ..panel import AdminPanel
class SysinfoPanel(AdminPanel):
id = 'sysinfo'
label = 'System information'
icon = 'hdd'
def get(self):
uname = os.popen("uname -a").read()
python_version = sys.version.strip()
packages = []
for dist in pkg_resources.working_set:
package = dict(
name=dist.project_name,
key=dist.key,
version=dist.version if dist.has_version() else u'Unknown version',
vcs=None,
)
location = os.path.normcase(os.path.abspath(dist.location))
vcs_name = vcs.get_backend_name(location)
if vcs_name:
vc = vcs.get_backend_from_location(location)()
url, revision = vc.get_info(location)
package['vcs'] = dict(name=vcs_name, url=url, revision=revision)
packages.append(package)
packages.sort(key=lambda d: d.get('key', None))
return render_template("admin/sysinfo.html",
python_version=python_version,
packages=packages,
uname=uname)
|
lgpl-2.1
|
Python
|
cb89d8f0dd5fad8b5fc935639fc59a7317679001
|
Update master.chromium.webkit to use a dedicated mac builder.
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
masters/master.chromium.webkit/master_mac_latest_cfg.py
|
masters/master.chromium.webkit/master_mac_latest_cfg.py
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import master_config
from master.factory import chromium_factory
defaults = {}
helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
T = helper.Triggerable
def mac():
return chromium_factory.ChromiumFactory('src/out', 'darwin')
defaults['category'] = 'nonlayout'
################################################################################
## Debug
################################################################################
# Triggerable scheduler for testers
T('mac_builder_dbg_trigger')
#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'f_mac_builder_dbg', scheduler='global_scheduler')
F('f_mac_builder_dbg', mac().ChromiumFactory(
target='Debug',
# Build 'all' instead of 'chromium_builder_tests' so that archiving works.
# TODO: Define a new build target that is archive-friendly?
options=['--build-tool=ninja', '--compiler=goma-clang', 'all'],
factory_properties={
'trigger': 'mac_builder_dbg_trigger',
'gclient_env': {
'GYP_DEFINES': 'fastbuild=1',
'GYP_GENERATORS': 'ninja',
},
'archive_build': True,
'blink_config': 'blink',
'build_name': 'Mac',
'gs_bucket': 'gs://chromium-webkit-snapshots',
'gs_acl': 'public-read',
}))
B('Mac10.6 Tests', 'f_mac_tester_10_06_dbg',
scheduler='mac_builder_dbg_trigger')
F('f_mac_tester_10_06_dbg', mac().ChromiumFactory(
tests=[
'browser_tests',
'cc_unittests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'blink_config': 'blink',
}))
B('Mac10.8 Tests', 'f_mac_tester_10_08_dbg',
scheduler='mac_builder_dbg_trigger')
F('f_mac_tester_10_08_dbg', mac().ChromiumFactory(
tests=[
'browser_tests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'blink_config': 'blink',
}))
def Update(_config, _active_master, c):
return helper.Update(c)
|
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from master import master_config
from master.factory import chromium_factory
defaults = {}
helper = master_config.Helper(defaults)
B = helper.Builder
F = helper.Factory
def mac():
return chromium_factory.ChromiumFactory('src/xcodebuild', 'darwin')
def mac_out():
return chromium_factory.ChromiumFactory('src/out', 'darwin')
################################################################################
## Release
################################################################################
defaults['category'] = 'nonlayout'
#
# Mac Rel Builder
#
B('Mac10.6 Tests', 'f_mac_tests_rel', scheduler='global_scheduler')
F('f_mac_tests_rel', mac_out().ChromiumFactory(
options=['--build-tool=ninja', '--compiler=goma-clang', '--',
'chromium_builder_tests'],
tests=[
'browser_tests',
'cc_unittests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'generate_gtest_json': True,
'gclient_env': {
'GYP_GENERATORS':'ninja',
'GYP_DEFINES':'fastbuild=1',
},
'blink_config': 'blink',
}))
B('Mac10.8 Tests', 'f_mac_tests_rel_108', scheduler='global_scheduler')
F('f_mac_tests_rel_108', mac_out().ChromiumFactory(
# Build 'all' instead of 'chromium_builder_tests' so that archiving works.
# TODO: Define a new build target that is archive-friendly?
options=['--build-tool=ninja', '--compiler=goma-clang', '--', 'all'],
tests=[
'browser_tests',
'content_browsertests',
'interactive_ui_tests',
'telemetry_unittests',
'unit',
],
factory_properties={
'archive_build': True,
'blink_config': 'blink',
'build_name': 'Mac',
'generate_gtest_json': True,
'gclient_env': {
'GYP_GENERATORS':'ninja',
'GYP_DEFINES':'fastbuild=1',
},
'gs_bucket': 'gs://chromium-webkit-snapshots',
}))
################################################################################
## Debug
################################################################################
#
# Mac Dbg Builder
#
B('Mac Builder (dbg)', 'f_mac_dbg', scheduler='global_scheduler')
F('f_mac_dbg', mac().ChromiumFactory(
target='Debug',
options=['--compiler=goma-clang', '--', '-target', 'blink_tests'],
factory_properties={
'blink_config': 'blink',
}))
def Update(_config, _active_master, c):
return helper.Update(c)
|
bsd-3-clause
|
Python
|
b195e909ce3d3903998a91de0b5763dd679b25e3
|
fix version
|
opencollab/debile,tcc-unb-fga/debile,lucaskanashiro/debile,opencollab/debile,mdimjasevic/debile,tcc-unb-fga/debile,mdimjasevic/debile,lucaskanashiro/debile
|
debile/slave/runners/findbugs.py
|
debile/slave/runners/findbugs.py
|
# Copyright (c) 2012-2013 Paul Tagliamonte <[email protected]>
# Copyright (c) 2013 Leo Cavaille <[email protected]>
# Copyright (c) 2013 Sylvestre Ledru <[email protected]>
# Copyright (c) 2015 Lucas Kanashiro <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from debile.slave.wrappers.findbugs import parse_findbugs
from debile.slave.utils import cd
from debile.utils.commands import run_command
import os
def findbugs(deb, analysis):
run_command(["dpkg", "-x", deb, "binary"])
with cd('binary'):
# Force english as findbugs is localized
os.putenv("LANG", "C")
out, err, _ = run_command([
'fb', 'analyze', '-effort:max', '-xml:withMessages', '.'
])
xmlbytes = out.encode("utf-8")
failed = False
# if err.strip() == '':
# return (analysis, err, failed)
for issue in parse_findbugs(xmlbytes):
analysis.results.append(issue)
if not failed and issue.severity in [
'performance', 'portability', 'error', 'warning'
]:
failed = True
return (analysis, err, failed, None, None)
def version():
out, _, ret = run_command(['fb', '-version'])
if ret != 0:
raise Exception("findbugs is not installed")
version = out.strip()
return ('findbugs', version.strip())
|
# Copyright (c) 2012-2013 Paul Tagliamonte <[email protected]>
# Copyright (c) 2013 Leo Cavaille <[email protected]>
# Copyright (c) 2013 Sylvestre Ledru <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
from debile.slave.wrappers.findbugs import parse_findbugs
from debile.slave.utils import cd
from debile.utils.commands import run_command
import os
def findbugs(deb, analysis):
run_command(["dpkg", "-x", deb, "binary"])
with cd('binary'):
# Force english as findbugs is localized
os.putenv("LANG", "C")
out, err, _ = run_command([
'fb', 'analyze', '-effort:max', '-xml:withMessages', '.'
])
xmlbytes = out.encode("utf-8")
failed = False
# if err.strip() == '':
# return (analysis, err, failed)
for issue in parse_findbugs(xmlbytes):
analysis.results.append(issue)
if not failed and issue.severity in [
'performance', 'portability', 'error', 'warning'
]:
failed = True
return (analysis, err, failed, None, None)
def version():
out, _, ret = run_command(['fb', '-version'])
if ret != 0:
raise Exception("findbugs is not installed")
name, version = out.split(" ")
return (name, version.strip())
|
mit
|
Python
|
2d3e2f796d6a839994c2708f31e60d52c6bf8c15
|
Simplify main()
|
Necior/sjp.pl
|
sjp.py
|
sjp.py
|
#!/usr/bin/env python3
import urllib.request # to download HTML source
import sys # to access CLI arguments and to use exit codes
from bs4 import BeautifulSoup # to parse HTML source
version = 0.01
def printUsageInfo():
helpMsg = """Usage:
sjp.py <word>
sjp.py (-h | --help | /?)
sjp.py (-v | --version)"""
print(helpMsg)
def printVersionInfo():
versionMsg = "sjp.py " + str(version)
print(versionMsg)
def getDefinition(word):
url = 'http://sjp.pl/' + urllib.parse.quote(word)
try:
html = urllib.request.urlopen(url).read()
except urllib.error.URLError:
print("[Error] Can't connect to the service")
sys.exit(2)
soup = BeautifulSoup(html)
# checks if definition is in dictionary:
if soup.find_all('span', style="color: #e00;"):
print("[Error] \"" + word + "\" not found")
sys.exit(1)
# definition is in dictionary, continue:
ex = soup.find_all('p',
style="margin-top: .5em; "
"font-size: medium; "
"max-width: 32em; ")
ex = ex[0]
return ex.contents[0::2] # returns a list of lines of definition
def main():
if len(sys.argv) <= 1:
printUsageInfo()
sys.exit()
if sys.argv[1] in ("-h", "--help", "/?"):
printUsageInfo()
sys.exit()
elif sys.argv[1] in ("-v", "--version"):
printVersionInfo()
sys.exit()
else:
print('\n'.join(getDefinition(sys.argv[1])))
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
import urllib.request # to download HTML source
import sys # to access CLI arguments and to use exit codes
from bs4 import BeautifulSoup # to parse HTML source
version = 0.01
def printUsageInfo():
helpMsg = """Usage:
sjp.py <word>
sjp.py (-h | --help | /?)
sjp.py (-v | --version)"""
print(helpMsg)
def printVersionInfo():
versionMsg = "sjp.py " + str(version)
print(versionMsg)
def getDefinition(word):
url = 'http://sjp.pl/' + urllib.parse.quote(word)
try:
html = urllib.request.urlopen(url).read()
except urllib.error.URLError:
print("[Error] Can't connect to the service")
sys.exit(2)
soup = BeautifulSoup(html)
# checks if definition is in dictionary:
if soup.find_all('span', style="color: #e00;"):
print("[Error] \"" + word + "\" not found")
sys.exit(1)
# definition is in dictionary, continue:
ex = soup.find_all('p',
style="margin-top: .5em; "
"font-size: medium; "
"max-width: 32em; ")
ex = ex[0]
return ex.contents[0::2] # returns a list of lines of definition
def main():
if len(sys.argv) > 1:
if sys.argv[1] in ["-h", "--help", "/?"]:
printUsageInfo()
sys.exit()
elif sys.argv[1] in ["-v", "--version"]:
printVersionInfo()
sys.exit()
else:
print('\n'.join(getDefinition(sys.argv[1])))
else:
printUsageInfo()
sys.exit()
if __name__ == "__main__":
main()
|
mit
|
Python
|
a78d1bcfdc3d979cd7be1f82345c29047993953d
|
Add more init logic to handle AWS HTTP API
|
MA3STR0/AsyncAWS
|
sqs.py
|
sqs.py
|
#!/usr/bin/env python
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPClient
from tornado.httputil import url_concat
import datetime
import hashlib
import hmac
class SQSRequest(HTTPRequest):
"""SQS AWS Adapter for Tornado HTTP request"""
def __init__(self, *args, **kwargs):
t = datetime.datetime.utcnow()
method = kwargs.get('method', 'GET')
url = kwargs.get('url') or args[0]
params = sorted(url.split('?')[1].split('&'))
canonical_querystring = '&'.join(params)
kwargs['url'] = url.split('?')[0] + '?' + canonical_querystring
args = tuple()
host = url.split('://')[1].split('/')[0]
canonical_uri = url.split('://')[1].split('.com')[1].split('?')[0]
service = 'sqs'
region = kwargs.get('region', 'eu-west-1')
amz_date = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d')
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amz_date + '\n'
signed_headers = 'host;x-amz-date'
payload_hash = hashlib.sha256('').hexdigest()
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' + amz_date + '\n' + credential_scope + '\n' + hashlib.sha256(canonical_request).hexdigest()
signing_key = self.getSignatureKey(kwargs['secret_key'], datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + kwargs['access_key'] + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
del kwargs['access_key']
del kwargs['secret_key']
headers = kwargs.get('headers', {})
headers.update({'x-amz-date':amz_date, 'Authorization':authorization_header})
kwargs['headers'] = headers
super(SQSRequest, self).__init__(*args, **kwargs)
|
#!/usr/bin/env python
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPClient
from tornado.httputil import url_concat
import datetime
import hashlib
import hmac
class SQSRequest(HTTPRequest):
"""SQS AWS Adapter for Tornado HTTP request"""
def __init__(self, *args, **kwargs):
t = datetime.datetime.utcnow()
method = kwargs.get('method', 'GET')
url = kwargs.get('url') or args[0]
params = sorted(url.split('?')[1].split('&'))
canonical_querystring = '&'.join(params)
kwargs['url'] = url.split('?')[0] + '?' + canonical_querystring
args = tuple()
host = url.split('://')[1].split('/')[0]
canonical_uri = url.split('://')[1].split('.com')[1].split('?')[0]
service = 'sqs'
region = kwargs.get('region', 'eu-west-1')
super(SQSRequest, self).__init__(*args, **kwargs)
|
mit
|
Python
|
2166f52ce5da81bf8f28a3dbbc92145b0913db07
|
Update usage of layouts.get_layout
|
drufat/vispy,ghisvail/vispy,michaelaye/vispy,ghisvail/vispy,drufat/vispy,ghisvail/vispy,michaelaye/vispy,drufat/vispy,Eric89GXL/vispy,Eric89GXL/vispy,Eric89GXL/vispy,michaelaye/vispy
|
examples/basics/visuals/graph.py
|
examples/basics/visuals/graph.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example demonstrates how to visualise a NetworkX graph using the
GraphVisual.
"""
import sys
import numpy as np
import networkx as nx
from vispy import app, gloo, visuals
from vispy.visuals.graphs import layouts
from vispy.visuals.transforms import STTransform
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title="Simple NetworkX Graph",
keys="interactive", size=(600, 600))
self.graph = nx.fast_gnp_random_graph(1000, 0.0006, directed=True)
self.visual = visuals.GraphVisual(
# np.asarray(nx.to_numpy_matrix(self.graph)),
nx.adjacency_matrix(self.graph),
layout=layouts.get_layout('force_directed'),
line_color=(1.0, 1.0, 1.0, 1.0),
arrow_type="stealth",
arrow_size=15,
node_symbol="disc",
node_size=10,
face_color="red",
border_width=0.0,
animate=True,
directed=True
)
self.visual.events.update.connect(lambda evt: self.update())
self.visual.transform = STTransform(self.visual_size, (20, 20))
self.timer = app.Timer(interval=0, connect=self.animate, start=True)
self.show()
@property
def visual_size(self):
return (
self.physical_size[0] - 40,
self.physical_size[1] - 40
)
def on_resize(self, event):
self.visual.transform.scale = self.visual_size
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.visual.transforms.configure(canvas=self, viewport=vp)
def on_draw(self, event):
gloo.clear('black')
self.visual.draw()
def animate(self, event):
ready = self.visual.animate_layout()
if ready:
self.timer.disconnect(self.animate)
if __name__ == '__main__':
win = Canvas()
if sys.flags.interactive != 1:
app.run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
This example demonstrates how to visualise a NetworkX graph using the
GraphVisual.
"""
import sys
import networkx as nx
from vispy import app, gloo, visuals
from vispy.visuals.graphs import layouts
from vispy.visuals.transforms import STTransform
class Canvas(app.Canvas):
def __init__(self):
app.Canvas.__init__(self, title="Simple NetworkX Graph",
keys="interactive", size=(600, 600))
self.graph = nx.fast_gnp_random_graph(100, 0.02)
self.visual = visuals.GraphVisual(
nx.adjacency_matrix(self.graph),
layout=layouts.get('force_directed'),
line_color=(1.0, 1.0, 1.0, 1.0),
arrow_type="stealth",
arrow_size=7.5,
node_symbol="disc",
node_size=10,
face_color="red",
border_width=0.0,
animate=True
)
self.visual.events.update.connect(lambda evt: self.update())
self.visual.transform = STTransform(self.visual_size, (20, 20))
self.timer = app.Timer(interval=0, connect=self.animate, start=True)
self.show()
@property
def visual_size(self):
return (
self.physical_size[0] - 40,
self.physical_size[1] - 40
)
def on_resize(self, event):
self.visual.transform.scale = self.visual_size
vp = (0, 0, self.physical_size[0], self.physical_size[1])
self.context.set_viewport(*vp)
self.visual.transforms.configure(canvas=self, viewport=vp)
def on_draw(self, event):
gloo.clear('black')
self.visual.draw()
def animate(self, event):
ready = self.visual.animate_layout()
if ready:
self.timer.disconnect(self.animate)
if __name__ == '__main__':
win = Canvas()
if sys.flags.interactive != 1:
app.run()
|
bsd-3-clause
|
Python
|
e43aa23b3d4b7d3319e4b2766cdb4a9b9382954b
|
Fix typo
|
mariocesar/django-tricks
|
django_tricks/models/abstract.py
|
django_tricks/models/abstract.py
|
from uuid import uuid4
from django.db import models
from .mixins import MPAwareModel
treebeard = True
try:
from treebeard.mp_tree import MP_Node
except ImportError:
treebeard = False
class UniqueTokenModel(models.Model):
token = models.CharField(max_length=32, unique=True, blank=True)
class Meta:
abstract = True
def get_token(self):
return str(uuid4().hex)
def save(self, **kwargs):
if not self.token:
self.token = self.get_token()
super().save(**kwargs)
if treebeard:
class MaterializedPathNode(MPAwareModel, MP_Node):
slug = models.SlugField(max_length=255, db_index=True, unique=False, blank=True)
node_order_by = ['name']
class Meta:
abstract = True
|
from uuid import uuid4
from django.db import models
from .mixins import MPAwareModel
treebeard = True
try:
from treebeard.mp_tree import MP_Node
except ImportError:
treebeard = False
class UniqueTokenModel(models.Model):
token = models.CharField(max_length=32, unique=True, blank=True)
class Meta:
abstract = True
def get_token(self):
return uuid4().hext
def save(self, **kwargs):
if not self.token:
self.token = self.get_token()
super().save(**kwargs)
if treebeard:
class MaterializedPathNode(MPAwareModel, MP_Node):
slug = models.SlugField(max_length=255, db_index=True, unique=False, blank=True)
node_order_by = ['name']
class Meta:
abstract = True
|
isc
|
Python
|
0a70a700f450c3c22ee0e7a32ffb57c29b823fe1
|
Exclude test/assembly on Windows
|
old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google,old8xp/gyp_from_google
|
test/assembly/gyptest-assembly.py
|
test/assembly/gyptest-assembly.py
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
A basic test of compiling assembler files.
"""
import sys
import TestGyp
if sys.platform != 'win32':
# TODO(bradnelson): get this working for windows.
test = TestGyp.TestGyp(formats=['make', 'ninja', 'scons', 'xcode'])
test.run_gyp('assembly.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('assembly.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello from program.c
Got 42.
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.pass_test()
|
#!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .hpp files are ignored when included in the source list on all
platforms.
"""
import sys
import TestGyp
# TODO(bradnelson): get this working for windows.
test = TestGyp.TestGyp(formats=['make', 'ninja', 'scons', 'xcode'])
test.run_gyp('assembly.gyp', chdir='src')
test.relocate('src', 'relocate/src')
test.build('assembly.gyp', test.ALL, chdir='relocate/src')
expect = """\
Hello from program.c
Got 42.
"""
test.run_built_executable('program', chdir='relocate/src', stdout=expect)
test.pass_test()
|
bsd-3-clause
|
Python
|
86c45216633a3a273d04a64bc54ca1026b3d5069
|
Fix comment middleware
|
lpomfrey/django-debreach,lpomfrey/django-debreach
|
debreach/middleware.py
|
debreach/middleware.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
import logging
import random
from Crypto.Cipher import AES
from django.core.exceptions import SuspiciousOperation
from debreach.compat import \
force_bytes, get_random_string, string_types, force_text
log = logging.getLogger(__name__)
class CSRFCryptMiddleware(object):
def process_request(self, request):
if request.POST.get('csrfmiddlewaretoken') \
and '$' in request.POST.get('csrfmiddlewaretoken'):
try:
POST = request.POST.copy()
token = POST.get('csrfmiddlewaretoken')
key, value = token.split('$')
value = base64.decodestring(force_bytes(value)).strip()
aes = AES.new(key.strip())
POST['csrfmiddlewaretoken'] = aes.decrypt(value).strip()
POST._mutable = False
request.POST = POST
except:
log.exception('Error decoding csrfmiddlewaretoken')
raise SuspiciousOperation(
'csrfmiddlewaretoken has been tampered with')
return
class RandomCommentMiddleware(object):
def process_response(self, request, response):
if not getattr(response, 'streaming', False) \
and response['Content-Type'].strip().startswith('text/html') \
and isinstance(response.content, string_types):
comment = '<!-- {0} -->'.format(
get_random_string(random.choice(range(12, 25))))
response.content = '{0}{1}'.format(
force_text(response.content), comment)
return response
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import base64
import logging
import random
from Crypto.Cipher import AES
from django.core.exceptions import SuspiciousOperation
from debreach.compat import \
force_bytes, get_random_string, string_types, force_text
log = logging.getLogger(__name__)
class CSRFCryptMiddleware(object):
def process_request(self, request):
if request.POST.get('csrfmiddlewaretoken') \
and '$' in request.POST.get('csrfmiddlewaretoken'):
try:
POST = request.POST.copy()
token = POST.get('csrfmiddlewaretoken')
key, value = token.split('$')
value = base64.decodestring(force_bytes(value)).strip()
aes = AES.new(key.strip())
POST['csrfmiddlewaretoken'] = aes.decrypt(value).strip()
POST._mutable = False
request.POST = POST
except:
log.exception('Error decoding csrfmiddlewaretoken')
raise SuspiciousOperation(
'csrfmiddlewaretoken has been tampered with')
return
class RandomCommentMiddleware(object):
def process_response(self, request, response):
if not getattr(response, 'streaming', False) \
and response['Content-Type'] == 'text/html' \
and isinstance(response.content, string_types):
comment = '<!-- {0} -->'.format(
get_random_string(random.choice(range(12, 25))))
response.content = '{0}{1}'.format(
force_text(response.content), comment)
return response
|
bsd-2-clause
|
Python
|
1e7bbd7b59abbe0bcb01fd98079a362f4f874d3b
|
Fix long waiting version number up
|
sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs
|
dedupsqlfs/__init__.py
|
dedupsqlfs/__init__.py
|
# -*- coding: utf8 -*-
# Documentation. {{{1
"""
This Python library implements a file system in user space using FUSE. It's
called DedupFS because the file system's primary feature is deduplication,
which enables it to store virtually unlimited copies of files because data
is only stored once.
In addition to deduplication the file system also supports transparent
compression using any of the compression methods zlib, bz2, lzma
and optionaly lzo, lz4, snappy, zstd.
These two properties make the file system ideal for backups: I'm currently
storing 250 GB worth of backups using only 8 GB of disk space.
The latest version is available at https://github.com/sergey-dryabzhinsky/dedupsqlfs
DedupFS is licensed under the MIT license.
Copyright 2010 Peter Odding <[email protected]>.
Copyright 2013-2020 Sergey Dryabzhinsky <[email protected]>.
"""
__name__ = "DedupSQLfs"
# for fuse mount
__fsname__ = "dedupsqlfs"
__fsversion__ = "3.3"
# Future 1.3
__version__ = "1.2.949-dev"
# Check the Python version, warn the user if untested.
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1] < 2):
msg = "Warning: %s(%s, $s) has only been tested on Python 3.2, while you're running Python %d.%d!\n"
sys.stderr.write(msg % (__name__, __fsversion__, __version__, sys.version_info[0], sys.version_info[1]))
# Do not abuse GC - we generate alot objects
import gc
if hasattr(gc, "set_threshold"):
gc.set_threshold(100000, 2000, 200)
|
# -*- coding: utf8 -*-
# Documentation. {{{1
"""
This Python library implements a file system in user space using FUSE. It's
called DedupFS because the file system's primary feature is deduplication,
which enables it to store virtually unlimited copies of files because data
is only stored once.
In addition to deduplication the file system also supports transparent
compression using any of the compression methods zlib, bz2, lzma
and optionaly lzo, lz4, snappy, zstd.
These two properties make the file system ideal for backups: I'm currently
storing 250 GB worth of backups using only 8 GB of disk space.
The latest version is available at https://github.com/sergey-dryabzhinsky/dedupsqlfs
DedupFS is licensed under the MIT license.
Copyright 2010 Peter Odding <[email protected]>.
Copyright 2013-2020 Sergey Dryabzhinsky <[email protected]>.
"""
__name__ = "DedupSQLfs"
# for fuse mount
__fsname__ = "dedupsqlfs"
__fsversion__ = "3.3"
# Future 1.3
__version__ = "1.2.947"
# Check the Python version, warn the user if untested.
import sys
if sys.version_info[0] < 3 or \
(sys.version_info[0] == 3 and sys.version_info[1] < 2):
msg = "Warning: %s(%s, $s) has only been tested on Python 3.2, while you're running Python %d.%d!\n"
sys.stderr.write(msg % (__name__, __fsversion__, __version__, sys.version_info[0], sys.version_info[1]))
# Do not abuse GC - we generate alot objects
import gc
if hasattr(gc, "set_threshold"):
gc.set_threshold(100000, 2000, 200)
|
mit
|
Python
|
dd7b10a89e3fd5e431b03e922fbbc0a49c3d8c5e
|
Fix failing wavelet example due to outdated code
|
kohr-h/odl,aringh/odl,aringh/odl,kohr-h/odl,odlgroup/odl,odlgroup/odl
|
examples/trafos/wavelet_trafo.py
|
examples/trafos/wavelet_trafo.py
|
# Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL 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 ODL. If not, see <http://www.gnu.org/licenses/>.
"""Simple example on the usage of the Wavelet Transform."""
import odl
# Discretized space: discretized functions on the rectangle [-1, 1] x [-1, 1]
# with 512 samples per dimension.
space = odl.uniform_discr([-1, -1], [1, 1], (256, 256))
# Make the Wavelet transform operator on this space. The range is calculated
# automatically. The default backend is PyWavelets (pywt).
wavelet_op = odl.trafos.WaveletTransform(space, wavelet='Haar', nlevels=2)
# Create a phantom and its wavelet transfrom and display them.
phantom = odl.phantom.shepp_logan(space, modified=True)
phantom.show(title='Shepp-Logan phantom')
# Note that the wavelet transform is a vector in rn.
phantom_wt = wavelet_op(phantom)
phantom_wt.show(title='wavelet transform')
# It may however (for some choices of wbasis) be interpreted as a vector in the
# domain of the transformation
phantom_wt_2d = space.element(phantom_wt)
phantom_wt_2d.show('wavelet transform in 2d')
# Calculate the inverse transform.
phantom_wt_inv = wavelet_op.inverse(phantom_wt)
phantom_wt_inv.show(title='wavelet transform inverted')
|
# Copyright 2014-2016 The ODL development group
#
# This file is part of ODL.
#
# ODL is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ODL 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 ODL. If not, see <http://www.gnu.org/licenses/>.
"""Simple example on the usage of the Wavelet Transform."""
import odl
# Discretized space: discretized functions on the rectangle [-1, 1] x [-1, 1]
# with 512 samples per dimension.
space = odl.uniform_discr([-1, -1], [1, 1], (256, 256))
# Make the Wavelet transform operator on this space. The range is calculated
# automatically. The default backend is PyWavelets (pywt).
wavelet_op = odl.trafos.WaveletTransform(space, nscales=2, wbasis='Haar')
# Create a phantom and its wavelet transfrom and display them.
phantom = odl.phantom.shepp_logan(space, modified=True)
phantom.show(title='Shepp-Logan phantom')
# Note that the wavelet transform is a vector in rn.
phantom_wt = wavelet_op(phantom)
phantom_wt.show(title='wavelet transform')
# It may however (for some choices of wbasis) be interpreted as a vector in the
# domain of the transformation
phantom_wt_2d = space.element(phantom_wt)
phantom_wt_2d.show('wavelet transform in 2d')
# Calculate the inverse transform.
phantom_wt_inv = wavelet_op.inverse(phantom_wt)
phantom_wt_inv.show(title='wavelet transform inverted')
|
mpl-2.0
|
Python
|
0d38b9592fbb63e25b080d2f17b690c478042455
|
Add comments to Perfect Game solution
|
robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles,robertdimarco/puzzles
|
google-code-jam-2012/perfect-game/perfect-game.py
|
google-code-jam-2012/perfect-game/perfect-game.py
|
#!/usr/bin/env python
# expected time per attempt is given by equation
# time = L[0] + (1-P[0])*L[1] + (1-P[0])*(1-P[1])*L[2] + ...
# where L is the expected time and P is the probability of failure, per level
# swap two levels if L[i]*P[i+1] > L[i+1]*P[i]
import sys
if len(sys.argv) < 2:
sys.exit('Usage: %s file.in' % sys.argv[0])
file = open(sys.argv[1], 'r')
T = int(file.readline())
for i in xrange(1, T+1):
N = int(file.readline())
L = map(int, file.readline().split(' '))
P = map(int, file.readline().split(' '))
assert N == len(L)
assert N == len(P)
levels = zip(L, P, range(N))
levels.sort(lambda li, pi: li[0] * pi[1] - li[1] * pi[0])
print "Case #%d:" % i, ' '.join([str(i) for li, pi, i in levels])
file.close()
|
#!/usr/bin/env python
import sys
if len(sys.argv) < 2:
sys.exit('Usage: %s file.in' % sys.argv[0])
file = open(sys.argv[1], 'r')
T = int(file.readline())
for i in xrange(1, T+1):
N = int(file.readline())
L = map(int, file.readline().split(' '))
P = map(int, file.readline().split(' '))
assert N == len(L)
assert N == len(P)
levels = zip(L, P, range(N))
levels.sort(lambda li, pi: li[0] * pi[1] - li[1] * pi[0])
print "Case #%d:" % i, ' '.join([str(i) for li, pi, i in levels])
file.close()
|
mit
|
Python
|
9f9e2db5105eab1f46590a6b8d6a5b5eff4ccb51
|
Use new BinarySensorDeviceClass enum in egardia (#61378)
|
nkgilley/home-assistant,nkgilley/home-assistant,rohitranjan1991/home-assistant,home-assistant/home-assistant,rohitranjan1991/home-assistant,GenericStudent/home-assistant,GenericStudent/home-assistant,toddeye/home-assistant,w1ll1am23/home-assistant,w1ll1am23/home-assistant,toddeye/home-assistant,mezz64/home-assistant,rohitranjan1991/home-assistant,mezz64/home-assistant,home-assistant/home-assistant
|
homeassistant/components/egardia/binary_sensor.py
|
homeassistant/components/egardia/binary_sensor.py
|
"""Interfaces with Egardia/Woonveilig alarm control panel."""
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.const import STATE_OFF, STATE_ON
from . import ATTR_DISCOVER_DEVICES, EGARDIA_DEVICE
EGARDIA_TYPE_TO_DEVICE_CLASS = {
"IR Sensor": BinarySensorDeviceClass.MOTION,
"Door Contact": BinarySensorDeviceClass.OPENING,
"IR": BinarySensorDeviceClass.MOTION,
}
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Initialize the platform."""
if discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None:
return
disc_info = discovery_info[ATTR_DISCOVER_DEVICES]
async_add_entities(
(
EgardiaBinarySensor(
sensor_id=disc_info[sensor]["id"],
name=disc_info[sensor]["name"],
egardia_system=hass.data[EGARDIA_DEVICE],
device_class=EGARDIA_TYPE_TO_DEVICE_CLASS.get(
disc_info[sensor]["type"], None
),
)
for sensor in disc_info
),
True,
)
class EgardiaBinarySensor(BinarySensorEntity):
"""Represents a sensor based on an Egardia sensor (IR, Door Contact)."""
def __init__(self, sensor_id, name, egardia_system, device_class):
"""Initialize the sensor device."""
self._id = sensor_id
self._name = name
self._state = None
self._device_class = device_class
self._egardia_system = egardia_system
def update(self):
"""Update the status."""
egardia_input = self._egardia_system.getsensorstate(self._id)
self._state = STATE_ON if egardia_input else STATE_OFF
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def is_on(self):
"""Whether the device is switched on."""
return self._state == STATE_ON
@property
def device_class(self):
"""Return the device class."""
return self._device_class
|
"""Interfaces with Egardia/Woonveilig alarm control panel."""
from homeassistant.components.binary_sensor import (
DEVICE_CLASS_MOTION,
DEVICE_CLASS_OPENING,
BinarySensorEntity,
)
from homeassistant.const import STATE_OFF, STATE_ON
from . import ATTR_DISCOVER_DEVICES, EGARDIA_DEVICE
EGARDIA_TYPE_TO_DEVICE_CLASS = {
"IR Sensor": DEVICE_CLASS_MOTION,
"Door Contact": DEVICE_CLASS_OPENING,
"IR": DEVICE_CLASS_MOTION,
}
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Initialize the platform."""
if discovery_info is None or discovery_info[ATTR_DISCOVER_DEVICES] is None:
return
disc_info = discovery_info[ATTR_DISCOVER_DEVICES]
async_add_entities(
(
EgardiaBinarySensor(
sensor_id=disc_info[sensor]["id"],
name=disc_info[sensor]["name"],
egardia_system=hass.data[EGARDIA_DEVICE],
device_class=EGARDIA_TYPE_TO_DEVICE_CLASS.get(
disc_info[sensor]["type"], None
),
)
for sensor in disc_info
),
True,
)
class EgardiaBinarySensor(BinarySensorEntity):
"""Represents a sensor based on an Egardia sensor (IR, Door Contact)."""
def __init__(self, sensor_id, name, egardia_system, device_class):
"""Initialize the sensor device."""
self._id = sensor_id
self._name = name
self._state = None
self._device_class = device_class
self._egardia_system = egardia_system
def update(self):
"""Update the status."""
egardia_input = self._egardia_system.getsensorstate(self._id)
self._state = STATE_ON if egardia_input else STATE_OFF
@property
def name(self):
"""Return the name of the device."""
return self._name
@property
def is_on(self):
"""Whether the device is switched on."""
return self._state == STATE_ON
@property
def device_class(self):
"""Return the device class."""
return self._device_class
|
apache-2.0
|
Python
|
ead5daf0e631a3482a8510abc36f48b227e862ee
|
Delete unused variable assignations.
|
AriMartti/ZhaltraucsLair
|
game.py
|
game.py
|
# -*- coding: utf-8 -*-
import functions.commands as command
import functions.database as db
f = open('ASCII/otsikko_unicode.asc', 'r')
print(f.read())
f.close()
while True:
'''
You can end loop by selecting 5 in main context or write
"quit" in game context.
'''
context = command.doMenu()
while context == "main":
prompt = "(main) >>> "
try:
c = int(input(prompt))
context = command.doMenu(c)
except ValueError as e:
print(e)
while context == "game":
position = db.getPosition()
prompt = "(game) >>> "
print("--\n{}".format(position))
c = input(prompt).lower().split()
if (command.isValid(c)):
context = command.execute(c)
else:
print('Invalid command. '
'Write "help" to get list of available commands.'
)
|
# -*- coding: utf-8 -*-
import functions.commands as command
import functions.database as db
prompt = ">>> "
view = {
'0.0' : "Tutorial. You see a rat attacking you, fight!",
'1.0' : "You stand in a start of dungeon. You see a torch."
}
position = '1.0'
f = open('ASCII/otsikko_unicode.asc', 'r')
print(f.read())
f.close()
while True:
'''
You can end loop by selecting 5 in main context or write
"quit" in game context.
'''
context = command.doMenu()
while context == "main":
prompt = "(main) >>> "
try:
c = int(input(prompt))
context = command.doMenu(c)
except ValueError as e:
print(e)
while context == "game":
position = db.getPosition()
prompt = "(game) >>> "
print("--\n{}".format(position))
c = input(prompt).lower().split()
if (command.isValid(c)):
context = command.execute(c)
else:
print('Invalid command. '
'Write "help" to get list of available commands.'
)
|
mit
|
Python
|
2d26d92956282be3f08cc3dcdb5fa16433822a1b
|
Change retry_if_fails to _retry_on_fail
|
Hamuko/nyaamagnet
|
Nyaa.py
|
Nyaa.py
|
from bs4 import BeautifulSoup
import re
import requests
import sys
def _retry_on_fail(req, *args, **kwargs):
try:
r = req(*args, **kwargs)
if r.status_code not in range(100, 399):
print('Connection error, retrying... (HTTP {})'.format(r.status_code), file=sys.stderr)
return _retry_on_fail(req, *args, **kwargs)
else:
return r
except requests.exceptions.ConnectionError as e:
print('Connection error, retrying... ({})'.format(e.args[0].args[1]), file=sys.stderr)
return _retry_on_fail(req, *args, **kwargs)
class Nyaa(object):
def __init__(self, url):
self.url = url
self.info_url = url + '?page=view&tid='
self.dl_url = url + '?page=download&tid='
@property
def last_entry(self):
r = requests.get(self.url)
if r.status_code not in range(100, 399):
print('Connection error. Nyaa might be down (HTTP {}).'.format(r.status_code), file=sys.stderr)
sys.exit(1)
soup = BeautifulSoup(r.text)
link = soup.find('tr', class_='tlistrow').find('td', class_='tlistname').a['href']
return int(re.search('tid=([0-9]*)', link).group(1))
class NyaaEntry(object):
def __init__(self, nyaa, nyaa_id):
self.info_url = '{}{}'.format(nyaa.info_url, nyaa_id)
self.download_url = '{}{}&magnet=1'.format(nyaa.dl_url, nyaa_id)
r = _retry_on_fail(requests.get, self.info_url)
setattr(r, 'encoding', 'utf-8')
self.page = BeautifulSoup(r.text)
if self.page.find('div', class_='content').text == '\xa0The torrent you are looking for does not appear to be in the database.':
self.exists = False
else:
self.exists = True
@property
def category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[0].text
@property
def sub_category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[1].text
@property
def name(self):
return self.page.find('td', class_='viewtorrentname').text
@property
def time(self):
return self.page.find('td', class_='vtop').text.split(', ')
@property
def status(self):
_status = self.page.find('div', class_=re.compile('content'))['class']
if 'trusted' in _status:
return 'trusted'
elif 'remake' in _status:
return 'remake'
elif 'aplus' in _status:
return 'a+'
else:
return 'normal'
@property
def hash(self):
r = _retry_on_fail(requests.head, self.download_url)
if 'Location' in r.headers:
return re.search(r'magnet:\?xt=urn:btih:(.*)&tr=', r.headers['Location']).group(1).upper()
else:
return None
|
from bs4 import BeautifulSoup
import re
import requests
import sys
def retry_if_fails(req, *args, **kwargs):
try:
r = req(*args, **kwargs)
if r.status_code not in range(100, 399):
print('Connection error, retrying... (HTTP {})'.format(r.status_code), file=sys.stderr)
return retry_if_fails(req, *args, **kwargs)
else:
return r
except requests.exceptions.ConnectionError as e:
print('Connection error, retrying... ({})'.format(e.args[0].args[1]), file=sys.stderr)
return retry_if_fails(req, *args, **kwargs)
class Nyaa(object):
def __init__(self, url):
self.url = url
self.info_url = url + '?page=view&tid='
self.dl_url = url + '?page=download&tid='
@property
def last_entry(self):
r = requests.get(self.url)
if r.status_code not in range(100, 399):
print('Connection error. Nyaa might be down (HTTP {}).'.format(r.status_code), file=sys.stderr)
sys.exit(1)
soup = BeautifulSoup(r.text)
link = soup.find('tr', class_='tlistrow').find('td', class_='tlistname').a['href']
return int(re.search('tid=([0-9]*)', link).group(1))
class NyaaEntry(object):
def __init__(self, nyaa, nyaa_id):
self.info_url = '{}{}'.format(nyaa.info_url, nyaa_id)
self.download_url = '{}{}&magnet=1'.format(nyaa.dl_url, nyaa_id)
r = retry_if_fails(requests.get, self.info_url)
setattr(r, 'encoding', 'utf-8')
self.page = BeautifulSoup(r.text)
if self.page.find('div', class_='content').text == '\xa0The torrent you are looking for does not appear to be in the database.':
self.exists = False
else:
self.exists = True
@property
def category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[0].text
@property
def sub_category(self):
return self.page.find('td', class_='viewcategory').find_all('a')[1].text
@property
def name(self):
return self.page.find('td', class_='viewtorrentname').text
@property
def time(self):
return self.page.find('td', class_='vtop').text.split(', ')
@property
def status(self):
_status = self.page.find('div', class_=re.compile('content'))['class']
if 'trusted' in _status:
return 'trusted'
elif 'remake' in _status:
return 'remake'
elif 'aplus' in _status:
return 'a+'
else:
return 'normal'
@property
def hash(self):
r = retry_if_fails(requests.head, self.download_url)
if 'Location' in r.headers:
return re.search(r'magnet:\?xt=urn:btih:(.*)&tr=', r.headers['Location']).group(1).upper()
else:
return None
|
mit
|
Python
|
10ceb00e249635868fb55c1ae1668ddb35b03bc3
|
Update demo
|
bameda/python-taiga,erikw/python-taiga,nephila/python-taiga,mlq/python-taiga,erikw/python-taiga,mlq/python-taiga,bameda/python-taiga
|
demo.py
|
demo.py
|
# -*- coding: utf-8 -*-
from taiga import TaigaAPI
from taiga.exceptions import TaigaException
api = TaigaAPI(
host='http://127.0.0.1:8000'
)
api.auth(
username='admin',
password='123123'
)
print (api.me())
new_project = api.projects.create('TEST PROJECT', 'TESTING API')
new_project.name = 'TEST PROJECT 3'
new_project.update()
jan_feb_milestone = new_project.add_milestone(
'New milestone jan feb', '2015-01-26', '2015-02-26'
)
userstory = new_project.add_user_story(
'New Story', description='Blablablabla',
milestone=jan_feb_milestone.id
)
userstory.attach('README.md')
userstory.add_task('New Task 2',
new_project.task_statuses[0].id
).attach('README.md')
print (userstory.list_tasks())
newissue = new_project.add_issue(
'New Issue',
new_project.priorities.get(name='High').id,
new_project.issue_statuses.get(name='New').id,
new_project.issue_types.get(name='Bug').id,
new_project.severities.get(name='Minor').id,
description='Bug #5'
).attach('README.md')
projects = api.projects.list()
print (projects)
stories = api.user_stories.list()
print (stories)
print (api.history.user_story.get(stories[0].id))
try:
projects[0].star()
except TaigaException:
projects[0].like()
api.milestones.list()
projects = api.projects.list()
print (projects)
another_new_project = projects.get(name='TEST PROJECT 3')
print (another_new_project)
users = api.users.list()
print (users)
print (api.search(projects.get(name='TEST PROJECT 3').id, 'New').user_stories[0].subject)
print new_project.add_issue_attribute(
'Device', description='(iPad, iPod, iPhone, Desktop, etc.)'
)
print(new_project.roles)
memberships = new_project.list_memberships()
new_project.add_role('New role', permissions=["add_issue", "modify_issue"])
new_project.add_membership('[email protected]', new_project.roles[0].id)
for membership in memberships:
print (membership.role_name)
|
# -*- coding: utf-8 -*-
from taiga import TaigaAPI
api = TaigaAPI(
host='http://127.0.0.1:8000'
)
api.auth(
username='admin',
password='123123'
)
print (api.me())
new_project = api.projects.create('TEST PROJECT', 'TESTING API')
new_project.name = 'TEST PROJECT 3'
new_project.update()
jan_feb_milestone = new_project.add_milestone(
'New milestone jan feb', '2015-01-26', '2015-02-26'
)
userstory = new_project.add_user_story(
'New Story', description='Blablablabla',
milestone=jan_feb_milestone.id
)
userstory.attach('README.md')
userstory.add_task('New Task 2',
new_project.task_statuses[0].id
).attach('README.md')
print (userstory.list_tasks())
newissue = new_project.add_issue(
'New Issue',
new_project.priorities.get(name='High').id,
new_project.issue_statuses.get(name='New').id,
new_project.issue_types.get(name='Bug').id,
new_project.severities.get(name='Minor').id,
description='Bug #5'
).attach('README.md')
projects = api.projects.list()
print (projects)
for user in new_project.users:
print (user)
stories = api.user_stories.list()
print (stories)
print (api.history.user_story.get(stories[0].id))
projects[0].star()
api.milestones.list()
projects = api.projects.list()
print (projects)
another_new_project = projects.get(name='TEST PROJECT 3')
print (another_new_project)
users = api.users.list()
print (users)
print (api.search(projects.get(name='TEST PROJECT 3').id, 'New').user_stories[0].subject)
print new_project.add_issue_attribute(
'Device', description='(iPad, iPod, iPhone, Desktop, etc.)'
)
print(new_project.roles)
memberships = new_project.list_memberships()
new_project.add_role('New role', permissions=["add_issue", "modify_issue"])
new_project.add_membership('[email protected]', new_project.roles[0].id)
for membership in memberships:
print (membership.role_name)
|
mit
|
Python
|
7692c4210289af68ad7952ddca89f70d250a26ed
|
Change base_directory location
|
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
|
great_expectations/data_context/datasource/pandas_source.py
|
great_expectations/data_context/datasource/pandas_source.py
|
import pandas as pd
import os
from .datasource import Datasource
from .filesystem_path_generator import FilesystemPathGenerator
from ...dataset.pandas_dataset import PandasDataset
class PandasCSVDatasource(Datasource):
"""
A PandasDataSource makes it easy to create, manage and validate expectations on
Pandas dataframes.
Use with the FilesystemPathGenerator for simple cases.
"""
def __init__(self, name, type_, data_context=None, generators=None, read_csv_kwargs=None):
if generators is None:
generators = {
"default": {"type": "filesystem", "base_directory": "/data"}
}
super(PandasCSVDatasource, self).__init__(name, type_, data_context, generators)
self._datasource_config.update(
{
"read_csv_kwargs": read_csv_kwargs or {}
}
)
self._build_generators()
def _get_generator_class(self, type_):
if type_ == "filesystem":
return FilesystemPathGenerator
else:
raise ValueError("Unrecognized BatchGenerator type %s" % type_)
def _get_data_asset(self, data_asset_name, batch_kwargs, expectations_config):
full_path = os.path.join(batch_kwargs["path"])
df = pd.read_csv(full_path, **self._datasource_config["read_csv_kwargs"])
return PandasDataset(df,
expectations_config=expectations_config,
data_context=self._data_context,
data_asset_name=data_asset_name,
batch_kwargs=batch_kwargs)
|
import pandas as pd
import os
from .datasource import Datasource
from .filesystem_path_generator import FilesystemPathGenerator
from ...dataset.pandas_dataset import PandasDataset
class PandasCSVDatasource(Datasource):
"""
A PandasDataSource makes it easy to create, manage and validate expectations on
Pandas dataframes.
Use with the FilesystemPathGenerator for simple cases.
"""
def __init__(self, name, type_, data_context=None, generators=None, base_directory="/data", read_csv_kwargs=None):
self._base_directory = base_directory
if generators is None:
generators = {
"default": {"type": "filesystem", "base_directory": "/data"}
}
super(PandasCSVDatasource, self).__init__(name, type_, data_context, generators)
self._datasource_config.update(
{
"base_directory": base_directory,
"read_csv_kwargs": read_csv_kwargs or {}
}
)
self._build_generators()
def _get_generator_class(self, type_):
if type_ == "filesystem":
return FilesystemPathGenerator
else:
raise ValueError("Unrecognized BatchGenerator type %s" % type_)
def _get_data_asset(self, data_asset_name, batch_kwargs, expectations_config):
full_path = os.path.join(batch_kwargs["path"])
df = pd.read_csv(full_path, **self._datasource_config["read_csv_kwargs"])
return PandasDataset(df,
expectations_config=expectations_config,
data_context=self._data_context,
data_asset_name=data_asset_name,
batch_kwargs=batch_kwargs)
|
apache-2.0
|
Python
|
b69289c62a5be3a523b4d32aec2b6d790dc95f0d
|
Add compare functions
|
abpolym/amit
|
amit.py
|
amit.py
|
import hashlib, ssdeep
def hash_ssdeep(inbytes):
return ssdeep.hash(inbytes)
def hash_md5(inbytes):
m = hashlib.md5()
m.update(inbytes)
return m.hexdigest()
def hash_sha1(inbytes):
m = hashlib.sha1()
m.update(inbytes)
return m.hexdigest()
def hash_sha256(inbytes):
m = hashlib.sha256()
m.update(inbytes)
return m.hexdigest()
def hash_all(inbytes):
a = []
a.append(hash_ssdeep(inbytes))
a.append(hash_md5(inbytes))
a.append(hash_sha1(inbytes))
a.append(hash_sha256(inbytes))
return a
def compare_ssdeep(hash1, hash2):
return ssdeep.compare(hash1, hash2)
def compare_md5(hash1, hash2):
return hash1 == hash2
def compare_sha1(hash2, hash1):
return hash1 == hash2
def compare_sha256(hash1, hash2):
return hash1 == hash2
def compare_all(hasharray1, hasharray2):
if len(hasharray1)!=len(hasharray2): return None
a = []
a.append(compare_ssdeep(hasharray1[0], hasharray2[0]))
a.append(compare_md5(hasharray1[1], hasharray2[1]))
a.append(compare_sha1(hasharray1[2], hasharray2[2]))
a.append(compare_sha256(hasharray1[3], hasharray2[3]))
return a
testdata = '\x90'*512*2
testdata2 = 'mod'+'\x90'*512*2
a1 = hash_all(testdata)
a2 = hash_all(testdata2)
for i in a1: print i
for i in a2: print i
print compare_all(a1, a2)
|
import hashlib, ssdeep
def hash_ssdeep(inbytes):
return ssdeep.hash(inbytes)
def hash_md5(inbytes):
m = hashlib.md5()
m.update(inbytes)
return m.hexdigest()
def hash_sha1(inbytes):
m = hashlib.sha1()
m.update(inbytes)
return m.hexdigest()
def hash_sha256(inbytes):
m = hashlib.sha256()
m.update(inbytes)
return m.hexdigest()
def hash_print_all(inbytes):
print hash_ssdeep(inbytes)
print hash_md5(inbytes)
print hash_sha1(inbytes)
print hash_sha256(inbytes)
testdata = '\x90'*512*2
testdata2 = 'mod\x90'*512*2
hash_print_all(testdata)
hash_print_all(testdata2)
|
mit
|
Python
|
d5e41dfaff393a0649336ef92d7b7917a7e0122d
|
fix allowed_hosts settings bug
|
chenders/hours,chenders/hours,chenders/hours
|
hours/settings.py
|
hours/settings.py
|
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECRET_KEY will be automatically generated and saved into local_settings.py on first import, if not already
# present
SECRET_KEY = ''
DEBUG = False
ALLOWED_HOSTS = [
'localhost'
]
TEMPLATE_DEBUG = True
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sources',
'core',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'hours.urls'
WSGI_APPLICATION = 'hours.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from hours_settings import *
try:
from local_settings import *
except ImportError:
pass
if SECRET_KEY == '':
print 'Creating SECRET_KEY..'
from django.utils.crypto import get_random_string
settings_dir = os.path.dirname(__file__)
with open(os.path.join(settings_dir, 'local_settings.py'), 'a') as local_settings_fd:
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)
local_settings_fd.write('\n%s\n' % "SECRET_KEY = '%s'" % SECRET_KEY)
|
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECRET_KEY will be automatically generated and saved into local_settings.py on first import, if not already
# present
SECRET_KEY = ''
DEBUG = False
ALLOWED_HOSTS = [
'localhost'
]
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sources',
'core',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'hours.urls'
WSGI_APPLICATION = 'hours.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
from hours_settings import *
try:
from local_settings import *
except ImportError:
pass
if SECRET_KEY == '':
print 'Creating SECRET_KEY..'
from django.utils.crypto import get_random_string
settings_dir = os.path.dirname(__file__)
with open(os.path.join(settings_dir, 'local_settings.py'), 'a') as local_settings_fd:
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)
local_settings_fd.write('\n%s\n' % "SECRET_KEY = '%s'" % SECRET_KEY)
|
mit
|
Python
|
8c4590e19c7b39fe6562671f7d63651e736ffa49
|
debug print
|
synth3tk/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,josephbisch/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,bvisness/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,josephbisch/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,bdaroz/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,bvisness/the-blue-alliance,phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance
|
controllers/admin/admin_migration_controller.py
|
controllers/admin/admin_migration_controller.py
|
import os
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from controllers.base_controller import LoggedInHandler
from models.event import Event
from helpers.match_manipulator import MatchManipulator
def add_year(event_key):
logging.info(event_key)
matches = event_key.get().matches
if matches:
for match in matches:
match.year = int(match.event.id()[:4])
match.dirty = True
MatchManipulator.createOrUpdate(match)
class AdminMigration(LoggedInHandler):
def get(self):
self._require_admin()
path = os.path.join(os.path.dirname(__file__), '../../templates/admin/migration.html')
self.response.out.write(template.render(path, self.template_values))
class AdminMigrationAddMatchYear(LoggedInHandler):
def get(self):
self._require_admin()
for year in range(1992, 2016):
event_keys = Event.query(Event.year == year).fetch(keys_only=True)
for event_key in event_keys:
deferred.defer(add_year, event_key, _queue="admin")
self.response.out.write(event_keys)
|
import os
from google.appengine.ext import ndb
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from controllers.base_controller import LoggedInHandler
from models.event import Event
from helpers.match_manipulator import MatchManipulator
def add_year(event_key):
matches = event_key.get().matches
if matches:
for match in matches:
match.year = int(match.event.id()[:4])
match.dirty = True
MatchManipulator.createOrUpdate(match)
class AdminMigration(LoggedInHandler):
def get(self):
self._require_admin()
path = os.path.join(os.path.dirname(__file__), '../../templates/admin/migration.html')
self.response.out.write(template.render(path, self.template_values))
class AdminMigrationAddMatchYear(LoggedInHandler):
def get(self):
self._require_admin()
for year in range(1992, 2016):
event_keys = Event.query(Event.year == year).fetch(keys_only=True)
for event_key in event_keys:
deferred.defer(add_year, event_key, _queue="admin")
self.response.out.write(event_keys)
|
mit
|
Python
|
895dfda101665e0f70e96d549443f9fe777de1e7
|
Add support for multiple urls per method, auto create method routers
|
shaunstanislaus/hug,janusnic/hug,timothycrosley/hug,yasoob/hug,timothycrosley/hug,MuhammadAlkarouri/hug,gbn972/hug,STANAPO/hug,gbn972/hug,jean/hug,alisaifee/hug,origingod/hug,janusnic/hug,MuhammadAlkarouri/hug,jean/hug,giserh/hug,STANAPO/hug,origingod/hug,philiptzou/hug,MuhammadAlkarouri/hug,shaunstanislaus/hug,philiptzou/hug,yasoob/hug,timothycrosley/hug,giserh/hug,alisaifee/hug
|
hug/decorators.py
|
hug/decorators.py
|
from functools import wraps, partial
from collections import OrderedDict
import sys
from hug.run import server
import hug.output_format
from falcon import HTTP_METHODS, HTTP_BAD_REQUEST
def call(urls, accept=HTTP_METHODS, output=hug.output_format.json, example=None):
if isinstance(urls, str):
urls = (urls, )
def decorator(api_function):
module = sys.modules[api_function.__module__]
def interface(request, response):
input_parameters = request.params
errors = {}
for key, type_handler in api_function.__annotations__.items():
try:
input_parameters[key] = type_handler(input_parameters[key])
except Exception as error:
errors[key] = str(error)
if errors:
response.data = output({"errors": errors})
response.status = HTTP_BAD_REQUEST
return
input_parameters['request'], input_parameters['response'] = (request, response)
response.data = output(api_function(**input_parameters))
if not 'HUG' in module.__dict__:
def api_auto_instantiate(*kargs, **kwargs):
module.HUG = server(module)
return module.HUG(*kargs, **kwargs)
module.HUG = api_auto_instantiate
module.HUG_API_CALLS = OrderedDict()
for url in urls:
handlers = module.HUG_API_CALLS.setdefault(url, {})
for method in accept:
handlers["on_{0}".format(method.lower())] = interface
api_function.interface = interface
interface.api_function = api_function
interface.output_format = output
interface.example = example
return api_function
return decorator
for method in HTTP_METHODS:
globals()[method.lower()] = partial(call, accept=(method, ))
|
from functools import wraps
from collections import OrderedDict
import sys
from hug.run import server
import hug.output_format
from falcon import HTTP_METHODS, HTTP_BAD_REQUEST
def call(url, accept=HTTP_METHODS, output=hug.output_format.json):
def decorator(api_function):
module = sys.modules[api_function.__module__]
def interface(request, response):
input_parameters = request.params
errors = {}
for key, type_handler in api_function.__annotations__.items():
try:
input_parameters[key] = type_handler(input_parameters[key])
except Exception as error:
errors[key] = str(error)
if errors:
response.data = output({"errors": errors})
response.status = HTTP_BAD_REQUEST
return
input_parameters['request'], input_parameters['response'] = (request, response)
response.data = output(api_function(**input_parameters))
if not 'HUG' in module.__dict__:
def api_auto_instantiate(*kargs, **kwargs):
module.HUG = server(module)
return module.HUG(*kargs, **kwargs)
module.HUG = api_auto_instantiate
module.HUG_API_CALLS = OrderedDict()
for method in accept:
module.HUG_API_CALLS.setdefault(url, {})["on_{0}".format(method.lower())] = interface
api_function.interface = interface
interface.api_function = api_function
return api_function
return decorator
def get(url):
return call(url=url, accept=('GET', ))
def post(url):
return call(url=url, accept=('POST', ))
def put(url):
return call(url=url, acccept=('PUT', ))
def delete(url):
return call(url=url, accept=('DELETE', ))
|
mit
|
Python
|
66dd418d481bfc5d3d910823856bdcea8d304a87
|
allow to pass a different root-path
|
hwaf/hwaf,hwaf/hwaf
|
hwaf-cmtcompat.py
|
hwaf-cmtcompat.py
|
# -*- python -*-
# stdlib imports
import os
import os.path as osp
import sys
# waf imports ---
import waflib.Options
import waflib.Utils
import waflib.Logs as msg
from waflib.Configure import conf
_heptooldir = osp.dirname(osp.abspath(__file__))
# add this directory to sys.path to ease the loading of other hepwaf tools
if not _heptooldir in sys.path: sys.path.append(_heptooldir)
### ---------------------------------------------------------------------------
@conf
def _cmt_get_srcs_lst(self, source, root=None):
'''hack to support implicit src/*cxx in CMT req-files'''
if root is None:
root = self.root
if isinstance(source, (list, tuple)):
src = []
for s in source:
src.extend(self._cmt_get_srcs_lst(s, root))
return src
elif not isinstance(source, type('')):
## a waflib.Node ?
return [source]
else:
src_node = root.find_dir('src')
srcs = root.ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.ant_glob(source)
pass
if not srcs:
# ok, try again from bldnode
src_node = root.find_dir('src')
srcs = root.get_bld().ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.get_bld().ant_glob(source)
pass
if not srcs:
# ok, maybe the output of a not-yet executed task
srcs = source
pass
pass
return waflib.Utils.to_list(srcs)
self.fatal("unreachable")
return []
|
# -*- python -*-
# stdlib imports
import os
import os.path as osp
import sys
# waf imports ---
import waflib.Options
import waflib.Utils
import waflib.Logs as msg
from waflib.Configure import conf
_heptooldir = osp.dirname(osp.abspath(__file__))
# add this directory to sys.path to ease the loading of other hepwaf tools
if not _heptooldir in sys.path: sys.path.append(_heptooldir)
### ---------------------------------------------------------------------------
@conf
def _cmt_get_srcs_lst(self, source):
'''hack to support implicit src/*cxx in CMT req-files'''
if isinstance(source, (list, tuple)):
src = []
for s in source:
src.extend(self._cmt_get_srcs_lst(s))
return src
elif not isinstance(source, type('')):
## a waflib.Node ?
return [source]
else:
src_node = self.path.find_dir('src')
srcs = self.path.ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.ant_glob(source)
pass
if not srcs:
# ok, try again from bldnode
src_node = self.path.find_dir('src')
srcs = self.path.get_bld().ant_glob(source)
if srcs:
# OK. finders, keepers.
pass
elif src_node:
# hack to mimick CMT's default (to take sources from src)
srcs = src_node.get_bld().ant_glob(source)
pass
if not srcs:
# ok, maybe the output of a not-yet executed task
srcs = source
pass
pass
return waflib.Utils.to_list(srcs)
self.fatal("unreachable")
return []
|
bsd-3-clause
|
Python
|
70ea214d8e258e4e7c95b9ba7948dde13e28a878
|
Make screengrab_torture_test test more functions
|
ludios/Desktopmagic
|
desktopmagic/scripts/screengrab_torture_test.py
|
desktopmagic/scripts/screengrab_torture_test.py
|
from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage, getDisplaysAsImages, getRectAsImage
def main():
print """\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
into at 256 colors.
"""
while True:
try:
getScreenAsImage()
print "S",
except GrabFailed, e:
print e
try:
getDisplaysAsImages()
print "D",
except GrabFailed, e:
print e
try:
getRectAsImage((0, 0, 1, 1))
print "R",
except GrabFailed, e:
print e
if __name__ == '__main__':
main()
|
from desktopmagic.screengrab_win32 import GrabFailed, getScreenAsImage
def main():
print """\
This program helps you test whether screengrab_win32 has memory leaks
and other problems. It takes a screenshot repeatedly and discards it.
Open Task Manager and make sure Physical Memory % is not ballooning.
Memory leaks might not be blamed on the python process itself (which
will show low memory usage).
Lock the workstation for a few minutes; make sure there are no leaks
and that there are no uncaught exceptions here.
Repeat above after RDPing into the workstation and minimizing RDP;
this is like disconnecting the monitor.
Change your color depth settings. Add and remove monitors. RDP
into at 256 colors.
"""
while True:
try:
getScreenAsImage()
print ".",
except GrabFailed, e:
print e
if __name__ == '__main__':
main()
|
mit
|
Python
|
9d1dc9c2c649bd117c2cd38cf664e34820f387ea
|
update docstring in fwhm.py
|
bennomeier/pyNMR,kourk0am/pyNMR
|
fwhm.py
|
fwhm.py
|
import numpy as np
def fwhm(x,y, silence = False):
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
if not silence:
print "Max: " + str(maxVal)
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
freqPoints = []
for k in range(len(biggerCondition)-1):
if biggerCondition[k+1] != biggerCondition[k]:
changePoints.append(k)
if len(changePoints) > 2:
if not silence:
print "WARNING: THE FWHM IS LIKELY TO GIVE INCORRECT VALUES"
#interpolate between points.
print "ChangePoints: ", changePoints
for k in changePoints:
# do a polyfit
# with the points before and after the point where the change occurs.
# note that here we are fitting the x values as a function of the y values.
# then we can use the polynom to compute the value of x at the threshold, i.e. at maxVal50.
yPolyFit = x[k-1:k+2]
xPolyFit = y[k-1:k+2]
z = np.polyfit(xPolyFit,yPolyFit,2)
p = np.poly1d(z)
print p
freq = p(maxVal50)
freqPoints.append(freq)
if len(freqPoints) == 2:
value = freqPoints[1] - freqPoints[0]
else:
value = None
print sorted(freqPoints)
return value
def main():
x = np.linspace(-10,10,100)
sigma = 2
y = 3.1*np.exp(-x**2/(2*sigma**2))
print "OK"
fwhmVal = fwhm(x,y)
print "FWHM: " + str(fwhmVal)
print str(2*np.sqrt(2*np.log(2))*2)
if __name__ == "__main__":
main()
|
import numpy as np
def fwhm(x,y, silence = False):
maxVal = np.max(y)
maxVal50 = 0.5*maxVal
if not silence:
print "Max: " + str(maxVal)
#this is to detect if there are multiple values
biggerCondition = [a > maxVal50 for a in y]
changePoints = []
freqPoints = []
for k in range(len(biggerCondition)-1):
if biggerCondition[k+1] != biggerCondition[k]:
changePoints.append(k)
if len(changePoints) > 2:
if not silence:
print "WARNING: THE FWHM IS LIKELY TO GIVE INCORRECT VALUES"
#interpolate between points.
print "ChangePoints: ", changePoints
for k in changePoints:
# do a polyfit
# with the points before and after the point where the change occurs.
# note that here we are fitting the frequency as a function of the return loss.
# then we can use the polynom to compute the frequency at returnloss = threshold.
yPolyFit = x[k-1:k+2]
xPolyFit = y[k-1:k+2]
z = np.polyfit(xPolyFit,yPolyFit,2)
p = np.poly1d(z)
print p
freq = p(maxVal50)
freqPoints.append(freq)
if len(freqPoints) == 2:
value = freqPoints[1] - freqPoints[0]
else:
value = None
print sorted(freqPoints)
return value
def main():
x = np.linspace(-10,10,100)
sigma = 2
y = 3.1*np.exp(-x**2/(2*sigma**2))
print "OK"
fwhmVal = fwhm(x,y)
print "FWHM: " + str(fwhmVal)
print str(2*np.sqrt(2*np.log(2))*2)
if __name__ == "__main__":
main()
|
mit
|
Python
|
161a1cdddd79df7126d6adf1117d51e679d1746c
|
Change --command option in "docker" to a positional argument
|
mnieber/dodo_commands
|
dodo_commands/extra/standard_commands/docker.py
|
dodo_commands/extra/standard_commands/docker.py
|
"""This command opens a bash shell in the docker container."""
from . import DodoCommand
class Command(DodoCommand): # noqa
decorators = ["docker", ]
def add_arguments_imp(self, parser): # noqa
parser.add_argument('command', nargs='?')
def handle_imp(self, command, **kwargs): # noqa
self.runcmd(
["/bin/bash"] + (["-c", command] if command else []),
cwd=self.get_config("/DOCKER/default_cwd", None))
|
"""This command opens a bash shell in the docker container."""
from . import DodoCommand
class Command(DodoCommand): # noqa
decorators = ["docker", ]
def add_arguments_imp(self, parser): # noqa
parser.add_argument('--command', default="")
def handle_imp(self, command, **kwargs): # noqa
self.runcmd(
["/bin/bash"] + (["-c", command] if command else []),
cwd=self.get_config("/DOCKER/default_cwd", None))
|
mit
|
Python
|
36063d227f7cd3ededdc99b23b0c7911f2233df2
|
Add available params in metering labels client's comment
|
cisco-openstack/tempest,Tesora/tesora-tempest,Juniper/tempest,vedujoshi/tempest,sebrandon1/tempest,masayukig/tempest,sebrandon1/tempest,Tesora/tesora-tempest,masayukig/tempest,cisco-openstack/tempest,Juniper/tempest,openstack/tempest,vedujoshi/tempest,openstack/tempest
|
tempest/lib/services/network/metering_labels_client.py
|
tempest/lib/services/network/metering_labels_client.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 tempest.lib.services.network import base
class MeteringLabelsClient(base.BaseNetworkClient):
def create_metering_label(self, **kwargs):
"""Creates an L3 metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
createMeteringLabel
"""
uri = '/metering/metering-labels'
post_data = {'metering_label': kwargs}
return self.create_resource(uri, post_data)
def show_metering_label(self, metering_label_id, **fields):
"""Shows details for a metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#showMeteringLabel
"""
uri = '/metering/metering-labels/%s' % metering_label_id
return self.show_resource(uri, **fields)
def delete_metering_label(self, metering_label_id):
"""Deletes an L3 metering label.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
deleteMeteringLabel
"""
uri = '/metering/metering-labels/%s' % metering_label_id
return self.delete_resource(uri)
def list_metering_labels(self, **filters):
"""Lists all L3 metering labels that belong to the tenant.
Available params: see http://developer.openstack.org/
api-ref-networking-v2-ext.html#
listMeteringLabels
"""
uri = '/metering/metering-labels'
return self.list_resources(uri, **filters)
|
# 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 tempest.lib.services.network import base
class MeteringLabelsClient(base.BaseNetworkClient):
def create_metering_label(self, **kwargs):
uri = '/metering/metering-labels'
post_data = {'metering_label': kwargs}
return self.create_resource(uri, post_data)
def show_metering_label(self, metering_label_id, **fields):
uri = '/metering/metering-labels/%s' % metering_label_id
return self.show_resource(uri, **fields)
def delete_metering_label(self, metering_label_id):
uri = '/metering/metering-labels/%s' % metering_label_id
return self.delete_resource(uri)
def list_metering_labels(self, **filters):
uri = '/metering/metering-labels'
return self.list_resources(uri, **filters)
|
apache-2.0
|
Python
|
93870690f17a4baddeb33549a1f6c67eeee1abe0
|
Increase cache tile duration from 6 hours to 1 week
|
alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,alkadis/vcv,phihag/adhocracy
|
src/adhocracy/lib/tiles/util.py
|
src/adhocracy/lib/tiles/util.py
|
import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 7 * 86400)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
|
import logging
from time import time
from pylons import tmpl_context as c
from adhocracy import config
from adhocracy.lib.cache import memoize
log = logging.getLogger(__name__)
class BaseTile(object):
'''
Base class for tiles
'''
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
from adhocracy.lib import templating
begin_time = time()
def render():
return templating.render_def(template_name, def_name,
tile=tile, **kwargs)
rendered = ""
if cached and config.get_bool('adhocracy.cache_tiles'):
@memoize('tile_cache' + template_name + def_name, 86400 / 4)
def _cached(**kwargs):
return render()
rendered = _cached(locale=c.locale, **kwargs)
else:
rendered = render()
if False:
log.debug("Rendering tile %s:%s took %sms" % (
template_name, def_name, (time() - begin_time) * 1000))
return rendered
|
agpl-3.0
|
Python
|
d5691c8031a32e0cfadc74e9fffad8a9e04bc63c
|
enable search navbar entry in production
|
MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,MidAtlanticPortal/marco-portal2,Ecotrust/marineplanner-core
|
portal/base/context_processors.py
|
portal/base/context_processors.py
|
from django.conf import settings
def search_disabled(request):
"""Facility for disabling search functionality.
This may be used in the future to automatically disable search if the search
backend goes down.
"""
return dict(SEARCH_DISABLED=False)
# return dict(SEARCH_DISABLED=not settings.DEBUG)
|
from django.conf import settings
def search_disabled(request):
"""Facility for disabling search functionality.
This may be used in the future to automatically disable search if the search
backend goes down.
"""
return dict(SEARCH_DISABLED=not settings.DEBUG)
|
isc
|
Python
|
87b9910a30cb915f5b99a17b0b49570b0027e665
|
load help module
|
shortdudey123/gbot
|
gbot.py
|
gbot.py
|
#!/usr/bin/env python
# =============================================================================
# file = gbot.py
# description = IRC bot
# author = GR <https://github.com/shortdudey123>
# create_date = 2014-07-09
# mod_date = 2014-07-09
# version = 0.1
# usage = called as a class
# notes =
# python_ver = 2.7.6
# =============================================================================
import src.bot as bot
__IDENTIFY__ = ''
if __name__ == "__main__":
gbot = bot.IRCBot(server="chat.freenode.com", nick="grbot", port=6667, realName='gbot', identify=__IDENTIFY__, debug=True, connectDelay=4, identVerifyCall='ACC')
gbot.setDefaultChannels({'##gbot': ''})
gbot.addAdmin("shortdudey123")
gbot.loadModules(['opme', 'coreVersion', 'moduleInfo', 'help'])
gbot.run()
|
#!/usr/bin/env python
# =============================================================================
# file = gbot.py
# description = IRC bot
# author = GR <https://github.com/shortdudey123>
# create_date = 2014-07-09
# mod_date = 2014-07-09
# version = 0.1
# usage = called as a class
# notes =
# python_ver = 2.7.6
# =============================================================================
import src.bot as bot
__IDENTIFY__ = ''
if __name__ == "__main__":
gbot = bot.IRCBot(server="chat.freenode.com", nick="grbot", port=6667, realName='gbot', identify=__IDENTIFY__, debug=True, connectDelay=4, identVerifyCall='ACC')
gbot.setDefaultChannels({'##gbot': ''})
gbot.addAdmin("shortdudey123")
gbot.loadModules(['opme', 'coreVersion', 'moduleInfo'])
gbot.run()
|
apache-2.0
|
Python
|
9f5afd72bf6dbb44ba764f6731c6313f0cb94bce
|
Use default outputs in shortcuts/utils.py
|
jonathanslenders/python-prompt-toolkit
|
prompt_toolkit/shortcuts/utils.py
|
prompt_toolkit/shortcuts/utils.py
|
from __future__ import unicode_literals
from prompt_toolkit.output.defaults import get_default_output
from prompt_toolkit.renderer import print_formatted_text as renderer_print_formatted_text
from prompt_toolkit.styles import default_style, BaseStyle
import six
__all__ = (
'print_formatted_text',
'clear',
'set_title',
'clear_title',
)
def print_formatted_text(formatted_text, style=None, output=None):
"""
Print a list of (style_str, text) tuples in the given style to the output.
E.g.::
style = Style.from_dict({
'hello': '#ff0066',
'world': '#884444 italic',
})
fragments = [
('class:hello', 'Hello'),
('class:world', 'World'),
]
print_formatted_text(fragments, style=style)
If you want to print a list of Pygments tokens, use
``prompt_toolkit.style.token_list_to_formatted_text`` to do the conversion.
:param text_fragments: List of ``(style_str, text)`` tuples.
:param style: :class:`.Style` instance for the color scheme.
"""
if style is None:
style = default_style()
assert isinstance(style, BaseStyle)
output = output or get_default_output()
renderer_print_formatted_text(output, formatted_text, style)
def clear():
"""
Clear the screen.
"""
out = get_default_output()
out.erase_screen()
out.cursor_goto(0, 0)
out.flush()
def set_title(text):
"""
Set the terminal title.
"""
assert isinstance(text, six.text_type)
output = get_default_output()
output.set_title(text)
def clear_title():
"""
Erase the current title.
"""
set_title('')
|
from __future__ import unicode_literals
from prompt_toolkit.output.defaults import create_output
from prompt_toolkit.renderer import print_formatted_text as renderer_print_formatted_text
from prompt_toolkit.styles import default_style, BaseStyle
import six
__all__ = (
'print_formatted_text',
'clear',
'set_title',
'clear_title',
)
def print_formatted_text(formatted_text, style=None, true_color=False, file=None):
"""
Print a list of (style_str, text) tuples in the given style to the output.
E.g.::
style = Style.from_dict({
'hello': '#ff0066',
'world': '#884444 italic',
})
fragments = [
('class:hello', 'Hello'),
('class:world', 'World'),
]
print_formatted_text(fragments, style=style)
If you want to print a list of Pygments tokens, use
``prompt_toolkit.style.token_list_to_formatted_text`` to do the conversion.
:param text_fragments: List of ``(style_str, text)`` tuples.
:param style: :class:`.Style` instance for the color scheme.
:param true_color: When True, use 24bit colors instead of 256 colors.
:param file: The output file. This can be `sys.stdout` or `sys.stderr`.
"""
if style is None:
style = default_style()
assert isinstance(style, BaseStyle)
output = create_output(true_color=true_color, stdout=file)
renderer_print_formatted_text(output, formatted_text, style)
def clear():
"""
Clear the screen.
"""
out = create_output()
out.erase_screen()
out.cursor_goto(0, 0)
out.flush()
def set_title(text):
"""
Set the terminal title.
"""
assert isinstance(text, six.text_type)
output = create_output()
output.set_title(text)
def clear_title():
"""
Erase the current title.
"""
set_title('')
|
bsd-3-clause
|
Python
|
2c350cbbd90afaab38223fdfe40737f72bf7974a
|
Set --device-type as required arg for harvest_tracking_email command.
|
ropable/resource_tracking,ropable/resource_tracking,ropable/resource_tracking
|
tracking/management/commands/harvest_tracking_email.py
|
tracking/management/commands/harvest_tracking_email.py
|
from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', dest='device_type', required=True, default=None,
help='Tracking device type, one of: iriditrak, dplus, spot, mp70')
def handle(self, *args, **options):
# Specify the device type to harvest from the mailbox.
device_type = None
if options['device_type'] and options['device_type'] in ('iriditrak', 'dplus', 'spot', 'mp70'):
device_type = options['device_type']
harvest_tracking_email(device_type)
|
from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', dest='device_type', default=None,
help='Tracking device type, one of: iriditrak, dplus, spot, mp70')
def handle(self, *args, **options):
# Specify the device type to harvest from the mailbox.
device_type = None
if options['device_type'] and options['device_type'] in ('iriditrak', 'dplus', 'spot', 'mp70'):
device_type = options['device_type']
harvest_tracking_email(device_type)
|
bsd-3-clause
|
Python
|
4d247da1ecd39bcd699a55b5387412a1ac9e1582
|
Split Energy and Environment, change Civil Liberties to Social Justice
|
texastribune/txlege84,texastribune/txlege84,texastribune/txlege84,texastribune/txlege84
|
txlege84/topics/management/commands/bootstraptopics.py
|
txlege84/topics/management/commands/bootstraptopics.py
|
from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics...')
topics = [
u'Budget & Taxes',
u'Business & Technology',
u'Criminal Justice',
u'Energy',
u'Environment',
u'Ethics',
u'Health & Human Services',
u'Higher Education',
u'Immigration & Border Security',
u'Public Education',
u'Social Justice',
u'Transportation',
]
for topic in topics:
Topic.objects.get_or_create(name=topic)
|
from django.core.management.base import BaseCommand
from topics.models import Topic
class Command(BaseCommand):
help = u'Bootstrap the topic lists in the database.'
def handle(self, *args, **kwargs):
self.load_topics()
def load_topics(self):
self.stdout.write(u'Loading hot list topics...')
topics = [
u'Budget & Taxes',
u'Business & Technology',
u'Civil Liberties',
u'Criminal Justice',
u'Energy & Environment',
u'Ethics',
u'Health & Human Services',
u'Higher Education',
u'Immigration & Border Security',
u'Public Education',
u'Transportation',
]
for topic in topics:
Topic.objects.get_or_create(name=topic)
|
mit
|
Python
|
2bf756404700f4c38e2f3895dfa8aba2d8dc13be
|
Refactor and remove char2int
|
jonathanstallings/data-structures
|
hash.py
|
hash.py
|
class HashTable(object):
"""docstring for HashTable"""
table_size = 0
entries_count = 0
alphabet_size = 52
def __init__(self, size=1024):
self.table_size = size
self.hashtable = [[] for i in range(size)]
def __repr__(self):
return "<HashTable: {}>".format(self.hashtable)
def __len__(self):
count = 0
for item in self.hashtable:
if len(item) != 0:
count += 1
return count
def hashing(self, key):
"""pass"""
hash_ = 0
for i, c in enumerate(key):
hash_ += pow(
self.alphabet_size, len(key) - i - 1) * ord(c)
return hash_ % self.table_size
def set(self, key, value):
if not isinstance(key, str):
raise TypeError('Only strings may be used as keys.')
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
del self.hashtable[hash_][i]
self.entries_count -= 1
self.hashtable[hash_].append((key, value))
self.entries_count += 1
def get(self, key):
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
return self.hashtable[hash_]
raise KeyError('Key not in hash table.')
if __name__ == '__main__':
pass
|
class HashTable(object):
"""docstring for HashTable"""
table_size = 0
entries_count = 0
alphabet_size = 52
def __init__(self, size=1024):
self.table_size = size
self.hashtable = [[] for i in range(size)]
def __repr__(self):
return "<HashTable: {}>".format(self.hashtable)
def __len__(self):
count = 0
for item in self.hashtable:
if len(item) != 0:
count += 1
return count
def char2int(self, char):
"""Convert a alpha character to an int."""
# offset for ASCII table
# if char >= 'A' and char <= 'Z':
# return ord(char) - 65
# elif char >= 'a' and char <= 'z':
# return ord(char) - 65 - 7
return ord(char)
def hashing(self, key):
"""pass"""
hash_ = 0
for i, c in enumerate(key):
hash_ += pow(
self.alphabet_size, len(key) - i - 1) * self.char2int(c)
return hash_ % self.table_size
def set(self, key, value):
if not isinstance(key, str):
raise TypeError('Only strings may be used as keys.')
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
del self.hashtable[hash_][i]
self.entries_count -= 1
self.hashtable[hash_].append((key, value))
self.entries_count += 1
def get(self, key):
hash_ = self.hashing(key)
for i, item in enumerate(self.hashtable[hash_]):
if item[0] == key:
return self.hashtable[hash_]
raise KeyError('Key not in hash table.')
if __name__ == '__main__':
pass
|
mit
|
Python
|
3039149ca20e9c472340495e4130e331d9c546b3
|
Fix nums assignment properly
|
prmcadam/calc
|
calc.py
|
calc.py
|
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a*b, nums)
if __name__ == '__main__':
command =sys.argv[1]
nums=map(float, sys.argv[2:])
if command=='add':
print add_all(nums)
if command=='multiply':
print multiply_all(nums)
|
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a*b, nums)
if __name__ == '__main__':
command =sys.argv[1]
nums=map(float(sys.argv[2:]))
if command=='add':
print add_all(nums)
if command=='multiply':
print multiply_all(nums)
|
bsd-3-clause
|
Python
|
fd8caec8567178abe09abc810f1e96bfc4bb531b
|
Fix bug in 'multiply' support
|
tanecious/calc
|
calc.py
|
calc.py
|
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__== '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(nums))
|
import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__== '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_all(sums))
|
bsd-3-clause
|
Python
|
183448b17cfd910444d3807da80ef8549622fce4
|
test the urltopath
|
arwineap/yumoter
|
init.py
|
init.py
|
import yumoter
yumoter = yumoter.yumoter('config/repos.json', '/home/aarwine/git/yumoter/repos')
yumoter.loadRepos("6.4", "wildwest")
a = yumoter._returnNewestByNameArch(["openssl"])
a = a[0]
print a
print "name", a.name
print "arch", a.arch
print "epoch", a.epoch
print "version", a.version
print "release", a.release
print "size", a.size
print "remote_url", a.remote_url
print yumoter._urlToPath(a.remote_url)
print yumoter._urlToPromoPath(a.remote_url)
b = yumoter.getDeps(a)
print "###"
for pkg in b:
print pkg
for dep in b[pkg]:
print "\t%s - %s" % (dep, dep.remote_url)
|
import yumoter
yumoter = yumoter.yumoter('config/repos.json', '/home/aarwine/git/yumoter/repos')
yumoter.loadRepos("6.4", "wildwest")
a = yumoter._returnNewestByNameArch(["openssl"])
a = a[0]
print a
print "name", a.name
print "arch", a.arch
print "epoch", a.epoch
print "version", a.version
print "release", a.release
print "size", a.size
print "remote_url", a.remote_url
print yumoter._urlToPromoPath(a.remote_url)
b = yumoter.getDeps(a)
print "###"
for pkg in b:
print pkg
for dep in b[pkg]:
print "\t%s - %s" % (dep, dep.remote_url)
|
mit
|
Python
|
27543f73244c7312ea511c7e00d9eecf7b7525e9
|
store model in self.model
|
kastnerkyle/pylearn2,hyqneuron/pylearn2-maxsom,JesseLivezey/plankton,fulmicoton/pylearn2,theoryno3/pylearn2,kastnerkyle/pylearn2,mclaughlin6464/pylearn2,lancezlin/pylearn2,jeremyfix/pylearn2,kastnerkyle/pylearn2,jeremyfix/pylearn2,alexjc/pylearn2,KennethPierce/pylearnk,caidongyun/pylearn2,junbochen/pylearn2,abergeron/pylearn2,chrish42/pylearn,fulmicoton/pylearn2,shiquanwang/pylearn2,KennethPierce/pylearnk,KennethPierce/pylearnk,junbochen/pylearn2,bartvm/pylearn2,bartvm/pylearn2,mclaughlin6464/pylearn2,skearnes/pylearn2,lisa-lab/pylearn2,lamblin/pylearn2,shiquanwang/pylearn2,junbochen/pylearn2,TNick/pylearn2,pombredanne/pylearn2,caidongyun/pylearn2,JesseLivezey/plankton,JesseLivezey/pylearn2,bartvm/pylearn2,ddboline/pylearn2,TNick/pylearn2,jamessergeant/pylearn2,junbochen/pylearn2,hantek/pylearn2,fishcorn/pylearn2,skearnes/pylearn2,nouiz/pylearn2,woozzu/pylearn2,matrogers/pylearn2,Refefer/pylearn2,lamblin/pylearn2,fyffyt/pylearn2,JesseLivezey/pylearn2,ashhher3/pylearn2,aalmah/pylearn2,matrogers/pylearn2,jamessergeant/pylearn2,theoryno3/pylearn2,caidongyun/pylearn2,shiquanwang/pylearn2,se4u/pylearn2,jeremyfix/pylearn2,fyffyt/pylearn2,pombredanne/pylearn2,w1kke/pylearn2,lisa-lab/pylearn2,cosmoharrigan/pylearn2,cosmoharrigan/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,CIFASIS/pylearn2,fyffyt/pylearn2,TNick/pylearn2,pombredanne/pylearn2,chrish42/pylearn,hantek/pylearn2,fishcorn/pylearn2,pkainz/pylearn2,daemonmaker/pylearn2,lamblin/pylearn2,Refefer/pylearn2,se4u/pylearn2,TNick/pylearn2,chrish42/pylearn,cosmoharrigan/pylearn2,KennethPierce/pylearnk,woozzu/pylearn2,w1kke/pylearn2,shiquanwang/pylearn2,se4u/pylearn2,sandeepkbhat/pylearn2,woozzu/pylearn2,se4u/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,Refefer/pylearn2,CIFASIS/pylearn2,mclaughlin6464/pylearn2,woozzu/pylearn2,chrish42/pylearn,hyqneuron/pylearn2-maxsom,ddboline/pylearn2,sandeepkbhat/pylearn2,pkainz/pylearn2,kastnerkyle/pylearn2,theoryno3/pylearn2,w1kke/pylearn2,mkraemer67/pylearn2,ddboline/pylearn2,goodfeli/pylearn2,lunyang/pylearn2,kose-y/pylearn2,cosmoharrigan/pylearn2,daemonmaker/pylearn2,sandeepkbhat/pylearn2,hyqneuron/pylearn2-maxsom,mkraemer67/pylearn2,fulmicoton/pylearn2,fishcorn/pylearn2,nouiz/pylearn2,lancezlin/pylearn2,JesseLivezey/pylearn2,nouiz/pylearn2,daemonmaker/pylearn2,kose-y/pylearn2,fishcorn/pylearn2,hantek/pylearn2,msingh172/pylearn2,pombredanne/pylearn2,caidongyun/pylearn2,JesseLivezey/plankton,fyffyt/pylearn2,lisa-lab/pylearn2,abergeron/pylearn2,hyqneuron/pylearn2-maxsom,abergeron/pylearn2,alexjc/pylearn2,kose-y/pylearn2,aalmah/pylearn2,mclaughlin6464/pylearn2,CIFASIS/pylearn2,JesseLivezey/pylearn2,CIFASIS/pylearn2,nouiz/pylearn2,mkraemer67/pylearn2,msingh172/pylearn2,ashhher3/pylearn2,lancezlin/pylearn2,alexjc/pylearn2,matrogers/pylearn2,Refefer/pylearn2,ashhher3/pylearn2,goodfeli/pylearn2,aalmah/pylearn2,lamblin/pylearn2,goodfeli/pylearn2,msingh172/pylearn2,jamessergeant/pylearn2,lunyang/pylearn2,aalmah/pylearn2,abergeron/pylearn2,lunyang/pylearn2,pkainz/pylearn2,lancezlin/pylearn2,alexjc/pylearn2,kose-y/pylearn2,skearnes/pylearn2,msingh172/pylearn2,fulmicoton/pylearn2,w1kke/pylearn2,JesseLivezey/plankton,lunyang/pylearn2,matrogers/pylearn2,bartvm/pylearn2,daemonmaker/pylearn2,theoryno3/pylearn2,mkraemer67/pylearn2,hantek/pylearn2,pkainz/pylearn2,goodfeli/pylearn2,lisa-lab/pylearn2,jamessergeant/pylearn2,ddboline/pylearn2
|
cost.py
|
cost.py
|
"""
Cost classes: classes that encapsulate the cost evaluation for the DAE
training criterion.
"""
# Standard library imports
from itertools import izip
# Third-party imports
from theano import tensor
class SupervisedCost(object):
"""
A cost object is allocated in the same fashion as other
objects in this file, with a 'conf' dictionary (or object
supporting __getitem__) containing relevant hyperparameters.
"""
def __init__(self, conf, model):
self.conf = conf
# TODO: Do stuff depending on conf parameters (for example
# use different cross-entropy if act_end == "tanh" or not)
self.model = model
def __call__(self, *inputs):
"""Symbolic expression denoting the reconstruction error."""
raise NotImplementedError()
class MeanSquaredError(SupervisedCost):
"""
Symbolic expression for mean-squared error between the input and the
denoised reconstruction.
"""
def __call__(self, prediction, target):
msq = lambda p, t: ((p - t)**2).sum(axis=1).mean()
if isinstance(prediction, tensor.Variable):
return msq(prediction, target)
else:
pairs = izip(prediction, target)
# TODO: Think of something more sensible to do than sum(). On one
# hand, if we're treating everything in parallel it should return
# a list. On the other, we need a scalar for everything else to
# work.
# This will likely get refactored out into a "costs" module or
# something like that.
return sum([msq(p, t) for p, t in pairs])
class CrossEntropy(SupervisedCost):
"""
Symbolic expression for elementwise cross-entropy between input
and reconstruction. Use for binary-valued features (but not for,
e.g., one-hot codes).
"""
def __call__(self, prediction, target):
ce = lambda x, z: x * tensor.log(z) + (1 - x) * tensor.log(1 - z)
if isinstance(prediction, tensor.Variable):
return ce(prediction, target)
pairs = izip(prediction, target)
return sum([ce(p, t).sum(axis=1).mean() for p, t in pairs])
##################################################
def get(str):
""" Evaluate str into a cost object, if it exists """
obj = globals()[str]
if issubclass(obj, Cost):
return obj
else:
raise NameError(str)
|
"""
Cost classes: classes that encapsulate the cost evaluation for the DAE
training criterion.
"""
# Standard library imports
from itertools import izip
# Third-party imports
from theano import tensor
class SupervisedCost(object):
"""
A cost object is allocated in the same fashion as other
objects in this file, with a 'conf' dictionary (or object
supporting __getitem__) containing relevant hyperparameters.
"""
def __init__(self, conf, model):
self.conf = conf
# TODO: Do stuff depending on conf parameters (for example
# use different cross-entropy if act_end == "tanh" or not)
def __call__(self, *inputs):
"""Symbolic expression denoting the reconstruction error."""
raise NotImplementedError()
class MeanSquaredError(SupervisedCost):
"""
Symbolic expression for mean-squared error between the input and the
denoised reconstruction.
"""
def __call__(self, prediction, target):
msq = lambda p, t: ((p - t)**2).sum(axis=1).mean()
if isinstance(prediction, tensor.Variable):
return msq(prediction, target)
else:
pairs = izip(prediction, target)
# TODO: Think of something more sensible to do than sum(). On one
# hand, if we're treating everything in parallel it should return
# a list. On the other, we need a scalar for everything else to
# work.
# This will likely get refactored out into a "costs" module or
# something like that.
return sum([msq(p, t) for p, t in pairs])
class CrossEntropy(SupervisedCost):
"""
Symbolic expression for elementwise cross-entropy between input
and reconstruction. Use for binary-valued features (but not for,
e.g., one-hot codes).
"""
def __call__(self, prediction, target):
ce = lambda x, z: x * tensor.log(z) + (1 - x) * tensor.log(1 - z)
if isinstance(prediction, tensor.Variable):
return ce(prediction, target)
pairs = izip(prediction, target)
return sum([ce(p, t).sum(axis=1).mean() for p, t in pairs])
##################################################
def get(str):
""" Evaluate str into a cost object, if it exists """
obj = globals()[str]
if issubclass(obj, Cost):
return obj
else:
raise NameError(str)
|
bsd-3-clause
|
Python
|
a04b18b8fbc8626b5592593a2b6ce635921a1e34
|
Delete text after entered, but this time actually do it
|
AndrewKLeech/Pip-Boy
|
data.py
|
data.py
|
from twitter import *
from tkinter import *
def showTweets(x, num):
# display a number of new tweets and usernames
for i in range(0, num):
line1 = (x[i]['user']['screen_name'])
line2 = (x[i]['text'])
w = Label(master, text=line1 + "\n" + line2 + "\n\n")
w.pack()
def getTweets():
x = t.statuses.home_timeline(screen_name="AndrewKLeech")
return x
def tweet():
global entryWidget
if entryWidget.get().strip() == "":
print("Empty")
else:
t.statuses.update(status=entryWidget.get().strip())
entryWidget.delete(0,END)
print("working")
# Put in token, token_key, con_secret, con_secret_key
t = Twitter(
auth=OAuth('705153959368007680-F5OUf8pvmOlXku1b7gpJPSAToqzV4Fb', 'bEGLkUJBziLc17EuKLTAMio8ChmFxP9aHYADwRXnxDsoC',
'gYDgR8lcTGcVZS9ucuEIYsMuj', '1dwHsLDN2go3aleQ8Q2vcKRfLETc51ipsP8310ayizL2p3Ycii'))
numberOfTweets = 5
master = Tk()
showTweets(getTweets(), numberOfTweets)
master.title("Tkinter Entry Widget")
master["padx"] = 40
master["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(master)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Make a new Tweet:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(master, text="Submit", command=tweet)
button.pack()
master.mainloop()
|
from twitter import *
from tkinter import *
def showTweets(x, num):
# display a number of new tweets and usernames
for i in range(0, num):
line1 = (x[i]['user']['screen_name'])
line2 = (x[i]['text'])
w = Label(master, text=line1 + "\n" + line2 + "\n\n")
w.pack()
def getTweets():
x = t.statuses.home_timeline(screen_name="AndrewKLeech")
return x
def tweet():
global entryWidget
if entryWidget.get().strip() == "":
print("Empty")
else:
#t.statuses.update(status=entryWidget.get().strip())
#entryWidget.put().strip()
entryWidget.insert(0,'')
print("working")
# Put in token, token_key, con_secret, con_secret_key
t = Twitter(
auth=OAuth('705153959368007680-F5OUf8pvmOlXku1b7gpJPSAToqzV4Fb', 'bEGLkUJBziLc17EuKLTAMio8ChmFxP9aHYADwRXnxDsoC',
'gYDgR8lcTGcVZS9ucuEIYsMuj', '1dwHsLDN2go3aleQ8Q2vcKRfLETc51ipsP8310ayizL2p3Ycii'))
numberOfTweets = 5
master = Tk()
showTweets(getTweets(), numberOfTweets)
master.title("Tkinter Entry Widget")
master["padx"] = 40
master["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(master)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Make a new Tweet:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
button = Button(master, text="Submit", command=tweet)
button.pack()
master.mainloop()
|
mit
|
Python
|
5c5de666e86d6f2627df79762b0e3b0f188861d4
|
Fix timestamp comparison on ciresources
|
CiscoSystems/project-config-third-party,CiscoSystems/project-config-third-party
|
scripts/claim_vlan.py
|
scripts/claim_vlan.py
|
import MySQLdb
from datetime import datetime, timedelta
db = MySQLdb.connect(host="10.0.196.2",
user="ciuser",
passwd="secret",
db="ciresources")
cur = db.cursor()
f = '%Y-%m-%d %H:%M:%S'
three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3)
three_hours_ago = three_hours_ago_dt.strftime(f)
cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp<'%s' LIMIT 1 FOR UPDATE" % three_hours_ago)
row = cur.fetchone()
if row is not None:
min_vlan = row[0]
max_vlan = row[1]
vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)}
cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans)
else:
raise Exception("No free VLANs found!")
db.commit()
db.close()
print("%(min_vlan)s:%(max_vlan)s" % vlans)
|
import MySQLdb
from datetime import datetime, timedelta
db = MySQLdb.connect(host="10.0.196.2",
user="ciuser",
passwd="secret",
db="ciresources")
cur = db.cursor()
f = '%Y-%m-%d %H:%M:%S'
three_hours_ago_dt = datetime.utcnow() - timedelta(hours=3)
three_hours_ago = three_hours_ago_dt.strftime(f)
cur.execute("SELECT * FROM vlans WHERE locked!=true OR timestamp > '%s' LIMIT 1 FOR UPDATE" % three_hours_ago)
row = cur.fetchone()
if row is not None:
min_vlan = row[0]
max_vlan = row[1]
vlans = {"min_vlan": min_vlan, "max_vlan":max_vlan, "timestamp": datetime.now().strftime(f)}
cur.execute("UPDATE vlans SET locked=true, timestamp='%(timestamp)s' where min_vlan=%(min_vlan)s AND max_vlan=%(max_vlan)s" % vlans)
else:
raise Exception("No free VLANs found!")
db.commit()
db.close()
print("%(min_vlan)s:%(max_vlan)s" % vlans)
|
apache-2.0
|
Python
|
efc3a2c31a00a2139f55ca5ce9f3cf4dac1dea1f
|
address comments
|
google/jax,google/jax,google/jax,google/jax,tensorflow/probability,tensorflow/probability
|
tests/debug_nans_test.py
|
tests/debug_nans_test.py
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Tests for --debug_nans."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import jax
from jax import test_util as jtu
from jax.test_util import check_grads
from jax import numpy as np
from jax import random
from jax.config import config
config.parse_flags_with_absl()
class DebugNaNsTest(jtu.JaxTestCase):
def setUp(self):
self.cfg = config.read("jax_debug_nans")
config.update("jax_debug_nans", True)
def tearDown(self):
config.update("jax_debug_nans", self.cfg)
def testSingleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
B = np.tanh(A)
def testMultipleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
D, V = np.linalg.eig(A)
def testJitComputation(self):
A = np.array([[1., 2.], [2., 3.]])
B = jax.jit(np.tanh)(A)
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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.
"""Tests for --debug_nans."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import absltest
from absl.testing import parameterized
import numpy as onp
import jax
from jax import test_util as jtu
from jax.test_util import check_grads
from jax import numpy as np
from jax import random
from jax.config import config
config.parse_flags_with_absl()
class DebugNaNsTest(jtu.JaxTestCase):
def setUp(self):
self.cfg = config.read("jax_debug_nans")
config.update("jax_debug_nans", True)
def tearDown(self):
config.update("jax_debug_nans", self.cfg)
def testSingleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
B = np.tanh(A)
def testMultipleResultPrimitive(self):
A = np.array([[1., 2.], [2., 3.]])
D, V = np.linalg.eig(A)
def testJitComputation(self):
A = np.array([[1., 2.], [2., 3.]])
B = jax.jit(np.tanh)(A)
|
apache-2.0
|
Python
|
eee6dd8f6d7555f97452fb5734e299203b337ace
|
Fix fast_classifier
|
pombredanne/milk,luispedro/milk,pombredanne/milk,pombredanne/milk,luispedro/milk,luispedro/milk
|
tests/fast_classifier.py
|
tests/fast_classifier.py
|
import numpy as np
class fast_classifier(object):
def __init__(self):
pass
def train(self, features, labels):
examples = {}
for f,lab in zip(features, labels):
if lab not in examples:
examples[lab] = f
return fast_model(examples)
class fast_model(object):
def __init__(self, examples):
self.examples = examples
assert len(self.examples)
def apply(self, f):
best = None
best_val = +np.inf
for k,v in self.examples.iteritems():
dist = np.dot(v-f, v-f)
if dist < best_val:
best = k
best_val = dist
return best
|
import numpy as np
class fast_classifier(object):
def __init__(self):
pass
def train(self, features, labels):
examples = {}
for f,lab in zip(features, labels):
if lab not in examples:
examples[lab] = f
return fast_model(examples)
class fast_model(object):
def __init__(self, examples):
self.examples = examples
def apply(self, features):
res = []
for f in features:
cur = None
best = +np.inf
for k,v in self.examples.iteritems():
dist = np.dot(v-f, v-f)
if dist < best:
best = dist
cur = k
res.append(k)
return res
|
mit
|
Python
|
83a15b47ecac219c2fe4ca1e49cfa9055f9197d2
|
Add some tests
|
aes/unleash-client-python,aes/unleash-client-python
|
tests/test_features.py
|
tests/test_features.py
|
from unittest import mock, TestCase
from unleash_client import features
class TestFactory(TestCase):
def test_simple_case(self):
strategies = {'Foo': mock.Mock(return_value='R')}
feature = {'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}]}
result = features.feature_gates(strategies, feature)
assert result == ['R']
assert strategies['Foo'].called_once_with(x=0)
def test_two_strategies(self):
strategies = {
'Foo': mock.Mock(return_value='F'),
'Bar': mock.Mock(return_value='B'),
}
feature = {'strategies': [
{'name': 'Foo', 'parameters': {'x': 0}},
{'name': 'Bar', 'parameters': {'y': 1}},
]}
result = features.feature_gates(strategies, feature)
assert result == ['F', 'B']
assert strategies['Foo'].called_once_with(x=0)
assert strategies['Bar'].called_once_with(y=1)
def test_unknown_strategy(self):
strategies = {}
feature = {'strategies': [{'name': 'absent', 'parameters': {'z': 9}}]}
with mock.patch('unleash_client.features.log') as log:
result = features.feature_gates(strategies, feature)
assert len(result) == 1
assert callable(result[0])
assert not result[0](basically_anything_here='foo')
assert log.warning.called
class TestFeature(TestCase):
def test_happy_path(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': True,
'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}],
}
toggle = features.Feature(strategies, feature_def)
assert isinstance(toggle, features.Feature)
assert toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 1, False: 1}
def test_empty_strategy_list(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': True,
'strategies': [],
}
toggle = features.Feature(strategies, feature_def)
assert isinstance(toggle, features.Feature)
assert not toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 0, False: 2}
def test_disable(self):
strategies = {'Foo': mock.Mock(return_value=lambda z: z)}
feature_def = {
'enabled': False,
'strategies': [{'name': 'Foo', 'parameters': {'x': 0}}],
}
toggle = features.Feature(strategies, feature_def)
assert not toggle({'z': True})
assert not toggle({'z': False})
assert toggle.choices == {True: 0, False: 2}
|
apache-2.0
|
Python
|
|
2b8b32605c9d211154f47d228038464ff5df7b56
|
fix import
|
opalmer/pywincffi,opalmer/pywincffi,opalmer/pywincffi,opalmer/pywincffi
|
tests/test_kernel32.py
|
tests/test_kernel32.py
|
import os
from pywincffi.core.ffi import ffi
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError
from pywincffi.kernel32.process import (
PROCESS_QUERY_LIMITED_INFORMATION, OpenProcess)
class TestOpenProcess(TestCase):
"""
Tests for :func:`pywincffi.kernel32.OpenProcess`
"""
def test_returns_handle(self):
handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
False,
os.getpid()
)
typeof = ffi.typeof(handle)
self.assertEqual(typeof.kind, "pointer")
self.assertEqual(typeof.cname, "void *")
def test_access_denied_for_null_desired_access(self):
with self.assertRaises(WindowsAPIError) as error:
OpenProcess(0, False, os.getpid())
self.assertEqual(error.exception.code, 5)
|
import os
from pywincffi.core.ffi import ffi
from pywincffi.core.testutil import TestCase
from pywincffi.exceptions import WindowsAPIError
from pywincffi.kernel32 import PROCESS_QUERY_LIMITED_INFORMATION, OpenProcess
class TestOpenProcess(TestCase):
"""
Tests for :func:`pywincffi.kernel32.OpenProcess`
"""
def test_returns_handle(self):
handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
False,
os.getpid()
)
typeof = ffi.typeof(handle)
self.assertEqual(typeof.kind, "pointer")
self.assertEqual(typeof.cname, "void *")
def test_access_denied_for_null_desired_access(self):
with self.assertRaises(WindowsAPIError) as error:
OpenProcess(0, False, os.getpid())
self.assertEqual(error.exception.code, 5)
|
mit
|
Python
|
224abc99becc1683605a6dc5c3460510efef3efb
|
Comment out the pyserial TestIsCorrectVariant test.
|
Jnesselr/s3g,makerbot/s3g,Jnesselr/s3g,makerbot/s3g,makerbot/s3g,makerbot/s3g
|
tests/test_pyserial.py
|
tests/test_pyserial.py
|
from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
'''
# This test is commented out because it requires an actual serial port.
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(list(comports)) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
'''
if __name__ == '__main__':
unittest.main()
|
from __future__ import (absolute_import, print_function, unicode_literals)
import os
import sys
lib_path = os.path.abspath('../')
sys.path.append(lib_path)
import io
import struct
import unittest
import threading
import time
import serial
try:
import unittest2 as unittest
except ImportError:
import unittest
class TestIsCorrectVariant(unittest.TestCase):
def test_isMbVariant(self):
self.assertTrue (serial.__version__.index('mb2') > 0 )
def test_hasScanEndpoints(self):
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
def test_variantDoesBlocking(self):
#grab a port
#try to grab it again
import serial.tools.list_ports as lp
scan = lp.list_ports_by_vid_pid
print('autograbbing a port')
comports = lp.comports()
if( len(list(comports)) < 1):
print('no comport availabe')
self.assertFalse(True, "no comports, cannot execute test")
portname = comports[-1][0] #item 0 in last comport as the port to test
print("Connecting to serial" + portname)
s = serial.Serial(portname)
with self.assertRaises(serial.SerialException) as ex:
s = serial.Serial(portname)
if __name__ == '__main__':
unittest.main()
|
agpl-3.0
|
Python
|
bb89223a7fcc1f2562c55ca432a3c52eec6efd8a
|
Put everything in one method like we discussed.
|
erykoff/redmapper,erykoff/redmapper
|
tests/test_background.py
|
tests/test_background.py
|
import unittest
import numpy.testing as testing
import numpy as np
import fitsio
from redmapper.background import Background
class BackgroundTestCase(unittest.TestCase):
def runTest(self):
file_name, file_path = 'test_bkg.fit', 'data'
# test that we fail if we try a non-existent file
self.assertRaises(IOError, Background, 'nonexistent.fit')
# test that we fail if we read a non-fits file
self.assertRaises(IOError, Background,
'%s/testconfig.yaml' % (file_path))
# test that we fail if we try a file without the right header info
self.assertRaises(AttributeError, Background,
'%s/test_dr8_pars.fit' % (file_path))
bkg = Background('%s/%s' % (file_path, file_name))
inputs = [(172,15,64), (323,3,103), (9,19,21), (242,4,87),
(70,12,58), (193,6,39), (87,14,88), (337,5,25), (333,8,9)]
py_outputs = np.array([bkg.sigma_g[idx] for idx in inputs])
idl_outputs = np.array([0.32197464, 6.4165196, 0.0032830855,
1.4605126, 0.0098356586, 0.79848081,
0.011284498, 9.3293247, 8.7064905])
testing.assert_almost_equal(py_outputs, idl_outputs, decimal=1)
if __name__=='__main__':
unittest.main()
|
import unittest
import numpy.testing as testing
import numpy as np
import fitsio
import redmapper
class BackgroundTestCase(unittest.TestCase):
def test_io(self): pass
def test_sigma_g(self):
inputs = [()]
idl_outputs = [0.32197464, 6.4165196, 0.0032830855, 1.4605126,
0.0098356586, 0.79848081, 0.011284498, 9.3293247]
for out in idl_outputs:
idx = tuple(np.random.randint(i) for i in self.bkg.sigma_g.shape)
testing.assert_almost_equal(self.bkg.sigma_g[idx], out, decimal=5)
def test_lookup(self): pass
def setUpClass(cls):
# test that we fail if we try a non-existent file
self.assertRaises(IOError, redmapper.background.Background,
'nonexistent.fit')
# test that we fail if we read a non-fits file
self.assertRaises(IOError, redmapper.background.Background,
'%s/testconfig.yaml' % (self.file_path))
# test that we fail if we try a file without the right header info
self.assertRaises(AttributeError, redmapper.background.Background,
'%s/test_dr8_pars.fit' % (self.file_path))
self.file_name, self.file_path = 'test_bkg.fit', 'data'
self.bkg = redmapper.background.Background('%s/%s' % (self.file_path,
self.file_name))
if __name__=='__main__':
unittest.main()
|
apache-2.0
|
Python
|
80c1275899045bfd50efa9b436ada7672c09e783
|
use md5 password hasher to speed up the tests
|
byteweaver/django-polls,byteweaver/django-polls
|
tests/test_settings.py
|
tests/test_settings.py
|
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'tests',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
|
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'tests',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
|
bsd-3-clause
|
Python
|
0d825461c5c28ce451092783937fe95171c243bd
|
Add full deprecated test
|
wind-python/windpowerlib
|
tests/test_deprecated.py
|
tests/test_deprecated.py
|
"""
SPDX-FileCopyrightText: 2019 oemof developer group <[email protected]>
SPDX-License-Identifier: MIT
"""
import warnings
import pytest
from windpowerlib.data import load_turbine_data_from_oedb
from windpowerlib.wind_turbine import get_turbine_types
def test_old_import():
msg = "Use >>from windpowerlib import get_turbine_types"
with pytest.raises(ImportError, match=msg):
get_turbine_types()
def test_old_name_load_data_from_oedb(recwarn):
load_turbine_data_from_oedb()
assert recwarn.pop(FutureWarning)
|
"""
SPDX-FileCopyrightText: 2019 oemof developer group <[email protected]>
SPDX-License-Identifier: MIT
"""
import warnings
import pytest
from windpowerlib.data import load_turbine_data_from_oedb
from windpowerlib.wind_turbine import get_turbine_types
def test_old_import():
msg = "Use >>from windpowerlib import get_turbine_types"
with pytest.raises(ImportError, match=msg):
get_turbine_types()
def test_old_name_load_data_from_oedb():
with warnings.catch_warnings():
warnings.simplefilter("error")
msg = "store_turbine_data_from_oedb"
with pytest.raises(FutureWarning, match=msg):
load_turbine_data_from_oedb()
|
mit
|
Python
|
ca40822d7898d02272cdf0a52fa5a8b75b983930
|
Fix syntax errors in addpost test
|
ollien/Timpani,ollien/Timpani,ollien/Timpani
|
tests/tests/addpost.py
|
tests/tests/addpost.py
|
import binascii
import os
import sqlalchemy
import selenium
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from timpani import database
LOGIN_TITLE = "Login - Timpani"
ADD_POST_TITLE = "Add Post - Timpani"
#A random constant used to varify that a unique post was made
POST_RANDOM = binascii.hexlify(os.urandom(16)).decode()
POST_TITLE = "Test post, please ignore."
POST_BODY = ("This is a test post. "
"There is no reason you should be paying attention to it. %s" % POST_RANDOM)
POST_TAGS = ["test", "post", "selenium"]
def test(driver, username, password):
databaseConnection = database.DatabaseConnection()
driver.get("http://127.0.0.1:8080/add_post")
(WebDriverWait(driver, 10)
.until(expected_conditions.title_contains("Timpani")))
#Check that we were redirected to the login page, as we are not logged in.
assert driver.title == LOGIN_TITLE, "Title is %s" % driver.title
loginForm = driver.find_element_by_id("login-form")
usernameField = driver.find_element_by_id("username-field")
passwordField = driver.find_element_by_id("password-field")
usernameField.send_keys(username)
passwordField.send_keys(password)
loginForm.submit()
(WebDriverWait(driver, 10)
.until_not(expected_conditions.title_is(LOGIN_TITLE)))
#We should have been redirected to the add_post page.
assert driver.title == ADD_POST_TITLE, "Title is %s" % driver.title
postForm = driver.find_element_by_id("post-form")
titleInput = driver.find_element_by_id("title-input")
editorField = driver.find_element_by_css_selector("#editor > .ql-editor")
tagsInput = driver.find_element_by_id("tag-input-div")
titleInput.click()
titleInput.send_keys(POST_TITLE)
editorField.click()
actionChain = selenium.webdriver.ActionChains(driver)
actionChain.send_keys(POST_BODY)
actionChain.perform()
tagsInput.click()
actionChain = selenium.webdriver.ActionChains(driver)
for tag in POST_TAGS:
actionChain.send_keys(tag)
actionChain.send_keys(keys.Keys.SPACE)
actionChain.perform()
postForm.submit()
post = (databaseConnection.session
.query(database.tables.Post)
.order_by(sqlalchemy.desc(database.tables.Post.id))
.first())
tags = (databaseConnection.session
.query(database.tables.Tag.name)
.filter(database.tables.Tag.post_id == post.id)
.all())
#Resolve sqlalchemy tuples
tags = [tag[0] for tag in tags]
assert post != None
assert post.title == POST_TITLE, "Title is %s" % post.title
assert POST_RANDOM in post.body
assert tags == POST_TAGS, "Tags are %s" % tags
|
import binascii
import os
import sqlalchemy
import selenium
from selenium.webdriver.common import keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from timpani import database
LOGIN_TITLE = "Login - Timpani"
ADD_POST_TITLE = "Add Post - Timpani"
#A random constant used to varify that a unique post was made
POST_RANDOM = binascii.hexlify(os.urandom(16)).decode()
POST_TITLE = "Test post, please ignore."
POST_BODY = ("This is a test post."
"There is no reason you should be paying attention to it. %s" % POST_RANDOM)
POST_TAGS = ["test", "post", "selenium"]
def test(driver, username, password):
databaseConnection = database.DatabaseConnection()
driver.get("http://127.0.0.1:8080/add_post")
WebDriverWait(driver, 10)
.until(expected_conditions.title_contains("Timpani"))
#Check that we were redirected to the login page, as we are not logged in.
assert driver.title == LOGIN_TITLE, "Title is %s" % driver.title
loginForm = driver.find_element_by_id("login-form")
usernameField = driver.find_element_by_id("username-field")
passwordField = driver.find_element_by_id("password-field")
usernameField.send_keys(username)
passwordField.send_keys(password)
loginForm.submit()
WebDriverWait(driver, 10)
.until_not(expected_conditions.title_is(LOGIN_TITLE))
#We should have been redirected to the add_post page.
assert driver.title == ADD_POST_TITLE, "Title is %s" % driver.title
postForm = driver.find_element_by_id("post-form")
titleInput = driver.find_element_by_id("title-input")
editorField = driver.find_element_by_css_selector("#editor > .ql-editor")
tagsInput = driver.find_element_by_id("tag-input-div")
titleInput.click()
titleInput.send_keys(POST_TITLE)
editorField.click()
actionChain = selenium.webdriver.ActionChains(driver)
actionChain.send_keys(POST_BODY)
actionChain.perform()
tagsInput.click()
actionChain = selenium.webdriver.ActionChains(driver)
for tag in POST_TAGS:
actionChain.send_keys(tag)
actionChain.send_keys(keys.Keys.SPACE)
actionChain.perform()
postForm.submit()
post = databaseConnection.session
.query(database.tables.Post)
.order_by(sqlalchemy.desc(database.tables.Post.id))
.first()
tags = databaseConnection.session
.query(database.tables.Tag.name)
.filter(database.tables.Tag.post_id == post.id)
.all()
#Resolve sqlalchemy tuples
tags = [tag[0] for tag in tags]
assert post != None
assert post.title == POST_TITLE, "Title is %s" % post.title
assert POST_RANDOM in post.body
assert tags == POST_TAGS, "Tags are %s" % tags
|
mit
|
Python
|
1be562eb115f302bd7fe47c2a90c5d4796a0eb98
|
make slider example more sophisticated
|
rhiever/bokeh,ptitjano/bokeh,jakirkham/bokeh,dennisobrien/bokeh,DuCorey/bokeh,timsnyder/bokeh,tacaswell/bokeh,phobson/bokeh,aiguofer/bokeh,timsnyder/bokeh,srinathv/bokeh,rs2/bokeh,DuCorey/bokeh,tacaswell/bokeh,percyfal/bokeh,akloster/bokeh,phobson/bokeh,justacec/bokeh,ChinaQuants/bokeh,bokeh/bokeh,alan-unravel/bokeh,carlvlewis/bokeh,awanke/bokeh,caseyclements/bokeh,draperjames/bokeh,birdsarah/bokeh,justacec/bokeh,clairetang6/bokeh,schoolie/bokeh,aavanian/bokeh,khkaminska/bokeh,timothydmorton/bokeh,percyfal/bokeh,bsipocz/bokeh,PythonCharmers/bokeh,alan-unravel/bokeh,KasperPRasmussen/bokeh,ChristosChristofidis/bokeh,stonebig/bokeh,xguse/bokeh,rs2/bokeh,htygithub/bokeh,abele/bokeh,ericdill/bokeh,ptitjano/bokeh,deeplook/bokeh,daodaoliang/bokeh,CrazyGuo/bokeh,caseyclements/bokeh,lukebarnard1/bokeh,awanke/bokeh,rothnic/bokeh,muku42/bokeh,daodaoliang/bokeh,DuCorey/bokeh,lukebarnard1/bokeh,srinathv/bokeh,srinathv/bokeh,ericmjl/bokeh,mutirri/bokeh,ChristosChristofidis/bokeh,daodaoliang/bokeh,jplourenco/bokeh,deeplook/bokeh,ericdill/bokeh,bokeh/bokeh,philippjfr/bokeh,quasiben/bokeh,satishgoda/bokeh,tacaswell/bokeh,khkaminska/bokeh,alan-unravel/bokeh,aavanian/bokeh,muku42/bokeh,laurent-george/bokeh,azjps/bokeh,Karel-van-de-Plassche/bokeh,msarahan/bokeh,josherick/bokeh,josherick/bokeh,saifrahmed/bokeh,josherick/bokeh,stonebig/bokeh,ahmadia/bokeh,aiguofer/bokeh,mutirri/bokeh,canavandl/bokeh,philippjfr/bokeh,maxalbert/bokeh,percyfal/bokeh,carlvlewis/bokeh,maxalbert/bokeh,KasperPRasmussen/bokeh,stuart-knock/bokeh,ChristosChristofidis/bokeh,CrazyGuo/bokeh,daodaoliang/bokeh,eteq/bokeh,bokeh/bokeh,caseyclements/bokeh,carlvlewis/bokeh,KasperPRasmussen/bokeh,saifrahmed/bokeh,paultcochrane/bokeh,abele/bokeh,aavanian/bokeh,dennisobrien/bokeh,htygithub/bokeh,rhiever/bokeh,birdsarah/bokeh,evidation-health/bokeh,PythonCharmers/bokeh,DuCorey/bokeh,jakirkham/bokeh,schoolie/bokeh,akloster/bokeh,aiguofer/bokeh,justacec/bokeh,aavanian/bokeh,dennisobrien/bokeh,roxyboy/bokeh,muku42/bokeh,bsipocz/bokeh,msarahan/bokeh,roxyboy/bokeh,laurent-george/bokeh,phobson/bokeh,stonebig/bokeh,rs2/bokeh,timothydmorton/bokeh,phobson/bokeh,canavandl/bokeh,ericmjl/bokeh,Karel-van-de-Plassche/bokeh,philippjfr/bokeh,draperjames/bokeh,mutirri/bokeh,schoolie/bokeh,gpfreitas/bokeh,matbra/bokeh,msarahan/bokeh,stuart-knock/bokeh,canavandl/bokeh,timothydmorton/bokeh,rs2/bokeh,ChinaQuants/bokeh,ericdill/bokeh,Karel-van-de-Plassche/bokeh,eteq/bokeh,paultcochrane/bokeh,evidation-health/bokeh,maxalbert/bokeh,percyfal/bokeh,timsnyder/bokeh,paultcochrane/bokeh,rothnic/bokeh,timsnyder/bokeh,DuCorey/bokeh,Karel-van-de-Plassche/bokeh,bokeh/bokeh,rhiever/bokeh,satishgoda/bokeh,deeplook/bokeh,ptitjano/bokeh,ahmadia/bokeh,muku42/bokeh,ericdill/bokeh,azjps/bokeh,jakirkham/bokeh,bsipocz/bokeh,azjps/bokeh,abele/bokeh,evidation-health/bokeh,KasperPRasmussen/bokeh,canavandl/bokeh,philippjfr/bokeh,saifrahmed/bokeh,quasiben/bokeh,CrazyGuo/bokeh,ChinaQuants/bokeh,bsipocz/bokeh,carlvlewis/bokeh,saifrahmed/bokeh,xguse/bokeh,msarahan/bokeh,mutirri/bokeh,azjps/bokeh,gpfreitas/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,birdsarah/bokeh,satishgoda/bokeh,akloster/bokeh,eteq/bokeh,ptitjano/bokeh,mindriot101/bokeh,jakirkham/bokeh,tacaswell/bokeh,alan-unravel/bokeh,rothnic/bokeh,rhiever/bokeh,stuart-knock/bokeh,azjps/bokeh,draperjames/bokeh,draperjames/bokeh,timsnyder/bokeh,ericmjl/bokeh,deeplook/bokeh,stuart-knock/bokeh,gpfreitas/bokeh,Karel-van-de-Plassche/bokeh,roxyboy/bokeh,aiguofer/bokeh,jakirkham/bokeh,mindriot101/bokeh,ahmadia/bokeh,ericmjl/bokeh,timothydmorton/bokeh,eteq/bokeh,lukebarnard1/bokeh,laurent-george/bokeh,schoolie/bokeh,paultcochrane/bokeh,htygithub/bokeh,rothnic/bokeh,justacec/bokeh,birdsarah/bokeh,PythonCharmers/bokeh,PythonCharmers/bokeh,jplourenco/bokeh,quasiben/bokeh,satishgoda/bokeh,CrazyGuo/bokeh,awanke/bokeh,ericmjl/bokeh,clairetang6/bokeh,matbra/bokeh,clairetang6/bokeh,clairetang6/bokeh,percyfal/bokeh,akloster/bokeh,matbra/bokeh,ptitjano/bokeh,xguse/bokeh,mindriot101/bokeh,rs2/bokeh,gpfreitas/bokeh,jplourenco/bokeh,srinathv/bokeh,ahmadia/bokeh,aavanian/bokeh,ChinaQuants/bokeh,aiguofer/bokeh,draperjames/bokeh,matbra/bokeh,abele/bokeh,caseyclements/bokeh,xguse/bokeh,awanke/bokeh,bokeh/bokeh,josherick/bokeh,jplourenco/bokeh,laurent-george/bokeh,dennisobrien/bokeh,htygithub/bokeh,schoolie/bokeh,lukebarnard1/bokeh,khkaminska/bokeh,dennisobrien/bokeh,philippjfr/bokeh,evidation-health/bokeh,stonebig/bokeh,roxyboy/bokeh,ChristosChristofidis/bokeh,maxalbert/bokeh,mindriot101/bokeh,khkaminska/bokeh
|
examples/plotting/file/slider.py
|
examples/plotting/file/slider.py
|
from bokeh.io import vform
from bokeh.plotting import figure, hplot, output_file, show, vplot, ColumnDataSource
from bokeh.models.actions import Callback
from bokeh.models.widgets import Slider
import numpy as np
x = np.linspace(0, 10, 500)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y))
plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)
callback = Callback(args=dict(source=source), code="""
var data = source.get('data');
var A = amp.get('value')
var k = freq.get('value')
var phi = phase.get('value')
var B = offset.get('value')
x = data['x']
y = data['y']
for (i = 0; i < x.length; i++) {
y[i] = B + A*Math.sin(k*x[i]+phi);
}
source.trigger('change');
""")
amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider
freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency", callback=callback)
callback.args["freq"] = freq_slider
phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase", callback=callback)
callback.args["phase"] = phase_slider
offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset", callback=callback)
callback.args["offset"] = offset_slider
layout = hplot(
vform(amp_slider, freq_slider, phase_slider, offset_slider),
plot
)
output_file("slider.html")
show(layout)
|
from bokeh.plotting import figure, output_file, show, vplot, ColumnDataSource
from bokeh.models.actions import Callback
from bokeh.models.widgets import Slider
import numpy as np
x = np.linspace(0, 10, 100)
y = np.sin(x)
source = ColumnDataSource(data=dict(x=x, y=y, y_orig=y))
plot = figure(y_range=(-20, 20))
plot.line('x', 'y', source=source)
callback = Callback(args=dict(source=source), code="""
var data = source.get('data');
var val = cb_obj.get('value')
data['y'] = Bokeh._.map(data['y_orig'], function(y){ return y*val; });
source.trigger('change');
""")
slider = Slider(start=1, end=20, value=1, step=1, title="Foo", callback=callback)
layout = vplot(slider, plot)
output_file("slider.html")
show(layout)
|
bsd-3-clause
|
Python
|
feb095effbe4cd92f253e7d5b68baf5b215056ef
|
Update views.py
|
dpgaspar/Flask-AppBuilder,qpxu007/Flask-AppBuilder,qpxu007/Flask-AppBuilder,zhounanshu/Flask-AppBuilder,rpiotti/Flask-AppBuilder,rpiotti/Flask-AppBuilder,qpxu007/Flask-AppBuilder,zhounanshu/Flask-AppBuilder,dpgaspar/Flask-AppBuilder,qpxu007/Flask-AppBuilder,zhounanshu/Flask-AppBuilder,dpgaspar/Flask-AppBuilder,rpiotti/Flask-AppBuilder,rpiotti/Flask-AppBuilder,dpgaspar/Flask-AppBuilder,zhounanshu/Flask-AppBuilder
|
examples/quickhowto/app/views.py
|
examples/quickhowto/app/views.py
|
from flask.ext.appbuilder.menu import Menu
from flask.ext.appbuilder.baseapp import BaseApp
from flask.ext.appbuilder.models.datamodel import SQLAModel
from flask.ext.appbuilder.views import GeneralView
from flask.ext.appbuilder.charts.views import ChartView, TimeChartView
from app import app, db
from models import Group, Contact
class ContactGeneralView(GeneralView):
datamodel = SQLAModel(Contact, db.session)
label_columns = {'group':'Contacts Group'}
list_columns = ['name','personal_celphone','birthday','group']
order_columns = ['name','personal_celphone','birthday']
#search_columns = ['name','personal_celphone','group','birthday']
show_fieldsets = [
('Summary',{'fields':['name','address','group']}),
('Personal Info',{'fields':['birthday','personal_phone','personal_celphone'],'expanded':False}),
]
class GroupGeneralView(GeneralView):
datamodel = SQLAModel(Group, db.session)
related_views = [ContactGeneralView()]
list_columns = ['name']
order_columns = ['name']
#search_columns = ['name']
class ContactChartView(ChartView):
#search_columns = ['name','group']
chart_title = 'Grouped contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['group']
datamodel = SQLAModel(Contact, db.session)
class ContactTimeChartView(TimeChartView):
#search_columns = ['name','group']
chart_title = 'Grouped Birth contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['birthday']
datamodel = SQLAModel(Contact, db.session)
genapp = BaseApp(app, db)
genapp.add_view(GroupGeneralView(), "List Groups",icon = "th-large",category = "Contacts")
genapp.add_view(ContactGeneralView(), "List Contacts",icon = "earphone",category = "Contacts")
genapp.add_separator("Contacts")
genapp.add_view(ContactChartView(), "Contacts Chart","/contactchartview/chart","signal","Contacts")
genapp.add_view(ContactTimeChartView(), "Contacts Birth Chart","/contacttimechartview/chart/month","signal","Contacts")
|
from flask.ext.appbuilder.menu import Menu
from flask.ext.appbuilder.baseapp import BaseApp
from flask.ext.appbuilder.models.datamodel import SQLAModel
from flask.ext.appbuilder.views import GeneralView
from flask.ext.appbuilder.charts.views import ChartView, TimeChartView
from app import app, db
from models import Group, Contact
class ContactGeneralView(GeneralView):
datamodel = SQLAModel(Contact, db.session)
label_columns = {'group':'Contacts Group'}
list_columns = ['name','personal_celphone','birthday','group']
order_columns = ['name','personal_celphone','birthday']
search_columns = ['name','personal_celphone','group','birthday']
show_fieldsets = [
('Summary',{'fields':['name','address','group']}),
('Personal Info',{'fields':['birthday','personal_phone','personal_celphone'],'expanded':False}),
]
class GroupGeneralView(GeneralView):
datamodel = SQLAModel(Group, db.session)
related_views = [ContactGeneralView()]
list_columns = ['name']
order_columns = ['name']
search_columns = ['name']
class ContactChartView(ChartView):
search_columns = ['name','group']
chart_title = 'Grouped contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['group']
datamodel = SQLAModel(Contact, db.session)
class ContactTimeChartView(TimeChartView):
search_columns = ['name','group']
chart_title = 'Grouped Birth contacts'
label_columns = ContactGeneralView.label_columns
group_by_columns = ['birthday']
datamodel = SQLAModel(Contact, db.session)
genapp = BaseApp(app, db)
genapp.add_view(GroupGeneralView(), "List Groups",icon = "th-large",category = "Contacts")
genapp.add_view(ContactGeneralView(), "List Contacts",icon = "earphone",category = "Contacts")
genapp.add_separator("Contacts")
genapp.add_view(ContactChartView(), "Contacts Chart","/contactchartview/chart","signal","Contacts")
genapp.add_view(ContactTimeChartView(), "Contacts Birth Chart","/contacttimechartview/chart/month","signal","Contacts")
|
bsd-3-clause
|
Python
|
08c29fcae3c622b0f47a0b73338b372ddcee42eb
|
support py2
|
hugovk/twarc,edsu/twarc,DocNow/twarc,remagio/twarc,remagio/twarc
|
utils/search.py
|
utils/search.py
|
#!/usr/bin/env python
"""
Filter tweet JSON based on a regular expression to apply to the text of the
tweet.
search.py <regex> file1
Or if you want a case insensitive match:
search.py -i <regex> file1
"""
from __future__ import print_function
import re
import sys
import json
import argparse
import fileinput
from twarc import json2csv
if len(sys.argv) == 1:
sys.exit("usage: search.py <regex> file1 file2")
parser = argparse.ArgumentParser(description="filter tweets by regex")
parser.add_argument('-i', '--ignore', dest='ignore', action='store_true',
help='ignore case')
parser.add_argument('regex')
parser.add_argument('files', metavar='FILE', nargs='*', default=['-'], help='files to read, if empty, stdin is used')
args = parser.parse_args()
flags = 0
if args.ignore:
flags = re.IGNORECASE
try:
regex = re.compile(args.regex, flags)
except Exception as e:
sys.exit("error: regex failed to compile: {}".format(e))
for line in fileinput.input(files=args.files):
tweet = json.loads(line)
text = json2csv.text(tweet)
if regex.search(text):
print(line, end='')
|
#!/usr/bin/env python
"""
Filter tweet JSON based on a regular expression to apply to the text of the
tweet.
search.py <regex> file1
Or if you want a case insensitive match:
search.py -i <regex> file1
"""
import re
import sys
import json
import argparse
import fileinput
from twarc import json2csv
if len(sys.argv) == 1:
sys.exit("usage: search.py <regex> file1 file2")
parser = argparse.ArgumentParser(description="filter tweets by regex")
parser.add_argument('-i', '--ignore', dest='ignore', action='store_true',
help='ignore case')
parser.add_argument('regex')
parser.add_argument('files', metavar='FILE', nargs='*', default=['-'], help='files to read, if empty, stdin is used')
args = parser.parse_args()
flags = 0
if args.ignore:
flags = re.IGNORECASE
try:
regex = re.compile(args.regex, flags)
except Exception as e:
sys.exit("error: regex failed to compile: {}".format(e))
for line in fileinput.input(files=args.files):
tweet = json.loads(line)
text = json2csv.text(tweet)
if regex.search(text):
print(line, end='')
|
mit
|
Python
|
4dc1552bbbdbfb060eb4559c5cded6a5c8e8fd02
|
Migrate kythe for Bazel 0.27 (#3769)
|
kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe,kythe/kythe
|
kythe/cxx/tools/fyi/testdata/compile_commands.bzl
|
kythe/cxx/tools/fyi/testdata/compile_commands.bzl
|
"""Rule for generating compile_commands.json.in with appropriate inlcude directories."""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
_TEMPLATE = """ {{
"directory": "OUT_DIR",
"command": "clang++ -c {filename} -std=c++11 -Wall -Werror -I. -IBASE_DIR {system_includes}",
"file": "{filename}",
}}"""
def _compile_commands_impl(ctx):
system_includes = " ".join([
"-I{}".format(d)
for d in find_cpp_toolchain(ctx).built_in_include_directories
])
ctx.actions.write(
output = ctx.outputs.compile_commands,
content = "[\n{}]\n".format(",\n".join([
_TEMPLATE.format(filename = name, system_includes = system_includes)
for name in ctx.attr.filenames
])),
)
compile_commands = rule(
attrs = {
"filenames": attr.string_list(
mandatory = True,
allow_empty = False,
),
# Do not add references, temporary attribute for find_cpp_toolchain.
# See go/skylark-api-for-cc-toolchain for more details.
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
doc = "Generates a compile_commannds.json.in template file.",
outputs = {
"compile_commands": "compile_commands.json.in",
},
implementation = _compile_commands_impl,
toolchains = ["@bazel_tools//tools/cpp:toolchain_type"],
)
|
"""Rule for generating compile_commands.json.in with appropriate inlcude directories."""
load("@bazel_tools//tools/cpp:toolchain_utils.bzl", "find_cpp_toolchain")
_TEMPLATE = """ {{
"directory": "OUT_DIR",
"command": "clang++ -c {filename} -std=c++11 -Wall -Werror -I. -IBASE_DIR {system_includes}",
"file": "{filename}",
}}"""
def _compile_commands_impl(ctx):
system_includes = " ".join([
"-I{}".format(d)
for d in find_cpp_toolchain(ctx).built_in_include_directories
])
ctx.actions.write(
output = ctx.outputs.compile_commands,
content = "[\n{}]\n".format(",\n".join([
_TEMPLATE.format(filename = name, system_includes = system_includes)
for name in ctx.attr.filenames
])),
)
compile_commands = rule(
attrs = {
"filenames": attr.string_list(
mandatory = True,
allow_empty = False,
),
# Do not add references, temporary attribute for find_cpp_toolchain.
# See go/skylark-api-for-cc-toolchain for more details.
"_cc_toolchain": attr.label(
default = Label("@bazel_tools//tools/cpp:current_cc_toolchain"),
),
},
doc = "Generates a compile_commannds.json.in template file.",
outputs = {
"compile_commands": "compile_commands.json.in",
},
implementation = _compile_commands_impl,
)
|
apache-2.0
|
Python
|
cabae8d7732cca922e3fb56db205e41a20186aa3
|
Remove markdown
|
salman-jpg/maya,ausiddiqui/maya
|
DataCleaning/data_cleaning.py
|
DataCleaning/data_cleaning.py
|
# -*- coding: utf-8 -*-
"""
Script for Importing data from MySQL database and cleaning
"""
import os
import pymysql
import pandas as pd
from bs4 import BeautifulSoup
from ftfy import fix_text
## Getting Data
# Changing directory
os.chdir("")
# Running the file containing MySQL information
execfile("connection_config.py")
# Connecting to MySQL
connection = pymysql.connect(host=hostname, user=usr, password=pwd, db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# Fetching data from the database
with connection.cursor() as cursor:
sql = "SELECT * FROM answers"
cursor.execute(sql)
result = cursor.fetchall()
# Closing connection
connection.close()
# Saving the data as a dataframe
data = pd.DataFrame(result)
# Saving the data to an excel file
#data.to_excel("answers.xlsx")
# Importing data from the excel file
#data = pd.read_excel("answers.xlsx")
## Data cleaning
data["body"] = data["body"].fillna("") # Filling missing values
# Cleaning html and fixing unicode
nrow = data.shape[0]
body = list()
for i in range(0, nrow):
body.append(BeautifulSoup(data["body"][i], "html"))
body[i] = body[i].get_text() # Remove html
body[i] = fix_text(body[i]) # Fix unicode characters
body = pd.Series(body)
# Strip whitespace
body_new = body.str.strip()
body_new = body_new.str.replace("[\s]{2,}", "")
# Remove markdown
body_new = body_new.str.replace("[$#~^*_]", "")
# Cleaning special characters
body_new = body_new.str.replace("[\r\n\t\xa0]", "")
body_new = body_new.str.replace("[\\\\]{1,}", " ")
# Putting the cleaned up data back in the dataframe
data["body"] = body_new
|
# -*- coding: utf-8 -*-
"""
Script for Importing data from MySQL database and cleaning
"""
import os
import pymysql
import pandas as pd
from bs4 import BeautifulSoup
from ftfy import fix_text
## Getting Data
# Changing directory
os.chdir("")
# Running the file containing MySQL information
execfile("connection_config.py")
# Connecting to MySQL
connection = pymysql.connect(host=hostname, user=usr, password=pwd, db=db, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
# Fetching data from the database
with connection.cursor() as cursor:
sql = "SELECT * FROM answers"
cursor.execute(sql)
result = cursor.fetchall()
# Closing connection
connection.close()
# Saving the data as a dataframe
data = pd.DataFrame(result)
# Saving the data to an excel file
#data.to_excel("answers.xlsx")
# Importing data from the excel file
#data = pd.read_excel("answers.xlsx")
## Data cleaning
data["body"] = data["body"].fillna("") # Filling missing values
# Cleaning html and fixing unicode
nrow = data.shape[0]
body = list()
for i in range(0, nrow):
body.append(BeautifulSoup(data["body"][i], "html"))
body[i] = body[i].get_text() # Remove html
body[i] = fix_text(body[i]) # Fix unicode characters
body = pd.Series(body)
# Strip whitespace
body_new = body.str.strip()
body_new = body_new.str.replace("[\s]{2,}", "")
# Cleaning special characters
body_new = body_new.str.replace("[\r\n\t$\xa0]", "")
body_new = body_new.str.replace("[\\\\]{1,}", " ")
# Putting the cleaned up data back in the dataframe
data["body"] = body_new
|
mit
|
Python
|
abcae974229dc28a60f78b706f7cd4070bc530fa
|
update doc
|
thaim/ansible,thaim/ansible
|
lib/ansible/modules/windows/win_feature.py
|
lib/ansible/modules/windows/win_feature.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Paul Durivage <[email protected]>, Trond Hindenes <[email protected]> and others
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_feature
version_added: "1.7"
short_description: Installs and uninstalls Windows Features
description:
- Installs or uninstalls Windows Roles or Features
options:
name:
description:
- Names of roles or features to install as a single feature or a comma-separated list of features
required: true
default: null
state:
description:
- State of the features or roles on the system
required: false
choices:
- present
- absent
default: present
restart:
description:
- Restarts the computer automatically when installation is complete, if restarting is required by the roles or features installed.
choices:
- yes
- no
default: null
include_sub_features:
description:
- Adds all subfeatures of the specified feature
choices:
- yes
- no
default: null
include_management_tools:
description:
- Adds the corresponding management tools to the specified feature
choices:
- yes
- no
default: null
source:
description:
- Specify a source to install the feature from
required: false
choices:
- {driveletter}:\sources\sxs
- \\{IP}\Share\sources\sxs
author:
- "Paul Durivage (@angstwad)"
- "Trond Hindenes (@trondhindenes)"
'''
EXAMPLES = '''
# This installs IIS.
# The names of features available for install can be run by running the following Powershell Command:
# PS C:\Users\Administrator> Import-Module ServerManager; Get-WindowsFeature
$ ansible -i hosts -m win_feature -a "name=Web-Server" all
$ ansible -i hosts -m win_feature -a "name=Web-Server,Web-Common-Http" all
ansible -m "win_feature" -a "name=NET-Framework-Core source=C:/Temp/iso/sources/sxs" windows
# Playbook example
---
- name: Install IIS
hosts: all
gather_facts: false
tasks:
- name: Install IIS
win_feature:
name: "Web-Server"
state: present
restart: yes
include_sub_features: yes
include_management_tools: yes
'''
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Paul Durivage <[email protected]>, Trond Hindenes <[email protected]> and others
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_feature
version_added: "1.7"
short_description: Installs and uninstalls Windows Features
description:
- Installs or uninstalls Windows Roles or Features
options:
name:
description:
- Names of roles or features to install as a single feature or a comma-separated list of features
required: true
default: null
state:
description:
- State of the features or roles on the system
required: false
choices:
- present
- absent
default: present
restart:
description:
- Restarts the computer automatically when installation is complete, if restarting is required by the roles or features installed.
choices:
- yes
- no
default: null
include_sub_features:
description:
- Adds all subfeatures of the specified feature
choices:
- yes
- no
default: null
include_management_tools:
description:
- Adds the corresponding management tools to the specified feature
choices:
- yes
- no
default: null
source:
description:
- Specify a source to install the feature from
required: false
choices:
- {driveletter}:\sources\sxs
- \\{IP}\Share\sources\sxs
author:
- "Paul Durivage (@angstwad)"
- "Trond Hindenes (@trondhindenes)"
'''
EXAMPLES = '''
# This installs IIS.
# The names of features available for install can be run by running the following Powershell Command:
# PS C:\Users\Administrator> Import-Module ServerManager; Get-WindowsFeature
$ ansible -i hosts -m win_feature -a "name=Web-Server" all
$ ansible -i hosts -m win_feature -a "name=Web-Server,Web-Common-Http" all
# Playbook example
---
- name: Install IIS
hosts: all
gather_facts: false
tasks:
- name: Install IIS
win_feature:
name: "Web-Server"
state: present
restart: yes
include_sub_features: yes
include_management_tools: yes
'''
|
mit
|
Python
|
23b56303d3afa4764d7fa4f4d82eafbaf57d0341
|
Update the version number
|
jeremiedecock/pyai,jeremiedecock/pyai
|
ailib/__init__.py
|
ailib/__init__.py
|
# PyAI
# The MIT License
#
# Copyright (c) 2014,2015,2016,2017 Jeremie DECOCK (http://www.jdhp.org)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.2.dev1'
__all__ = ['ml',
'mdp',
'optimize',
'signal']
|
# PyAI
# The MIT License
#
# Copyright (c) 2014,2015,2016,2017 Jeremie DECOCK (http://www.jdhp.org)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
#
__version__ = '0.2.dev0'
__all__ = ['ml',
'mdp',
'optimize',
'signal']
|
mit
|
Python
|
d2cfc7f2fefcb9a317ab3cd18ebc8785fb764d9f
|
remove last bang
|
chrisy/exabgp,blablacar/exabgp,benagricola/exabgp,fugitifduck/exabgp,lochiiconnectivity/exabgp,earies/exabgp,fugitifduck/exabgp,blablacar/exabgp,benagricola/exabgp,lochiiconnectivity/exabgp,earies/exabgp,dneiter/exabgp,fugitifduck/exabgp,lochiiconnectivity/exabgp,PowerDNS/exabgp,benagricola/exabgp,chrisy/exabgp,chrisy/exabgp,blablacar/exabgp,PowerDNS/exabgp,earies/exabgp,dneiter/exabgp,PowerDNS/exabgp,dneiter/exabgp
|
lib/exabgp/bgp/message/open/capability/refresh.py
|
lib/exabgp/bgp/message/open/capability/refresh.py
|
# encoding: utf-8
"""
refresh.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2012 Exa Networks. All rights reserved.
"""
# =================================================================== RouteRefresh
class RouteRefresh (list):
def __str__ (self):
return "Route Refresh (unparsed)"
def extract (self):
return []
class CiscoRouteRefresh (list):
def __str__ (self):
return "Cisco Route Refresh (unparsed)"
def extract (self):
return []
|
#!/usr/bin/env python
# encoding: utf-8
"""
refresh.py
Created by Thomas Mangin on 2012-07-17.
Copyright (c) 2012 Exa Networks. All rights reserved.
"""
# =================================================================== RouteRefresh
class RouteRefresh (list):
def __str__ (self):
return "Route Refresh (unparsed)"
def extract (self):
return []
class CiscoRouteRefresh (list):
def __str__ (self):
return "Cisco Route Refresh (unparsed)"
def extract (self):
return []
|
bsd-3-clause
|
Python
|
4fa4fb3f583e787da9594ac8a714a22981842c71
|
remove now-bogus test
|
chevah/pydoctor,jelmer/pydoctor,chevah/pydoctor,jelmer/pydoctor,hawkowl/pydoctor,hawkowl/pydoctor,jelmer/pydoctor
|
pydoctor/test/test_commandline.py
|
pydoctor/test/test_commandline.py
|
from pydoctor import driver
import sys, cStringIO
def geterrtext(*options):
options = list(options)
se = sys.stderr
f = cStringIO.StringIO()
print options
sys.stderr = f
try:
try:
driver.main(options)
except SystemExit:
pass
else:
assert False, "did not fail"
finally:
sys.stderr = se
return f.getvalue()
def test_invalid_option():
err = geterrtext('--no-such-option')
assert 'no such option' in err
def test_cannot_advance_blank_system():
err = geterrtext('--make-html')
assert 'forget an --add-package?' in err
def test_invalid_systemclasses():
err = geterrtext('--system-class')
assert 'requires an argument' in err
err = geterrtext('--system-class=notdotted')
assert 'dotted name' in err
err = geterrtext('--system-class=no-such-module.System')
assert 'could not import module' in err
err = geterrtext('--system-class=pydoctor.model.Class')
assert 'is not a subclass' in err
def test_projectbasedir():
"""
The --project-base-dir option should set the projectbasedirectory attribute
on the options object.
"""
value = "projbasedirvalue"
options, args = driver.parse_args([
"--project-base-dir", value])
assert options.projectbasedirectory == value
|
from pydoctor import driver
import sys, cStringIO
def geterrtext(*options):
options = list(options)
se = sys.stderr
f = cStringIO.StringIO()
print options
sys.stderr = f
try:
try:
driver.main(options)
except SystemExit:
pass
else:
assert False, "did not fail"
finally:
sys.stderr = se
return f.getvalue()
def test_invalid_option():
err = geterrtext('--no-such-option')
assert 'no such option' in err
def test_no_do_nothing():
err = geterrtext()
assert "this invocation isn't going to do anything" in err
def test_cannot_advance_blank_system():
err = geterrtext('--make-html')
assert 'forget an --add-package?' in err
def test_invalid_systemclasses():
err = geterrtext('--system-class')
assert 'requires an argument' in err
err = geterrtext('--system-class=notdotted')
assert 'dotted name' in err
err = geterrtext('--system-class=no-such-module.System')
assert 'could not import module' in err
err = geterrtext('--system-class=pydoctor.model.Class')
assert 'is not a subclass' in err
def test_projectbasedir():
"""
The --project-base-dir option should set the projectbasedirectory attribute
on the options object.
"""
value = "projbasedirvalue"
options, args = driver.parse_args([
"--project-base-dir", value])
assert options.projectbasedirectory == value
|
isc
|
Python
|
579904c318031ed049f697f89109bd6909b68eba
|
Revise docstring
|
bowen0701/algorithms_data_structures
|
alg_merge_sort.py
|
alg_merge_sort.py
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _merge_recur(x_list, y_list):
"""Merge two sorted lists by Recusions."""
if len(x_list) == 0:
return y_list
if len(y_list) == 0:
return x_list
if x_list[0] <= y_list[0]:
return [x_list[0]] + _merge_recur(x_list[1:], y_list)
else:
return [y_list[0]] + _merge_recur(x_list, y_list[1:])
def _merge_iter(x_list, y_list):
"""Merge two sorted lists by Iteration (i.e. Two Fingers Algorithm)."""
z_list = []
x_pos = 0
y_pos = 0
for z_pos in xrange(len(x_list) + len(y_list)):
if x_pos < len(x_list) and y_pos < len(y_list):
if x_list[x_pos] <= y_list[y_pos]:
z_list.append(x_list[x_pos])
x_pos += 1
else:
z_list.append(y_list[y_pos])
y_pos += 1
elif x_pos < len(x_list) and y_pos >= len(y_list):
z_list.append(x_list[x_pos])
x_pos += 1
elif x_pos >= len(x_list) and y_pos < len(y_list):
z_list.append(y_list[y_pos])
y_pos += 1
else:
pass
return z_list
def merge_sort(a_list, merge):
"""Merge sort by Divide and Conquer Algorithm.
Time complexity: O(n*logn).
"""
if len(a_list) == 1:
return a_list
else:
mid = len(a_list) // 2
return merge(merge_sort(a_list[:mid], merge),
merge_sort(a_list[mid:], merge))
def main():
import time
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
start_time = time.time()
print(merge_sort(a_list, _merge_recur))
print('Run time of merge sort with recusions: {}'
.format(time.time() - start_time))
start_time = time.time()
print(merge_sort(a_list, _merge_iter))
print('Run time of merge sort with iterations: {}'
.format(time.time() - start_time))
if __name__ == '__main__':
main()
|
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
def _merge_recur(x_list, y_list):
"""Merge two sorted lists by recusions."""
if len(x_list) == 0:
return y_list
if len(y_list) == 0:
return x_list
if x_list[0] <= y_list[0]:
return [x_list[0]] + _merge_recur(x_list[1:], y_list)
else:
return [y_list[0]] + _merge_recur(x_list, y_list[1:])
def _merge_iter(x_list, y_list):
"""Merge two sorted lists by iteration."""
z_list = []
x_pos = 0
y_pos = 0
for z_pos in xrange(len(x_list) + len(y_list)):
if x_pos < len(x_list) and y_pos < len(y_list):
if x_list[x_pos] <= y_list[y_pos]:
z_list.append(x_list[x_pos])
x_pos += 1
else:
z_list.append(y_list[y_pos])
y_pos += 1
elif x_pos < len(x_list) and y_pos >= len(y_list):
z_list.append(x_list[x_pos])
x_pos += 1
elif x_pos >= len(x_list) and y_pos < len(y_list):
z_list.append(y_list[y_pos])
y_pos += 1
else:
pass
return z_list
def merge_sort(a_list, merge):
"""Merge sort by divide and conquer algorithm.
Time complexity: O(n*logn).
"""
if len(a_list) == 1:
return a_list
else:
mid = len(a_list) // 2
return merge(merge_sort(a_list[:mid], merge),
merge_sort(a_list[mid:], merge))
def main():
import time
a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
start_time = time.time()
print(merge_sort(a_list, _merge_recur))
print('Run time of merge sort with recusions: {}'
.format(time.time() - start_time))
start_time = time.time()
print(merge_sort(a_list, _merge_iter))
print('Run time of merge sort with iterations: {}'
.format(time.time() - start_time))
if __name__ == '__main__':
main()
|
bsd-2-clause
|
Python
|
2c5a345aa7e21045d6a76225dc192f14b62db4f6
|
fix review permission manage command
|
pyohio/symposion,pyohio/symposion
|
symposion/reviews/management/commands/create_review_permissions.py
|
symposion/reviews/management/commands/create_review_permissions.py
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from symposion.proposals.models import ProposalSection
class Command(BaseCommand):
def handle(self, *args, **options):
ct = ContentType.objects.get(
app_label="symposion_reviews",
model="review"
)
for ps in ProposalSection.objects.all():
for action in ["review", "manage"]:
perm, created = Permission.objects.get_or_create(
codename="can_%s_%s" % (action, ps.section.slug),
content_type__pk=ct.id,
defaults={"name": "Can %s %s" % (action, ps), "content_type": ct}
)
print perm
|
from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from symposion.proposals.models import ProposalSection
class Command(BaseCommand):
def handle(self, *args, **options):
ct, created = ContentType.objects.get_or_create(
model="",
app_label="reviews",
defaults={"name": "reviews"}
)
for ps in ProposalSection.objects.all():
for action in ["review", "manage"]:
perm, created = Permission.objects.get_or_create(
codename="can_%s_%s" % (action, ps.section.slug),
content_type__pk=ct.id,
defaults={"name": "Can %s %s" % (action, ps), "content_type": ct}
)
print perm
|
bsd-3-clause
|
Python
|
c8398415bf82a1f68c7654c8d4992661587fccf7
|
Update pathlib-recursive-rmdir.py
|
jabocg/scraps
|
python/pathlib-recursive-rmdir.py
|
python/pathlib-recursive-rmdir.py
|
import pathlib
# path: pathlib.Path - directory to remove
def removeDirectory(path):
for i in path.glob('*'):
if i.is_dir():
removeDirectory(i)
else:
i.unlink()
# NOTE: can replace above lines with `removeConents(path)` scrap form pathlib-recursive-remove-contents
path.rmdir()
|
import pathlib
# path: pathlib.Path - directory to remove
def removeDirectory(path):
for i in path.glob('*'):
if i.is_dir():
removeDirectory(i)
else:
i.unlink()
path.rmdir()
|
mit
|
Python
|
7668331e7cc4f5e2a310fcddcb3f90af4c18bb30
|
add Python 3 compatibility imports to capabilities.py
|
nodakai/watchman,dhruvsinghal/watchman,kwlzn/watchman,wez/watchman,nodakai/watchman,nodakai/watchman,wez/watchman,nodakai/watchman,kwlzn/watchman,kwlzn/watchman,wez/watchman,nodakai/watchman,dhruvsinghal/watchman,dhruvsinghal/watchman,facebook/watchman,dhruvsinghal/watchman,wez/watchman,nodakai/watchman,facebook/watchman,nodakai/watchman,nodakai/watchman,dhruvsinghal/watchman,kwlzn/watchman,facebook/watchman,wez/watchman,wez/watchman,kwlzn/watchman,facebook/watchman,facebook/watchman,wez/watchman,facebook/watchman,facebook/watchman,wez/watchman,wez/watchman,dhruvsinghal/watchman,facebook/watchman,facebook/watchman,dhruvsinghal/watchman,dhruvsinghal/watchman,nodakai/watchman,kwlzn/watchman,kwlzn/watchman
|
python/pywatchman/capabilities.py
|
python/pywatchman/capabilities.py
|
# Copyright 2015 Facebook, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * 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 Facebook 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 HOLDER 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# no unicode literals
import re
def parse_version(vstr):
res = 0
for n in vstr.split('.'):
res = res * 1000
res = res + int(n)
return res
cap_versions = {
"cmd-watch-del-all": "3.1.1",
"cmd-watch-project": "3.1",
"relative_root": "3.3",
"term-dirname": "3.1",
"term-idirname": "3.1",
"wildmatch": "3.7",
}
def check(version, name):
if name in cap_versions:
return version >= parse_version(cap_versions[name])
return False
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers['version'])
vers['capabilities'] = {}
for name in opts['optional']:
vers['capabilities'][name] = check(parsed_version, name)
failed = False
for name in opts['required']:
have = check(parsed_version, name)
vers['capabilities'][name] = have
if not have:
vers['error'] = 'client required capability `' + name + \
'` is not supported by this server'
return vers
|
# Copyright 2015 Facebook, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * 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 Facebook 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 HOLDER 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.
import re
def parse_version(vstr):
res = 0
for n in vstr.split('.'):
res = res * 1000
res = res + int(n)
return res
cap_versions = {
"cmd-watch-del-all": "3.1.1",
"cmd-watch-project": "3.1",
"relative_root": "3.3",
"term-dirname": "3.1",
"term-idirname": "3.1",
"wildmatch": "3.7",
}
def check(version, name):
if name in cap_versions:
return version >= parse_version(cap_versions[name])
return False
def synthesize(vers, opts):
""" Synthesize a capability enabled version response
This is a very limited emulation for relatively recent feature sets
"""
parsed_version = parse_version(vers['version'])
vers['capabilities'] = {}
for name in opts['optional']:
vers['capabilities'][name] = check(parsed_version, name)
failed = False
for name in opts['required']:
have = check(parsed_version, name)
vers['capabilities'][name] = have
if not have:
vers['error'] = 'client required capability `' + name + \
'` is not supported by this server'
return vers
|
mit
|
Python
|
97545d3055a0e0044723e0cb4b7ffd7803d1dbd5
|
Make class constants.
|
ohsu-qin/qipipe
|
qipipe/staging/airc_collection.py
|
qipipe/staging/airc_collection.py
|
import re
from .staging_error import StagingError
__all__ = ['with_name']
EXTENT = {}
"""A name => collection dictionary for all supported AIRC collections."""
def collection_with_name(name):
"""
@param name: the OHSU QIN collection name
@return: the corresponding AIRC collection
"""
return EXTENT[name]
class AIRCCollection(object):
"""The AIRC Study characteristics."""
def __init__(self, collection, subject_pattern, session_pattern, dicom_pattern):
"""
@param collection: the collection name
@param subject_pattern: the subject directory name match regular expression pattern
@param session_pattern: the session directory name match regular expression pattern
@param dicom_pattern: the DICOM directory name match glob pattern
"""
self.collection = collection
self.subject_pattern = subject_pattern
self.session_pattern = session_pattern
self.dicom_pattern = dicom_pattern
EXTENT[collection] = self
def path2subject_number(self, path):
"""
@param path: the directory path
@return: the subject number
"""
match = re.search(self.subject_pattern, path)
if not match:
raise StagingError("The directory path %s does not match the subject pattern %s" % (path, self.subject_pattern))
return int(match.group(1))
def path2session_number(self, path):
"""
@param path: the directory path
@return: the session number
"""
return int(re.search(self.session_pattern, path).group(1))
class AIRCCollection:
BREAST = AIRCCollection('Breast', 'BreastChemo(\d+)', 'Visit(\d+)', '*concat*/*')
"""The Breast collection."""
SARCOMA = AIRCCollection('Sarcoma', 'Subj_(\d+)', '(?:Visit_|S\d+V)(\d+)', '*concat*/*')
"""The Sarcoma collection."""
|
import re
from .staging_error import StagingError
__all__ = ['with_name']
EXTENT = {}
"""A name => collection dictionary for all supported AIRC collections."""
def collection_with_name(name):
"""
@param name: the OHSU QIN collection name
@return: the corresponding AIRC collection
"""
return EXTENT[name]
class AIRCCollection(object):
"""The AIRC Study characteristics."""
def __init__(self, collection, subject_pattern, session_pattern, dicom_pattern):
"""
@param collection: the collection name
@param subject_pattern: the subject directory name match regular expression pattern
@param session_pattern: the session directory name match regular expression pattern
@param dicom_pattern: the DICOM directory name match glob pattern
"""
self.collection = collection
self.subject_pattern = subject_pattern
self.session_pattern = session_pattern
self.dicom_pattern = dicom_pattern
EXTENT[collection] = self
def path2subject_number(self, path):
"""
@param path: the directory path
@return: the subject number
"""
match = re.search(self.subject_pattern, path)
if not match:
raise StagingError("The directory path %s does not match the subject pattern %s" % (path, self.subject_pattern))
return int(match.group(1))
def path2session_number(self, path):
"""
@param path: the directory path
@return: the session number
"""
return int(re.search(self.session_pattern, path).group(1))
BREAST = AIRCCollection('Breast', 'BreastChemo(\d+)', 'Visit(\d+)', '*concat*/*')
SARCOMA = AIRCCollection('Sarcoma', 'Subj_(\d+)', '(?:Visit_|S\d+V)(\d+)', '*concat*/*')
|
bsd-2-clause
|
Python
|
ed263e083dcb49bdd3f2d6cc707008cb5fe8ce1b
|
remove account.reconcile before deleting a account.move
|
hbrunn/bank-statement-reconcile,damdam-s/bank-statement-reconcile,BT-jmichaud/bank-statement-reconcile,damdam-s/bank-statement-reconcile,Antiun/bank-statement-reconcile,Antiun/bank-statement-reconcile,StefanRijnhart/bank-statement-reconcile,BT-ojossen/bank-statement-reconcile,OpenPymeMx/bank-statement-reconcile,acsone/bank-statement-reconcile,OpenPymeMx/bank-statement-reconcile,jakar/odoo-bank-statement-reconcile,BT-fgarbely/bank-statement-reconcile,BT-fgarbely/bank-statement-reconcile,StefanRijnhart/bank-statement-reconcile,acsone/bank-statement-reconcile,hbrunn/bank-statement-reconcile,VitalPet/bank-statement-reconcile,brain-tec/bank-statement-reconcile,jakar/odoo-bank-statement-reconcile,raycarnes/bank-statement-reconcile,rschnapka/bank-statement-reconcile,BT-ojossen/bank-statement-reconcile,brain-tec/bank-statement-reconcile,BT-jmichaud/bank-statement-reconcile,VitalPet/bank-statement-reconcile,raycarnes/bank-statement-reconcile,Endika/bank-statement-reconcile,Endika/bank-statement-reconcile
|
account_statement_ext/account.py
|
account_statement_ext/account.py
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv.orm import Model
from openerp.osv import fields
class account_move(Model):
_inherit = 'account.move'
def unlink(self, cr, uid, ids, context=None):
"""
Delete the reconciliation when we delete the moves. This
allow an easier way of cancelling the bank statement.
"""
reconcile_to_delete = []
reconcile_obj = self.pool.get('account.move.reconcile')
for move in self.browse(cr, uid, ids, context=context):
for move_line in move.line_id:
if move_line.reconcile_id:
reconcile_to_delete.append(move_line.reconcile_id.id)
reconcile_obj.unlink(cr,uid,reconcile_to_delete,context=context)
return super(account_move, self).unlink(cr, uid, ids, context=context)
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Author: Joel Grand-Guillaume
# Copyright 2011-2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv.orm import Model
from openerp.osv import fields
class account_move(Model):
_inherit = 'account.move'
def unlink(self, cr, uid, ids, context=None):
"""
Delete the reconciliation when we delete the moves. This
allow an easier way of cancelling the bank statement.
"""
for move in self.browse(cr, uid, ids, context=context):
for move_line in move.line_id:
if move_line.reconcile_id:
move_line.reconcile_id.unlink(context=context)
return super(account_move, self).unlink(cr, uid, ids, context=context)
|
agpl-3.0
|
Python
|
55373ddcf68641ec0654b58b8471c01e749366f9
|
Use a single redis client object for the module
|
lucius-feng/tinman,lucius-feng/tinman,lucius-feng/tinman,gmr/tinman,gmr/tinman
|
tinman/handlers/redis.py
|
tinman/handlers/redis.py
|
"""The RedisRequestHandler uses tornado-redis to support Redis. It will
auto-establish a single redis connection when initializing the connection.
"""
import logging
import tornadoredis
from tornado import web
LOGGER = logging.getLogger(__name__)
redis_client = None
class RedisRequestHandler(web.RequestHandler):
"""This request handler will connect to Redis on initialize if the
connection is not previously set.
"""
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
def _connect_to_redis(self):
"""Connect to a Redis server returning the handle to the redis
connection.
:rtype: tornadoredis.Redis
"""
settings = self._redis_settings
LOGGER.debug('Connecting to redis: %r', settings)
client = tornadoredis.Client(**settings)
client.connect()
return client
def _new_redis_client(self):
"""Create a new redis client and assign it to the module level handle.
"""
global redis_client
redis_client = self._connect_to_redis()
@property
def _redis_settings(self):
"""Return the Redis settings from configuration as a dict, defaulting
to localhost:6379:0 if it's not set in configuration. The dict format
is set to be passed as kwargs into the Client object.
:rtype: dict
"""
settings = self.application.settings.get('redis', dict())
return {'host': settings.get('host', self.REDIS_HOST),
'port': settings.get('port', self.REDIS_PORT),
'selected_db': settings.get('db', self.REDIS_DB)}
def prepare(self):
"""Prepare RedisRequestHandler requests, ensuring that there is a
connected tornadoredis.Client object.
"""
global redis_client
super(RedisRequestHandler, self).prepare()
if redis_client is None or not redis_client.connection.connected:
LOGGER.info('Creating new Redis instance')
self._new_redis_client()
@property
def redis_client(self):
"""Return a handle to the active redis client.
:rtype: tornadoredis.Redis
"""
global redis_client
return redis_client
|
"""The RedisRequestHandler uses tornado-redis to support Redis. It will
auto-establish a single redis connection when initializing the connection.
"""
import logging
import tornadoredis
from tornado import web
LOGGER = logging.getLogger(__name__)
class RedisRequestHandler(web.RequestHandler):
"""This request handler will connect to Redis on initialize if the
connection is not previously set.
"""
REDIS_CLIENT = 'redis'
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
def prepare(self):
super(RedisRequestHandler, self).prepare()
if not self._has_redis_client:
self._set_redis_client(self._connect_to_redis())
@property
def _has_redis_client(self):
return hasattr(self.application.tinman, self.REDIS_CLIENT)
def _connect_to_redis(self):
LOGGER.debug('Connecting to redis: %r', self._redis_connection_settings)
client = tornadoredis.Client(**self._redis_connection_settings)
client.connect()
return client
@property
def _redis_connection_settings(self):
return {'host': self._redis_settings.get('host', self.REDIS_HOST),
'port': self._redis_settings.get('port', self.REDIS_PORT),
'selected_db': self._redis_settings.get('db', self.REDIS_DB)}
@property
def _redis_settings(self):
LOGGER.debug('Redis settings')
return self.application.settings.get('redis', dict())
def _set_redis_client(self, client):
setattr(self.application.tinman, self.REDIS_CLIENT, client)
@property
def redis_client(self):
LOGGER.debug('Returning redis client')
return getattr(self.application.tinman, self.REDIS_CLIENT, None)
|
bsd-3-clause
|
Python
|
65972062c03133a79ff77d90f8a11fd16f7d16ff
|
Correct column name
|
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
|
luigi/tasks/rfam/pgload_go_term_mapping.py
|
luigi/tasks/rfam/pgload_go_term_mapping.py
|
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.go_terms.pgload_go_terms import PGLoadGoTerms
from .go_term_mapping_csv import RfamGoTermsCSV
from .pgload_families import RfamPGLoadFamilies
CONTROL_FILE = """LOAD CSV
FROM '{filename}' WITH ENCODING ISO-8859-14
HAVING FIELDS
(
go_term_id,
rfam_model_id
)
INTO {db_url}
TARGET COLUMNS
(
go_term_id,
rfam_model_id
)
SET
search_path = '{search_path}'
WITH
skip header = 1,
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists load_rfam_go_terms (
go_term_id character varying(10) COLLATE pg_catalog."default" NOT NULL,
rfam_model_id character varying(20) COLLATE pg_catalog."default" NOT NULL
);
$$,
$$
truncate table load_rfam_go_terms;
$$
AFTER LOAD DO
$$ insert into rfam_go_terms (
go_term_id,
rfam_model_id
) (
select
go_term_id,
rfam_model_id
from load_rfam_go_terms
)
ON CONFLICT (go_term_id, rfam_model_id) DO UPDATE SET
go_term_id = excluded.go_term_id,
rfam_model_id = excluded.rfam_model_id
;
$$,
$$
drop table load_rfam_go_terms;
$$
;
"""
class RfamPGLoadGoTerms(PGLoader): # pylint: disable=R0904
"""
This will run pgloader on the Rfam go term mapping CSV file. The importing
will update any existing mappings and will not produce duplicates.
"""
def requires(self):
return [
RfamGoTermsCSV(),
PGLoadGoTerms(),
RfamPGLoadFamilies(),
]
def control_file(self):
filename = RfamGoTermsCSV().output().fn
return CONTROL_FILE.format(
filename=filename,
db_url=self.db_url(table='load_rfam_go_terms'),
search_path=self.db_search_path(),
)
|
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 tasks.utils.pgloader import PGLoader
from tasks.go_terms.pgload_go_terms import PGLoadGoTerms
from .go_term_mapping_csv import RfamGoTermsCSV
from .pgload_families import RfamPGLoadFamilies
CONTROL_FILE = """LOAD CSV
FROM '{filename}' WITH ENCODING ISO-8859-14
HAVING FIELDS
(
go_term_id,
rfam_model_id
)
INTO {db_url}
TARGET COLUMNS
(
go_term_id,
name
)
SET
search_path = '{search_path}'
WITH
skip header = 1,
fields escaped by double-quote,
fields terminated by ','
BEFORE LOAD DO
$$
create table if not exists load_rfam_go_terms (
go_term_id character varying(10) COLLATE pg_catalog."default" NOT NULL,
rfam_model_id character varying(20) COLLATE pg_catalog."default" NOT NULL
);
$$,
$$
truncate table load_rfam_go_terms;
$$
AFTER LOAD DO
$$ insert into rfam_go_terms (
go_term_id,
rfam_model_id
) (
select
go_term_id,
rfam_model_id
from load_rfam_go_terms
)
ON CONFLICT (go_term_id, rfam_model_id) DO UPDATE SET
go_term_id = excluded.go_term_id,
rfam_model_id = excluded.rfam_model_id
;
$$,
$$
drop table load_rfam_go_terms;
$$
;
"""
class RfamPGLoadGoTerms(PGLoader): # pylint: disable=R0904
"""
This will run pgloader on the Rfam go term mapping CSV file. The importing
will update any existing mappings and will not produce duplicates.
"""
def requires(self):
return [
RfamGoTermsCSV(),
PGLoadGoTerms(),
RfamPGLoadFamilies(),
]
def control_file(self):
filename = RfamGoTermsCSV().output().fn
return CONTROL_FILE.format(
filename=filename,
db_url=self.db_url(table='load_rfam_go_terms'),
search_path=self.db_search_path(),
)
|
apache-2.0
|
Python
|
a9aad224d6875e774cd0f7db7e30965ea6a3fbdc
|
Fix simple typo: taget -> target (#591)
|
keon/algorithms
|
algorithms/search/jump_search.py
|
algorithms/search/jump_search.py
|
import math
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain target value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
|
import math
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain taget value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
|
mit
|
Python
|
9c062d779fe7cb3fc439ff03f25ade58f6045ee5
|
fix PythonActivity path
|
TangibleDisplay/twiz
|
androidhelpers.py
|
androidhelpers.py
|
from jnius import PythonJavaClass, java_method, autoclass
# SERVICE = Autoclass('org.renpy.PythonService').mService
SERVICE = autoclass('org.renpy.android.PythonActivity').mActivity
Intent = autoclass('android.content.Intent')
BluetoothManager = SERVICE.getSystemService(SERVICE.BLUETOOTH_SERVICE)
ADAPTER = BluetoothManager.getAdapter()
REQUEST_ENABLE_BT = 0x100
def activity_result(request_code, result_code, data):
print("get result: %s, %s, %s" % (
request_code == REQUEST_ENABLE_BT, result_code, data))
def start_scanning(callback):
if not ADAPTER.isEnabled():
SERVICE.startActivityForResult(
Intent(ADAPTER.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT)
SERVICE.bind(on_activity_result=activity_result)
else:
ADAPTER.startLeScan(callback)
def stop_scanning(callback):
ADAPTER.stopLeScan(callback)
class AndroidScanner(PythonJavaClass):
__javainterfaces__ = ['android.bluetooth.BluetoothAdapter$LeScanCallback']
@java_method('Landroid.bluetooth.BluetoothDevice,I,[B')
def onLeScan(device, irssi, scan_record):
print device.getName()
print irssi
print scan_record
|
from jnius import PythonJavaClass, java_method, autoclass
# SERVICE = Autoclass('org.renpy.PythonService').mService
SERVICE = autoclass('org.renpy.PythonActivity').mActivity
Intent = autoclass('android.content.Intent')
BluetoothManager = SERVICE.getSystemService(SERVICE.BLUETOOTH_SERVICE)
ADAPTER = BluetoothManager.getAdapter()
REQUEST_ENABLE_BT = 0x100
def activity_result(request_code, result_code, data):
print("get result: %s, %s, %s" % (
request_code == REQUEST_ENABLE_BT, result_code, data))
def start_scanning(callback):
if not ADAPTER.isEnabled():
SERVICE.startActivityForResult(
Intent(ADAPTER.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT)
SERVICE.bind(on_activity_result=activity_result)
else:
ADAPTER.startLeScan(callback)
def stop_scanning(callback):
ADAPTER.stopLeScan(callback)
class AndroidScanner(PythonJavaClass):
__javainterfaces__ = ['android.bluetooth.BluetoothAdapter$LeScanCallback']
@java_method('Landroid.bluetooth.BluetoothDevice,I,[B')
def onLeScan(device, irssi, scan_record):
print device.getName()
print irssi
print scan_record
|
mit
|
Python
|
9ff6f01f7319270f66e2cc32aa5201ad53228e8f
|
Add __init__ and __call_internal__ for isotropicHernquistdf
|
jobovy/galpy,jobovy/galpy,jobovy/galpy,jobovy/galpy
|
galpy/df/isotropicHernquistdf.py
|
galpy/df/isotropicHernquistdf.py
|
# Class that implements isotropic spherical Hernquist DF
# computed using the Eddington formula
from .sphericaldf import sphericaldf
from .Eddingtondf import Eddingtondf
class isotropicHernquistdf(Eddingtondf):
"""Class that implements isotropic spherical Hernquist DF computed using the Eddington formula"""
def __init__(self,pot=None,ro=None,vo=None):
# Initialize using sphericaldf rather than Eddingtondf, because
# Eddingtondf will have code specific to computing the Eddington
# integral, which is not necessary for Hernquist
sphericaldf.__init__(self,pot=pot,ro=ro,vo=vo)
def __call_internal__(self,*args):
"""
NAME:
__call_internal__
PURPOSE
Calculate the distribution function for an isotropic Hernquist
INPUT:
E - The energy
OUTPUT:
fH - The distribution function
HISTORY:
2020-07 - Written
"""
E = args[0]
if _APY_LOADED and isinstance(E,units.quantity.Quantity):
E.to(units.km**2/units.s**2).value/vo**2.
# Scale energies
phi0 = evaluatePotentials(self._pot,0,0)
Erel = -E
Etilde = Erel/phi0
# Handle potential E out of bounds
Etilde_out = numpy.where(Etilde<0|Etilde>1)[0]
if len(Etilde_out)>0:
# Set to dummy and 0 later, prevents functions throwing errors?
Etilde[Etilde_out]=0.5
_GMa = phi0*self._pot.a**2.
fH = numpy.power((2**0.5)*((2*numpy.pi)**3) *((_GMa)**1.5),-1)\
*(numpy.sqrt(Etilde)/numpy.power(1-Etilde,2))\
*((1-2*Etilde)*(8*numpy.power(Etilde,2)-8*Etilde-3)\
+((3*numpy.arcsin(numpy.sqrt(Etilde)))\
/numpy.sqrt(Etilde*(1-Etilde))))
# Fix out of bounds values
if len(Etilde_out) > 0:
fH[Etilde_out] = 0
return fH
|
# Class that implements isotropic spherical Hernquist DF
# computed using the Eddington formula
from .sphericaldf import sphericaldf
from .Eddingtondf import Eddingtondf
class isotropicHernquistdf(Eddingtondf):
"""Class that implements isotropic spherical Hernquist DF computed using the Eddington formula"""
def __init__(self,ro=None,vo=None):
# Initialize using sphericaldf rather than Eddingtondf, because
# Eddingtondf will have code specific to computing the Eddington
# integral, which is not necessary for Hernquist
sphericaldf.__init__(self,ro=ro,vo=vo)
def fE(self,E):
# Stub for computing f(E)
return None
|
bsd-3-clause
|
Python
|
c5c509ff9e2c4599fcf51044abc9e7cbe4a152e1
|
remove redundant method [skip ci]
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
|
custom/enikshay/management/commands/base_model_reconciliation.py
|
custom/enikshay/management/commands/base_model_reconciliation.py
|
import csv
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import EmailMessage
from django.conf import settings
from custom.enikshay.const import ENROLLED_IN_PRIVATE
class BaseModelReconciliationCommand(BaseCommand):
email_subject = None
result_file_name_prefix = None
result_file_headers = None
def __init__(self, *args, **kwargs):
super(BaseModelReconciliationCommand, self).__init__(*args, **kwargs)
self.commit = False
self.recipient = None
self.result_file_name = None
def add_arguments(self, parser):
parser.add_argument('--commit', action='store_true')
parser.add_argument('--recipient', type=str)
def handle(self, *args, **options):
raise CommandError(
"This is the base reconciliation class and should not be run. "
"One of it's inherited commands should be run.")
def public_app_case(self, person_case):
if person_case.get_case_property(ENROLLED_IN_PRIVATE) == 'true':
return False
return True
def email_report(self):
csv_file = open(self.result_file_name)
email = EmailMessage(
subject=self.email_subject,
body="Please find attached report for a %s run finished at %s." %
('real' if self.commit else 'mock', datetime.now()),
to=self.recipient,
from_email=settings.DEFAULT_FROM_EMAIL
)
email.attach(filename=self.result_file_name, content=csv_file.read())
csv_file.close()
email.send()
def setup_result_file(self):
file_name = "{file_name_prefix}_{timestamp}.csv".format(
file_name_prefix=self.result_file_name_prefix,
timestamp=datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
)
with open(file_name, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=self.result_file_headers)
writer.writeheader()
return file_name
def writerow(self, row):
with open(self.result_file_name, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=self.result_file_headers)
writer.writerow(row)
|
import csv
from datetime import datetime
from django.core.management.base import BaseCommand, CommandError
from django.core.mail import EmailMessage
from django.conf import settings
from custom.enikshay.const import ENROLLED_IN_PRIVATE
class BaseModelReconciliationCommand(BaseCommand):
email_subject = None
result_file_name_prefix = None
result_file_headers = None
def __init__(self, *args, **kwargs):
super(BaseModelReconciliationCommand, self).__init__(*args, **kwargs)
self.commit = False
self.recipient = None
self.result_file_name = None
def add_arguments(self, parser):
parser.add_argument('--commit', action='store_true')
parser.add_argument('--recipient', type=str)
def handle(self, *args, **options):
raise CommandError(
"This is the base reconciliation class and should not be run. "
"One of it's inherited commands should be run.")
def public_app_case(self, person_case):
if person_case.get_case_property(ENROLLED_IN_PRIVATE) == 'true':
return False
return True
@staticmethod
def get_result_file_headers():
raise NotImplementedError
def email_report(self):
csv_file = open(self.result_file_name)
email = EmailMessage(
subject=self.email_subject,
body="Please find attached report for a %s run finished at %s." %
('real' if self.commit else 'mock', datetime.now()),
to=self.recipient,
from_email=settings.DEFAULT_FROM_EMAIL
)
email.attach(filename=self.result_file_name, content=csv_file.read())
csv_file.close()
email.send()
def setup_result_file(self):
file_name = "{file_name_prefix}_{timestamp}.csv".format(
file_name_prefix=self.result_file_name_prefix,
timestamp=datetime.now().strftime("%Y-%m-%d-%H-%M-%S"),
)
with open(file_name, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=self.get_result_file_headers)
writer.writeheader()
return file_name
def writerow(self, row):
with open(self.result_file_name, 'a') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=self.get_result_file_headers)
writer.writerow(row)
|
bsd-3-clause
|
Python
|
8f90b8cd67b6bca0c8c2123c229b18bd0ee078d8
|
Implement FlatfileCommentProvider._load_one.
|
rescrv/firmant
|
firmant/plugins/datasource/flatfile/comments.py
|
firmant/plugins/datasource/flatfile/comments.py
|
import datetime
import pytz
import os
import re
from firmant.utils import not_implemented
from firmant.datasource.comments import Comment
comment_re = r'(?P<year>\d{4}),(?P<month>\d{2}),(?P<day>\d{2}),(?P<slug>.+)' +\
r',(?P<created>[1-9][0-9]*),(?P<id>[0-9a-f]{40})'
comment_re = re.compile(comment_re)
class FlatfileCommentProvider(object):
def __init__(self, rc, settings):
self.settings = settings
def for_entry(self, status, slug, year, month, day):
not_implemented()
def _load_one(self, status, entry_pkey, created, id):
comment_dt = entry_pkey[0].strftime('%Y,%m,%d')
comment_filename = '%s,%s,%i,%s' % \
(comment_dt, entry_pkey[1], created, id)
comment_path = os.path.join(self.settings['FLATFILE_BASE'],
'comments',
status,
comment_filename)
if not os.access(comment_path, os.R_OK):
return None
f = open(comment_path)
d = f.read()
f.close()
headers, content = d.split('\n\n', 1)
comment = Comment()
for header in headers.split('\n'):
if header.startswith('Name:\t'):
comment.name = header[6:]
elif header.startswith('Email:\t'):
comment.email = header[7:]
elif header.startswith('URL:\t'):
comment.url = header[5:]
elif header.startswith('Host:\t'):
comment.ip = header[6:]
elif header.startswith('Agent:\t'):
comment.useragent = header[7:]
if content.endswith('\n'):
content = content[:-1]
comment.content = content
comment.status = status
comment.entry_pkey = entry_pkey
created_dt = datetime.datetime.fromtimestamp(created)
comment.created = pytz.utc.localize(created_dt)
return comment
|
import datetime
import pytz
import os
import re
from firmant.utils import not_implemented
comment_re = r'(?P<year>\d{4}),(?P<month>\d{2}),(?P<day>\d{2}),(?P<slug>.+)' +\
r',(?P<created>[1-9][0-9]*),(?P<id>[0-9a-f]{40})'
comment_re = re.compile(comment_re)
class FlatfileCommentProvider(object):
def __init__(self, rc, settings):
self.settings = settings
def for_entry(self, status, slug, year, month, day):
not_implemented()
|
bsd-3-clause
|
Python
|
68ecbb59c856a20f8f00cae47f1075086da982c7
|
Add bitmask imports to nddata.__init__.py
|
dhomeier/astropy,saimn/astropy,lpsinger/astropy,StuartLittlefair/astropy,bsipocz/astropy,lpsinger/astropy,dhomeier/astropy,larrybradley/astropy,astropy/astropy,dhomeier/astropy,mhvk/astropy,aleksandr-bakanov/astropy,aleksandr-bakanov/astropy,bsipocz/astropy,larrybradley/astropy,pllim/astropy,stargaser/astropy,stargaser/astropy,MSeifert04/astropy,StuartLittlefair/astropy,saimn/astropy,astropy/astropy,MSeifert04/astropy,pllim/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,saimn/astropy,mhvk/astropy,astropy/astropy,lpsinger/astropy,mhvk/astropy,lpsinger/astropy,pllim/astropy,lpsinger/astropy,stargaser/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,saimn/astropy,astropy/astropy,MSeifert04/astropy,dhomeier/astropy,bsipocz/astropy,astropy/astropy,mhvk/astropy,pllim/astropy,larrybradley/astropy,larrybradley/astropy,saimn/astropy,stargaser/astropy,pllim/astropy,dhomeier/astropy,MSeifert04/astropy,mhvk/astropy,larrybradley/astropy,aleksandr-bakanov/astropy,bsipocz/astropy
|
astropy/nddata/__init__.py
|
astropy/nddata/__init__.py
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, because it provides metadata that cannot
be easily provided by a single array.
"""
from .nddata import *
from .nddata_base import *
from .nddata_withmixins import *
from .nduncertainty import *
from .flag_collection import *
from .decorators import *
from .mixins.ndarithmetic import *
from .mixins.ndslicing import *
from .mixins.ndio import *
from .compat import *
from .utils import *
from .ccddata import *
from .bitmask import *
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.nddata`.
"""
warn_unsupported_correlated = _config.ConfigItem(
True,
'Whether to issue a warning if `~astropy.nddata.NDData` arithmetic '
'is performed with uncertainties and the uncertainties do not '
'support the propagation of correlated uncertainties.'
)
warn_setting_unit_directly = _config.ConfigItem(
True,
'Whether to issue a warning when the `~astropy.nddata.NDData` unit '
'attribute is changed from a non-``None`` value to another value '
'that data values/uncertainties are not scaled with the unit change.'
)
conf = Conf()
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The `astropy.nddata` subpackage provides the `~astropy.nddata.NDData`
class and related tools to manage n-dimensional array-based data (e.g.
CCD images, IFU Data, grid-based simulation data, ...). This is more than
just `numpy.ndarray` objects, because it provides metadata that cannot
be easily provided by a single array.
"""
from .nddata import *
from .nddata_base import *
from .nddata_withmixins import *
from .nduncertainty import *
from .flag_collection import *
from .decorators import *
from .mixins.ndarithmetic import *
from .mixins.ndslicing import *
from .mixins.ndio import *
from .compat import *
from .utils import *
from .ccddata import *
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.nddata`.
"""
warn_unsupported_correlated = _config.ConfigItem(
True,
'Whether to issue a warning if `~astropy.nddata.NDData` arithmetic '
'is performed with uncertainties and the uncertainties do not '
'support the propagation of correlated uncertainties.'
)
warn_setting_unit_directly = _config.ConfigItem(
True,
'Whether to issue a warning when the `~astropy.nddata.NDData` unit '
'attribute is changed from a non-``None`` value to another value '
'that data values/uncertainties are not scaled with the unit change.'
)
conf = Conf()
|
bsd-3-clause
|
Python
|
1156be60da01ee34230dcf5e9e993e72fbe7b635
|
make linter happy
|
ivelum/djangoql,ivelum/djangoql,ivelum/djangoql
|
test_project/test_project/urls.py
|
test_project/test_project/urls.py
|
"""test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include
from django.contrib import admin
try:
from django.urls import re_path # Django >= 4.0
except ImportError:
try:
from django.conf.urls import re_path # Django < 4.0
except ImportError: # Django < 2.0
from django.conf.urls import url as re_path
from core.views import completion_demo
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', completion_demo),
]
if settings.DEBUG and settings.DJDT:
import debug_toolbar
urlpatterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
"""test_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf import settings
from django.conf.urls import include
from django.contrib import admin
try:
from django.urls import re_path # Django >= 4.0
except ImportError:
try:
from django.conf.urls import re_path # Django < 4.0
except ImportError: # Django < 2.0
from django.conf.urls import url as re_path
from core.views import completion_demo
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
re_path(r'^$', completion_demo),
]
if settings.DEBUG and settings.DJDT:
import debug_toolbar
urlpatterns = [
re_path(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
|
mit
|
Python
|
e716a71bad4e02410e2a0908d630abbee1d4c691
|
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
|
schinckel/django,DasIch/django,coldmind/django,rwillmer/django,jpic/django,techdragon/django,abomyi/django,EmadMokhtar/Django,koniiiik/django,auvipy/django,elkingtonmcb/django,Balachan27/django,jscn/django,darkryder/django,lunafeng/django,sergei-maertens/django,Leila20/django,chyeh727/django,huang4fstudio/django,saydulk/django,gitaarik/django,redhat-openstack/django,mitar/django,litchfield/django,zulip/django,yakky/django,digimarc/django,takeshineshiro/django,Adnn/django,willhardy/django,blaze33/django,digimarc/django,rogerhu/django,hobarrera/django,whs/django,eyohansa/django,gengue/django,akaariai/django,mjtamlyn/django,Beeblio/django,elky/django,lmorchard/django,ajaali/django,WSDC-NITWarangal/django,zanderle/django,jhoos/django,YYWen0o0/python-frame-django,charettes/django,mathspace/django,MikeAmy/django,twz915/django,stevenewey/django,googleinterns/django,errx/django,ajaali/django,AndrewGrossman/django,seanwestfall/django,doismellburning/django,SujaySKumar/django,marqueedev/django,darkryder/django,jdelight/django,yamila-moreno/django,lsqtongxin/django,rajsadho/django,kisna72/django,MarkusH/django,Proggie02/TestRepo,rrrene/django,tbeadle/django,davgibbs/django,WSDC-NITWarangal/django,jenalgit/django,xwolf12/django,kcpawan/django,tcwicklund/django,hunter007/django,ccn-2m/django,zhoulingjun/django,PetrDlouhy/django,bliti/django-nonrel-1.5,fenginx/django,hellhovnd/django,rogerhu/django,alx-eu/django,YangSongzhou/django,frePPLe/django,tomchristie/django,Vixionar/django,atul-bhouraskar/django,kcpawan/django,oinopion/django,weiawe/django,daniponi/django,ryangallen/django,GhostThrone/django,edevil/django,tomchristie/django,programadorjc/django,MoritzS/django,gitaarik/django,rsalmaso/django,archen/django,tbeadle/django,hnakamur/django,zanderle/django,fafaman/django,webgeodatavore/django,zhoulingjun/django,andresgz/django,avneesh91/django,django-nonrel/django,epandurski/django,gannetson/django,elena/django,frdb194/django,mshafiq9/django,payeldillip/django,leekchan/django_test,atul-bhouraskar/django,Argon-Zhou/django,wkschwartz/django,liu602348184/django,irwinlove/django,manhhomienbienthuy/django,ckirby/django,alilotfi/django,vsajip/django,wkschwartz/django,mcella/django,mathspace/django,gunchleoc/django,quxiaolong1504/django,reinout/django,dsanders11/django,bak1an/django,dex4er/django,Y3K/django,techdragon/django,ajaali/django,GaussDing/django,shacker/django,Beeblio/django,donkirkby/django,frdb194/django,rlugojr/django,druuu/django,rsvip/Django,loic/django,denys-duchier/django,willhardy/django,ckirby/django,Nepherhotep/django,sam-tsai/django,HousekeepLtd/django,hkchenhongyi/django,elkingtonmcb/django,ptoraskar/django,oscaro/django,frankvdp/django,h4r5h1t/django-hauthy,mitchelljkotler/django,z0by/django,Proggie02/TestRepo,auvipy/django,felixxm/django,etos/django,scorphus/django,ptoraskar/django,sgzsh269/django,chrisfranzen/django,asser/django,joakim-hove/django,joequery/django,django/django,SoftwareMaven/django,kcpawan/django,runekaagaard/django-contrib-locking,webgeodatavore/django,taaviteska/django,gdub/django,theo-l/django,sarvex/django,xwolf12/django,AlexHill/django,takeshineshiro/django,mcrowson/django,rsalmaso/django,double-y/django,mitchelljkotler/django,litchfield/django,dbaxa/django,kangfend/django,django-nonrel/django,PolicyStat/django,beni55/django,spisneha25/django,deployed/django,synasius/django,olasitarska/django,NullSoldier/django,ar45/django,fafaman/django,marckuz/django,shaistaansari/django,varunnaganathan/django,follow99/django,lmorchard/django,ckirby/django,memtoko/django,frishberg/django,abomyi/django,xrmx/django,bitcity/django,xadahiya/django,ABaldwinHunter/django-clone,eyohansa/django,takis/django,nhippenmeyer/django,claudep/django,yewang15215/django,liavkoren/djangoDev,MarcJoan/django,mrbox/django,rlugojr/django,tayfun/django,marckuz/django,ticosax/django,kcpawan/django,beckastar/django,dgladkov/django,ryanahall/django,kaedroho/django,pquentin/django,rapilabs/django,mcardillo55/django,hkchenhongyi/django,arun6582/django,hottwaj/django,zsiciarz/django,jarshwah/django,rlugojr/django,sadaf2605/django,nhippenmeyer/django,github-account-because-they-want-it/django,blueyed/django,aisipos/django,karyon/django,loic/django,jgeskens/django,aidanlister/django,mlavin/django,rapilabs/django,jylaxp/django,t0in4/django,caotianwei/django,krishna-pandey-git/django,zedr/django,GaussDing/django,asser/django,double-y/django,ericfc/django,andresgz/django,dbaxa/django,craynot/django,wkschwartz/django,sergei-maertens/django,Y3K/django,JavML/django,tbeadle/django,avanov/django,redhat-openstack/django,drjeep/django,shownomercy/django,crazy-canux/django,jasonbot/django,hackerbot/DjangoDev,willharris/django,ericholscher/django,iambibhas/django,dwightgunning/django,frePPLe/django,ghedsouza/django,benspaulding/django,kswiat/django,yask123/django,rhertzog/django,chyeh727/django,ArnossArnossi/django,tragiclifestories/django,mcella/django,hassanabidpk/django,rwillmer/django,wsmith323/django,mojeto/django,mojeto/django,double-y/django,divio/django,denys-duchier/django,peterlauri/django,mbox/django,dfdx2/django,tysonclugg/django,djbaldey/django,marqueedev/django,marcelocure/django,andreif/django,benjaminjkraft/django,gunchleoc/django,Beauhurst/django,marqueedev/django,darkryder/django,marctc/django,harisibrahimkv/django,salamer/django,vitan/django,timgraham/django,schinckel/django,extremewaysback/django,jaywreddy/django,sjlehtin/django,SebasSBM/django,sdcooke/django,mammique/django,adamchainz/django,shtouff/django,edmorley/django,riteshshrv/django,runekaagaard/django-contrib-locking,savoirfairelinux/django,rsalmaso/django,felixjimenez/django,hobarrera/django,divio/django,twz915/django,ziima/django,aspidites/django,cainmatt/django,akaariai/django,alimony/django,yceruto/django,lsqtongxin/django,labcodes/django,xwolf12/django,unaizalakain/django,h4r5h1t/django-hauthy,ericholscher/django,carljm/django,makinacorpus/django,georgemarshall/django,drjeep/django,imtapps/django-imt-fork,yewang15215/django,DONIKAN/django,fenginx/django,andreif/django,leeon/annotated-django,anant-dev/django,mitya57/django,RaoUmer/django,beckastar/django,dpetzold/django,rizumu/django,vincepandolfo/django,ojake/django,imtapps/django-imt-fork,chrishas35/django-travis-ci,bspink/django,follow99/django,elky/django,tomchristie/django,seanwestfall/django,TimYi/django,GhostThrone/django,monetate/django,coldmind/django,mcella/django,Mixser/django,jrrembert/django,jnovinger/django,poiati/django,wkschwartz/django,koordinates/django,mitchelljkotler/django,codepantry/django,knifenomad/django,1013553207/django,irwinlove/django,theo-l/django,dracos/django,JavML/django,jallohm/django,felixjimenez/django,mdj2/django,apollo13/django,ironbox360/django,vincepandolfo/django,sam-tsai/django,ptoraskar/django,mshafiq9/django,blaze33/django,kaedroho/django,freakboy3742/django,tanmaythakur/django,ziima/django,WSDC-NITWarangal/django,Sonicbids/django,DasIch/django,TimYi/django,varunnaganathan/django,davgibbs/django,jscn/django,jsoref/django,barbuza/django,abomyi/django,takeshineshiro/django,loic/django,leereilly/django-1,taaviteska/django,oscaro/django,mttr/django,yakky/django,gunchleoc/django,z0by/django,kennethlove/django,hybrideagle/django,ebar0n/django,hnakamur/django,edmorley/django,barbuza/django,aspidites/django,yakky/django,riteshshrv/django,adelton/django,kaedroho/django,zhaodelong/django,hasadna/django,django-nonrel/django-nonrel,marctc/django,joakim-hove/django,chrisfranzen/django,programadorjc/django,treyhunner/django,davidharrigan/django,craynot/django,bliti/django-nonrel-1.5,mcardillo55/django,HousekeepLtd/django,kosz85/django,coldmind/django,MounirMesselmeni/django,TimBuckley/effective_django,aroche/django,jaywreddy/django,ytjiang/django,Beauhurst/django,epandurski/django,freakboy3742/django,camilonova/django,HonzaKral/django,blueyed/django,ABaldwinHunter/django-clone-classic,camilonova/django,MarkusH/django,RossBrunton/django,charettes/django,Endika/django,adambrenecki/django,akaariai/django,eyohansa/django,petecummings/django,jhoos/django,b-me/django,makinacorpus/django,ziima/django,akintoey/django,sadaf2605/django,jrrembert/django,ABaldwinHunter/django-clone,aerophile/django,extremewaysback/django,tomchristie/django,shacker/django,mojeto/django,RevelSystems/django,adelton/django,huang4fstudio/django,pelme/django,ojengwa/django-1,synasius/django,aleida/django,YangSongzhou/django,jyotsna1820/django,hobarrera/django,wetneb/django,ytjiang/django,denis-pitul/django,wsmith323/django,EliotBerriot/django,MoritzS/django,jdelight/django,pquentin/django,jrrembert/django,mcrowson/django,z0by/django,jeezybrick/django,eugena/django,adambrenecki/django,etos/django,BMJHayward/django,akshatharaj/django,BlindHunter/django,zedr/django,indevgr/django,erikr/django,vitaly4uk/django,dfunckt/django,MikeAmy/django,harisibrahimkv/django,takis/django,follow99/django,auready/django,deployed/django,github-account-because-they-want-it/django,nealtodd/django,Y3K/django,kholidfu/django,zerc/django,jasonbot/django,dsanders11/django,yograterol/django,JorgeCoock/django,dudepare/django,duqiao/django,gdi2290/django,vitaly4uk/django,rynomster/django,hackerbot/DjangoDev,karyon/django,gannetson/django,beni55/django,joakim-hove/django,Balachan27/django,druuu/django,lsqtongxin/django,jhoos/django,rsvip/Django,peterlauri/django,eugena/django,guettli/django,tysonclugg/django,yograterol/django,scorphus/django,donkirkby/django,sadaf2605/django,yceruto/django,andela-ooladayo/django,irwinlove/django,gcd0318/django,aerophile/django,x111ong/django,ryanahall/django,areski/django,wetneb/django,alrifqi/django,matiasb/django,xrmx/django,pjdelport/django,andyzsf/django,jmcarp/django,mewtaylor/django,neiudemo1/django,AndrewGrossman/django,vmarkovtsev/django,zerc/django,synasius/django,apocquet/django,raphaelmerx/django,GaussDing/django,mjtamlyn/django,IRI-Research/django,peterlauri/django,weiawe/django,ojake/django,myang321/django,beck/django,x111ong/django,xadahiya/django,pquentin/django,duqiao/django,davidharrigan/django,alexallah/django,tuhangdi/django,rtindru/django,rmboggs/django,xrmx/django,aerophile/django,wweiradio/django,gdi2290/django,mbox/django,phalt/django,KokareIITP/django,krisys/django,wweiradio/django,ataylor32/django,willhardy/django,lwiecek/django,charettes/django,rapilabs/django,megaumi/django,sopier/django,ABaldwinHunter/django-clone-classic,yewang15215/django,fenginx/django,akshatharaj/django,leekchan/django_test,jmcarp/django,zhoulingjun/django,sgzsh269/django,hobarrera/django,haxoza/django,phalt/django,aisipos/django,pasqualguerrero/django,oberlin/django,jasonwzhy/django,Matt-Deacalion/django,haxoza/django,extremewaysback/django,joequery/django,dwightgunning/django,roselleebarle04/django,krisys/django,redhat-openstack/django,yograterol/django,akshatharaj/django,koordinates/django,mitchelljkotler/django,TridevGuha/django,aidanlister/django,shacker/django,ticosax/django,denis-pitul/django,erikr/django,nju520/django,duqiao/django,shownomercy/django,postrational/django,vitaly4uk/django,mattrobenolt/django,dydek/django,nemesisdesign/django,whs/django,monetate/django,mlavin/django,ajoaoff/django,jylaxp/django,ironbox360/django,simone/django-gb,t0in4/django,donkirkby/django,kisna72/django,knifenomad/django,avanov/django,frdb194/django,frePPLe/django,quamilek/django,jgoclawski/django,cainmatt/django,gchp/django,druuu/django,hunter007/django,Yong-Lee/django,phalt/django,mattrobenolt/django,HonzaKral/django,anant-dev/django,alimony/django,github-account-because-they-want-it/django,megaumi/django,mrfuxi/django,takeshineshiro/django,divio/django,vitan/django,jallohm/django,willhardy/django,ccn-2m/django,delhivery/django,jvkops/django,NullSoldier/django,aleida/django,abomyi/django,ryangallen/django,ojengwa/django-1,kennethlove/django,mcardillo55/django,darjeeling/django,dudepare/django,leekchan/django_test,alexmorozov/django,wweiradio/django,yigitguler/django,TimYi/django,Yong-Lee/django,himleyb85/django,github-account-because-they-want-it/django,jgoclawski/django,hybrideagle/django,poiati/django,sgzsh269/django,blindroot/django,Argon-Zhou/django,programadorjc/django,gcd0318/django,sdcooke/django,hottwaj/django,dex4er/django,jeezybrick/django,eugena/django,avneesh91/django,marctc/django,TridevGuha/django,pauloxnet/django,epandurski/django,mrfuxi/django,akaihola/django,ifduyue/django,uranusjr/django,Adnn/django,gohin/django,h4r5h1t/django-hauthy,edmorley/django,kutenai/django,oinopion/django,hynekcer/django,Beauhurst/django,hnakamur/django,huang4fstudio/django,hynekcer/django,aerophile/django,simone/django-gb,jhoos/django,AltSchool/django,ABaldwinHunter/django-clone-classic,mattrobenolt/django,caotianwei/django,benjaminjkraft/django,andela-ooladayo/django,alx-eu/django,jyotsna1820/django,Balachan27/django,elkingtonmcb/django,zulip/django,ajoaoff/django,jscn/django,alrifqi/django,pipermerriam/django,GaussDing/django,elena/django,jscn/django,jejimenez/django,solarissmoke/django,Vixionar/django,jasonbot/django,double-y/django,solarissmoke/django,henryfjordan/django,liuliwork/django,adrianholovaty/django,marqueedev/django,liavkoren/djangoDev,JorgeCoock/django,marissazhou/django,imtapps/django-imt-fork,waytai/django,elky/django,HonzaKral/django,nielsvanoch/django,KokareIITP/django,auvipy/django,riteshshrv/django,chrisfranzen/django,syaiful6/django,whs/django,HousekeepLtd/django,kangfend/django,ar45/django,googleinterns/django,x111ong/django,frankvdp/django,areski/django,oberlin/django,sadaf2605/django,DONIKAN/django,ericfc/django,kevintaw/django,aspidites/django,unaizalakain/django,rrrene/django,jmcarp/django,alilotfi/django,cainmatt/django,megaumi/django,treyhunner/django,joequery/django,seocam/django,indevgr/django,RossBrunton/django,edevil/django,alx-eu/django,elijah513/django,nhippenmeyer/django,asser/django,AlexHill/django,t0in4/django,savoirfairelinux/django,andyzsf/django,elijah513/django,jhg/django,hkchenhongyi/django,darkryder/django,rajsadho/django,risicle/django,simonw/django,camilonova/django,jarshwah/django,rizumu/django,carljm/django,RossBrunton/django,alexallah/django,extremewaysback/django,piquadrat/django,apocquet/django,NullSoldier/django,fpy171/django,guettli/django,SujaySKumar/django,rtindru/django,mttr/django,liuliwork/django,nemesisdesign/django,delhivery/django,maxsocl/django,jsoref/django,gdub/django,jn7163/django,jnovinger/django,dursk/django,beck/django,aroche/django,tcwicklund/django,SujaySKumar/django,b-me/django,auready/django,karyon/django,tuhangdi/django,shaistaansari/django,sarvex/django,himleyb85/django,curtisstpierre/django,ryangallen/django,scorphus/django,auvipy/django,jn7163/django,RossBrunton/django,ASCrookes/django,mattseymour/django,lisael/pg-django,delinhabit/django,mmardini/django,DONIKAN/django,devops2014/djangosite,synasius/django,mjtamlyn/django,dfdx2/django,b-me/django,carljm/django,yewang15215/django,aisipos/django,hybrideagle/django,BMJHayward/django,piquadrat/django,dydek/django,saydulk/django,tayfun/django,eyohansa/django,zhaodelong/django,pjdelport/django,dwightgunning/django,xwolf12/django,Y3K/django,mjtamlyn/django,dhruvagarwal/django,taaviteska/django,dex4er/django,sbellem/django,jejimenez/django,apollo13/django,takis/django,ivandevp/django,blueyed/django,ecederstrand/django,andreif/django,KokareIITP/django,SujaySKumar/django,YangSongzhou/django,jarshwah/django,avanov/django,webgeodatavore/django,ojengwa/django-1,WillGuan105/django,robhudson/django,b-me/django,beck/django,gdub/django,marctc/django,syphar/django,baylee/django,hottwaj/django,Leila20/django,salamer/django,andela-ifageyinbo/django,atul-bhouraskar/django,monetate/django,fpy171/django,matiasb/django,jpic/django,akshatharaj/django,cobalys/django,ericfc/django,Korkki/django,mrfuxi/django,mitar/django,camilonova/django,liu602348184/django,bobcyw/django,lmorchard/django,supriyantomaftuh/django,xadahiya/django,shaib/django,pasqualguerrero/django,asser/django,myang321/django,dursk/django,seocam/django,apollo13/django,aisipos/django,uranusjr/django,techdragon/django,HonzaKral/django,PetrDlouhy/django,waytai/django,jaywreddy/django,erikr/django,marcelocure/django,denisenkom/django,rockneurotiko/django,ccn-2m/django,craynot/django,IRI-Research/django,shownomercy/django,leereilly/django-1,mitar/django,szopu/django,jpic/django,andela-ifageyinbo/django,bitcity/django,crazy-canux/django,varunnaganathan/django,rajsadho/django,vsajip/django,stevenewey/django,timgraham/django,daniponi/django,mlavin/django,treyhunner/django,BMJHayward/django,Adnn/django,solarissmoke/django,theo-l/django,scorphus/django,craynot/django,Beauhurst/django,mcrowson/django,rynomster/django,sbellem/django,BlindHunter/django,WillGuan105/django,tanmaythakur/django,WillGuan105/django,mathspace/django,payeldillip/django,sergei-maertens/django,ataylor32/django,hcsturix74/django,rockneurotiko/django,archen/django,BrotherPhil/django,treyhunner/django,payeldillip/django,mbox/django,katrid/django,Korkki/django,IRI-Research/django,tayfun/django,areski/django,mcella/django,henryfjordan/django,oscaro/django,ebar0n/django,dhruvagarwal/django,benjaminjkraft/django,nju520/django,rynomster/django,mcrowson/django,lunafeng/django,ghickman/django,kholidfu/django,MarcJoan/django,Endika/django,krisys/django,tayfun/django,lwiecek/django,Nepherhotep/django,darjeeling/django,arun6582/django,labcodes/django,kisna72/django,rhertzog/django,leeon/annotated-django,simonw/django,ajaali/django,hkchenhongyi/django,moreati/django,jgeskens/django,gohin/django,MoritzS/django,zhoulingjun/django,auready/django,zsiciarz/django,AndrewGrossman/django,Anonymous-X6/django,deployed/django,shtouff/django,syaiful6/django,liavkoren/djangoDev,irwinlove/django,manhhomienbienthuy/django,dursk/django,frishberg/django,baylee/django,davidharrigan/django,quxiaolong1504/django,oscaro/django,jgoclawski/django,xrmx/django,kangfend/django,zedr/django,szopu/django,alimony/django,joakim-hove/django,robhudson/django,willharris/django,ivandevp/django,filias/django,Anonymous-X6/django,spisneha25/django,nemesisdesign/django,evansd/django,django-nonrel/django-nonrel,googleinterns/django,alexmorozov/django,alrifqi/django,waytai/django,aleida/django,jarshwah/django,nemesisdesign/django,shaib/django,nju520/django,andela-ifageyinbo/django,ticosax/django,jejimenez/django,GhostThrone/django,weiawe/django,savoirfairelinux/django,jylaxp/django,django/django,shtouff/django,feroda/django,ptoraskar/django,vsajip/django,chyeh727/django,ivandevp/django,vmarkovtsev/django,beckastar/django,Leila20/django,rsalmaso/django,phalt/django,akaariai/django,timgraham/django,hellhovnd/django,drjeep/django,kevintaw/django,rtindru/django,nealtodd/django,Sonicbids/django,BrotherPhil/django,ar45/django,avneesh91/django,sjlehtin/django,spisneha25/django,maxsocl/django,tuhangdi/django,zulip/django,vitaly4uk/django,mdj2/django,bobcyw/django,moreati/django,tuhangdi/django,dsanders11/django,ojake/django,jvkops/django,googleinterns/django,matiasb/django,baylee/django,bak1an/django,Yong-Lee/django,mewtaylor/django,iambibhas/django,bobcyw/django,olasitarska/django,stewartpark/django,dgladkov/django,GitAngel/django,riklaunim/django-custom-multisite,reinout/django,ericfc/django,lzw120/django,delhivery/django,taaviteska/django,blighj/django,hcsturix74/django,sarvex/django,bliti/django-nonrel-1.5,BlindHunter/django,feroda/django,benspaulding/django,mattseymour/django,denys-duchier/django,BlindHunter/django,harisibrahimkv/django,filias/django,gohin/django,robhudson/django,wsmith323/django,aroche/django,kswiat/django,x111ong/django,ericholscher/django,varunnaganathan/django,hassanabidpk/django,riklaunim/django-custom-multisite,saydulk/django,bspink/django,quxiaolong1504/django,davgibbs/django,yamila-moreno/django,kosz85/django,rmboggs/django,bitcity/django,adelton/django,EmadMokhtar/Django,lunafeng/django,dudepare/django,arun6582/django,guettli/django,rmboggs/django,liuliwork/django,evansd/django,megaumi/django,bobcyw/django,stewartpark/django,yograterol/django,savoirfairelinux/django,SebasSBM/django,intgr/django,Korkki/django,wsmith323/django,makinacorpus/django,mdj2/django,codepantry/django,curtisstpierre/django,henryfjordan/django,georgemarshall/django,frankvdp/django,chrisfranzen/django,fpy171/django,ghedsouza/django,salamer/django,kamyu104/django,seocam/django,nealtodd/django,rsvip/Django,gitaarik/django,mattseymour/django,aidanlister/django,ASCrookes/django,yceruto/django,mmardini/django,MarcJoan/django,timgraham/django,programadorjc/django,rtindru/django,daniponi/django,wetneb/django,jasonwzhy/django,z0by/django,ironbox360/django,hasadna/django,shtouff/django,dursk/django,haxoza/django,schinckel/django,piquadrat/django,Balachan27/django,aidanlister/django,sopier/django,barbuza/django,PetrDlouhy/django,andela-ifageyinbo/django,mewtaylor/django,labcodes/django,lsqtongxin/django,koordinates/django,codepantry/django,MikeAmy/django,vmarkovtsev/django,dpetzold/django,NullSoldier/django,manhhomienbienthuy/django,roselleebarle04/django,kosz85/django,indevgr/django,myang321/django,elkingtonmcb/django,Beeblio/django,fafaman/django,willharris/django,sarthakmeh03/django,intgr/django,TimBuckley/effective_django,darjeeling/django,ulope/django,YYWen0o0/python-frame-django,ArnossArnossi/django,rizumu/django,jenalgit/django,jenalgit/django,shaistaansari/django,leereilly/django-1,tcwicklund/django,davgibbs/django,hackerbot/DjangoDev,andela-ooladayo/django,marckuz/django,jhg/django,sjlehtin/django,anant-dev/django,petecummings/django,freakboy3742/django,tragiclifestories/django,roselleebarle04/django,arun6582/django,hcsturix74/django,krishna-pandey-git/django,ABaldwinHunter/django-clone,ghickman/django,divio/django,jaywreddy/django,dsanders11/django,Mixser/django,h4r5h1t/django-hauthy,baylee/django,vincepandolfo/django,hynekcer/django,andresgz/django,wetneb/django,SebasSBM/django,blueyed/django,Argon-Zhou/django,szopu/django,sarvex/django,wweiradio/django,zanderle/django,PolicyStat/django,edmorley/django,himleyb85/django,shaistaansari/django,kevintaw/django,lwiecek/django,blaze33/django,Beeblio/django,joequery/django,oinopion/django,payeldillip/django,Matt-Deacalion/django,mshafiq9/django,chrishas35/django-travis-ci,MarcJoan/django,bikong2/django,bspink/django,gitaarik/django,djbaldey/django,donkirkby/django,risicle/django,jenalgit/django,Proggie02/TestRepo,JorgeCoock/django,yakky/django,andreif/django,sjlehtin/django,intgr/django,dfunckt/django,caotianwei/django,jrrembert/django,apocquet/django,nealtodd/django,krishna-pandey-git/django,evansd/django,digimarc/django,rrrene/django,Mixser/django,ifduyue/django,zerc/django,ataylor32/django,marissazhou/django,rhertzog/django,PolicyStat/django,ccn-2m/django,koniiiik/django,postrational/django,AndrewGrossman/django,tanmaythakur/django,BMJHayward/django,hunter007/django,akaihola/django,hellhovnd/django,zulip/django,solarissmoke/django,iambibhas/django,marcelocure/django,mlavin/django,dpetzold/django,PetrDlouhy/django,adamchainz/django,Vixionar/django,yigitguler/django,reinout/django,bikong2/django,JorgeCoock/django,jhg/django,gengue/django,SoftwareMaven/django,mammique/django,vincepandolfo/django,salamer/django,simonw/django,nhippenmeyer/django,marissazhou/django,jdelight/django,pelme/django,alrifqi/django,ulope/django,frankvdp/django,petecummings/django,neiudemo1/django,SoftwareMaven/django,ebar0n/django,tcwicklund/django,oberlin/django,hassanabidpk/django,Leila20/django,dwightgunning/django,nju520/django,andrewsmedina/django,MounirMesselmeni/django,karyon/django,HousekeepLtd/django,tbeadle/django,robhudson/django,katrid/django,Nepherhotep/django,ryanahall/django,tysonclugg/django,ironbox360/django,1013553207/django,caotianwei/django,riteshshrv/django,syphar/django,ABaldwinHunter/django-clone,rizumu/django,alilotfi/django,supriyantomaftuh/django,myang321/django,MarkusH/django,ajoaoff/django,jn7163/django,kisna72/django,codepantry/django,daniponi/django,tanmaythakur/django,digimarc/django,andrewsmedina/django,Sonicbids/django,gengue/django,ojengwa/django-1,elijah513/django,dracos/django,raphaelmerx/django,Anonymous-X6/django,alx-eu/django,filias/django,sarthakmeh03/django,poiati/django,webgeodatavore/django,DrMeers/django,rynomster/django,DONIKAN/django,GitAngel/django,doismellburning/django,riklaunim/django-custom-multisite,georgemarshall/django,leeon/annotated-django,pipermerriam/django,seanwestfall/django,redhat-openstack/django,kamyu104/django,mrbox/django,MatthewWilkes/django,SoftwareMaven/django,mattrobenolt/django,RevelSystems/django,DrMeers/django,MarkusH/django,TridevGuha/django,adrianholovaty/django,mewtaylor/django,pauloxnet/django,feroda/django,hellhovnd/django,YangSongzhou/django,rajsadho/django,jhg/django,RaoUmer/django,etos/django,kutenai/django,WSDC-NITWarangal/django,vitan/django,TimBuckley/effective_django,bak1an/django,seocam/django,mttr/django,curtisstpierre/django,memtoko/django,koordinates/django,mojeto/django,jsoref/django,mmardini/django,supriyantomaftuh/django,hcsturix74/django,RevelSystems/django,etos/django,charettes/django,ticosax/django,stevenewey/django,ghedsouza/django,techdragon/django,dhruvagarwal/django,rlugojr/django,alimony/django,andresgz/django,zhaodelong/django,supriyantomaftuh/django,petecummings/django,elena/django,ajoaoff/django,mathspace/django,kamyu104/django,druuu/django,rrrene/django,benspaulding/django,lzw120/django,frdb194/django,shacker/django,bspink/django,rhertzog/django,sarthakmeh03/django,mattseymour/django,blindroot/django,bikong2/django,kswiat/django,jeezybrick/django,sopier/django,dhruvagarwal/django,auready/django,quamilek/django,claudep/django,lmorchard/django,kangfend/django,lunafeng/django,blindroot/django,ArnossArnossi/django,aspidites/django,poiati/django,jgeskens/django,intgr/django,mitya57/django,theo-l/django,pipermerriam/django,kutenai/django,cainmatt/django,vmarkovtsev/django,chyeh727/django,mrbox/django,raphaelmerx/django,nielsvanoch/django,jasonwzhy/django,gannetson/django,rsvip/Django,Anonymous-X6/django,piquadrat/django,carljm/django,GitAngel/django,gchp/django,sdcooke/django,WillGuan105/django,hottwaj/django,Yong-Lee/django,krishna-pandey-git/django,shaib/django,rwillmer/django,RaoUmer/django,alexmorozov/django,dracos/django,denisenkom/django,memtoko/django,felixxm/django,vitan/django,sarthakmeh03/django,elky/django,tysonclugg/django,saydulk/django,django/django,krisys/django,schinckel/django,erikr/django,AlexHill/django,akintoey/django,pjdelport/django,xadahiya/django,adambrenecki/django,yask123/django,denys-duchier/django,rockneurotiko/django,quamilek/django,kevintaw/django,runekaagaard/django-contrib-locking,ziima/django,atul-bhouraskar/django,henryfjordan/django,eugena/django,waytai/django,EliotBerriot/django,MikeAmy/django,sephii/django,mitya57/django,bak1an/django,ASCrookes/django,claudep/django,jsoref/django,nielsvanoch/django,liu602348184/django,jyotsna1820/django,shaib/django,indevgr/django,AltSchool/django,duqiao/django,blighj/django,stewartpark/django,mttr/django,uranusjr/django,gohin/django,guettli/django,delinhabit/django,mcardillo55/django,jeezybrick/django,ASCrookes/django,jasonwzhy/django,jallohm/django,harisibrahimkv/django,gchp/django,MounirMesselmeni/django,lisael/pg-django,sdcooke/django,yamila-moreno/django,jallohm/django,simonw/django,kholidfu/django,devops2014/djangosite,DrMeers/django,anant-dev/django,EmadMokhtar/Django,AltSchool/django,ebar0n/django,Matt-Deacalion/django,beckastar/django,ytjiang/django,kamyu104/django,KokareIITP/django,litchfield/django,DasIch/django,rmboggs/django,sephii/django,simone/django-gb,TimYi/django,MatthewWilkes/django,MounirMesselmeni/django,mammique/django,avneesh91/django,jnovinger/django,sopier/django,areski/django,pelme/django,jvkops/django,dbaxa/django,koniiiik/django,djbaldey/django,apollo13/django,maxsocl/django,jylaxp/django,tragiclifestories/django,neiudemo1/django,akintoey/django,pipermerriam/django,reinout/django,pasqualguerrero/django,errx/django,blindroot/django,ckirby/django,stewartpark/django,dudepare/django,frePPLe/django,jdelight/django,ghedsouza/django,blighj/django,bitcity/django,Mixser/django,feroda/django,adelton/django,bikong2/django,ytjiang/django,sergei-maertens/django,adamchainz/django,gchp/django,davidharrigan/django,moreati/django,dydek/django,jpic/django,hassanabidpk/django,gcd0318/django,shownomercy/django,labcodes/django,seanwestfall/django,pasqualguerrero/django,pauloxnet/django,ghickman/django,helenst/django,loic/django,crazy-canux/django,manhhomienbienthuy/django,lisael/pg-django,JavML/django,postrational/django,Endika/django,django-nonrel/django,huang4fstudio/django,denis-pitul/django,takis/django,Adnn/django,katrid/django,stevenewey/django,gdi2290/django,ivandevp/django,AltSchool/django,jvkops/django,hackerbot/DjangoDev,oberlin/django,YYWen0o0/python-frame-django,zerc/django,jn7163/django,Korkki/django,marckuz/django,spisneha25/django,MatthewWilkes/django,alexallah/django,errx/django,delinhabit/django,frishberg/django,Matt-Deacalion/django,felixjimenez/django,devops2014/djangosite,uranusjr/django,ArnossArnossi/django,sbellem/django,fpy171/django,mrfuxi/django,yamila-moreno/django,1013553207/django,yask123/django,Argon-Zhou/django,sam-tsai/django,ulope/django,unaizalakain/django,rockneurotiko/django,kosz85/django,ecederstrand/django,weiawe/django,gdub/django,ghickman/django,marcelocure/django,blighj/django,coldmind/django,gcd0318/django,BrotherPhil/django,benjaminjkraft/django,1013553207/django,sephii/django,jgoclawski/django,raphaelmerx/django,jyotsna1820/django,dfunckt/django,dracos/django,elijah513/django,felixjimenez/django,follow99/django,epandurski/django,denis-pitul/django,cobalys/django,mrbox/django,apocquet/django,TridevGuha/django,sbellem/django,moreati/django,adamchainz/django,monetate/django,djbaldey/django,zsiciarz/django,gunchleoc/django,hynekcer/django,ecederstrand/django,unaizalakain/django,jmcarp/django,EliotBerriot/django,andela-ooladayo/django,t0in4/django,peterlauri/django,hnakamur/django,alexmorozov/django,beni55/django,tragiclifestories/django,kholidfu/django,yask123/django,DasIch/django,syaiful6/django,cobalys/django,knifenomad/django,litchfield/django,kutenai/django,katrid/django,filias/django,willharris/django,RaoUmer/django,mmardini/django,MatthewWilkes/django,andyzsf/django,rwillmer/django,ecederstrand/django,dfdx2/django,himleyb85/django,pauloxnet/django,hybrideagle/django,fenginx/django,ifduyue/django,drjeep/django,ryangallen/django,helenst/django,dgladkov/django,twz915/django,syaiful6/django,curtisstpierre/django,liuliwork/django,zsiciarz/django,ABaldwinHunter/django-clone-classic,felixxm/django,jnovinger/django,georgemarshall/django,jasonbot/django,MoritzS/django,sam-tsai/django,neiudemo1/django,django-nonrel/django-nonrel,haxoza/django,dfdx2/django,gengue/django,akaihola/django,andrewsmedina/django,whs/django,django/django,avanov/django,quamilek/django,archen/django,olasitarska/django,akintoey/django,frishberg/django,matiasb/django,jejimenez/django,GhostThrone/django,JavML/django,koniiiik/django,barbuza/django,marissazhou/django,dgladkov/django,SebasSBM/django,hunter007/django,ataylor32/django,alilotfi/django,mitya57/django,BrotherPhil/django,django-nonrel/django,dbaxa/django,knifenomad/django,elena/django,syphar/django,oinopion/django,ifduyue/django,felixxm/django,ojake/django,helenst/django,risicle/django,ryanahall/django,maxsocl/django,beck/django,lzw120/django,twz915/django,hasadna/django,Nepherhotep/django,gannetson/django,crazy-canux/django,risicle/django,ar45/django,kennethlove/django,liu602348184/django,zhaodelong/django,delinhabit/django,delhivery/django,edevil/django,darjeeling/django,GitAngel/django,RevelSystems/django,roselleebarle04/django,lwiecek/django,quxiaolong1504/django,evansd/django,rapilabs/django,EliotBerriot/django,zanderle/django,adrianholovaty/django,dydek/django,sgzsh269/django,dfunckt/django,alexallah/django,mshafiq9/django,Endika/django,dpetzold/django,claudep/django,Vixionar/django,doismellburning/django,fafaman/django,denisenkom/django,Proggie02/TestRepo,syphar/django,rogerhu/django,yigitguler/django,chrishas35/django-travis-ci,aroche/django,beni55/django
|
django/contrib/admin/__init__.py
|
django/contrib/admin/__init__.py
|
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here
# has been referenced in documentation.
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's admin module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
# (see #8245).
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an admin module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'admin'):
raise
|
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL
from django.contrib.admin.options import StackedInline, TabularInline
from django.contrib.admin.sites import AdminSite, site
def autodiscover():
"""
Auto-discover INSTALLED_APPS admin.py modules and fail silently when
not present. This forces an import on them to register any admin bits they
may want.
"""
import copy
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
mod = import_module(app)
# Attempt to import the app's admin module.
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
# Reset the model registry to the state before the last import as
# this import will have to reoccur on the next request and this
# could raise NotRegistered and AlreadyRegistered exceptions
# (see #8245).
site._registry = before_import_registry
# Decide whether to bubble up this error. If the app just
# doesn't have an admin module, we can ignore the error
# attempting to import it, otherwise we want it to bubble up.
if module_has_submodule(mod, 'admin'):
raise
|
bsd-3-clause
|
Python
|
74b3b60cfe6f12f119ac91f04177abc4c7427e5c
|
bump version
|
kmaehashi/sensorbee-python
|
sensorbee/_version.py
|
sensorbee/_version.py
|
# -*- coding: utf-8 -*-
__version__ = '0.1.2'
|
# -*- coding: utf-8 -*-
__version__ = '0.1.1'
|
mit
|
Python
|
ff41218c0a63959a34969eefafd9951c48ef667f
|
convert `test/test_sparql/test_sparql_parser.py` to pytest (#2063)
|
RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib
|
test/test_sparql/test_sparql_parser.py
|
test/test_sparql/test_sparql_parser.py
|
import math
import sys
from typing import Set, Tuple
from rdflib import Graph, Literal
from rdflib.namespace import Namespace
from rdflib.plugins.sparql.processor import processUpdate
from rdflib.term import Node
def triple_set(graph: Graph) -> Set[Tuple[Node, Node, Node]]:
return set(graph.triples((None, None, None)))
class TestSPARQLParser:
def test_insert_recursionlimit(self) -> None:
# These values are experimentally determined
# to cause the RecursionError reported in
# https://github.com/RDFLib/rdflib/issues/1336
resource_count = math.ceil(sys.getrecursionlimit() / (33 - 3))
self.do_insert(resource_count)
def test_insert_large(self) -> None:
self.do_insert(200)
def do_insert(self, resource_count: int) -> None:
EGV = Namespace("http://example.org/vocab#")
EGI = Namespace("http://example.org/instance#")
prop0, prop1, prop2 = EGV["prop0"], EGV["prop1"], EGV["prop2"]
g0 = Graph()
for index in range(resource_count):
resource = EGI[f"resource{index}"]
g0.add((resource, prop0, Literal(index)))
g0.add((resource, prop1, Literal("example resource")))
g0.add((resource, prop2, Literal(f"resource #{index}")))
g0ntriples = g0.serialize(format="ntriples")
g1 = Graph()
assert triple_set(g0) != triple_set(g1)
processUpdate(g1, f"INSERT DATA {{ {g0ntriples!s} }}")
assert triple_set(g0) == triple_set(g1)
|
import math
import sys
import unittest
from typing import Set, Tuple
from rdflib import Graph, Literal
from rdflib.namespace import Namespace
from rdflib.plugins.sparql.processor import processUpdate
from rdflib.term import Node
def triple_set(graph: Graph) -> Set[Tuple[Node, Node, Node]]:
return set(graph.triples((None, None, None)))
class SPARQLParserTests(unittest.TestCase):
def test_insert_recursionlimit(self) -> None:
# These values are experimentally determined
# to cause the RecursionError reported in
# https://github.com/RDFLib/rdflib/issues/1336
resource_count = math.ceil(sys.getrecursionlimit() / (33 - 3))
self.do_insert(resource_count)
def test_insert_large(self) -> None:
self.do_insert(200)
def do_insert(self, resource_count: int) -> None:
EGV = Namespace("http://example.org/vocab#")
EGI = Namespace("http://example.org/instance#")
prop0, prop1, prop2 = EGV["prop0"], EGV["prop1"], EGV["prop2"]
g0 = Graph()
for index in range(resource_count):
resource = EGI[f"resource{index}"]
g0.add((resource, prop0, Literal(index)))
g0.add((resource, prop1, Literal("example resource")))
g0.add((resource, prop2, Literal(f"resource #{index}")))
g0ntriples = g0.serialize(format="ntriples")
g1 = Graph()
self.assertNotEqual(triple_set(g0), triple_set(g1))
processUpdate(g1, f"INSERT DATA {{ {g0ntriples!s} }}")
self.assertEqual(triple_set(g0), triple_set(g1))
if __name__ == "__main__":
unittest.main()
|
bsd-3-clause
|
Python
|
7e24165c828a64389d593c63299df4ff22dcb881
|
disable swagger docs for tests
|
aexeagmbh/django-rest-auth,SakuradaJun/django-rest-auth,citizen-stig/django-rest-auth,ZachLiuGIS/django-rest-auth,SakuradaJun/django-rest-auth,alacritythief/django-rest-auth,philippeluickx/django-rest-auth,serxoz/django-rest-auth,bopo/django-rest-auth,bung87/django-rest-auth,julioeiras/django-rest-auth,flexpeace/django-rest-auth,jerinzam/django-rest-auth,serxoz/django-rest-auth,elberthcabrales/django-rest-auth,gushedaoren/django-rest-auth,bung87/django-rest-auth,alacritythief/django-rest-auth,Tivix/django-rest-auth,caruccio/django-rest-auth,antetna/django-rest-auth,mjrulesamrat/django-rest-auth,eugena/django-rest-auth,caruccio/django-rest-auth,kdzch/django-rest-auth,roopesh90/django-rest-auth,flexpeace/django-rest-auth,maxim-kht/django-rest-auth,jerinzam/django-rest-auth,mjrulesamrat/django-rest-auth,gushedaoren/django-rest-auth,eugena/django-rest-auth,roopesh90/django-rest-auth,illing2005/django-rest-auth,julioeiras/django-rest-auth,ZachLiuGIS/django-rest-auth,iHub/django-rest-auth,illing2005/django-rest-auth,georgemarshall/django-rest-auth,iHub/django-rest-auth,citizen-stig/django-rest-auth,maxim-kht/django-rest-auth,georgemarshall/django-rest-auth,bopo/django-rest-auth,antetna/django-rest-auth,elberthcabrales/django-rest-auth
|
rest_auth/urls.py
|
rest_auth/urls.py
|
from django.conf import settings
from django.conf.urls import patterns, url, include
from rest_auth.views import Login, Logout, Register, UserDetails, \
PasswordChange, PasswordReset, VerifyEmail, PasswordResetConfirm
urlpatterns = patterns('rest_auth.views',
# URLs that do not require a session or valid token
url(r'^register/$', Register.as_view(),
name='rest_register'),
url(r'^password/reset/$', PasswordReset.as_view(),
name='rest_password_reset'),
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirm.as_view(
), name='rest_password_reset_confirm'),
url(r'^login/$', Login.as_view(), name='rest_login'),
url(r'^verify-email/(?P<activation_key>\w+)/$',
VerifyEmail.as_view(), name='verify_email'),
# URLs that require a user to be logged in with a valid
# session / token.
url(r'^logout/$', Logout.as_view(), name='rest_logout'),
url(r'^user/$', UserDetails.as_view(),
name='rest_user_details'),
url(r'^password/change/$', PasswordChange.as_view(),
name='rest_password_change'),
)
if settings.DEBUG and not settings.IS_TEST:
urlpatterns += patterns('',
# Swagger Docs
url(r'^docs/',
include('rest_framework_swagger.urls')),
)
|
from django.conf import settings
from django.conf.urls import patterns, url, include
from rest_auth.views import Login, Logout, Register, UserDetails, \
PasswordChange, PasswordReset, VerifyEmail, PasswordResetConfirm
urlpatterns = patterns('rest_auth.views',
# URLs that do not require a session or valid token
url(r'^register/$', Register.as_view(),
name='rest_register'),
url(r'^password/reset/$', PasswordReset.as_view(),
name='rest_password_reset'),
url(r'^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirm.as_view(
), name='rest_password_reset_confirm'),
url(r'^login/$', Login.as_view(), name='rest_login'),
url(r'^verify-email/(?P<activation_key>\w+)/$',
VerifyEmail.as_view(), name='verify_email'),
# URLs that require a user to be logged in with a valid
# session / token.
url(r'^logout/$', Logout.as_view(), name='rest_logout'),
url(r'^user/$', UserDetails.as_view(),
name='rest_user_details'),
url(r'^password/change/$', PasswordChange.as_view(),
name='rest_password_change'),
)
if settings.DEBUG:
urlpatterns += patterns('',
# Swagger Docs
url(r'^docs/',
include('rest_framework_swagger.urls')),
)
|
mit
|
Python
|
33ef365bffb3aefa053409a72d44b069bdae8c77
|
Make django middleware not crash if user isn't set.
|
rhettg/BlueOx
|
blueox/contrib/django/middleware.py
|
blueox/contrib/django/middleware.py
|
import sys
import traceback
import logging
import blueox
from django.conf import settings
class Middleware(object):
def __init__(self):
host = getattr(settings, 'BLUEOX_HOST', '127.0.0.1')
port = getattr(settings, 'BLUEOX_PORT', 3514)
blueox.configure(host, port)
def process_request(self, request):
request.blueox = blueox.Context(".".join((getattr(settings, 'BLUEOX_NAME', ''), 'request')))
request.blueox.start()
blueox.set('method', request.method)
blueox.set('path', request.path)
headers = {}
for k,v in request.META.iteritems():
if k.startswith('HTTP_') or k in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
headers[k] = v
blueox.set('headers', headers)
blueox.set('uri', request.build_absolute_uri())
blueox.set('client_ip', request.META['REMOTE_ADDR'])
return None
def process_response(self, request, response):
# process_request() is not guaranteed to be called
if not hasattr(request, 'blueox'):
return response
# We collect some additional data in the response, just to ensure
# middleware ordering doesn't matter.
if hasattr(request, 'user'):
blueox.set('user', request.user.id)
for key in ('version', 'revision'):
if hasattr(request, key):
blueox.set(key, getattr(request, key))
# Other middleware may have blocked our response.
if response is not None:
blueox.set('response_status_code', response.status_code)
if not response.streaming:
blueox.set('response_size', len(response.content))
headers = {}
for k, v in response.items():
headers[k] = v
blueox.set('response_headers', headers)
request.blueox.done()
return response
def process_exception(self, request, exception):
blueox.set('exception', ''.join(traceback.format_exception(*sys.exc_info())))
return None
|
import sys
import traceback
import logging
import blueox
from django.conf import settings
class Middleware:
def __init__(self):
host = getattr(settings, 'BLUEOX_HOST', '127.0.0.1')
port = getattr(settings, 'BLUEOX_PORT', 3514)
blueox.configure(host, port)
def process_request(self, request):
request.blueox = blueox.Context(".".join((getattr(settings, 'BLUEOX_NAME', ''), 'request')))
request.blueox.start()
blueox.set('method', request.method)
blueox.set('path', request.path)
headers = {}
for k,v in request.META.iteritems():
if k.startswith('HTTP_') or k in ('CONTENT_LENGTH', 'CONTENT_TYPE'):
headers[k] = v
blueox.set('headers', headers)
blueox.set('uri', request.build_absolute_uri())
blueox.set('client_ip', request.META['REMOTE_ADDR'])
for key in ('version', 'revision'):
if hasattr(request, key):
blueox.set(key, getattr(request, key))
if request.user:
blueox.set('user', request.user.id)
return None
def process_response(self, request, response):
# process_request() is not guaranteed to be called
if not hasattr(request, 'blueox'):
return response
# Other middleware may have blocked our response.
if response is not None:
blueox.set('response_status_code', response.status_code)
if not response.streaming:
blueox.set('response_size', len(response.content))
headers = {}
for k, v in response.items():
headers[k] = v
blueox.set('response_headers', headers)
request.blueox.done()
return response
def process_exception(self, request, exception):
blueox.set('exception', ''.join(traceback.format_exception(*sys.exc_info())))
return None
|
isc
|
Python
|
d1b1a6d845419b5c1b8bec3d7f3bded83cf6c9a1
|
Fix ObjectNodeItem upperBound visibility
|
amolenaar/gaphor,amolenaar/gaphor
|
gaphor/UML/actions/objectnode.py
|
gaphor/UML/actions/objectnode.py
|
"""Object node item."""
from gaphor import UML
from gaphor.core.modeling.properties import attribute
from gaphor.diagram.presentation import ElementPresentation, Named
from gaphor.diagram.shapes import Box, EditableText, IconBox, Text, draw_border
from gaphor.diagram.support import represents
from gaphor.UML.modelfactory import stereotypes_str
DEFAULT_UPPER_BOUND = "*"
@represents(UML.ObjectNode)
class ObjectNodeItem(ElementPresentation, Named):
"""Representation of object node. Object node is ordered and has upper
bound specification.
Ordering information can be hidden by user.
"""
def __init__(self, diagram, id=None):
super().__init__(
diagram,
id,
shape=IconBox(
Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text=lambda: self.subject.name or ""),
style={
"min-width": 50,
"min-height": 30,
"padding": (5, 10, 5, 10),
},
draw=draw_border,
),
Text(
text=lambda: self.subject.upperBound
not in (None, "", DEFAULT_UPPER_BOUND)
and f"{{ upperBound = {self.subject.upperBound} }}"
or "",
),
Text(
text=lambda: self.show_ordering
and self.subject.ordering
and f"{{ ordering = {self.subject.ordering} }}"
or "",
),
),
)
self.watch("subject[NamedElement].name")
self.watch("subject.appliedStereotype.classifier.name")
self.watch("subject[ObjectNode].upperBound")
self.watch("subject[ObjectNode].ordering")
self.watch("show_ordering")
show_ordering: attribute[bool] = attribute("show_ordering", bool, False)
|
"""Object node item."""
from gaphor import UML
from gaphor.core.modeling.properties import attribute
from gaphor.diagram.presentation import ElementPresentation, Named
from gaphor.diagram.shapes import Box, EditableText, IconBox, Text, draw_border
from gaphor.diagram.support import represents
from gaphor.UML.modelfactory import stereotypes_str
DEFAULT_UPPER_BOUND = "*"
@represents(UML.ObjectNode)
class ObjectNodeItem(ElementPresentation, Named):
"""Representation of object node. Object node is ordered and has upper
bound specification.
Ordering information can be hidden by user.
"""
def __init__(self, diagram, id=None):
super().__init__(
diagram,
id,
shape=IconBox(
Box(
Text(
text=lambda: stereotypes_str(self.subject),
),
EditableText(text=lambda: self.subject.name or ""),
style={
"min-width": 50,
"min-height": 30,
"padding": (5, 10, 5, 10),
},
draw=draw_border,
),
Text(
text=lambda: self.subject.upperBound
not in (None, DEFAULT_UPPER_BOUND)
and f"{{ upperBound = {self.subject.upperBound} }}",
),
Text(
text=lambda: self.show_ordering
and self.subject.ordering
and f"{{ ordering = {self.subject.ordering} }}"
or "",
),
),
)
self.watch("subject[NamedElement].name")
self.watch("subject.appliedStereotype.classifier.name")
self.watch("subject[ObjectNode].upperBound")
self.watch("subject[ObjectNode].ordering")
self.watch("show_ordering")
show_ordering: attribute[bool] = attribute("show_ordering", bool, False)
|
lgpl-2.1
|
Python
|
0d7add686605d9d86e688f9f65f617555282ab60
|
Add debugging CLI hook for email sending
|
ascoderu/opwen-cloudserver,ascoderu/opwen-cloudserver
|
opwen_email_server/backend/email_sender.py
|
opwen_email_server/backend/email_sender.py
|
from typing import Tuple
from opwen_email_server import azure_constants as constants
from opwen_email_server import config
from opwen_email_server.services.queue import AzureQueue
from opwen_email_server.services.sendgrid import SendgridEmailSender
QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_KEY,
name=constants.QUEUE_EMAIL_SEND)
EMAIL = SendgridEmailSender(key=config.EMAIL_SENDER_KEY)
def send(email: dict) -> Tuple[str, int]:
success = EMAIL.send_email(email)
if not success:
return 'error', 500
return 'sent', 200
if __name__ == '__main__':
from argparse import ArgumentParser
from json import loads
from uuid import uuid4
parser = ArgumentParser()
parser.add_argument('email')
args = parser.parse_args()
email = loads(args.email)
email.setdefault('_uid', str(uuid4()))
send(email)
|
from typing import Tuple
from opwen_email_server import azure_constants as constants
from opwen_email_server import config
from opwen_email_server.services.queue import AzureQueue
from opwen_email_server.services.sendgrid import SendgridEmailSender
QUEUE = AzureQueue(account=config.QUEUES_ACCOUNT, key=config.QUEUES_KEY,
name=constants.QUEUE_EMAIL_SEND)
EMAIL = SendgridEmailSender(key=config.EMAIL_SENDER_KEY)
def send(email: dict) -> Tuple[str, int]:
success = EMAIL.send_email(email)
if not success:
return 'error', 500
return 'sent', 200
|
apache-2.0
|
Python
|
5875de6fb894a2903ec1f10c7dbc65c7071c7732
|
Fix NullHandler logger addition
|
gmr/rabbitpy,gmr/rabbitpy,jonahbull/rabbitpy
|
rmqid/__init__.py
|
rmqid/__init__.py
|
__version__ = '0.4.0'
from rmqid.connection import Connection
from rmqid.exchange import Exchange
from rmqid.message import Message
from rmqid.queue import Queue
from rmqid.tx import Tx
from rmqid.simple import consumer
from rmqid.simple import get
from rmqid.simple import publish
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rmqid').addHandler(NullHandler())
|
__version__ = '0.4.0'
from rmqid.connection import Connection
from rmqid.exchange import Exchange
from rmqid.message import Message
from rmqid.queue import Queue
from rmqid.tx import Tx
from rmqid.simple import consumer
from rmqid.simple import get
from rmqid.simple import publish
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger().addHandler(NullHandler())
|
bsd-3-clause
|
Python
|
e3ac422da8a0c873a676b57ff796d15fac6fc532
|
change haproxy config formatting
|
madcore-ai/core,madcore-ai/core
|
bin/haproxy_get_ssl.py
|
bin/haproxy_get_ssl.py
|
#!/usr/bin/env python
import redis, sys, os, json, jinja2
from jinja2 import Template
r_server = redis.StrictRedis('127.0.0.1', db=2)
check = r_server.get("need_CSR")
if check == "1":
i_key = "owner-info"
data=json.loads (r_server.get(i_key))
email = data['Email']
hostname = data['Hostname']
frontend_conf = ""
backend_conf = ""
#### get certificate
os.system("mkdir -p /opt/certs/letsencrypt")
os.system("cd /opt/certs && openssl req -inform pem -outform der -in server.csr -out ./letsencrypt/server.der")
os.system("service haproxy stop")
request = ("cd /opt/certs/letsencrypt && letsencrypt certonly --csr server.der --standalone --non-interactive --agree-tos --email %s --standalone-supported-challenges http-01" % email)
os.system(request)
os.system(" cd /opt/certs/letsencrypt && cat 0001_chain.pem ../server.key > ../server.bundle.pem")
os.system("rm -rf /opt/certs/letsencrypt")
r_server.set("need_CSR", "0")
r_server.bgsave
### reconfigure haproxy
app_key="apps"
data_apps=r_server.get(app_key)
os.system("rm -rf /opt/haproxy/haproxy.cfg")
config_template=open('/opt/controlbox/bin/templates/haproxy.cfg').read()
if data_apps:
apps=json.loads(data_apps)
for app in apps:
i = "use_backend %s if { hdr_end(host) -i %s }\n " % (app["name"], app["name"] + "." + data['Hostname'])
frontend_conf = frontend_conf + i
ii = ("backend %s\n balance roundrobin\n server %s 127.0.0.1:%s check\n " % (app["name"], app["name"], app["port"]))
backend_conf = backend_conf + ii
template = Template(config_template)
config = (template.render(hostname=hostname, crt_path="/opt/certs/server.bundle.pem", subdomain1=frontend_conf, backend2=backend_conf))
else:
template = Template(config_template)
config = (template.render(hostname=hostname, crt_path="/opt/certs/server.bundle.pem"))
open("/opt/haproxy/haproxy.cfg", "w").write(config)
os.system("service haproxy start")
else:
print "Don't need new certificate"
|
#!/usr/bin/env python
import redis, sys, os, json, jinja2
from jinja2 import Template
r_server = redis.StrictRedis('127.0.0.1', db=2)
check = r_server.get("need_CSR")
if check == "1":
i_key = "owner-info"
data=json.loads (r_server.get(i_key))
email = data['Email']
hostname = data['Hostname']
frontend_conf = ""
backend_conf = ""
#### get certificate
os.system("mkdir -p /opt/certs/letsencrypt")
os.system("cd /opt/certs && openssl req -inform pem -outform der -in server.csr -out ./letsencrypt/server.der")
os.system("service haproxy stop")
request = ("cd /opt/certs/letsencrypt && letsencrypt certonly --csr server.der --standalone --non-interactive --agree-tos --email %s --standalone-supported-challenges http-01" % email)
os.system(request)
os.system(" cd /opt/certs/letsencrypt && cat 0001_chain.pem ../server.key > ../server.bundle.pem")
os.system("rm -rf /opt/certs/letsencrypt")
r_server.set("need_CSR", "0")
r_server.bgsave
### reconfigure haproxy
app_key="apps"
data_apps=r_server.get(app_key)
os.system("rm -rf /opt/haproxy/haproxy.cfg")
config_template=open('/opt/controlbox/bin/templates/haproxy.cfg').read()
if data_apps:
apps=json.loads(data_apps)
for app in apps:
i = "use_backend %s if { hdr_end(host) -i %s }\n " % (app["name"], app["name"] + "." + data['Hostname'])
frontend_conf = frontend_conf + i
ii = ("backend %s\n balance roundrobin\n server %s 127.0.0.1:%s check\n " % (app["name"], app["name"], app["port"]))
backend_conf = backend_conf + ii
template = Template(config_template)
config = (template.render(hostname=hostname, crt_path="/opt/certs/server.bundle.pem", subdomain1=frontend_conf, backend2=backend_conf))
else:
template = Template(config_template)
config = (template.render(hostname=hostname, crt_path="/opt/certs/server.bundle.pem"))
open("/opt/haproxy/haproxy.cfg", "w").write(config)
os.system("service haproxy start")
else:
print "Don't need new certificate"
|
mit
|
Python
|
cc6c80ad64fe7f4d4cb2b4e367c595f1b08f9d3b
|
Remove script crash when no sonos is found
|
Lilleengen/i3blocks-sonos
|
i3blocks-sonos.py
|
i3blocks-sonos.py
|
#!/usr/bin/env python3
#
# By Henrik Lilleengen ([email protected])
#
# Released under the MIT License: https://opensource.org/licenses/MIT
import soco, sys
speakers = list(soco.discover())
if len(speakers) > 0:
state = speakers[0].get_current_transport_info()['current_transport_state']
if state == 'PLAYING':
if len(sys.argv) > 1 and sys.argv[1] == "1":
speakers[0].stop()
print("")
else:
track = speakers[0].get_current_track_info()
print(" " + track['title'] + " - " + track['artist'])
else:
if len(sys.argv) > 1 and sys.argv[1] == "1":
speakers[0].play()
track = speakers[0].get_current_track_info()
print(" " + track['title'] + " - " + track['artist'])
else:
print("")
|
#!/usr/bin/env python3
#
# By Henrik Lilleengen ([email protected])
#
# Released under the MIT License: https://opensource.org/licenses/MIT
import soco, sys
speakers = list(soco.discover())
state = speakers[0].get_current_transport_info()['current_transport_state']
if state == 'PLAYING':
if len(sys.argv) > 1 and sys.argv[1] == "1":
speakers[0].stop()
print("")
else:
track = speakers[0].get_current_track_info()
print(" " + track['title'] + " - " + track['artist'])
else:
if len(sys.argv) > 1 and sys.argv[1] == "1":
speakers[0].play()
track = speakers[0].get_current_track_info()
print(" " + track['title'] + " - " + track['artist'])
else:
print("")
|
mit
|
Python
|
74084defad8222ba69340d0d983acdf33ddef17c
|
Correct the test of assertEqual failing.
|
jwg4/qual,jwg4/calexicon
|
calexicon/dates/tests/test_dates.py
|
calexicon/dates/tests/test_dates.py
|
import unittest
from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_equality(self):
self.assertTrue(self.date_wc != date(2010, 8, 1))
def test_not_equal(self):
""" Check that assertNotEqual works correctly.
The main purpose of this test is to have code
coverage for the false branch of the
custom assertEqual. """
try:
self.assertEqual(self.date_wc, date(2010, 8, 1))
except AssertionError:
pass
def test_comparisons(self):
self.assertTrue(self.date_wc < date(2010, 8, 2))
self.assertFalse(self.date_wc < date(2010, 7, 31))
self.assertTrue(self.date_wc > date(2010, 7, 2))
self.assertFalse(self.date_wc > date(2010, 8, 31))
def test_nonstrict_comparisons(self):
self.assertTrue(self.date_wc <= date(2010, 8, 2))
self.assertFalse(self.date_wc <= date(2010, 7, 31))
self.assertTrue(self.date_wc >= date(2010, 7, 2))
self.assertFalse(self.date_wc >= date(2010, 8, 31))
self.assertTrue(self.date_wc <= date(2010, 8, 1))
self.assertTrue(self.date_wc >= date(2010, 8, 1))
def test_subtraction(self):
self.assertEqual(self.date_wc - date(2012, 10, 30), timedelta(days=-821))
|
import unittest
from datetime import date, timedelta
from calexicon.dates import DateWithCalendar
class TestDateWithCalendar(unittest.TestCase):
def setUp(self):
date_dt = date(2010, 8, 1)
self.date_wc = DateWithCalendar(None, date_dt)
def test_equality(self):
self.assertTrue(self.date_wc != date(2010, 8, 1))
def test_not_equal(self):
""" Check that assertNotEqual works correctly.
The main purpose of this test is to have code
coverage for the false branch of the
custom assertEqual. """
self.assertNotEqual(self.date_wc, date(2010, 8, 1))
def test_comparisons(self):
self.assertTrue(self.date_wc < date(2010, 8, 2))
self.assertFalse(self.date_wc < date(2010, 7, 31))
self.assertTrue(self.date_wc > date(2010, 7, 2))
self.assertFalse(self.date_wc > date(2010, 8, 31))
def test_nonstrict_comparisons(self):
self.assertTrue(self.date_wc <= date(2010, 8, 2))
self.assertFalse(self.date_wc <= date(2010, 7, 31))
self.assertTrue(self.date_wc >= date(2010, 7, 2))
self.assertFalse(self.date_wc >= date(2010, 8, 31))
self.assertTrue(self.date_wc <= date(2010, 8, 1))
self.assertTrue(self.date_wc >= date(2010, 8, 1))
def test_subtraction(self):
self.assertEqual(self.date_wc - date(2012, 10, 30), timedelta(days=-821))
|
apache-2.0
|
Python
|
ce48ef985a8e79d0cd636abf2116917fde24d6d2
|
Remove an unnecessary method override
|
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative
|
candidates/tests/test_posts_view.py
|
candidates/tests/test_posts_view.py
|
from __future__ import unicode_literals
from django_webtest import WebTest
from .uk_examples import UK2015ExamplesMixin
class TestPostsView(UK2015ExamplesMixin, WebTest):
def test_single_election_posts_page(self):
response = self.app.get('/posts')
self.assertTrue(
response.html.find(
'h2', text='2015 General Election'
)
)
self.assertTrue(
response.html.find(
'a', text='Member of Parliament for Camberwell and Peckham'
)
)
def test_two_elections_posts_page(self):
self.earlier_election.current = True
self.earlier_election.save()
response = self.app.get('/posts')
self.assertTrue(
response.html.find(
'h2', text='2010 General Election'
)
)
self.assertTrue(
response.html.find(
'h2', text='2015 General Election'
)
)
|
from __future__ import unicode_literals
from django_webtest import WebTest
from .uk_examples import UK2015ExamplesMixin
class TestPostsView(UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestPostsView, self).setUp()
def test_single_election_posts_page(self):
response = self.app.get('/posts')
self.assertTrue(
response.html.find(
'h2', text='2015 General Election'
)
)
self.assertTrue(
response.html.find(
'a', text='Member of Parliament for Camberwell and Peckham'
)
)
def test_two_elections_posts_page(self):
self.earlier_election.current = True
self.earlier_election.save()
response = self.app.get('/posts')
self.assertTrue(
response.html.find(
'h2', text='2010 General Election'
)
)
self.assertTrue(
response.html.find(
'h2', text='2015 General Election'
)
)
|
agpl-3.0
|
Python
|
eb96a44e87bc29d24695ea881014d41b8fc793b1
|
split cell search out of general search function
|
mozilla/ichnaea,therewillbecode/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea
|
ichnaea/search.py
|
ichnaea/search.py
|
from statsd import StatsdTimer
from ichnaea.db import Cell, RADIO_TYPE
from ichnaea.decimaljson import quantize
def search_cell(session, data):
radio = RADIO_TYPE.get(data['radio'], 0)
cell = data['cell'][0]
mcc = cell['mcc']
mnc = cell['mnc']
lac = cell['lac']
cid = cell['cid']
query = session.query(Cell)
query = query.filter(Cell.radio == radio)
query = query.filter(Cell.mcc == mcc)
query = query.filter(Cell.mnc == mnc)
query = query.filter(Cell.cid == cid)
if lac >= 0:
query = query.filter(Cell.lac == lac)
result = query.first()
if result is None:
return
return {
'lat': quantize(result.lat),
'lon': quantize(result.lon),
'accuracy': 20000,
}
def search_request(request):
data = request.validated
if not data['cell']:
# we don't have any wifi entries yet
return {'status': 'not_found'}
session = request.celldb.session()
with StatsdTimer('get_cell_location'):
result = search_cell(session, data)
if result is None:
return {'status': 'not_found'}
return {
'status': 'ok',
'lat': result['lat'],
'lon': result['lon'],
'accuracy': result['accuracy'],
}
|
from statsd import StatsdTimer
from ichnaea.db import Cell, RADIO_TYPE
from ichnaea.decimaljson import quantize
def search_request(request):
data = request.validated
if not data['cell']:
# we don't have any wifi entries yet
return {
'status': 'not_found',
}
radio = RADIO_TYPE.get(data['radio'], 0)
cell = data['cell'][0]
mcc = cell['mcc']
mnc = cell['mnc']
lac = cell['lac']
cid = cell['cid']
session = request.celldb.session()
query = session.query(Cell)
query = query.filter(Cell.radio == radio)
query = query.filter(Cell.mcc == mcc)
query = query.filter(Cell.mnc == mnc)
query = query.filter(Cell.cid == cid)
if lac >= 0:
query = query.filter(Cell.lac == lac)
with StatsdTimer('get_cell_location'):
result = query.first()
if result is None:
return {
'status': 'not_found',
}
return {
'status': 'ok',
'lat': quantize(result.lat),
'lon': quantize(result.lon),
'accuracy': 20000,
}
|
apache-2.0
|
Python
|
a64215f5b6b242893448478a2dfdd4c4b2f6ac46
|
Add the actual content to test_cc_license.py
|
creativecommons/cc.license,creativecommons/cc.license
|
cc/license/tests/test_cc_license.py
|
cc/license/tests/test_cc_license.py
|
"""Tests for functionality within the cc.license module.
This file is a catch-all for tests with no place else to go."""
import cc.license
def test_locales():
locales = cc.license.locales()
for l in locales:
assert type(l) == unicode
for c in ('en', 'de', 'he', 'ja', 'fr'):
assert c in locales
|
mit
|
Python
|
|
014925aa73e85fe3cb0d939a3d5d9c30424e32b4
|
Add Numbers and Symbols Exception
|
MohamadKh75/Arthon
|
func.py
|
func.py
|
# PyArt by MohamadKh75
# 2017-10-05
# ********************
from pathlib import Path
# Set the Alphabet folder path
folder_path = Path("Alphabet").resolve()
# Read all Capital Letters - AA is Capital A
def letter_reader(letter):
# if it's Capital - AA is Capital A
if 65 <= ord(letter) <= 90:
letter_file = open(str(folder_path) + str("\\") + str(letter) + str(letter) + ".txt", 'r')
letter_txt = letter_file.read()
# if it's small - a is small a
elif 97 <= ord(letter) <= 122:
letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r')
letter_txt = letter_file.read()
# if it's symbol or number - NOT SUPPORTED in Ver. 1.0
else:
print("Sorry, Numbers and Symbols are NOT supported yet :)\n"
"I'll Add them in Ver. 2.0")
return
print(letter_txt)
letter_file.close()
|
# PyArt by MohamadKh75
# 2017-10-05
# ********************
from pathlib import Path
# Set the Alphabet folder path
folder_path = Path("Alphabet").resolve()
# Read all Capital Letters - AA is Capital A
def letter_reader(letter):
# if it's Capital - AA is Capital A
if 65 <= ord(letter) <= 90:
letter_file = open(str(folder_path) + str("\\") + str(letter) + str(letter) + ".txt", 'r')
letter_txt = letter_file.read()
# if it's small - a is small a
elif 97 <= ord(letter) <= 122:
letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r')
letter_txt = letter_file.read()
# if it's symbol
else:
letter_file = open(str(folder_path) + str("\\") + str(letter) + ".txt", 'r')
letter_txt = letter_file.read()
print(letter_txt)
letter_file.close()
|
mit
|
Python
|
262e60aa8da3430c860e574e8141495bc7043cab
|
Move hook render logic from app to hook
|
vtemian/git-to-trello,vtemian/git-to-trello
|
hook.py
|
hook.py
|
import json
from flask import Blueprint, render_template, request
import requests
import config
hook = Blueprint('hooks', __name__, 'templates')
@hook.route('/hook')
def home():
return render_template('new.html')
@hook.route('/hook/new', methods=['POST'])
def new():
data = {
"name": request.form['name'],
"active": request.form['active'] if 'active' in request.form else 'false',
"events": request.form['events'].split(','),
"config": {
"url": request.form['url'],
"content_type": request.form['content_type']
}
}
auth_url = "?access_token=%s" % config.GITHUB_TOKEN
url = "%s%s" % ("https://api.github.com/repos/vtemian/todopy/hooks", auth_url)
response = requests.post(url, data=json.dumps(data))
return render_template('response.html', response=response.content)
@hook.route('/hook/push', methods=['POST'])
def push():
data = json.loads(request.data)
print data['state'], data['sha'], data['pull_request']['body']
return render_template('response.html', response='awsm')
|
import json
from flask import Blueprint, render_template, request
import requests
import config
hook = Blueprint('hooks', __name__, 'templates')
@hook.route('/hook/new', methods=['POST'])
def new():
data = {
"name": request.form['name'],
"active": request.form['active'] if 'active' in request.form else 'false',
"events": request.form['events'].split(','),
"config": {
"url": request.form['url'],
"content_type": request.form['content_type']
}
}
auth_url = "?access_token=%s" % config.GITHUB_TOKEN
url = "%s%s" % ("https://api.github.com/repos/vtemian/todopy/hooks", auth_url)
response = requests.post(url, data=json.dumps(data))
return render_template('response.html', response=response.content)
@hook.route('/hook/push', methods=['POST'])
def push():
data = json.loads(request.data)
print data['state'], data['sha'], data['pull_request']['body']
return render_template('response.html', response='awsm')
|
mit
|
Python
|
b82b8d7af363b58902e1aa3920b26c47f5b34aa4
|
Use python3 if available to run gen_git_source.py.
|
tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,karllessard/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,annarev/tensorflow,gunan/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,aldian/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,gunan/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,frreiss/tensorflow-fred,sarvex/tensorflow,petewarden/tensorflow,annarev/tensorflow,aldian/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,petewarden/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,aldian/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,renyi533/tensorflow,yongtang/tensorflow,gunan/tensorflow,annarev/tensorflow,arborh/tensorflow,aldian/tensorflow,Intel-Corporation/tensorflow,aldian/tensorflow,aam-at/tensorflow,adit-chandra/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,freedomtan/tensorflow,sarvex/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,annarev/tensorflow,karllessard/tensorflow,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,annarev/tensorflow,petewarden/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,gunan/tensorflow,arborh/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_saved_model,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,Intel-tensorflow/tensorflow,arborh/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,annarev/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,xzturn/tensorflow,renyi533/tensorflow,aldian/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,xzturn/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,gunan/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,renyi533/tensorflow,Intel-Corporation/tensorflow,gunan/tensorflow,aam-at/tensorflow,sarvex/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,xzturn/tensorflow,cxxgtxy/tensorflow,jhseu/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,davidzchen/tensorflow,davidzchen/tensorflow,jhseu/tensorflow,xzturn/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,sarvex/tensorflow,sarvex/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,arborh/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,Intel-Corporation/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,arborh/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,Intel-tensorflow/tensorflow,jhseu/tensorflow,karllessard/tensorflow,karllessard/tensorflow,jhseu/tensorflow,yongtang/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,jhseu/tensorflow,ppwwyyxx/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,ppwwyyxx/tensorflow,xzturn/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,aldian/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,xzturn/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,adit-chandra/tensorflow,tensorflow/tensorflow-pywrap_saved_model,freedomtan/tensorflow,petewarden/tensorflow,jhseu/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,jhseu/tensorflow,arborh/tensorflow,gunan/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,aldian/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jhseu/tensorflow,tensorflow/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,jhseu/tensorflow,Intel-Corporation/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,Intel-tensorflow/tensorflow,freedomtan/tensorflow,arborh/tensorflow,tensorflow/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,renyi533/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,karllessard/tensorflow,gunan/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,arborh/tensorflow,arborh/tensorflow,gautam1858/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,ppwwyyxx/tensorflow,renyi533/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,davidzchen/tensorflow
|
third_party/git/git_configure.bzl
|
third_party/git/git_configure.bzl
|
"""Repository rule for Git autoconfiguration.
`git_configure` depends on the following environment variables:
* `PYTHON_BIN_PATH`: location of python binary.
"""
_PYTHON_BIN_PATH = "PYTHON_BIN_PATH"
def _fail(msg):
"""Output failure message when auto configuration fails."""
red = "\033[0;31m"
no_color = "\033[0m"
fail("%sGit Configuration Error:%s %s\n" % (red, no_color, msg))
def _get_python_bin(repository_ctx):
"""Gets the python bin path."""
python_bin = repository_ctx.os.environ.get(_PYTHON_BIN_PATH)
if python_bin != None:
return python_bin
python_bin_path = repository_ctx.which("python3")
if python_bin_path != None:
return str(python_bin_path)
python_bin_path = repository_ctx.which("python")
if python_bin_path != None:
return str(python_bin_path)
_fail("Cannot find python in PATH, please make sure " +
"python is installed and add its directory in PATH, or --define " +
"%s='/something/else'.\nPATH=%s" % (
_PYTHON_BIN_PATH,
repository_ctx.os.environ.get("PATH", ""),
))
def _git_conf_impl(repository_ctx):
repository_ctx.template(
"BUILD",
Label("//third_party/git:BUILD.tpl"),
)
tensorflow_root_path = str(repository_ctx.path(
Label("@org_tensorflow//:BUILD"),
))[:-len("BUILD")]
python_script_path = repository_ctx.path(
Label("@org_tensorflow//tensorflow/tools/git:gen_git_source.py"),
)
generated_files_path = repository_ctx.path("gen")
r = repository_ctx.execute(
["test", "-f", "%s/.git/logs/HEAD" % tensorflow_root_path],
)
if r.return_code == 0:
unused_var = repository_ctx.path(Label("//:.git/HEAD")) # pylint: disable=unused-variable
result = repository_ctx.execute([
_get_python_bin(repository_ctx),
python_script_path,
"--configure",
tensorflow_root_path,
"--gen_root_path",
generated_files_path,
], quiet = False)
if not result.return_code == 0:
_fail(result.stderr)
git_configure = repository_rule(
implementation = _git_conf_impl,
environ = [
_PYTHON_BIN_PATH,
],
)
|
"""Repository rule for Git autoconfiguration.
`git_configure` depends on the following environment variables:
* `PYTHON_BIN_PATH`: location of python binary.
"""
_PYTHON_BIN_PATH = "PYTHON_BIN_PATH"
def _fail(msg):
"""Output failure message when auto configuration fails."""
red = "\033[0;31m"
no_color = "\033[0m"
fail("%sGit Configuration Error:%s %s\n" % (red, no_color, msg))
def _get_python_bin(repository_ctx):
"""Gets the python bin path."""
python_bin = repository_ctx.os.environ.get(_PYTHON_BIN_PATH)
if python_bin != None:
return python_bin
python_bin_path = repository_ctx.which("python")
if python_bin_path != None:
return str(python_bin_path)
_fail("Cannot find python in PATH, please make sure " +
"python is installed and add its directory in PATH, or --define " +
"%s='/something/else'.\nPATH=%s" % (
_PYTHON_BIN_PATH,
repository_ctx.os.environ.get("PATH", ""),
))
def _git_conf_impl(repository_ctx):
repository_ctx.template(
"BUILD",
Label("//third_party/git:BUILD.tpl"),
)
tensorflow_root_path = str(repository_ctx.path(
Label("@org_tensorflow//:BUILD"),
))[:-len("BUILD")]
python_script_path = repository_ctx.path(
Label("@org_tensorflow//tensorflow/tools/git:gen_git_source.py"),
)
generated_files_path = repository_ctx.path("gen")
r = repository_ctx.execute(
["test", "-f", "%s/.git/logs/HEAD" % tensorflow_root_path],
)
if r.return_code == 0:
unused_var = repository_ctx.path(Label("//:.git/HEAD")) # pylint: disable=unused-variable
result = repository_ctx.execute([
_get_python_bin(repository_ctx),
python_script_path,
"--configure",
tensorflow_root_path,
"--gen_root_path",
generated_files_path,
], quiet = False)
if not result.return_code == 0:
_fail(result.stderr)
git_configure = repository_rule(
implementation = _git_conf_impl,
environ = [
_PYTHON_BIN_PATH,
],
)
|
apache-2.0
|
Python
|
6968792b38981616b7a00526d2ab24985dcd2ce3
|
include host flags in cluster command
|
blaze/distributed,amosonn/distributed,amosonn/distributed,dask/distributed,dask/distributed,broxtronix/distributed,dask/distributed,amosonn/distributed,mrocklin/distributed,dask/distributed,broxtronix/distributed,blaze/distributed,broxtronix/distributed,mrocklin/distributed,mrocklin/distributed
|
distributed/cluster.py
|
distributed/cluster.py
|
import paramiko
from time import sleep
from toolz import assoc
def start_center(addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dcenter --host %s\n' % addr)
channel.recv(10000)
return {'client': ssh, 'channel': channel}
def start_worker(center_addr, addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dworker %s:8787\n --host %s' % (center_addr, addr))
channel.recv(10000)
return {'client': ssh, 'channel': channel}
class Cluster(object):
def __init__(self, center, workers):
self.center = assoc(start_center(center), 'address', center)
self.workers = [assoc(start_worker(center, worker), 'address', worker)
for worker in workers]
sleep(1)
self.report()
def report(self):
self.center['channel'].settimeout(1)
print("Center\n------")
print(self.center['channel'].recv(10000).decode())
for worker in self.workers:
channel = worker['channel']
address = worker['address']
channel.settimeout(1)
print("Worker: %s\n---------" % address+ '-' * len(address))
print(channel.recv(10000).decode())
def add_worker(self, address):
self.workers.append(assoc(start_worker(self.center['address'], address),
'address', address))
def close(self):
for d in self.workers:
d['channel'].close()
self.center['channel'].close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
|
import paramiko
from time import sleep
from toolz import assoc
def start_center(addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dcenter\n')
channel.recv(10000)
return {'client': ssh, 'channel': channel}
def start_worker(center_addr, addr):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(addr)
channel = ssh.invoke_shell()
channel.settimeout(20)
sleep(0.1)
channel.send('dworker %s:8787\n' % center_addr)
channel.recv(10000)
return {'client': ssh, 'channel': channel}
class Cluster(object):
def __init__(self, center, workers):
self.center = assoc(start_center(center), 'address', center)
self.workers = [assoc(start_worker(center, worker), 'address', worker)
for worker in workers]
sleep(1)
self.report()
def report(self):
self.center['channel'].settimeout(1)
print("Center\n------")
print(self.center['channel'].recv(10000).decode())
for worker in self.workers:
channel = worker['channel']
address = worker['address']
channel.settimeout(1)
print("Worker: %s\n---------" % address+ '-' * len(address))
print(channel.recv(10000).decode())
def add_worker(self, address):
self.workers.append(assoc(start_worker(self.center['address'], address),
'address', address))
def close(self):
for d in self.workers:
d['channel'].close()
self.center['channel'].close()
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
|
bsd-3-clause
|
Python
|
ed6d94d27d4274c5a1b282c6d092852ea0a5626d
|
Fix exception on User admin registration if not already registered. Closes #40
|
kavdev/djangotoolbox,Knotis/djangotoolbox
|
djangotoolbox/admin.py
|
djangotoolbox/admin.py
|
from django import forms
from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
'is_staff', 'is_superuser')
class CustomUserAdmin(UserAdmin):
fieldsets = None
form = UserForm
search_fields = ('=username',)
list_filter = ('is_staff', 'is_superuser', 'is_active')
try:
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
except NotRegistered:
pass
try:
admin.site.unregister(Group)
except NotRegistered:
pass
|
from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
'is_staff', 'is_superuser')
class CustomUserAdmin(UserAdmin):
fieldsets = None
form = UserForm
search_fields = ('=username',)
list_filter = ('is_staff', 'is_superuser', 'is_active')
admin.site.unregister(User)
admin.site.unregister(Group)
admin.site.register(User, CustomUserAdmin)
|
bsd-3-clause
|
Python
|
917013e2e5c02a4a263f13c1874736fca5ad2cf9
|
combine import statement
|
RaymondKlass/entity-extract
|
entity_extract/examples/pos_extraction.py
|
entity_extract/examples/pos_extraction.py
|
#from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.utilities import SentSplit, Tokenizer
from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.pos_tagger import PosTagger
#p = PosExtractor()
#data = p.extract_entities('This is a sentence about the pie in the sky. If would be interesting. If only there was')
#for d in data:
# print d
|
#from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.utilities import SentSplit
from entity_extract.extractor.utilities import Tokenizer
from entity_extract.extractor.extractors import PosExtractor
from entity_extract.extractor.pos_tagger import PosTagger
#p = PosExtractor()
#data = p.extract_entities('This is a sentence about the pie in the sky. If would be interesting. If only there was')
#for d in data:
# print d
|
mit
|
Python
|
995209472d9a9a843d05f0649da38015f8e8a195
|
update requirements for metadata extractor
|
usc-isi-i2/etk,usc-isi-i2/etk,usc-isi-i2/etk
|
etk/extractors/html_metadata_extractor.py
|
etk/extractors/html_metadata_extractor.py
|
from typing import List
from etk.extractor import Extractor
from etk.etk_extraction import Extraction, Extractable
class HTMLMetadataExtractor(Extractor):
"""
Extracts META, microdata, JSON-LD and RDFa from HTML pages.
Uses https://stackoverflow.com/questions/36768068/get-meta-tag-content-property-with-beautifulsoup-and-python to
extract the META tags
Uses https://github.com/scrapinghub/extruct to extract metadata from HTML pages
"""
def __init__(self):
pass
@property
def input_type(self):
"""
The type of input that an extractor wants
Returns: HTML text
"""
return self.InputType.TEXT
# @property
def name(self):
return "HTML metadata extractor"
# @property
def category(self):
return "HTML extractor"
def extract(self, extractables: List[Extractable],
extract_meta: bool = True,
extract_microdata: bool = True,
extract_json_ld: bool = True,
extract_rdfa: bool = True) \
-> List[Extraction]:
"""
Args:
extractables ():
extract_meta ():
extract_microdata ():
extract_json_ld ():
extract_rdfa ():
Returns: List[Extraction], where each extraction contains a dict with each type of metadata.
"""
pass
|
from typing import List
from etk.extractor import Extractor
from etk.etk_extraction import Extraction, Extractable
class HTMLMetadataExtractor(Extractor):
"""
Extracts microdata, JSON-LD and RDFa from HTML pages
"""
def __init__(self):
"consider parameterizing as in extruct, to select only specific types of metadata."
pass
@property
def input_type(self):
"""
The type of input that an extractor wants
Returns: HTML text
"""
return self.InputType.TEXT
# @property
def name(self):
return "HTML metadata extractor"
# @property
def category(self):
return "HTML extractor"
def extract(self, extractables: List[Extractable]) -> List[Extraction]:
"""
Uses https://github.com/scrapinghub/extruct to extract metadata from HTML pages
Args:
extractables (List[Extractable]): each extractable is expected to contain an HTML string.
Returns: List[Extraction], where each extraction contains the dict returned by extruct
"""
pass
|
mit
|
Python
|
fbe268300142a47d4923109bd7ee81689084dd7b
|
add z, objectIndex, compositing and alpha attribute to Options
|
CaptainDesAstres/Blender-Render-Manager,CaptainDesAstres/Simple-Blender-Render-Manager
|
settingMod/Options.py
|
settingMod/Options.py
|
#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Rendering Options'''
import xml.etree.ElementTree as xmlMod
import os
class Options:
'''class to manage Rendering Options'''
def __init__(self, xml= None):
'''initialize Rendering Options with default value or values extracted from an xml object'''
if xml is None:
self.defaultInit()
else:
self.fromXml(xml)
def defaultInit(self):
'''initialize Rendering Options with default value'''
self.z = True
self.objectIndex = True
self.compositing = False
self.alpha = True
def fromXml(self, xml):
'''initialize Rendering Options with values extracted from an xml object'''
self.z = xml.find('z') is not None
self.objectIndex = xml.find('objectIndex') is not None
self.compositing = xml.find('compositing') is not None
self.alpha = xml.find('alpha') is not None
def toXml(self):
'''export Rendering Options into xml syntaxed string'''
txt = '<options>\n'
if self.z:
txt += '<z />\n'
if self.objectIndex:
txt += '<objectIndex />\n'
if self.compositing:
txt += '<compositing />\n'
if self.alpha:
txt += '<alpha />\n'
txt += '</options>\n'
return txt
def see(self, log, versions):
'''menu to explore and edit Rendering Options settings'''
change = False
log.menuIn('Rendering Options')
while True:
os.system('clear')
log.print()
self.print()
print('''\n\n Menu :
0- Save and quit
''')
choice = input('Action?').strip().lower()
if choice in ['0', 'q', 'quit', 'cancel']:
log.menuOut()
return change
else:
log.error('Unvalid menu choice', False)
def print(self):
'''a method to print Rendering Options'''
|
#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
'''module to manage Rendering Options'''
import xml.etree.ElementTree as xmlMod
import os
class Options:
'''class to manage Rendering Options'''
def __init__(self, xml= None):
'''initialize Rendering Options with default value or values extracted from an xml object'''
if xml is None:
self.defaultInit()
else:
self.fromXml(xml)
def defaultInit(self):
'''initialize Rendering Options with default value'''
def fromXml(self, xml):
'''initialize Rendering Options with values extracted from an xml object'''
def toXml(self):
'''export Rendering Options into xml syntaxed string'''
txt = '<options>\n'
txt += '</options>\n'
return txt
def see(self, log, versions):
'''menu to explore and edit Rendering Options settings'''
change = False
log.menuIn('Rendering Options')
while True:
os.system('clear')
log.print()
self.print()
print('''\n\n Menu :
0- Save and quit
''')
choice = input('Action?').strip().lower()
if choice in ['0', 'q', 'quit', 'cancel']:
log.menuOut()
return change
else:
log.error('Unvalid menu choice', False)
def print(self):
'''a method to print Rendering Options'''
|
mit
|
Python
|
51b611fa8d1a8b2567aec21bd7aee8eeecb6d12a
|
Remove another comment from is_list_like docstring that's no longer relevant
|
prat0318/bravado-core
|
bravado_core/schema.py
|
bravado_core/schema.py
|
from collections import Mapping
from bravado_core.exception import SwaggerMappingError
# 'object' and 'array' are omitted since this should really be read as
# "Swagger types that map to python primitives"
SWAGGER_PRIMITIVES = (
'integer',
'number',
'string',
'boolean',
'null',
)
def has_default(swagger_spec, schema_object_spec):
return 'default' in swagger_spec.deref(schema_object_spec)
def get_default(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('default')
def is_required(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('required', False)
def has_format(swagger_spec, schema_object_spec):
return 'format' in swagger_spec.deref(schema_object_spec)
def get_format(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('format')
def is_param_spec(swagger_spec, schema_object_spec):
return 'in' in swagger_spec.deref(schema_object_spec)
def is_ref(spec):
return is_dict_like(spec) and '$ref' in spec
def is_dict_like(spec):
"""
:param spec: swagger object specification in dict form
:rtype: boolean
"""
return isinstance(spec, Mapping)
def is_list_like(spec):
"""
:param spec: swagger object specification in dict form
:rtype: boolean
"""
return type(spec) in (list, tuple)
def get_spec_for_prop(swagger_spec, object_spec, object_value, prop_name):
"""Given a jsonschema object spec and value, retrieve the spec for the
given property taking 'additionalProperties' into consideration.
:param object_spec: spec for a jsonschema 'object' in dict form
:param object_value: jsonschema object containing the given property. Only
used in error message.
:param prop_name: name of the property to retrieve the spec for
:return: spec for the given property or None if no spec found
:rtype: dict
"""
deref = swagger_spec.deref
props_spec = deref(object_spec).get('properties', {})
prop_spec = deref(props_spec).get(prop_name)
if prop_spec is not None:
return deref(prop_spec)
additional_props = deref(object_spec).get('additionalProperties', True)
if isinstance(additional_props, bool):
# no spec for additional properties to conform to - this is basically
# a way to send pretty much anything across the wire as is.
return None
additional_props = deref(additional_props)
if is_dict_like(additional_props):
# spec that all additional props MUST conform to
return additional_props
raise SwaggerMappingError(
"Don't know what to do with `additionalProperties` in spec {0} "
"when inspecting value {1}".format(object_spec, object_value))
|
from collections import Mapping
from bravado_core.exception import SwaggerMappingError
# 'object' and 'array' are omitted since this should really be read as
# "Swagger types that map to python primitives"
SWAGGER_PRIMITIVES = (
'integer',
'number',
'string',
'boolean',
'null',
)
def has_default(swagger_spec, schema_object_spec):
return 'default' in swagger_spec.deref(schema_object_spec)
def get_default(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('default')
def is_required(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('required', False)
def has_format(swagger_spec, schema_object_spec):
return 'format' in swagger_spec.deref(schema_object_spec)
def get_format(swagger_spec, schema_object_spec):
return swagger_spec.deref(schema_object_spec).get('format')
def is_param_spec(swagger_spec, schema_object_spec):
return 'in' in swagger_spec.deref(schema_object_spec)
def is_ref(spec):
return is_dict_like(spec) and '$ref' in spec
def is_dict_like(spec):
"""
:param spec: swagger object specification in dict form
:rtype: boolean
"""
return isinstance(spec, Mapping)
def is_list_like(spec):
"""No longer needed since json-ref has been excised.
:param spec: swagger object specification in dict form
:rtype: boolean
"""
return type(spec) in (list, tuple)
def get_spec_for_prop(swagger_spec, object_spec, object_value, prop_name):
"""Given a jsonschema object spec and value, retrieve the spec for the
given property taking 'additionalProperties' into consideration.
:param object_spec: spec for a jsonschema 'object' in dict form
:param object_value: jsonschema object containing the given property. Only
used in error message.
:param prop_name: name of the property to retrieve the spec for
:return: spec for the given property or None if no spec found
:rtype: dict
"""
deref = swagger_spec.deref
props_spec = deref(object_spec).get('properties', {})
prop_spec = deref(props_spec).get(prop_name)
if prop_spec is not None:
return deref(prop_spec)
additional_props = deref(object_spec).get('additionalProperties', True)
if isinstance(additional_props, bool):
# no spec for additional properties to conform to - this is basically
# a way to send pretty much anything across the wire as is.
return None
additional_props = deref(additional_props)
if is_dict_like(additional_props):
# spec that all additional props MUST conform to
return additional_props
raise SwaggerMappingError(
"Don't know what to do with `additionalProperties` in spec {0} "
"when inspecting value {1}".format(object_spec, object_value))
|
bsd-3-clause
|
Python
|
f120be17e4b1d63bd98c2390cf4ec39b8e61e8fd
|
define _VersionTupleEnumMixin class
|
googlefonts/fonttools,fonttools/fonttools
|
Lib/fontTools/ufoLib/utils.py
|
Lib/fontTools/ufoLib/utils.py
|
"""The module contains miscellaneous helpers.
It's not considered part of the public ufoLib API.
"""
import warnings
import functools
numberTypes = (int, float)
def deprecated(msg=""):
"""Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_function():
... "I just print 'hello world'."
... print("hello world")
>>> some_function()
hello world
>>> some_function.__doc__ == "I just print 'hello world'."
True
"""
def deprecated_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(
f"{func.__name__} function is a deprecated. {msg}",
category=DeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapper
return deprecated_decorator
# To be mixed with enum.Enum in UFOFormatVersion and GLIFFormatVersion
class _VersionTupleEnumMixin:
@property
def major(self):
return self.value[0]
@property
def minor(self):
return self.value[1]
@classmethod
def _missing_(cls, value):
# allow to initialize a version enum from a single (major) integer
if isinstance(value, int):
return cls((value, 0))
# or from None to obtain the current default version
if value is None:
return cls.default()
return super()._missing_(value)
def __str__(self):
return f"{self.major}.{self.minor}"
@classmethod
def default(cls):
# get the latest defined version (i.e. the max of all versions)
return max(cls.__members__.values())
@classmethod
def supported_versions(cls):
return frozenset(cls.__members__.values())
if __name__ == "__main__":
import doctest
doctest.testmod()
|
"""The module contains miscellaneous helpers.
It's not considered part of the public ufoLib API.
"""
import warnings
import functools
numberTypes = (int, float)
def deprecated(msg=""):
"""Decorator factory to mark functions as deprecated with given message.
>>> @deprecated("Enough!")
... def some_function():
... "I just print 'hello world'."
... print("hello world")
>>> some_function()
hello world
>>> some_function.__doc__ == "I just print 'hello world'."
True
"""
def deprecated_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
warnings.warn(
f"{func.__name__} function is a deprecated. {msg}",
category=DeprecationWarning,
stacklevel=2,
)
return func(*args, **kwargs)
return wrapper
return deprecated_decorator
if __name__ == "__main__":
import doctest
doctest.testmod()
|
mit
|
Python
|
dff9df9463fd302665169dc68c17252a08a96739
|
add HRK currency
|
nimbis/django-shop,divio/django-shop,jrief/django-shop,khchine5/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,jrief/django-shop,awesto/django-shop,awesto/django-shop,khchine5/django-shop,khchine5/django-shop,awesto/django-shop,nimbis/django-shop,khchine5/django-shop,jrief/django-shop,divio/django-shop,nimbis/django-shop
|
shop/money/iso4217.py
|
shop/money/iso4217.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# Dictionary of currency representations:
# key: official ISO 4217 code
# value[0]: numeric representation
# value[1]: number of digits
# value[2]: currency symbol in UTF-8
# value[3]: textual description
CURRENCIES = {
'AED': ('784', 2, 'د.إ', _('United Arab Emirates dirham')),
'AUD': ('036', 2, '$', _("Australian Dollar")),
'BHD': ('048', 3, '.د.ب', _('Bahraini dinar')),
'BRL': ('986', 2, 'R$', _("Brazilian Real")),
'CHF': ('756', 2, 'SFr.', _("Swiss Franc")),
'CNY': ('156', 2, '¥', _("Chinese Yuan")),
'CZK': ('203', 2, 'Kč', _("Czech Koruna")),
'EUR': ('978', 2, '€', _("Euro")),
'GBP': ('826', 2, '£', _("Pound Sterling")),
'HRK': ('191', 2, 'kn', _("Croatian kuna")),
'HUF': ('348', 0, 'Ft', _("Hungarian Forint")),
'ILS': ('376', 2, '₪', _("Israeli Sheqel")),
'JPY': ('392', 0, '¥', _("Japanese Yen")),
'KWD': ('414', 3, 'د.ك', _("Kuwaiti Dinar")),
'OMR': ('512', 3, 'ر.ع.', _('Omani rial')),
'QAR': ('634', 2, 'ر.ق', _('Qatari riyal')),
'RUB': ('643', 2, '₽', _("Russian Ruble")),
'SAR': ('682', 2, 'ر.س', _('Saudi riyal')),
'UAH': ('980', 2, '₴', _("Ukrainian Hryvnia")),
'USD': ('840', 2, '$', _("US Dollar")),
# feel free to add more currencies, alphabetically ordered
}
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
# Dictionary of currency representations:
# key: official ISO 4217 code
# value[0]: numeric representation
# value[1]: number of digits
# value[2]: currency symbol in UTF-8
# value[3]: textual description
CURRENCIES = {
'AED': ('784', 2, 'د.إ', _('United Arab Emirates dirham')),
'AUD': ('036', 2, '$', _("Australian Dollar")),
'BHD': ('048', 3, '.د.ب', _('Bahraini dinar')),
'BRL': ('986', 2, 'R$', _("Brazilian Real")),
'CHF': ('756', 2, 'SFr.', _("Swiss Franc")),
'CNY': ('156', 2, '¥', _("Chinese Yuan")),
'CZK': ('203', 2, 'Kč', _("Czech Koruna")),
'EUR': ('978', 2, '€', _("Euro")),
'GBP': ('826', 2, '£', _("Pound Sterling")),
'HUF': ('348', 0, 'Ft', _("Hungarian Forint")),
'ILS': ('376', 2, '₪', _("Israeli Sheqel")),
'JPY': ('392', 0, '¥', _("Japanese Yen")),
'KWD': ('414', 3, 'د.ك', _("Kuwaiti Dinar")),
'OMR': ('512', 3, 'ر.ع.', _('Omani rial')),
'QAR': ('634', 2, 'ر.ق', _('Qatari riyal')),
'RUB': ('643', 2, '₽', _("Russian Ruble")),
'SAR': ('682', 2, 'ر.س', _('Saudi riyal')),
'UAH': ('980', 2, '₴', _("Ukrainian Hryvnia")),
'USD': ('840', 2, '$', _("US Dollar")),
# feel free to add more currencies, alphabetically ordered
}
|
bsd-3-clause
|
Python
|
f9d29a5ba9bc196fdd669a1de01d8b8dde5ae8b8
|
Corrige l'espacement
|
sgmap/openfisca-france,sgmap/openfisca-france
|
openfisca_france/model/caracteristiques/capacite_travail.py
|
openfisca_france/model/caracteristiques/capacite_travail.py
|
# -*- coding: utf-8 -*-
from openfisca_france.model.base import *
class taux_capacite_travail(Variable):
value_type = float
default_value = 1.0
entity = Individu
label = u"Taux de capacité de travail, appréciée par la commission des droits et de l'autonomie des personnes handicapées (CDAPH)"
definition_period = MONTH
class taux_incapacite(Variable):
value_type = float
entity = Individu
label = u"Taux d'incapacité"
definition_period = MONTH
|
# -*- coding: utf-8 -*-
from openfisca_france.model.base import *
class taux_capacite_travail(Variable):
value_type = float
default_value = 1.0
entity = Individu
label = u"Taux de capacité de travail, appréciée par la commission des droits et de l'autonomie des personnes handicapées (CDAPH)"
definition_period = MONTH
class taux_incapacite(Variable):
value_type = float
entity = Individu
label = u"Taux d'incapacité"
definition_period = MONTH
|
agpl-3.0
|
Python
|
03c7498dc8ba09a2135a7c214d7903f7509b956b
|
Use log-uniform distribution for learning-rate.
|
bsautermeister/machine-learning-examples
|
hyperparam_opt/tensorflow/hyperopt_dnn_mnist.py
|
hyperparam_opt/tensorflow/hyperopt_dnn_mnist.py
|
import sys
import argparse
import numpy as np
import tensorflow as tf
from hyperparam_opt.tensorflow.dnn_mnist import HyperParams, train
from hyperopt import fmin, hp, Trials, tpe, STATUS_OK
from tensorflow.examples.tutorials.mnist import input_data
MNIST = None
def optimizer(args):
hyper = HyperParams(**args)
print(hyper.to_string())
loss, accuracy, epochs = train(MNIST, hyper)
return {
'status': STATUS_OK,
'loss': loss,
'epochs': epochs,
'metrics': {
'accuracy': accuracy
}
}
def main(_):
# Import data
global MNIST
MNIST = input_data.read_data_sets(FLAGS.data_dir)
space = {
'lr': hp.loguniform('lr', np.log(0.0001), np.log(0.01)),
'batch_size': hp.quniform('batch_size', 8, 256, 2),
'n_hidden': hp.quniform('n_hidden', 32, 256, 1),
'keep_prob': hp.uniform('keep_prob', 0.2, 1.0),
}
t = Trials()
best = fmin(optimizer, space, algo=tpe.suggest, max_evals=10, trials=t)
print('TPE best:'.format(best))
for trial in t.trials:
print('{} --> {}'.format(trial['result'], trial['misc']['vals']))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='../../data/tmp/mnist',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
|
import sys
import argparse
import tensorflow as tf
from hyperparam_opt.tensorflow.dnn_mnist import HyperParams, train
from hyperopt import fmin, hp, Trials, tpe, STATUS_OK
from tensorflow.examples.tutorials.mnist import input_data
MNIST = None
def optimizer(args):
hyper = HyperParams(**args)
print(hyper.to_string())
loss, accuracy, epochs = train(MNIST, hyper)
return {
'status': STATUS_OK,
'loss': loss,
'epochs': epochs,
'metrics': {
'accuracy': accuracy
}
}
def main(_):
# Import data
global MNIST
MNIST = input_data.read_data_sets(FLAGS.data_dir)
space = {
'lr': hp.uniform('lr', 0.0001, 0.01),
'batch_size': hp.quniform('batch_size', 8, 256, 2),
'n_hidden': hp.quniform('n_hidden', 32, 256, 1),
'keep_prob': hp.uniform('keep_prob', 0.2, 1.0),
}
t = Trials()
best = fmin(optimizer, space, algo=tpe.suggest, max_evals=10, trials=t)
print('TPE best:'.format(best))
for trial in t.trials:
print('{} --> {}'.format(trial['result'], trial['misc']['vals']))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='../../data/tmp/mnist',
help='Directory for storing input data')
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
|
mit
|
Python
|
ec3e08da9551e2a7e7e114c4d425871b2a915425
|
fix leaked greenlet
|
ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services,ooici/coi-services
|
ion/agents/platform/rsn/test/test_oms_client.py
|
ion/agents/platform/rsn/test/test_oms_client.py
|
#!/usr/bin/env python
"""
@package ion.agents.platform.rsn.test.test_oms_client
@file ion/agents/platform/rsn/test/test_oms_client.py
@author Carlos Rueda
@brief Test cases for CIOMSClient.
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
from pyon.public import log
from ion.agents.platform.rsn.simulator.logger import Logger
Logger.set_logger(log)
from pyon.util.int_test import IonIntegrationTestCase
from ion.agents.platform.rsn.oms_client_factory import CIOMSClientFactory
from ion.agents.platform.rsn.test.oms_test_mixin import OmsTestMixin
from nose.plugins.attrib import attr
import os
@attr('INT', group='sa')
class Test(IonIntegrationTestCase, OmsTestMixin):
@classmethod
def setUpClass(cls):
OmsTestMixin.setUpClass()
def setUp(self):
oms_uri = os.getenv('OMS', "launchsimulator")
oms_uri = self._dispatch_simulator(oms_uri)
log.debug("oms_uri = %s", oms_uri)
self.oms = CIOMSClientFactory.create_instance(oms_uri)
OmsTestMixin.start_http_server()
def done():
CIOMSClientFactory.destroy_instance(self.oms)
event_notifications = OmsTestMixin.stop_http_server()
log.info("event_notifications = %s" % str(event_notifications))
self.addCleanup(done)
|
#!/usr/bin/env python
"""
@package ion.agents.platform.rsn.test.test_oms_simple
@file ion/agents/platform/rsn/test/test_oms_simple.py
@author Carlos Rueda
@brief Test cases for CIOMSClient.
"""
__author__ = 'Carlos Rueda'
__license__ = 'Apache 2.0'
from pyon.public import log
from ion.agents.platform.rsn.simulator.logger import Logger
Logger.set_logger(log)
from pyon.util.int_test import IonIntegrationTestCase
from ion.agents.platform.rsn.oms_client_factory import CIOMSClientFactory
from ion.agents.platform.rsn.test.oms_test_mixin import OmsTestMixin
from nose.plugins.attrib import attr
@attr('INT', group='sa')
class Test(IonIntegrationTestCase, OmsTestMixin):
@classmethod
def setUpClass(cls):
OmsTestMixin.setUpClass()
cls.oms = CIOMSClientFactory.create_instance()
OmsTestMixin.start_http_server()
@classmethod
def tearDownClass(cls):
CIOMSClientFactory.destroy_instance(cls.oms)
event_notifications = OmsTestMixin.stop_http_server()
log.info("event_notifications = %s" % str(event_notifications))
|
bsd-2-clause
|
Python
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.