commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 0
2.94k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
444
| message
stringlengths 16
3.45k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43.2k
| prompt
stringlengths 17
4.58k
| response
stringlengths 1
4.43k
| prompt_tagged
stringlengths 58
4.62k
| response_tagged
stringlengths 1
4.43k
| text
stringlengths 132
7.29k
| text_tagged
stringlengths 173
7.33k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
85ff425513c27191309c49bd78b2b94c59603349
|
examples/monitor.py
|
examples/monitor.py
|
#! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.getSources()
|
#! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path = mojito.openView(mojito.getSources())
view = bus.get_object("com.intel.Mojito", path)
view = dbus.Interface(view, "com.intel.Mojito.View")
def added(item, data):
print item, data
view.connect_to_signal("ItemAdded", added)
view.start()
loop = gobject.MainLoop()
loop.run()
|
Create a view and start it
|
Create a view and start it
|
Python
|
lgpl-2.1
|
lcp/mojito,lcp/libsocialweb,GNOME/libsocialweb,GNOME/libsocialweb,lcp/mojito,ThomasBollmeier/libsocialweb-flickr-oauth,ThomasBollmeier/libsocialweb-flickr-oauth,lcp/libsocialweb,GNOME/libsocialweb,lcp/mojito,ThomasBollmeier/libsocialweb-flickr-oauth,lcp/libsocialweb
|
#! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.getSources()
Create a view and start it
|
#! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path = mojito.openView(mojito.getSources())
view = bus.get_object("com.intel.Mojito", path)
view = dbus.Interface(view, "com.intel.Mojito.View")
def added(item, data):
print item, data
view.connect_to_signal("ItemAdded", added)
view.start()
loop = gobject.MainLoop()
loop.run()
|
<commit_before>#! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.getSources()
<commit_msg>Create a view and start it<commit_after>
|
#! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path = mojito.openView(mojito.getSources())
view = bus.get_object("com.intel.Mojito", path)
view = dbus.Interface(view, "com.intel.Mojito.View")
def added(item, data):
print item, data
view.connect_to_signal("ItemAdded", added)
view.start()
loop = gobject.MainLoop()
loop.run()
|
#! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.getSources()
Create a view and start it#! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path = mojito.openView(mojito.getSources())
view = bus.get_object("com.intel.Mojito", path)
view = dbus.Interface(view, "com.intel.Mojito.View")
def added(item, data):
print item, data
view.connect_to_signal("ItemAdded", added)
view.start()
loop = gobject.MainLoop()
loop.run()
|
<commit_before>#! /usr/bin/env python
import dbus
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
print mojito.getSources()
<commit_msg>Create a view and start it<commit_after>#! /usr/bin/env python
import dbus, gobject
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.start_service_by_name("com.intel.Mojito")
mojito = bus.get_object("com.intel.Mojito", "/com/intel/Mojito")
mojito = dbus.Interface(mojito, "com.intel.Mojito")
path = mojito.openView(mojito.getSources())
view = bus.get_object("com.intel.Mojito", path)
view = dbus.Interface(view, "com.intel.Mojito.View")
def added(item, data):
print item, data
view.connect_to_signal("ItemAdded", added)
view.start()
loop = gobject.MainLoop()
loop.run()
|
cc3a0f230c2f64fd2e4d974c536e9d2e99d89992
|
tilezilla/errors.py
|
tilezilla/errors.py
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
|
Add exception for empty db search return
|
Add exception for empty db search return
|
Python
|
bsd-3-clause
|
ceholden/tilezilla,ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tile,ceholden/landsat_tiles
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
Add exception for empty db search return
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
|
<commit_before>""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
<commit_msg>Add exception for empty db search return<commit_after>
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
|
""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
Add exception for empty db search return""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
|
<commit_before>""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
<commit_msg>Add exception for empty db search return<commit_after>""" Errors generated by this module
"""
class ConfigException(Exception):
pass
class FillValueException(Exception):
""" All of a tile is "fill" values
"""
pass
class ProductNotFoundException(Exception):
pass
|
1592aa20fb41fed607ac48fd6ac1038f4bb6c665
|
pylib/cqlshlib/__init__.py
|
pylib/cqlshlib/__init__.py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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.
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 cassandra.metadata import RegisteredTableExtension
import io
import struct
# Add a handler for scylla_encryption_options extension to at least print
# the info when doing "desc <table>".
#
# The end result will not be cut-and-paste usable; we'd need to modify the
# driver for this. But it is something.
class Encr(RegisteredTableExtension):
name = 'scylla_encryption_options'
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
# For scylla_encryption_options, the blob is actually
# a serialized unorderd_map<string, string>.
bytes = io.BytesIO(ext_blob)
def read_string():
# strings are little endian 32-bit len + bytes
utf_length = struct.unpack('<I', bytes.read(4))[0]
return bytes.read(utf_length)
def read_pair():
# each map::value_type is written as <string><string>
key = read_string()
val = read_string()
return key, val
def read_map():
# num elements
len = struct.unpack('<I', bytes.read(4))[0]
res = {}
# x value_type pairs
for x in range(0, len):
p = read_pair()
res[p[0]] = p[1]
return res
return "%s = %s" % (ext_key, read_map())
|
Add extension handler for "scylla_encryption_options"
|
cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info about these.
This adds a handler, and while the end result will not be
the actual cql statement to recreate the table, it at least
will provide feedback to the user.
v2:
* format comments
* indentation
|
Python
|
apache-2.0
|
scylladb/scylla-tools-java,scylladb/scylla-tools-java,scylladb/scylla-tools-java,scylladb/scylla-tools-java
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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.
cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info about these.
This adds a handler, and while the end result will not be
the actual cql statement to recreate the table, it at least
will provide feedback to the user.
v2:
* format comments
* indentation
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 cassandra.metadata import RegisteredTableExtension
import io
import struct
# Add a handler for scylla_encryption_options extension to at least print
# the info when doing "desc <table>".
#
# The end result will not be cut-and-paste usable; we'd need to modify the
# driver for this. But it is something.
class Encr(RegisteredTableExtension):
name = 'scylla_encryption_options'
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
# For scylla_encryption_options, the blob is actually
# a serialized unorderd_map<string, string>.
bytes = io.BytesIO(ext_blob)
def read_string():
# strings are little endian 32-bit len + bytes
utf_length = struct.unpack('<I', bytes.read(4))[0]
return bytes.read(utf_length)
def read_pair():
# each map::value_type is written as <string><string>
key = read_string()
val = read_string()
return key, val
def read_map():
# num elements
len = struct.unpack('<I', bytes.read(4))[0]
res = {}
# x value_type pairs
for x in range(0, len):
p = read_pair()
res[p[0]] = p[1]
return res
return "%s = %s" % (ext_key, read_map())
|
<commit_before># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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.
<commit_msg>cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info about these.
This adds a handler, and while the end result will not be
the actual cql statement to recreate the table, it at least
will provide feedback to the user.
v2:
* format comments
* indentation<commit_after>
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 cassandra.metadata import RegisteredTableExtension
import io
import struct
# Add a handler for scylla_encryption_options extension to at least print
# the info when doing "desc <table>".
#
# The end result will not be cut-and-paste usable; we'd need to modify the
# driver for this. But it is something.
class Encr(RegisteredTableExtension):
name = 'scylla_encryption_options'
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
# For scylla_encryption_options, the blob is actually
# a serialized unorderd_map<string, string>.
bytes = io.BytesIO(ext_blob)
def read_string():
# strings are little endian 32-bit len + bytes
utf_length = struct.unpack('<I', bytes.read(4))[0]
return bytes.read(utf_length)
def read_pair():
# each map::value_type is written as <string><string>
key = read_string()
val = read_string()
return key, val
def read_map():
# num elements
len = struct.unpack('<I', bytes.read(4))[0]
res = {}
# x value_type pairs
for x in range(0, len):
p = read_pair()
res[p[0]] = p[1]
return res
return "%s = %s" % (ext_key, read_map())
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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.
cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info about these.
This adds a handler, and while the end result will not be
the actual cql statement to recreate the table, it at least
will provide feedback to the user.
v2:
* format comments
* indentation# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 cassandra.metadata import RegisteredTableExtension
import io
import struct
# Add a handler for scylla_encryption_options extension to at least print
# the info when doing "desc <table>".
#
# The end result will not be cut-and-paste usable; we'd need to modify the
# driver for this. But it is something.
class Encr(RegisteredTableExtension):
name = 'scylla_encryption_options'
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
# For scylla_encryption_options, the blob is actually
# a serialized unorderd_map<string, string>.
bytes = io.BytesIO(ext_blob)
def read_string():
# strings are little endian 32-bit len + bytes
utf_length = struct.unpack('<I', bytes.read(4))[0]
return bytes.read(utf_length)
def read_pair():
# each map::value_type is written as <string><string>
key = read_string()
val = read_string()
return key, val
def read_map():
# num elements
len = struct.unpack('<I', bytes.read(4))[0]
res = {}
# x value_type pairs
for x in range(0, len):
p = read_pair()
res[p[0]] = p[1]
return res
return "%s = %s" % (ext_key, read_map())
|
<commit_before># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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.
<commit_msg>cqlsh: Add extension handler for "scylla_encryption_options"
Refs #731
Scylla encryption options are not stored with "normal" options.
Because these are 100% intertwined with drivers, and adding
stuff there breaks things.
Instead they are extensions. The python driver allows adding
extension handlers to print info about these.
This adds a handler, and while the end result will not be
the actual cql statement to recreate the table, it at least
will provide feedback to the user.
v2:
* format comments
* indentation<commit_after># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not 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 cassandra.metadata import RegisteredTableExtension
import io
import struct
# Add a handler for scylla_encryption_options extension to at least print
# the info when doing "desc <table>".
#
# The end result will not be cut-and-paste usable; we'd need to modify the
# driver for this. But it is something.
class Encr(RegisteredTableExtension):
name = 'scylla_encryption_options'
@classmethod
def after_table_cql(cls, table_meta, ext_key, ext_blob):
# For scylla_encryption_options, the blob is actually
# a serialized unorderd_map<string, string>.
bytes = io.BytesIO(ext_blob)
def read_string():
# strings are little endian 32-bit len + bytes
utf_length = struct.unpack('<I', bytes.read(4))[0]
return bytes.read(utf_length)
def read_pair():
# each map::value_type is written as <string><string>
key = read_string()
val = read_string()
return key, val
def read_map():
# num elements
len = struct.unpack('<I', bytes.read(4))[0]
res = {}
# x value_type pairs
for x in range(0, len):
p = read_pair()
res[p[0]] = p[1]
return res
return "%s = %s" % (ext_key, read_map())
|
79404e483462fd71aed1150e91657becd8a5aaf8
|
clifford/test/test_multivector_inverse.py
|
clifford/test/test_multivector_inverse.py
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
Swap hitzer inverse test to use np.testing
|
Swap hitzer inverse test to use np.testing
|
Python
|
bsd-3-clause
|
arsenovic/clifford,arsenovic/clifford
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
Swap hitzer inverse test to use np.testing
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
<commit_before>import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
<commit_msg>Swap hitzer inverse test to use np.testing<commit_after>
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
Swap hitzer inverse test to use np.testingimport numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
<commit_before>import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
assert np.all(np.abs(((mv * mv_inv) - 1.).value) < 1.e-11)
<commit_msg>Swap hitzer inverse test to use np.testing<commit_after>import numpy as np
import pytest
import clifford as cf
class TestClosedForm:
@pytest.mark.parametrize('p, q', [
(p, total_dims - p)
for total_dims in [1, 2, 3, 4, 5]
for p in range(total_dims + 1)
])
def test_hitzer_inverse(self, p, q):
Ntests = 100
layout, blades = cf.Cl(p, q)
for i in range(Ntests):
mv = layout.randomMV()
mv_inv = mv.hitzer_inverse()
np.testing.assert_almost_equal((mv * mv_inv).value,
(1.0 + 0*blades["e1"]).value)
|
ba8509a34104ff6aab5e97a6bed842b245ec4b64
|
examples/pi-montecarlo/pi_distarray.py
|
examples/pi-montecarlo/pi_distarray.py
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
Update pi-montecarlo example to use `sum` again.
|
Update pi-montecarlo example to use `sum` again.
|
Python
|
bsd-3-clause
|
RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
Update pi-montecarlo example to use `sum` again.
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
<commit_before># encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
<commit_msg>Update pi-montecarlo example to use `sum` again.<commit_after>
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
Update pi-montecarlo example to use `sum` again.# encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
<commit_before># encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
def local_sum(mask):
return mask.ndarray.sum()
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
lsum = context.apply(local_sum, (mask.key,))
return 4 * sum(lsum) / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
<commit_msg>Update pi-montecarlo example to use `sum` again.<commit_after># encoding: utf-8
# ---------------------------------------------------------------------------
# Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc.
# Distributed under the terms of the BSD License. See COPYING.rst.
# ---------------------------------------------------------------------------
"""
Estimate pi using a Monte Carlo method with distarray.
Usage:
$ python pi_distarray.py <number of points>
"""
from __future__ import division, print_function
import sys
from util import timer
from distarray.dist import Context, Distribution, hypot
from distarray.dist.random import Random
context = Context()
random = Random(context)
@timer
def calc_pi(n):
"""Estimate pi using distributed NumPy arrays."""
distribution = Distribution.from_shape(context=context, shape=(n,))
x = random.rand(distribution)
y = random.rand(distribution)
r = hypot(x, y)
mask = (r < 1)
return 4 * mask.sum().toarray() / n
if __name__ == '__main__':
N = int(sys.argv[1])
result, time = calc_pi(N)
print('time : %3.4g\nresult: %.7f' % (time, result))
|
bba6c1f65010c208909d4f342b1d776c46c040c8
|
Lib/importlib/test/__main__.py
|
Lib/importlib/test/__main__.py
|
import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sys.argv:
util.using___import__ = True
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
Add support for a --builtin argument to importlib.test to trigger running import-specific tests with __import__ instead of importlib.
|
Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.
|
Python
|
mit
|
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
|
import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.
|
import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sys.argv:
util.using___import__ = True
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
<commit_before>import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
<commit_msg>Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.<commit_after>
|
import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sys.argv:
util.using___import__ = True
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sys.argv:
util.using___import__ = True
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
<commit_before>import os.path
from test.support import run_unittest
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
<commit_msg>Add support for a --builtin argument to importlib.test to trigger running
import-specific tests with __import__ instead of importlib.<commit_after>import importlib
from importlib.test.import_ import util
import os.path
from test.support import run_unittest
import sys
import unittest
def test_main():
start_dir = os.path.dirname(__file__)
top_dir = os.path.dirname(os.path.dirname(start_dir))
test_loader = unittest.TestLoader()
if '--builtin' in sys.argv:
util.using___import__ = True
run_unittest(test_loader.discover(start_dir, top_level_dir=top_dir))
if __name__ == '__main__':
test_main()
|
8b7c5b7001ac005849fb31d83415db3a6517feb7
|
reddit_adzerk/adzerkads.py
|
reddit_adzerk/adzerkads.py
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
self.frame_id = "ad_main"
|
Set the frame id to what aderk expects.
|
Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)
|
Python
|
bsd-3-clause
|
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
self.frame_id = "ad_main"
|
<commit_before>from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
<commit_msg>Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)<commit_after>
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
self.frame_id = "ad_main"
|
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
self.frame_id = "ad_main"
|
<commit_before>from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
<commit_msg>Set the frame id to what aderk expects.
(See a corresponding change to ads.html in reddit)<commit_after>from pylons import c, g
from r2.lib.pages import Ads as BaseAds
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
adzerk_test_srs = g.live_config.get("adzerk_test_srs")
if adzerk_test_srs and c.site.name in adzerk_test_srs:
self.ad_url = g.config["adzerk_url"]
self.frame_id = "ad_main"
|
7df717a48fb74ddd3b9ade644fb805020a20e91c
|
axiom/test/historic/test_processor1to2.py
|
axiom/test/historic/test_processor1to2.py
|
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.dummyRunCalls = []
def dummyRun(calledOn):
self.dummyRunCalls.append(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
self.assertEquals(self.dummyRunCalls, [proc])
|
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.calledBack = Deferred()
def dummyRun(calledOn):
self.calledBack.callback(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
def assertion(result):
self.assertEquals(result, proc)
return self.calledBack.addCallback(assertion)
|
Fix an intermittent axiom test failure that occurs only in certain environments.
|
Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.
|
Python
|
mit
|
twisted/axiom,hawkowl/axiom
|
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.dummyRunCalls = []
def dummyRun(calledOn):
self.dummyRunCalls.append(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
self.assertEquals(self.dummyRunCalls, [proc])
Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.
|
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.calledBack = Deferred()
def dummyRun(calledOn):
self.calledBack.callback(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
def assertion(result):
self.assertEquals(result, proc)
return self.calledBack.addCallback(assertion)
|
<commit_before>
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.dummyRunCalls = []
def dummyRun(calledOn):
self.dummyRunCalls.append(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
self.assertEquals(self.dummyRunCalls, [proc])
<commit_msg>Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.<commit_after>
|
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.calledBack = Deferred()
def dummyRun(calledOn):
self.calledBack.callback(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
def assertion(result):
self.assertEquals(result, proc)
return self.calledBack.addCallback(assertion)
|
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.dummyRunCalls = []
def dummyRun(calledOn):
self.dummyRunCalls.append(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
self.assertEquals(self.dummyRunCalls, [proc])
Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.calledBack = Deferred()
def dummyRun(calledOn):
self.calledBack.callback(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
def assertion(result):
self.assertEquals(result, proc)
return self.calledBack.addCallback(assertion)
|
<commit_before>
from axiom.item import Item
from axiom.attributes import text
from axiom.batch import processor
from axiom.iaxiom import IScheduler
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.dummyRunCalls = []
def dummyRun(calledOn):
self.dummyRunCalls.append(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
self.assertEquals(self.dummyRunCalls, [proc])
<commit_msg>Fix an intermittent axiom test failure that occurs only in certain environments.
Fixes #2857
Author: glyph
Reviewer: exarkun, mithrandi
This change fixes `axiom.test.historic.test_processor1to2.ProcessorUpgradeTest.test_pollingRemoval` to wait until its processor has actually been run before making any assertions.<commit_after>
from twisted.internet.defer import Deferred
from axiom.test.historic.stubloader import StubbedTest
from axiom.test.historic.stub_processor1to2 import DummyProcessor
class ProcessorUpgradeTest(StubbedTest):
def setUp(self):
# Ick, we need to catch the run event of DummyProcessor, and I can't
# think of another way to do it.
self.dummyRun = DummyProcessor.run.im_func
self.calledBack = Deferred()
def dummyRun(calledOn):
self.calledBack.callback(calledOn)
DummyProcessor.run = dummyRun
return StubbedTest.setUp(self)
def tearDown(self):
# Okay this is a pretty irrelevant method on a pretty irrelevant class,
# but we'll fix it anyway.
DummyProcessor.run = self.dummyRun
return StubbedTest.tearDown(self)
def test_pollingRemoval(self):
"""
Test that processors lose their idleInterval but none of the rest of
their stuff, and that they get scheduled by the upgrader so they can
figure out what state they should be in.
"""
proc = self.store.findUnique(DummyProcessor)
self.assertEquals(proc.busyInterval, 100)
self.failIfEqual(proc.scheduled, None)
def assertion(result):
self.assertEquals(result, proc)
return self.calledBack.addCallback(assertion)
|
a7692bc810d1a30c9d0fa91bf1689651bd34d8c6
|
moniek/accounting/views.py
|
moniek/accounting/views.py
|
from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
|
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
|
Create home and accounts stub view
|
Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name>
|
Python
|
agpl-3.0
|
bwesterb/moniek,bwesterb/moniek
|
from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name>
|
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
|
<commit_before>from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
<commit_msg>Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name><commit_after>
|
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
|
from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name>from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
|
<commit_before>from django.http import HttpResponse
def home(request):
return HttpResponse("Hi")
<commit_msg>Create home and accounts stub view
Signed-off-by: Bas Westerbaan <1d31d94f30d40df7951505d1034e1e923d02ec49@westerbaan.name><commit_after>from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
def home(request):
return render_to_response('accounting/home.html', {},
RequestContext(request))
def accounts(request):
return HttpResponse("Hi")
|
1c736a5f48b2deb9732c65a5dec7ea47e542f6f4
|
thinc/neural/_classes/resnet.py
|
thinc/neural/_classes/resnet.py
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
Make residual connections work for list-valued inputs
|
Make residual connections work for list-valued inputs
|
Python
|
mit
|
spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
Make residual connections work for list-valued inputs
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
<commit_before>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
<commit_msg>Make residual connections work for list-valued inputs<commit_after>
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
Make residual connections work for list-valued inputsfrom .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
<commit_before>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self._layers[0](X)
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_output, sgd)
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
<commit_msg>Make residual connections work for list-valued inputs<commit_after>from .model import Model
from ...api import layerize
from .affine import Affine
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
Y = self._layers[0](X)
if isinstance(X, list) or isinstance(X, tuple):
return [X[i]+Y[i] for i in range(len(X))]
else:
return X + Y
def begin_update(self, X, drop=0.):
y, bp_y = self._layers[0].begin_update(X, drop=drop)
if isinstance(X, list) or isinstance(X, tuple):
output = [X[i]+y[i] for i in range(len(X))]
else:
output = X+y
def residual_bwd(d_output, sgd=None):
dX = bp_y(d_output, sgd)
if isinstance(d_output, list) or isinstance(d_output, tuple):
return [d_output[i]+dX[i] for i in range(len(d_output))]
else:
return d_output + dX
return output, residual_bwd
def on_data(self, X, y=None):
for layer in self._layers:
for hook in layer.on_data_hooks:
hook(layer, X, y)
if hasattr(layer, 'W'):
layer.W.fill(0)
|
db24629b7cc34f9a137c6bc5569dc7a39245fa52
|
thinglang/compiler/sentinels.py
|
thinglang/compiler/sentinels.py
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
Add serialization sentintels for import table
|
Add serialization sentintels for import table
|
Python
|
mit
|
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
Add serialization sentintels for import table
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
<commit_before>from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
<commit_msg>Add serialization sentintels for import table<commit_after>
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
Add serialization sentintels for import tablefrom thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
<commit_before>from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
<commit_msg>Add serialization sentintels for import table<commit_after>from thinglang.compiler.opcodes import MEMBERS, METHODS, FRAME_SIZE, ARGUMENTS
from thinglang.compiler.opcodes import Opcode
class SentinelImportTableEntry(Opcode):
"""
Signifies an import table entry
"""
class SentinelImportTableEnd(Opcode):
"""
Signifies the end of the import table
"""
class SentinelThingDefinition(Opcode):
"""
Signifies the start of thing definition
"""
ARGS = MEMBERS, METHODS
class SentinelMethodDefinition(Opcode):
"""
Signifies a method definition boundary.
"""
ARGS = FRAME_SIZE, ARGUMENTS
class SentinelMethodEnd(Opcode):
"""
Signifies a method boundary.
"""
pass
class SentinelCodeEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
class SentinelDataEnd(Opcode):
"""
Signifies the code section boundary.
"""
pass
|
b3adfb4913638151307b0f04d87afc01dec78e84
|
tob-api/api/indy/claimParser.py
|
tob-api/api/indy/claimParser.py
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return self.__claim
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return json.dumps(self.__claim)
|
Fix error when saving the claim to the wallet.
|
Fix error when saving the claim to the wallet.
|
Python
|
apache-2.0
|
WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook,swcurran/TheOrgBook,swcurran/TheOrgBook,WadeBarnes/TheOrgBook
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return self.__claimFix error when saving the claim to the wallet.
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return json.dumps(self.__claim)
|
<commit_before>import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return self.__claim<commit_msg>Fix error when saving the claim to the wallet.<commit_after>
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return json.dumps(self.__claim)
|
import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return self.__claimFix error when saving the claim to the wallet.import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return json.dumps(self.__claim)
|
<commit_before>import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return self.__claim<commit_msg>Fix error when saving the claim to the wallet.<commit_after>import json
import logging
class ClaimParser(object):
"""
Parses a generic claim.
"""
def __init__(self, claim: str) -> None:
self.__logger = logging.getLogger(__name__)
self.__orgData = claim
self.__parse()
def __parse(self):
self.__logger.debug("Parsing claim ...")
data = json.loads(self.__orgData)
self.__claim_type = data["claim_type"]
self.__claim = data["claim_data"]
self.__issuer_did = data["claim_data"]["issuer_did"]
def getField(self, field):
return self.__claim["claim"][field][0]
@property
def schemaName(self) -> str:
return self.__claim_type
@property
def issuerDid(self) -> str:
return self.__issuer_did
@property
def json(self) -> str:
return json.dumps(self.__claim)
|
57461a7ebd35544c506e6b5021ff11c3b6dd943e
|
normandy/studies/models.py
|
normandy/studies/models.py
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
Add ordering to Extension model
|
Add ordering to Extension model
|
Python
|
mpl-2.0
|
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
Add ordering to Extension model
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
<commit_before>from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
<commit_msg>Add ordering to Extension model<commit_after>
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
Add ordering to Extension modelfrom django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
<commit_before>from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
<commit_msg>Add ordering to Extension model<commit_after>from django.db import models
from django.template.loader import render_to_string
from normandy.recipes.models import Recipe
class Extension(models.Model):
name = models.CharField(max_length=255)
xpi = models.FileField(upload_to='extensions')
class Meta:
ordering = ('-id',)
@property
def recipes_used_by(self):
"""Set of enabled recipes that are using this extension."""
return Recipe.objects.filter(
latest_revision__arguments_json__contains=self.xpi.url,
)
def recipes_used_by_html(self):
return render_to_string('admin/field_recipe_list.html', {
'recipes': self.recipes_used_by.order_by('latest_revision__name'),
})
recipes_used_by_html.short_description = 'Used in Recipes'
|
948f57469bc9e8144d6fceb49b5e2cf1d5858eeb
|
ores/wsgi/preprocessors.py
|
ores/wsgi/preprocessors.py
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
return wrapped_f
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
|
Set minify to False as well as sometimes setting it to True.
|
Set minify to False as well as sometimes setting it to True.
|
Python
|
mit
|
wiki-ai/ores,he7d3r/ores,he7d3r/ores,wiki-ai/ores,wiki-ai/ores,he7d3r/ores
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
return wrapped_f
Set minify to False as well as sometimes setting it to True.
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
|
<commit_before>from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
return wrapped_f
<commit_msg>Set minify to False as well as sometimes setting it to True.<commit_after>
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
|
from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
return wrapped_f
Set minify to False as well as sometimes setting it to True.from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
|
<commit_before>from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
format_ = request.args.get('format')
if format_ == 'json':
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
return f(*args, **kwargs)
return wrapped_f
<commit_msg>Set minify to False as well as sometimes setting it to True.<commit_after>from functools import wraps
from flask import current_app, request
def minifiable(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] = \
request.args.get('format') != 'json'
return f(*args, **kwargs)
return wrapped_f
|
8a577edcc723ad30cc1b84c00435474e980353d3
|
gaphor/diagram/profiles/extension.py
|
gaphor/diagram/profiles/extension.py
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.diagram.diagramline import NamedLine
class ExtensionItem(NamedLine):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
__uml__ = UML.Extension
def __init__(self, id=None, model=None):
NamedLine.__init__(self, id, model)
self.watch("subject<Extension>.ownedEnd")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents
@represents(UML.Extension)
class ExtensionItem(LinePresentation):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
),
EditableText(text=lambda: self.subject and self.subject.name or ""),
)
self.watch("subject<NamedElement>.name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
Convert Extension item to new line style
|
Convert Extension item to new line style
|
Python
|
lgpl-2.1
|
amolenaar/gaphor,amolenaar/gaphor
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.diagram.diagramline import NamedLine
class ExtensionItem(NamedLine):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
__uml__ = UML.Extension
def __init__(self, id=None, model=None):
NamedLine.__init__(self, id, model)
self.watch("subject<Extension>.ownedEnd")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
Convert Extension item to new line style
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents
@represents(UML.Extension)
class ExtensionItem(LinePresentation):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
),
EditableText(text=lambda: self.subject and self.subject.name or ""),
)
self.watch("subject<NamedElement>.name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
<commit_before>"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.diagram.diagramline import NamedLine
class ExtensionItem(NamedLine):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
__uml__ = UML.Extension
def __init__(self, id=None, model=None):
NamedLine.__init__(self, id, model)
self.watch("subject<Extension>.ownedEnd")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
<commit_msg>Convert Extension item to new line style<commit_after>
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents
@represents(UML.Extension)
class ExtensionItem(LinePresentation):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
),
EditableText(text=lambda: self.subject and self.subject.name or ""),
)
self.watch("subject<NamedElement>.name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.diagram.diagramline import NamedLine
class ExtensionItem(NamedLine):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
__uml__ = UML.Extension
def __init__(self, id=None, model=None):
NamedLine.__init__(self, id, model)
self.watch("subject<Extension>.ownedEnd")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
Convert Extension item to new line style"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents
@represents(UML.Extension)
class ExtensionItem(LinePresentation):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
),
EditableText(text=lambda: self.subject and self.subject.name or ""),
)
self.watch("subject<NamedElement>.name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
<commit_before>"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.diagram.diagramline import NamedLine
class ExtensionItem(NamedLine):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
__uml__ = UML.Extension
def __init__(self, id=None, model=None):
NamedLine.__init__(self, id, model)
self.watch("subject<Extension>.ownedEnd")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
<commit_msg>Convert Extension item to new line style<commit_after>"""
ExtensionItem -- Graphical representation of an association.
"""
# TODO: for Extension.postload(): in some cases where the association ends
# are connected to the same Class, the head_end property is connected to the
# tail end and visa versa.
from gaphor import UML
from gaphor.UML.modelfactory import stereotypes_str
from gaphor.diagram.presentation import LinePresentation
from gaphor.diagram.shapes import Box, EditableText, Text
from gaphor.diagram.support import represents
@represents(UML.Extension)
class ExtensionItem(LinePresentation):
"""
ExtensionItem represents associations.
An ExtensionItem has two ExtensionEnd items. Each ExtensionEnd item
represents a Property (with Property.association == my association).
"""
def __init__(self, id=None, model=None):
super().__init__(id, model)
self.shape_middle = Box(
Text(
text=lambda: stereotypes_str(self.subject),
style={"min-width": 0, "min-height": 0},
),
EditableText(text=lambda: self.subject and self.subject.name or ""),
)
self.watch("subject<NamedElement>.name")
self.watch("subject.appliedStereotype.classifier.name")
def draw_head(self, context):
cr = context.cairo
cr.move_to(0, 0)
cr.line_to(15, -10)
cr.line_to(15, 10)
cr.line_to(0, 0)
cr.set_source_rgb(0, 0, 0)
cr.fill()
cr.move_to(15, 0)
|
26f0b938bb8619f3ec705ff247c4d671613883fa
|
django/santropolFeast/member/factories.py
|
django/santropolFeast/member/factories.py
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
Add a random <Route> to a generated <Client>
|
Add a random <Route> to a generated <Client>
Issue #214
|
Python
|
agpl-3.0
|
savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,madmath/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,madmath/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/santropol-feast
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
Add a random <Route> to a generated <Client>
Issue #214
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
<commit_before># coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
<commit_msg>Add a random <Route> to a generated <Client>
Issue #214<commit_after>
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
Add a random <Route> to a generated <Client>
Issue #214# coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
<commit_before># coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
<commit_msg>Add a random <Route> to a generated <Client>
Issue #214<commit_after># coding=utf-8
import factory
import datetime
import random
from django.contrib.auth.models import User
from member.models import Member, Address, Contact, Client, PAYMENT_TYPE, Route
from member.models import DELIVERY_TYPE, GENDER_CHOICES
class AddressFactory (factory.DjangoModelFactory):
class Meta:
model = Address
street = factory.Faker('street_address')
city = 'Montreal'
postal_code = factory.Faker('postalcode')
class ContactFactory (factory.DjangoModelFactory):
class Meta:
model = Contact
type = 'Home phone'
value = factory.Faker('phone_number')
class MemberFactory (factory.DjangoModelFactory):
class Meta:
model = Member
firstname = factory.Faker('first_name')
lastname = factory.Faker('last_name')
address = factory.SubFactory(AddressFactory)
class ClientFactory (factory.DjangoModelFactory):
class Meta:
model = Client
member = factory.SubFactory(MemberFactory)
billing_member = member
billing_payment_type = random.choice(PAYMENT_TYPE)[0]
rate_type = "default"
member = member
emergency_contact = factory.SubFactory(MemberFactory)
status = random.choice(Client.CLIENT_STATUS)[0]
language = "en"
alert = factory.Faker('sentence')
delivery_type = random.choice(DELIVERY_TYPE)[0]
gender = random.choice(GENDER_CHOICES)[0]
birthdate = factory.Faker('date')
route = random.choice(Route.objects.all())
|
7a3863355c36347c691d35166932e83a3f0352ea
|
examples/rmg/minimal_sensitivity/input.py
|
examples/rmg/minimal_sensitivity/input.py
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
Update RMG example minimal_sensitivity with multiplicity label
|
Update RMG example minimal_sensitivity with multiplicity label
|
Python
|
mit
|
nyee/RMG-Py,nyee/RMG-Py,enochd/RMG-Py,comocheng/RMG-Py,pierrelb/RMG-Py,chatelak/RMG-Py,chatelak/RMG-Py,comocheng/RMG-Py,pierrelb/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,nickvandewiele/RMG-Py
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
Update RMG example minimal_sensitivity with multiplicity label
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
<commit_before># Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
<commit_msg>Update RMG example minimal_sensitivity with multiplicity label<commit_after>
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
Update RMG example minimal_sensitivity with multiplicity label# Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
<commit_before># Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
<commit_msg>Update RMG example minimal_sensitivity with multiplicity label<commit_after># Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# Constraints on generated species
generatedSpeciesConstraints(
maximumRadicalElectrons = 2,
)
# List of species
species(
label='ethane',
multiplicity = 1,
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveConcentrationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
|
7539a5445d24193395eed5dc658a4e69d8782736
|
buffpy/tests/test_profile.py
|
buffpy/tests/test_profile.py
|
from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffpy.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
from unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
assert profile.schedules == "123"
mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1"))
def test_profile_schedules_setter():
""" Should update profile's schedules. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
"times": ["mo"]
}
mocked_api.post.assert_called_once_with(
url=PATHS["UPDATE_SCHEDULES"].format("1"),
data="schedules[0][times][]=mo&")
def test_profile_updates():
""" Should properly call buffer's updates. """
mocked_api = MagicMock()
with patch("buffpy.models.profile.Updates") as mocked_updates:
profile = Profile(api=mocked_api, raw_response={"id": 1})
assert profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
Migrate profile tests to pytest
|
Migrate profile tests to pytest
|
Python
|
mit
|
vtemian/buffpy
|
from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffpy.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
Migrate profile tests to pytest
|
from unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
assert profile.schedules == "123"
mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1"))
def test_profile_schedules_setter():
""" Should update profile's schedules. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
"times": ["mo"]
}
mocked_api.post.assert_called_once_with(
url=PATHS["UPDATE_SCHEDULES"].format("1"),
data="schedules[0][times][]=mo&")
def test_profile_updates():
""" Should properly call buffer's updates. """
mocked_api = MagicMock()
with patch("buffpy.models.profile.Updates") as mocked_updates:
profile = Profile(api=mocked_api, raw_response={"id": 1})
assert profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
<commit_before>from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffpy.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
<commit_msg>Migrate profile tests to pytest<commit_after>
|
from unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
assert profile.schedules == "123"
mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1"))
def test_profile_schedules_setter():
""" Should update profile's schedules. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
"times": ["mo"]
}
mocked_api.post.assert_called_once_with(
url=PATHS["UPDATE_SCHEDULES"].format("1"),
data="schedules[0][times][]=mo&")
def test_profile_updates():
""" Should properly call buffer's updates. """
mocked_api = MagicMock()
with patch("buffpy.models.profile.Updates") as mocked_updates:
profile = Profile(api=mocked_api, raw_response={"id": 1})
assert profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffpy.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
Migrate profile tests to pytestfrom unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
assert profile.schedules == "123"
mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1"))
def test_profile_schedules_setter():
""" Should update profile's schedules. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
"times": ["mo"]
}
mocked_api.post.assert_called_once_with(
url=PATHS["UPDATE_SCHEDULES"].format("1"),
data="schedules[0][times][]=mo&")
def test_profile_updates():
""" Should properly call buffer's updates. """
mocked_api = MagicMock()
with patch("buffpy.models.profile.Updates") as mocked_updates:
profile = Profile(api=mocked_api, raw_response={"id": 1})
assert profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
<commit_before>from nose.tools import eq_
from mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
'name': 'me',
'service': 'twiter',
'id': 1
}
def test_profile_schedules_getter():
'''
Test schedules gettering from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
eq_(profile.schedules, '123')
mocked_api.get.assert_called_once_with(url = PATHS['GET_SCHEDULES'] % 1)
def test_profile_schedules_setter():
'''
Test schedules setter from buffer api
'''
mocked_api = MagicMock()
mocked_api.get.return_value = '123'
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
'times': ['mo']
}
mocked_api.post.assert_called_once_with(url=PATHS['UPDATE_SCHEDULES'] % 1,
data='schedules[0][times][]=mo&')
def test_profile_updates():
'''
Test updates relationship with a profile
'''
mocked_api = MagicMock()
with patch('buffpy.models.profile.Updates') as mocked_updates:
profile = Profile(api=mocked_api, raw_response={'id': 1})
updates = profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
<commit_msg>Migrate profile tests to pytest<commit_after>from unittest.mock import MagicMock, patch
from buffpy.models.profile import Profile, PATHS
mocked_response = {
"name": "me",
"service": "twiter",
"id": 1
}
def test_profile_schedules_getter():
""" Should retrieve profiles from buffer's API. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
assert profile.schedules == "123"
mocked_api.get.assert_called_once_with(url=PATHS["GET_SCHEDULES"].format("1"))
def test_profile_schedules_setter():
""" Should update profile's schedules. """
mocked_api = MagicMock()
mocked_api.get.return_value = "123"
profile = Profile(mocked_api, mocked_response)
profile.schedules = {
"times": ["mo"]
}
mocked_api.post.assert_called_once_with(
url=PATHS["UPDATE_SCHEDULES"].format("1"),
data="schedules[0][times][]=mo&")
def test_profile_updates():
""" Should properly call buffer's updates. """
mocked_api = MagicMock()
with patch("buffpy.models.profile.Updates") as mocked_updates:
profile = Profile(api=mocked_api, raw_response={"id": 1})
assert profile.updates
mocked_updates.assert_called_once_with(api=mocked_api, profile_id=1)
|
b656869588d0dab127856bafbd1988f7ba09c48b
|
server/crashmanager/cron.py
|
server/crashmanager/cron.py
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
os.chmod(tmpf, 0o644)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
Set file permissions to readable in export_signatures
|
Set file permissions to readable in export_signatures
|
Python
|
mpl-2.0
|
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
Set file permissions to readable in export_signatures
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
os.chmod(tmpf, 0o644)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
<commit_before>import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
<commit_msg>Set file permissions to readable in export_signatures<commit_after>
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
os.chmod(tmpf, 0o644)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
Set file permissions to readable in export_signaturesimport os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
os.chmod(tmpf, 0o644)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
<commit_before>import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
<commit_msg>Set file permissions to readable in export_signatures<commit_after>import os
import shutil
from tempfile import mkstemp
from django.core.management import call_command
from celeryconf import app
SIGNATURES_ZIP = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'files', 'signatures.zip'))
@app.task
def bug_update_status():
call_command('bug_update_status')
@app.task
def cleanup_old_crashes():
call_command('cleanup_old_crashes')
@app.task
def triage_new_crashes():
call_command('triage_new_crashes')
@app.task
def export_signatures():
fd, tmpf = mkstemp(prefix="fm-sigs-", suffix=".zip")
os.close(fd)
try:
call_command('export_signatures', tmpf)
os.chmod(tmpf, 0o644)
shutil.copy(tmpf, SIGNATURES_ZIP)
finally:
os.unlink(tmpf)
|
c383e06d51d4e59d400ab6fd62eff2359ab4e728
|
python/the_birthday_bar.py
|
python/the_birthday_bar.py
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
Refactor to use map and filter
|
Refactor to use map and filter
|
Python
|
mit
|
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
Refactor to use map and filter
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
<commit_before>#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
<commit_msg>Refactor to use map and filter<commit_after>
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
Refactor to use map and filter#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
<commit_before>#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
birthday_chocolates = 0
for piece in sliding_window(month, squares):
if sum(piece) == day:
birthday_chocolates += 1
return birthday_chocolates
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
<commit_msg>Refactor to use map and filter<commit_after>#!/bin/python3
import itertools
import collections
def sliding_window(n, seq):
"""
Copied from toolz
https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#sliding_window
A sequence of overlapping subsequences
>>> list(sliding_window(2, [1, 2, 3, 4]))
[(1, 2), (2, 3), (3, 4)]
This function creates a sliding window suitable for transformations like
sliding means / smoothing
>>> mean = lambda seq: float(sum(seq)) / len(seq)
>>> list(map(mean, sliding_window(2, [1, 2, 3, 4])))
[1.5, 2.5, 3.5]
"""
return zip(*(collections.deque(itertools.islice(it, i), 0) or it
for i, it in enumerate(itertools.tee(seq, n))))
def birthday_chocolate(squares, day, month):
consecutive_sums = map(lambda piece: sum(piece), sliding_window(month, squares))
birthday_bars = list(filter(lambda consecutive_sum: day == consecutive_sum,
consecutive_sums))
return len(birthday_bars)
_ = int(input().strip())
SQUARES = list(map(int, input().strip().split(' ')))
DAY, MONTH = map(int, input().strip().split(' '))
print(birthday_chocolate(SQUARES, DAY, MONTH))
|
ccab0ca5d1eba65d1ad6d1c3e4fe35b0cf883e0e
|
src/card.py
|
src/card.py
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "Attribute not found."
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "{N/A}"
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
Change the default __getattr_ value
|
Change the default __getattr_ value
|
Python
|
mit
|
theneosloth/Bolas
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "Attribute not found."
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
Change the default __getattr_ value
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "{N/A}"
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
<commit_before>class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "Attribute not found."
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
<commit_msg>Change the default __getattr_ value<commit_after>
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "{N/A}"
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "Attribute not found."
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
Change the default __getattr_ valueclass Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "{N/A}"
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
<commit_before>class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "Attribute not found."
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
<commit_msg>Change the default __getattr_ value<commit_after>class Card:
"""
A wrapper around a Scryfall json card object.
"""
def __init__(self, cardData):
self._data = cardData
def __getattr__(self, attr):
"""
A hack that makes all attributes inaccessible,
and instead returns the stored json values
"""
if attr in self._data and isinstance(self._data[attr], str):
return self._data[attr]
else:
return "{N/A}"
def __contains__(self, arg):
return arg in self._data
def __str__(self):
"""
Returns the string representation of a magic card.
The ** is the Discord way to bolden the text
"""
# Power/toughness, seen only if it's a creature
pt = ""
if "power" in self._data:
pt = "{0}/{1}".format(self.power, self.toughness)
return "**{0}** {1}\n{2} {3}\n{4}\n".format(self.name, self.mana_cost,
self.type_line,
pt,
self.oracle_text)
|
0d65c7a3afdbc610cd7ada4e5604eda54f5305b6
|
calicoctl/calico_ctl/__init__.py
|
calicoctl/calico_ctl/__init__.py
|
__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
|
__version__ = "0.17.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.12.0-dev"
__felix_version__ = "1.3.0-dev"
|
Update docs to version v0.17.0
|
Update docs to version v0.17.0
|
Python
|
apache-2.0
|
TrimBiggs/calico-containers,projectcalico/calico-docker,TrimBiggs/calico-containers,projectcalico/calico-containers,insequent/calico-docker,projectcalico/calico-containers,insequent/calico-docker,Metaswitch/calico-docker,quater/calico-containers,caseydavenport/calico-containers,quater/calico-containers,caseydavenport/calico-docker,TrimBiggs/calico-docker,caseydavenport/calico-containers,TrimBiggs/calico-docker,Metaswitch/calico-docker,projectcalico/calico-docker,caseydavenport/calico-docker,caseydavenport/calico-containers,projectcalico/calico-containers
|
__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
Update docs to version v0.17.0
|
__version__ = "0.17.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.12.0-dev"
__felix_version__ = "1.3.0-dev"
|
<commit_before>__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
<commit_msg>Update docs to version v0.17.0<commit_after>
|
__version__ = "0.17.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.12.0-dev"
__felix_version__ = "1.3.0-dev"
|
__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
Update docs to version v0.17.0__version__ = "0.17.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.12.0-dev"
__felix_version__ = "1.3.0-dev"
|
<commit_before>__version__ = "0.16.1-dev"
__libnetwork_plugin_version__ = "v0.7.0-dev"
__libcalico_version__ = "v0.11.0-dev"
__felix_version__ = "1.3.0a6-dev"
<commit_msg>Update docs to version v0.17.0<commit_after>__version__ = "0.17.0-dev"
__libnetwork_plugin_version__ = "v0.8.0-dev"
__libcalico_version__ = "v0.12.0-dev"
__felix_version__ = "1.3.0-dev"
|
8086ecd7d96dd4da4e90c583fd6300b9f87e3ef2
|
src/main.py
|
src/main.py
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i.name, ' ', i.score
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
player = raw_input("Your score is %d, please enter your name: " % final_score)
score_board_object.add_score(final_score, player)
score_board_object.save_scores(SCORE_FILE_PATH)
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
score_board_object.add_score(final_score)
score_board_object.save_scores(SCORE_FILE_PATH)
|
Change the use of score_board object due to our change in score_board.py
|
Change the use of score_board object due to our change in score_board.py
|
Python
|
mit
|
serenafr/My2048
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i.name, ' ', i.score
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
player = raw_input("Your score is %d, please enter your name: " % final_score)
score_board_object.add_score(final_score, player)
score_board_object.save_scores(SCORE_FILE_PATH)
Change the use of score_board object due to our change in score_board.py
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
score_board_object.add_score(final_score)
score_board_object.save_scores(SCORE_FILE_PATH)
|
<commit_before>import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i.name, ' ', i.score
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
player = raw_input("Your score is %d, please enter your name: " % final_score)
score_board_object.add_score(final_score, player)
score_board_object.save_scores(SCORE_FILE_PATH)
<commit_msg>Change the use of score_board object due to our change in score_board.py<commit_after>
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
score_board_object.add_score(final_score)
score_board_object.save_scores(SCORE_FILE_PATH)
|
import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i.name, ' ', i.score
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
player = raw_input("Your score is %d, please enter your name: " % final_score)
score_board_object.add_score(final_score, player)
score_board_object.save_scores(SCORE_FILE_PATH)
Change the use of score_board object due to our change in score_board.pyimport board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
score_board_object.add_score(final_score)
score_board_object.save_scores(SCORE_FILE_PATH)
|
<commit_before>import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i.name, ' ', i.score
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
player = raw_input("Your score is %d, please enter your name: " % final_score)
score_board_object.add_score(final_score, player)
score_board_object.save_scores(SCORE_FILE_PATH)
<commit_msg>Change the use of score_board object due to our change in score_board.py<commit_after>import board
import score_board
from os.path import expanduser
SCORE_FILE_PATH = expanduser('~/.config/my2048/scores.conf')
KEY_MOVE_MAP = {
'a': board.Move.LEFT,
'w': board.Move.UP,
's': board.Move.DOWN,
'd': board.Move.RIGHT,
}
def print_score_board(score_board):
for i in score_board.get_scores():
print i
if __name__ == "__main__":
score_board_object = score_board.Score_Board()
while True:
score_board_object.load_scores(SCORE_FILE_PATH)
print_score_board(score_board_object)
board_object = board.Board(2)
board_object.output()
print '\n'
next_step = ''
while board_object.can_move():
next_step = raw_input()
next_move = KEY_MOVE_MAP[next_step]
board_object.move(next_move)
print board_object.get_score()
board_object.output()
final_score = board_object.get_score()
score_board_object.add_score(final_score)
score_board_object.save_scores(SCORE_FILE_PATH)
|
dc0f76c676ec142fa6381fa4d6ac45e6f6127edf
|
common/util/update_wf_lib.py
|
common/util/update_wf_lib.py
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
Choose the pulses to update depending on library
|
Choose the pulses to update depending on library
|
Python
|
apache-2.0
|
BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))Choose the pulses to update depending on library
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
<commit_before>#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))<commit_msg>Choose the pulses to update depending on library<commit_after>
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))Choose the pulses to update depending on library#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
<commit_before>#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
pulseList.append([AC(q, ct) for ct in range(24)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))<commit_msg>Choose the pulses to update depending on library<commit_after>#update waveforms in target sequence from current ChanParams settings.
#Warning: this updates all channels, beware of possible conflicts
import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('seqPath', help='path of sequence to be updated')
parser.add_argument('seqName', help='name of sequence to be updated')
args = parser.parse_args()
from QGL import *
from QGL.drivers import APS2Pattern
from QGL import config
qubits = ChannelLibrary.channelLib.connectivityG.nodes()
edges = ChannelLibrary.channelLib.connectivityG.edges()
pulseList = []
for q in qubits:
if config.pulse_primitives_lib == 'standard':
pulseList.append([AC(q, ct) for ct in range(24)])
else:
pulseList.append([X90(q), Y90(q), X90m(q), Y90m(q)])
for edge in edges:
pulseList.append(ZX90_CR(edge[0],edge[1]))
#update waveforms in the desired sequence (generated with APS2Pattern.SAVE_WF_OFFSETS = True)
PatternUtils.update_wf_library(pulseList, os.path.normpath(os.path.join(args.seqPath, args.seqName)))
|
ba8d5c6ac809899265d13e366d66592efa12ca34
|
imgfilter/filters/blurred_context.py
|
imgfilter/filters/blurred_context.py
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
|
Fix bug in blurred context recognition
|
Fix bug in blurred context recognition
|
Python
|
mit
|
vismantic-ohtuprojekti/qualipy,vismantic-ohtuprojekti/image-filtering-suite
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
Fix bug in blurred context recognition
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
|
<commit_before>import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
<commit_msg>Fix bug in blurred context recognition<commit_after>
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
|
import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
Fix bug in blurred context recognitionimport cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
|
<commit_before>import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, obj_mask[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, obj_mask[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
return vertical_blur(obj_mask, extracted_object) or \
horizontal_blur(obj_mask, extracted_object)
<commit_msg>Fix bug in blurred context recognition<commit_after>import cv2
import numpy
import tempfile
import subprocess
from .. import get_data
from whole_blur import is_blurred as whole_blur
def run_object_extraction(image_path):
temp1 = tempfile.mkstemp(suffix=".jpg")[1]
temp2 = tempfile.mkstemp(suffix=".jpg")[1]
subprocess.call([get_data("object_extraction/extract_object"),
image_path, temp1, temp2])
return temp2
def vertical_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 0)
cv2.imwrite(tmp_file, img[:, mask])
return whole_blur(tmp_file)
def horizontal_blur(img, obj_mask, tmp_file):
mask = numpy.all(obj_mask != 255, 1)
cv2.imwrite(tmp_file, img[mask])
return whole_blur(tmp_file)
def is_blurred(image_path):
extracted_object = run_object_extraction(image_path)
img = cv2.imread(image_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
obj_mask = cv2.imread(extracted_object, cv2.CV_LOAD_IMAGE_GRAYSCALE)
if img is None or obj_mask is None:
return None
return vertical_blur(img, obj_mask, extracted_object) or \
horizontal_blur(img, obj_mask, extracted_object)
|
e88c62f6e02cd84807d0b56468a0e0c21d2d4967
|
imgur_downloader/directory_helper.py
|
imgur_downloader/directory_helper.py
|
import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~/ImgurDownloader/') + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~') + '/' + settings.default_download_directory + '/' + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
Raise an exception if File exist where download directory should be.
|
Raise an exception if File exist where download directory should be.
|
Python
|
mit
|
odty101/ImgurDownloader
|
import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~/ImgurDownloader/') + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
Raise an exception if File exist where download directory should be.
|
import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~') + '/' + settings.default_download_directory + '/' + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
<commit_before>import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~/ImgurDownloader/') + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
<commit_msg>Raise an exception if File exist where download directory should be.<commit_after>
|
import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~') + '/' + settings.default_download_directory + '/' + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~/ImgurDownloader/') + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
Raise an exception if File exist where download directory should be.import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~') + '/' + settings.default_download_directory + '/' + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
<commit_before>import os
import logging
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~/ImgurDownloader/') + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
<commit_msg>Raise an exception if File exist where download directory should be.<commit_after>import os
import logging
from configuration import settings
logger = logging.getLogger(__name__)
def setup_download_dir(directory_name):
"""
A helper function to create the download directory if it down not exist or is a file
:param directory_name: Name of the directory to create
:return: The absolute pathname of the directory just created.
"""
# Check if Path for album exists if not create
if os.path.isabs(directory_name):
path_name = str(directory_name)
else:
path_name = os.path.expanduser('~') + '/' + settings.default_download_directory + '/' + str(directory_name)
# If desired path is already a file raise
if os.path.isfile(path_name):
logger.error('File exist at path {}'.format(path_name))
raise FileExistsError
# Do not attempt to create the directory if it exists
if not os.path.isdir(path_name):
os.makedirs(path_name)
logger.info('Download directory is: {}'.format(path_name))
return path_name
|
b542dd8466aa4b1c1373d320d860dbb92132c962
|
lib/ansible/runner/connection/__init__.py
|
lib/ansible/runner/connection/__init__.py
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
Fix import in ssh connection
|
Fix import in ssh connection
|
Python
|
mit
|
thaim/ansible,thaim/ansible
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
Fix import in ssh connection
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
<commit_before># (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
<commit_msg>Fix import in ssh connection<commit_after>
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
Fix import in ssh connection# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
<commit_before># (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
<commit_msg>Fix import in ssh connection<commit_after># (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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/>.
#
################################################
import local
import paramiko_ssh
import ssh
class Connection(object):
''' Handles abstract connections to remote hosts '''
def __init__(self, runner):
self.runner = runner
def connect(self, host, port=None):
conn = None
transport = self.runner.transport
if transport == 'local':
conn = local.LocalConnection(self.runner, host)
elif transport == 'paramiko':
conn = paramiko_ssh.ParamikoConnection(self.runner, host, port)
elif transport == 'ssh':
conn = ssh.SSHConnection(self.runner, host, port)
if conn is None:
raise Exception("unsupported connection type")
return conn.connect()
|
3326cbd7d14611671fe307aca30950aafb675f1e
|
tests/journey/test_chamber_of_deputies_official_missions_dataset.py
|
tests/journey/test_chamber_of_deputies_official_missions_dataset.py
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
Update testes (Chamber of Deputies changed real world data)
|
Update testes (Chamber of Deputies changed real world data)
|
Python
|
mit
|
datasciencebr/serenata-toolbox
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
Update testes (Chamber of Deputies changed real world data)
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
<commit_before>import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
<commit_msg>Update testes (Chamber of Deputies changed real world data)<commit_after>
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
Update testes (Chamber of Deputies changed real world data)import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
<commit_before>import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(57, len(df))
expectedCanceled = ['No', 'Yes']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
<commit_msg>Update testes (Chamber of Deputies changed real world data)<commit_after>import os
from datetime import date
from unittest import main, TestCase
import numpy as np
from serenata_toolbox.chamber_of_deputies.official_missions_dataset import OfficialMissionsDataset
class TestOfficialMissionsDataset(TestCase):
def setUp(self):
self.subject = OfficialMissionsDataset()
def test_fetch(self):
df = self.subject.fetch(date(2017, 1, 1), date(2017, 2, 28))
actualColumns = df.columns
expectedColumns = [
'participant', 'destination', 'subject', 'start', 'end',
'canceled', 'report_status', 'report_details_link'
]
self.assertTrue(np.array_equal(expectedColumns, actualColumns))
self.assertEqual(53, len(df))
expectedCanceled = ['No']
actualCanceled = df.canceled.unique()
self.assertTrue(np.array_equal(np.array(expectedCanceled), np.array(actualCanceled)))
if __name__ == '__main__':
main()
|
3c6a64c7a5a7b652d8bd79bbe2a10fcf7e287d8c
|
Lib/fontbakery/specifications/ufo_sources_test.py
|
Lib/fontbakery/specifications/ufo_sources_test.py
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return ufo_path
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
print('Test FAIL with empty UFO.')
c = list(check(empty_ufo_font))
status, message = c[-1]
assert status == FAIL
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return (ufo, ufo_path)
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
ufo, ufo_path = empty_ufo_font
print('Test FAIL with empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == FAIL
ufo.info.unitsPerEm = 1000
ufo.info.ascender = 800
ufo.info.descender = -200
ufo.info.xHeight = 500
ufo.info.capHeight = 700
ufo.info.familyName = "Test"
ufo.save()
print('Test PASS with almost empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == PASS
|
Test both failure and success of check for required fields
|
Test both failure and success of check for required fields
|
Python
|
apache-2.0
|
moyogo/fontbakery,moyogo/fontbakery,googlefonts/fontbakery,moyogo/fontbakery,graphicore/fontbakery,googlefonts/fontbakery,graphicore/fontbakery,graphicore/fontbakery,googlefonts/fontbakery
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return ufo_path
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
print('Test FAIL with empty UFO.')
c = list(check(empty_ufo_font))
status, message = c[-1]
assert status == FAIL
Test both failure and success of check for required fields
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return (ufo, ufo_path)
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
ufo, ufo_path = empty_ufo_font
print('Test FAIL with empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == FAIL
ufo.info.unitsPerEm = 1000
ufo.info.ascender = 800
ufo.info.descender = -200
ufo.info.xHeight = 500
ufo.info.capHeight = 700
ufo.info.familyName = "Test"
ufo.save()
print('Test PASS with almost empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == PASS
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return ufo_path
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
print('Test FAIL with empty UFO.')
c = list(check(empty_ufo_font))
status, message = c[-1]
assert status == FAIL
<commit_msg>Test both failure and success of check for required fields<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return (ufo, ufo_path)
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
ufo, ufo_path = empty_ufo_font
print('Test FAIL with empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == FAIL
ufo.info.unitsPerEm = 1000
ufo.info.ascender = 800
ufo.info.descender = -200
ufo.info.xHeight = 500
ufo.info.capHeight = 700
ufo.info.familyName = "Test"
ufo.save()
print('Test PASS with almost empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == PASS
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return ufo_path
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
print('Test FAIL with empty UFO.')
c = list(check(empty_ufo_font))
status, message = c[-1]
assert status == FAIL
Test both failure and success of check for required fields# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return (ufo, ufo_path)
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
ufo, ufo_path = empty_ufo_font
print('Test FAIL with empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == FAIL
ufo.info.unitsPerEm = 1000
ufo.info.ascender = 800
ufo.info.descender = -200
ufo.info.xHeight = 500
ufo.info.capHeight = 700
ufo.info.familyName = "Test"
ufo.save()
print('Test PASS with almost empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == PASS
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return ufo_path
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
print('Test FAIL with empty UFO.')
c = list(check(empty_ufo_font))
status, message = c[-1]
assert status == FAIL
<commit_msg>Test both failure and success of check for required fields<commit_after># -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import defcon
import pytest
from fontbakery.checkrunner import (DEBUG, ENDCHECK, ERROR, FAIL, INFO, PASS,
SKIP, WARN)
check_statuses = (ERROR, FAIL, SKIP, PASS, WARN, INFO, DEBUG)
@pytest.fixture
def empty_ufo_font(tmpdir):
ufo = defcon.Font()
ufo_path = str(tmpdir.join("empty_font.ufo"))
ufo.save(ufo_path)
return (ufo, ufo_path)
def test_check_required_fields(empty_ufo_font):
from fontbakery.specifications.ufo_sources import (
com_daltonmaag_check_required_fields as check)
ufo, ufo_path = empty_ufo_font
print('Test FAIL with empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == FAIL
ufo.info.unitsPerEm = 1000
ufo.info.ascender = 800
ufo.info.descender = -200
ufo.info.xHeight = 500
ufo.info.capHeight = 700
ufo.info.familyName = "Test"
ufo.save()
print('Test PASS with almost empty UFO.')
c = list(check(ufo_path))
status, message = c[-1]
assert status == PASS
|
67da90d339f7cfcef8d6033dbbabed4386a1e6b7
|
examples/downloader.py
|
examples/downloader.py
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns a DefererdResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns an EventualResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
Remove another reference to DeferredResult.
|
Remove another reference to DeferredResult.
|
Python
|
mit
|
itamarst/crochet,wrmsr/crochet,rolando/crochet
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns a DefererdResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
Remove another reference to DeferredResult.
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns an EventualResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
<commit_before>#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns a DefererdResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
<commit_msg>Remove another reference to DeferredResult.<commit_after>
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns an EventualResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns a DefererdResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
Remove another reference to DeferredResult.#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns an EventualResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
<commit_before>#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns a DefererdResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
<commit_msg>Remove another reference to DeferredResult.<commit_after>#!/usr/bin/python
"""
A flask web application that downloads a page in the background.
"""
import logging
from flask import Flask, session, escape
from crochet import setup, run_in_reactor, retrieve_result, TimeoutError
# Can be called multiple times with no ill-effect:
setup()
app = Flask(__name__)
@run_in_reactor
def download_page(url):
"""
Download a page.
"""
from twisted.web.client import getPage
return getPage(url)
@app.route('/')
def index():
if 'download' not in session:
# Calling an @run_in_reactor function returns an EventualResult:
result = download_page('http://www.google.com')
session['download'] = result.stash()
return "Starting download, refresh to track progress."
# retrieval is a one-time operation, so session value cannot be reused:
result = retrieve_result(session.pop('download'))
try:
download = result.wait(timeout=0.1)
return "Downloaded: " + escape(download)
except TimeoutError:
session['download'] = result.stash()
return "Download in progress..."
if __name__ == '__main__':
import os, sys
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app.secret_key = os.urandom(24)
app.run()
|
3e397e79f49fc02bf78d3adaaaa90a65cf5caa67
|
{{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py
|
{{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
@pytest.fixture
def carousel(app):
"""Fixture to get the carousel widget of the test app."""
return app.carousel
def test_carousel(carousel):
"""Test for the carousel widget of the app checking the slides' names and
the text of one of the slide labels.
Args:
carousel (:class:`Carousel`): Carousel widget of :class:`{{cookiecutter.app_class_name}}`
Raises:
AssertionError: If the first slide does not contain *Hello*
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
Remove the carousel fixture for the sake of simplicity
|
Remove the carousel fixture for the sake of simplicity
|
Python
|
mit
|
hackebrot/cookiedozer,hackebrot/cookiedozer
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
@pytest.fixture
def carousel(app):
"""Fixture to get the carousel widget of the test app."""
return app.carousel
def test_carousel(carousel):
"""Test for the carousel widget of the app checking the slides' names and
the text of one of the slide labels.
Args:
carousel (:class:`Carousel`): Carousel widget of :class:`{{cookiecutter.app_class_name}}`
Raises:
AssertionError: If the first slide does not contain *Hello*
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
Remove the carousel fixture for the sake of simplicity
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
<commit_before># -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
@pytest.fixture
def carousel(app):
"""Fixture to get the carousel widget of the test app."""
return app.carousel
def test_carousel(carousel):
"""Test for the carousel widget of the app checking the slides' names and
the text of one of the slide labels.
Args:
carousel (:class:`Carousel`): Carousel widget of :class:`{{cookiecutter.app_class_name}}`
Raises:
AssertionError: If the first slide does not contain *Hello*
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
<commit_msg>Remove the carousel fixture for the sake of simplicity<commit_after>
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
@pytest.fixture
def carousel(app):
"""Fixture to get the carousel widget of the test app."""
return app.carousel
def test_carousel(carousel):
"""Test for the carousel widget of the app checking the slides' names and
the text of one of the slide labels.
Args:
carousel (:class:`Carousel`): Carousel widget of :class:`{{cookiecutter.app_class_name}}`
Raises:
AssertionError: If the first slide does not contain *Hello*
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
Remove the carousel fixture for the sake of simplicity# -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
<commit_before># -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
@pytest.fixture
def carousel(app):
"""Fixture to get the carousel widget of the test app."""
return app.carousel
def test_carousel(carousel):
"""Test for the carousel widget of the app checking the slides' names and
the text of one of the slide labels.
Args:
carousel (:class:`Carousel`): Carousel widget of :class:`{{cookiecutter.app_class_name}}`
Raises:
AssertionError: If the first slide does not contain *Hello*
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
<commit_msg>Remove the carousel fixture for the sake of simplicity<commit_after># -*- coding: utf-8 -*-
import pytest
def test_app_title(app):
"""Simply tests if the default app title meets the expectations.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the title does not match
"""
assert app.title == '{{cookiecutter.app_title}}'
def test_carousel(app):
"""Test for the carousel widget of the app checking the slides' names.
Args:
app (:class:`{{cookiecutter.app_class_name}}`): Default app instance
Raises:
AssertionError: If the names of the slides do not match the expectations
"""
names = [slide.name for slide in app.carousel.slides]
expected = ['hello', 'kivy', 'cookiecutterdozer', 'license', 'github']
assert names == expected
|
f5cd0de26f430f33fa91bfd21bc96914fe9c56b8
|
troposphere/cloudwatch.py
|
troposphere/cloudwatch.py
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
Allow Ref's in addition to basestrings
|
Allow Ref's in addition to basestrings
|
Python
|
bsd-2-clause
|
jantman/troposphere,Yipit/troposphere,unravelin/troposphere,xxxVxxx/troposphere,alonsodomin/troposphere,Hons/troposphere,inetCatapult/troposphere,ptoraskar/troposphere,johnctitus/troposphere,cryptickp/troposphere,DualSpark/troposphere,dmm92/troposphere,7digital/troposphere,nicolaka/troposphere,ikben/troposphere,WeAreCloudar/troposphere,amosshapira/troposphere,samcrang/troposphere,jdc0589/troposphere,ccortezb/troposphere,dmm92/troposphere,craigbruce/troposphere,mhahn/troposphere,cloudtools/troposphere,garnaat/troposphere,wangqiang8511/troposphere,LouTheBrew/troposphere,pas256/troposphere,horacio3/troposphere,ikben/troposphere,alonsodomin/troposphere,kid/troposphere,cloudtools/troposphere,7digital/troposphere,mannytoledo/troposphere,micahhausler/troposphere,johnctitus/troposphere,iblazevic/troposphere,horacio3/troposphere,pas256/troposphere,yxd-hde/troposphere
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
Allow Ref's in addition to basestrings
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
<commit_before># Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
<commit_msg>Allow Ref's in addition to basestrings<commit_after>
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
Allow Ref's in addition to basestrings# Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
<commit_before># Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
<commit_msg>Allow Ref's in addition to basestrings<commit_after># Copyright (c) 2013, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty, Ref
from .validators import integer, positive_integer, boolean
class MetricDimension(AWSProperty):
props = {
'Name': (basestring, True),
'Value': (basestring, True),
}
class Alarm(AWSObject):
type = "AWS::CloudWatch::Alarm"
props = {
'ActionsEnabled': (boolean, False),
'AlarmActions': ([basestring, Ref], False),
'AlarmDescription': (basestring, False),
'AlarmName': (basestring, False),
'ComparisonOperator': (basestring, True),
'Dimensions': ([MetricDimension], False),
'EvaluationPeriods': (positive_integer, True),
'InsufficientDataActions': ([basestring, Ref], False),
'MetricName': (basestring, True),
'Namespace': (basestring, True),
'OKActions': ([basestring, Ref], False),
'Period': (positive_integer, True),
'Statistic': (basestring, True),
'Threshold': (integer, True),
'Unit': (basestring, False),
}
|
2a99d8e3877162a3e06b324b84cb92ae26661d53
|
packs/linux/actions/get_open_ports.py
|
packs/linux/actions/get_open_ports.py
|
import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
Add a note about root and nmap binary dependency.
|
Add a note about root and nmap binary dependency.
|
Python
|
apache-2.0
|
armab/st2contrib,StackStorm/st2contrib,lmEshoo/st2contrib,tonybaloney/st2contrib,armab/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,jtopjian/st2contrib,dennybaa/st2contrib,pinterb/st2contrib,pinterb/st2contrib,meirwah/st2contrib,pearsontechnology/st2contrib,armab/st2contrib,tonybaloney/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,digideskio/st2contrib,digideskio/st2contrib,pidah/st2contrib,lmEshoo/st2contrib,dennybaa/st2contrib,psychopenguin/st2contrib,StackStorm/st2contrib,meirwah/st2contrib,tonybaloney/st2contrib,jtopjian/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,psychopenguin/st2contrib
|
import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
Add a note about root and nmap binary dependency.
|
import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
<commit_before>import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
<commit_msg>Add a note about root and nmap binary dependency.<commit_after>
|
import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
Add a note about root and nmap binary dependency.import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
<commit_before>import nmap
from st2actions.runners.pythonrunner import Action
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
<commit_msg>Add a note about root and nmap binary dependency.<commit_after>import nmap
from st2actions.runners.pythonrunner import Action
"""
Note: This action requires nmap binary to be available and needs to run as root.
"""
class PortScanner(Action):
def run(self, host):
result = []
port_details = {}
ps = nmap.PortScanner()
scan_res = ps.scan(host, arguments='--min-parallelism 100 -sT -sU -sZ')
for target_host in ps.all_hosts():
if target_host in ps.all_hosts():
for comm in ps[target_host].all_protocols():
if comm in ['tcp','udp','ip','sctp']:
ports = ps[target_host][comm].keys()
ports.sort()
for port in ports:
port_details = {port:{'state':ps[host][comm][port]['state'], 'service':ps[host][comm][port]['name'], 'protocol':comm}}
result.append(port_details)
return result
if __name__ == "__main__":
ps = PortScanner()
ps.run()
|
3b7452b6ffc52a4bc21128ddb9b04a6839286fe0
|
cpm_data/wagtail_hooks.py
|
cpm_data/wagtail_hooks.py
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(MyPageModelAdmin)
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
search_fields = ('name_en', 'name_be', 'name_ru')
class JuryMemberModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_icon = 'group'
menu_order = 210
list_display = ('name_en', 'name_be', 'name_ru', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
class PartnerModelAdmin(ModelAdmin):
model = Partner
menu_label = 'Partners'
menu_icon = 'grip'
menu_order = 220
list_display = ('name_en', 'name_be', 'name_ru', 'image')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(SeasonModelAdmin)
modeladmin_register(JuryMemberModelAdmin)
modeladmin_register(PartnerModelAdmin)
|
Add modeladmin classes for Season, JuryMember, Partner models
|
Add modeladmin classes for Season, JuryMember, Partner models
|
Python
|
unlicense
|
nott/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,nott/next.filmfest.by,nott/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by,kinaklub/next.filmfest.by
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(MyPageModelAdmin)
Add modeladmin classes for Season, JuryMember, Partner models
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
search_fields = ('name_en', 'name_be', 'name_ru')
class JuryMemberModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_icon = 'group'
menu_order = 210
list_display = ('name_en', 'name_be', 'name_ru', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
class PartnerModelAdmin(ModelAdmin):
model = Partner
menu_label = 'Partners'
menu_icon = 'grip'
menu_order = 220
list_display = ('name_en', 'name_be', 'name_ru', 'image')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(SeasonModelAdmin)
modeladmin_register(JuryMemberModelAdmin)
modeladmin_register(PartnerModelAdmin)
|
<commit_before>from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(MyPageModelAdmin)
<commit_msg>Add modeladmin classes for Season, JuryMember, Partner models<commit_after>
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
search_fields = ('name_en', 'name_be', 'name_ru')
class JuryMemberModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_icon = 'group'
menu_order = 210
list_display = ('name_en', 'name_be', 'name_ru', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
class PartnerModelAdmin(ModelAdmin):
model = Partner
menu_label = 'Partners'
menu_icon = 'grip'
menu_order = 220
list_display = ('name_en', 'name_be', 'name_ru', 'image')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(SeasonModelAdmin)
modeladmin_register(JuryMemberModelAdmin)
modeladmin_register(PartnerModelAdmin)
|
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(MyPageModelAdmin)
Add modeladmin classes for Season, JuryMember, Partner modelsfrom wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
search_fields = ('name_en', 'name_be', 'name_ru')
class JuryMemberModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_icon = 'group'
menu_order = 210
list_display = ('name_en', 'name_be', 'name_ru', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
class PartnerModelAdmin(ModelAdmin):
model = Partner
menu_label = 'Partners'
menu_icon = 'grip'
menu_order = 220
list_display = ('name_en', 'name_be', 'name_ru', 'image')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(SeasonModelAdmin)
modeladmin_register(JuryMemberModelAdmin)
modeladmin_register(PartnerModelAdmin)
|
<commit_before>from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember
class MyPageModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ('name', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(MyPageModelAdmin)
<commit_msg>Add modeladmin classes for Season, JuryMember, Partner models<commit_after>from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from cpm_data.models import JuryMember, Partner, Season
class SeasonModelAdmin(ModelAdmin):
model = Season
menu_label = 'Seasons'
menu_icon = 'date'
menu_order = 200
list_display = ('name_en', 'name_be', 'name_ru')
search_fields = ('name_en', 'name_be', 'name_ru')
class JuryMemberModelAdmin(ModelAdmin):
model = JuryMember
menu_label = 'Jury'
menu_icon = 'group'
menu_order = 210
list_display = ('name_en', 'name_be', 'name_ru', 'country')
search_fields = ('name_en', 'name_be', 'name_ru')
class PartnerModelAdmin(ModelAdmin):
model = Partner
menu_label = 'Partners'
menu_icon = 'grip'
menu_order = 220
list_display = ('name_en', 'name_be', 'name_ru', 'image')
search_fields = ('name_en', 'name_be', 'name_ru')
modeladmin_register(SeasonModelAdmin)
modeladmin_register(JuryMemberModelAdmin)
modeladmin_register(PartnerModelAdmin)
|
2bfe8077d12a60450da10d53322d39d052bc6e0d
|
bud_get/cli.py
|
bud_get/cli.py
|
""" CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
""" CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
parser.add_argument('--version', action='version', version='v%s' % VERSION)
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
Print version in command line.
|
Print version in command line.
|
Python
|
unlicense
|
doggan/bud-get
|
""" CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
Print version in command line.
|
""" CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
parser.add_argument('--version', action='version', version='v%s' % VERSION)
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
<commit_before>""" CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
<commit_msg>Print version in command line.<commit_after>
|
""" CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
parser.add_argument('--version', action='version', version='v%s' % VERSION)
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
""" CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
Print version in command line.""" CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
parser.add_argument('--version', action='version', version='v%s' % VERSION)
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
<commit_before>""" CLI interface.
"""
import argparse
import bud_get
def main():
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
<commit_msg>Print version in command line.<commit_after>""" CLI interface.
"""
import argparse
import bud_get
from pkg_resources import get_distribution
def main():
VERSION = get_distribution('bud-get').version
parser = argparse.ArgumentParser()
parser.add_argument("infile", help = "the input data file")
parser.add_argument("outfile", help = "the output file")
parser.add_argument('--version', action='version', version='v%s' % VERSION)
args = parser.parse_args()
in_path = args.infile
out_path = args.outfile
print "Processing [%s]..." % in_path
csv_data = bud_get.filter_csv(in_path)
bud_get.write_csv(csv_data, out_path)
if __name__ == "__main__":
main()
|
dc512b896ca7311c0c04dc11b5283dc0ffb4f1e1
|
seating_charts/management/commands/sync_students.py
|
seating_charts/management/commands/sync_students.py
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
Remove extra seating students during sync
|
Remove extra seating students during sync
|
Python
|
mit
|
rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps,rectory-school/rectory-apps
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
Remove extra seating students during sync
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
<commit_before>#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
<commit_msg>Remove extra seating students during sync<commit_after>
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
Remove extra seating students during sync#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
<commit_before>#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
<commit_msg>Remove extra seating students during sync<commit_after>#!/usr/bin/python
import logging
from datetime import date
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from validate_email import validate_email
from academics.models import Enrollment, AcademicYear
from seating_charts.models import SeatingStudent
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Sync academic students with seating students"
def handle(self, *args, **kwargs):
academic_year = AcademicYear.objects.current()
current_enrollments = Enrollment.objects.filter(student__current=True, academic_year=academic_year)
for enrollment in current_enrollments:
#Get the seating student based on the student, not the enrollment
try:
seating_student = SeatingStudent.objects.get(enrollment__student=enrollment.student)
#We found a seating student, but the enrollment was incorrect
if seating_student.enrollment != enrollment:
seating_student.enrollment = enrollment
seating_student.save()
except SeatingStudent.DoesNotExist:
#We did not find a seating student
seating_student = SeatingStudent()
seating_student.enrollment = enrollment
seating_student.save()
# Remove extra students
extra_students = SeatingStudent.objects.exclude(enrollment__student__in=[e.student for e in current_enrollments]).all()
extra_students.delete()
|
e1f499afc2e6e5e4f2033e2cb1cad39bc7d6862e
|
examples/Mode7-Transform/Sin.py
|
examples/Mode7-Transform/Sin.py
|
#!/usr/local/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
#!/usr/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
Use /usr/bin/python for sine table script
|
Use /usr/bin/python for sine table script
|
Python
|
mit
|
Optiroc/libSFX,Optiroc/libSFX,kylophone/libSFX
|
#!/usr/local/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
Use /usr/bin/python for sine table script
|
#!/usr/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
<commit_before>#!/usr/local/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
<commit_msg>Use /usr/bin/python for sine table script<commit_after>
|
#!/usr/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
#!/usr/local/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
Use /usr/bin/python for sine table script#!/usr/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
<commit_before>#!/usr/local/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
<commit_msg>Use /usr/bin/python for sine table script<commit_after>#!/usr/bin/python
import sys
import math
import struct
steps = 256
try:
fname = sys.argv[1]
f = open(fname, 'wb')
for x in range(0, steps):
sine = int(127.5 * math.sin(math.radians(float(x) * (360.0 / float(steps)))))
f.write(struct.pack('b', sine))
f.close()
except Exception as e:
sys.exit(e)
|
9e9f71fd8a8fa9a78263c2adf260343c489eb602
|
GitChat.py
|
GitChat.py
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
Check directory is git repo
|
Check directory is git repo
|
Python
|
apache-2.0
|
shubhodeep9/GitChat,shubhodeep9/GitChat
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
Check directory is git repo
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
<commit_msg>Check directory is git repo<commit_after>
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
Check directory is git repo#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
<commit_before>#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
login = LoginController()
print login.USERNAME
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
<commit_msg>Check directory is git repo<commit_after>#!/usr/bin/env python
"""
A simple echo client
"""
from login import LoginController
def main():
checkDirectory()
login = LoginController()
print login.USERNAME
#method to check if directory is a git repo
def checkDirectory():
try:
open('.git/config')
except IOError:
raise SystemExit('Not a git repo')
# import socket
# host = ''
# port = 65535
# size = 1024
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect((host,port))
# while 1:
# inp = raw_input('Enter:')
# s.send(inp)
# data = s.recv(size)
# if inp == 'BYE':
# s.close()
# break
# print 'Received:', data
if __name__ == '__main__':
main()
|
18f3cd10d07467eb9770ffe52b3d5b007f6967fe
|
cupy/array_api/_typing.py
|
cupy/array_api/_typing.py
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
Add a missing subscription slot to `NestedSequence`
|
MAINT: Add a missing subscription slot to `NestedSequence`
|
Python
|
mit
|
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
MAINT: Add a missing subscription slot to `NestedSequence`
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
<commit_before>"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
<commit_msg>MAINT: Add a missing subscription slot to `NestedSequence`<commit_after>
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
MAINT: Add a missing subscription slot to `NestedSequence`"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
<commit_before>"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
NestedSequence = Sequence[Sequence[Any]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
<commit_msg>MAINT: Add a missing subscription slot to `NestedSequence`<commit_after>"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from cupy.cuda import Device as _Device
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import Any, Literal, Sequence, Type, Union, TYPE_CHECKING, TypeVar
from . import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
# This should really be recursive, but that isn't supported yet. See the
# similar comment in numpy/typing/_array_like.py
_T = TypeVar("_T")
NestedSequence = Sequence[Sequence[_T]]
Device = _Device
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsDLPack = Any
SupportsBufferProtocol = Any
PyCapsule = Any
|
2f8fc66174b96f5ca45e4d656d9c1545d6d88720
|
ixprofile_client/__init__.py
|
ixprofile_client/__init__.py
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
Update social pipeline to social_core
|
Update social pipeline to social_core
|
Python
|
mit
|
infoxchange/ixprofile-client,infoxchange/ixprofile-client
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
Update social pipeline to social_core
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
<commit_before>"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
<commit_msg>Update social pipeline to social_core<commit_after>
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
Update social pipeline to social_core"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
<commit_before>"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social.pipeline.social_auth.social_details',
'social.pipeline.social_auth.social_uid',
'social.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social.pipeline.user.create_user',
'social.pipeline.social_auth.associate_user',
'social.pipeline.social_auth.load_extra_data',
'social.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
<commit_msg>Update social pipeline to social_core<commit_after>"""
A django-socialauth based client for the IX Profile server
"""
try:
# Django 1.7+
from django.apps import AppConfig
except ImportError:
# Stub for old Django
AppConfig = object
from django.conf import settings
SOCIAL_AUTH_PIPELINE = (
'social_core.pipeline.social_auth.social_details',
'social_core.pipeline.social_auth.social_uid',
'social_core.pipeline.social_auth.social_user',
'ixprofile_client.pipeline.match_user',
'social_core.pipeline.user.create_user',
'social_core.pipeline.social_auth.associate_user',
'social_core.pipeline.social_auth.load_extra_data',
'social_core.pipeline.user.user_details',
)
class IXProfileClientConfig(AppConfig):
"""
Application configuration for the IX Profile client.
"""
name = 'ixprofile_client'
def ready(self):
"""
Configure the social auth pipeline.
"""
settings.SOCIAL_AUTH_PIPELINE = SOCIAL_AUTH_PIPELINE
# pylint:disable=invalid-name
default_app_config = 'ixprofile_client.IXProfileClientConfig'
# pylint:enable=invalid-name
|
4d6d22cd8244f7d6479eb2256c6d7822cad1ed0b
|
bibliopixel/main/main.py
|
bibliopixel/main/main.py
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
|
Disable and run and help commands; don't read settings.
|
Disable and run and help commands; don't read settings.
|
Python
|
mit
|
rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
Disable and run and help commands; don't read settings.
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
|
<commit_before>import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
<commit_msg>Disable and run and help commands; don't read settings.<commit_after>
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
|
import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
Disable and run and help commands; don't read settings.import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
|
<commit_before>import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run', 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
parser.add_argument('--settings',
help='Filename for settings',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
settings = PresetLibrary(os.path.expanduser(args.settings), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, settings) or 0)
<commit_msg>Disable and run and help commands; don't read settings.<commit_after>import argparse, os, sys
from .. import log
from .. project.importer import import_symbol
from .. project.preset_library import PresetLibrary
__all__ = ['main']
COMMANDS = ('all_pixel', 'devices', 'demo', 'run') # 'set', 'show')
MODULES = {c: import_symbol('.' + c, 'bibliopixel.main') for c in COMMANDS}
PRESET_LIBRARY_DEFAULT = '~/.bibliopixel'
LOG_LEVELS = ('debug', 'info', 'warning', 'error', 'critical')
ENABLE_PRESETS = False
def no_command(*_):
print('ERROR: No command entered')
print('Valid:', *COMMANDS)
return -1
def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
for name, module in sorted(MODULES.items()):
subparser = subparsers.add_parser(name, help=module.HELP)
module.set_parser(subparser)
parser.add_argument('--loglevel', choices=LOG_LEVELS, default='info')
if ENABLE_PRESETS:
parser.add_argument('--presets',
help='Filename for presets',
default=PRESET_LIBRARY_DEFAULT)
args = ['--help' if i == 'help' else i for i in sys.argv[1:]]
args = parser.parse_args(args)
log.set_log_level(args.loglevel)
presets = ENABLE_PRESETS and PresetLibrary(
os.path.expanduser(args.presets), True)
run = getattr(args, 'run', no_command)
sys.exit(run(args, presets) or 0)
|
62f6ac310f23ee529110529a3071f3c34f100fbb
|
examples/protocol/netstrings.py
|
examples/protocol/netstrings.py
|
grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
Update the netstring code with newfound knowledge.
|
Update the netstring code with newfound knowledge.
|
Python
|
mit
|
rbtcollins/parsley,rbtcollins/parsley,python-parsley/parsley,python-parsley/parsley
|
grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
Update the netstring code with newfound knowledge.
|
grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
<commit_before>grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
<commit_msg>Update the netstring code with newfound knowledge.<commit_after>
|
grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
Update the netstring code with newfound knowledge.grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
<commit_before>grammar = """
digit = anything:x ?(x.isdigit())
nonzeroDigit = anything:x ?(x != '0' and x.isdigit())
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
<commit_msg>Update the netstring code with newfound knowledge.<commit_after>grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
initial = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
self.transport = transport
def sendNetstring(self, string):
self.transport.write('%d:%s,' % (len(string), string))
|
12b181b585a54301c92103aa6ee979b628b76b59
|
examples/crontabReader.py
|
examples/crontabReader.py
|
from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
Add import error message to example
|
Add import error message to example
|
Python
|
mit
|
Salamek/cron-descriptor,Salamek/cron-descriptor
|
from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
Add import error message to example
|
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
<commit_before>from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
<commit_msg>Add import error message to example<commit_after>
|
import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
Add import error message to exampleimport re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
<commit_before>from cron_descriptor import Options, ExpressionDescriptor
import re
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
<commit_msg>Add import error message to example<commit_after>import re
try:
from cron_descriptor import Options, ExpressionDescriptor
except ImportError:
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\033[1mFailed to import cron_descriptor, maybe ? "pip install cron-descriptor ?"\033[0m')
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
raise
class CrontabReader(object):
"""
Simple example reading /etc/contab
"""
rex = re.compile("^(\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}\s+\S{1,3}).+$")
def __init__(self, cronfile):
"""Initialize CrontabReader
Args:
cronfile: Path to cronfile
Returns:
None
"""
options = Options()
options.day_of_week_start_index_zero = False
options.use_24hour_time_format = True
with open(cronfile) as f:
for line in f.readlines():
parsed_line = self.parse_cron_line(line)
if parsed_line:
print("{} -> {}".format(parsed_line, ExpressionDescriptor(parsed_line, options)))
def parse_cron_line(self, line):
"""Parses crontab line and returns only starting time string
Args:
line: crontab line
Returns:
Time part of cron line
"""
stripped = line.strip()
if stripped and stripped.startswith('#') is False:
rexres = self.rex.search(stripped)
if rexres:
return ' '.join(rexres.group(1).split())
return None
CrontabReader('/etc/crontab')
|
d82f569e5ea66020791325a31c4e0625ed1ee3a0
|
captura/views.py
|
captura/views.py
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = Estudio.objects.filter(status='rechazado')
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
Add userid to query to get socio-economic studies
|
Add userid to query to get socio-economic studies
|
Python
|
mit
|
erikiado/jp2_online,erikiado/jp2_online,erikiado/jp2_online
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = Estudio.objects.filter(status='rechazado')
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
Add userid to query to get socio-economic studies
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
<commit_before>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = Estudio.objects.filter(status='rechazado')
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
<commit_msg>Add userid to query to get socio-economic studies<commit_after>
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = Estudio.objects.filter(status='rechazado')
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
Add userid to query to get socio-economic studiesfrom django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
<commit_before>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = Estudio.objects.filter(status='rechazado')
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
<commit_msg>Add userid to query to get socio-economic studies<commit_after>from django.contrib.auth.decorators import user_passes_test, login_required
from django.shortcuts import render
from perfiles_usuario.utils import is_capturista
from estudios_socioeconomicos.models import Estudio
@login_required
#@user_passes_test(is_capturista)
def capturista_dashboard(request):
"""View to render the capturista control dashboard.
This view shows the list of socio-economic studies that are under review
and the action buttons to add and edit each socio-economic study.
"""
estudios = []
iduser = request.user.id
rechazados = Estudio.objects.filter(status='rechazado')
for estudio in rechazados:
if estudio.capturista_id == iduser:
estudios.append(estudio)
return render(request, 'captura/dashboard_capturista.html',
{'estudios': estudios})
|
229b92a2d83fc937da20aa4ea5325be5b587f1bc
|
docweb/tests/__init__.py
|
docweb/tests/__init__.py
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
|
Make Django to find the pydoc-tool.py script tests
|
Make Django to find the pydoc-tool.py script tests
|
Python
|
bsd-3-clause
|
pv/pydocweb,pv/pydocweb
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
Make Django to find the pydoc-tool.py script tests
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
|
<commit_before>import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
<commit_msg>Make Django to find the pydoc-tool.py script tests<commit_after>
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
|
import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
Make Django to find the pydoc-tool.py script testsimport unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
|
<commit_before>import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
<commit_msg>Make Django to find the pydoc-tool.py script tests<commit_after>import unittest
from django.test import TestCase
class AccessTests(TestCase):
"""
Simple tests that check that basic pages can be accessed
and they contain something sensible.
"""
def test_docstring_index(self):
response = self.client.get('/docs/')
self.failUnless('All docstrings' in str(response))
def test_wiki_new_page(self):
response = self.client.get('/Some New Page/')
self.failUnless('Create new' in str(response))
def test_changes(self):
response = self.client.get('/changes/')
self.failUnless('Recent changes' in str(response))
def test_search(self):
response = self.client.get('/search/')
self.failUnless('Fulltext' in str(response))
def test_stats(self):
response = self.client.get('/stats/')
self.failUnless('Overview' in str(response))
def test_patch(self):
response = self.client.get('/patch/')
self.failUnless('Generate patch' in str(response))
def test_non_authenticated(self):
for url in ['/merge/', '/control/', '/accounts/password/',
'/Some%20New%20Page/edit/']:
response = self.client.get(url)
# It should contain a redirect to the login page
self.failUnless(('Location: http://testserver/accounts/login/?next=%s'%url)
in str(response), response)
# -- Allow Django test command to find the script tests
import os
import sys
test_dir = os.path.join(os.path.dirname(__file__), '..', '..', 'tests')
sys.path.append(test_dir)
from test_pydoc_tool import *
|
0b8cf8f8942c59432ead113dd7c0e55360946c16
|
masters/master.chromium.linux/master_site_config.py
|
masters/master.chromium.linux/master_site_config.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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
|
# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
buildslave_version = 'buildbot_slave_8_4'
twisted_version = 'twisted_10_2'
|
Switch chromium.linux slaves to buildbot 0.8.
|
Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98
|
# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
buildslave_version = 'buildbot_slave_8_4'
twisted_version = 'twisted_10_2'
|
<commit_before># 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
<commit_msg>Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
buildslave_version = 'buildbot_slave_8_4'
twisted_version = 'twisted_10_2'
|
# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98# 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
buildslave_version = 'buildbot_slave_8_4'
twisted_version = 'twisted_10_2'
|
<commit_before># 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
<commit_msg>Switch chromium.linux slaves to buildbot 0.8.
Review URL: https://chromiumcodereview.appspot.com/10912181
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@155812 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># 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.
"""ActiveMaster definition."""
import socket
class ChromiumLinux(object):
project_name = 'Chromium Linux'
master_port = 8087
slave_port = 8187
master_port_alt = 8287
tree_closing_notification_recipients = []
from_address = 'buildbot@chromium.org'
master_host = 'master1a.golo.chromium.org'
is_production_host = socket.getfqdn() == master_host
buildslave_version = 'buildbot_slave_8_4'
twisted_version = 'twisted_10_2'
|
3035521c5a8e04b8eeb6874d8769dd5859747d53
|
devpi_builder/cli.py
|
devpi_builder/cli.py
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
print('Skipping {} {} as it is matched by the blacklist.'.format(package, version))
else:
print('Building {} {}.'.format(package, version))
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
print(e)
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
logger.info('Skipping %s %s as it is matched by the blacklist.', package, version)
else:
logger.info('Building %s %s', package, version)
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
logger.exception(e)
|
Use a logger instead of printing to stdout
|
Use a logger instead of printing to stdout
|
Python
|
bsd-3-clause
|
tylerdave/devpi-builder
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
print('Skipping {} {} as it is matched by the blacklist.'.format(package, version))
else:
print('Building {} {}.'.format(package, version))
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
print(e)
Use a logger instead of printing to stdout
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
logger.info('Skipping %s %s as it is matched by the blacklist.', package, version)
else:
logger.info('Building %s %s', package, version)
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
logger.exception(e)
|
<commit_before># coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
print('Skipping {} {} as it is matched by the blacklist.'.format(package, version))
else:
print('Building {} {}.'.format(package, version))
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
print(e)
<commit_msg>Use a logger instead of printing to stdout<commit_after>
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
logger.info('Skipping %s %s as it is matched by the blacklist.', package, version)
else:
logger.info('Building %s %s', package, version)
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
logger.exception(e)
|
# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
print('Skipping {} {} as it is matched by the blacklist.'.format(package, version))
else:
print('Building {} {}.'.format(package, version))
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
print(e)
Use a logger instead of printing to stdout# coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
logger.info('Skipping %s %s as it is matched by the blacklist.', package, version)
else:
logger.info('Building %s %s', package, version)
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
logger.exception(e)
|
<commit_before># coding=utf-8
"""
Command line interface for brandon
"""
import argparse
from devpi_builder import requirements, wheeler, devpi
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
print('Skipping {} {} as it is matched by the blacklist.'.format(package, version))
else:
print('Building {} {}.'.format(package, version))
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
print(e)
<commit_msg>Use a logger instead of printing to stdout<commit_after># coding=utf-8
"""
Command line interface for brandon
"""
import argparse
import logging
from devpi_builder import requirements, wheeler, devpi
logging.basicConfig()
logger = logging.getLogger(__name__)
def main(args=None):
parser = argparse.ArgumentParser(description='Create wheels for all given project versions and upload them to the given index.')
parser.add_argument('requirements', help='requirements.txt style file specifying which project versions to package.')
parser.add_argument('index', help='The index to upload the packaged software to.')
parser.add_argument('user', help='The user to log in as.')
parser.add_argument('password', help='Password of the user.')
parser.add_argument('--blacklist', help='Packages matched by this requirements.txt style file will never be build.')
args = parser.parse_args(args=args)
with wheeler.Builder() as builder, devpi.Client(args.index, args.user, args.password) as devpi_client:
for package, version in requirements.read(args.requirements):
if devpi_client.package_version_exists(package, version):
continue
if args.blacklist and requirements.matched_by_file(package, version, args.blacklist):
logger.info('Skipping %s %s as it is matched by the blacklist.', package, version)
else:
logger.info('Building %s %s', package, version)
try:
wheel_file = builder(package, version)
devpi_client.upload(wheel_file)
except wheeler.BuildError as e:
logger.exception(e)
|
f11e56076e10d2c7e1db529751c53c1c5dc2074f
|
cihai/_compat.py
|
cihai/_compat.py
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
|
Revert "Port with_metaclass from flask"
|
Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.
|
Python
|
mit
|
cihai/cihai,cihai/cihai-python,cihai/cihai
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
|
<commit_before># -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
<commit_msg>Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.<commit_after>
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
|
# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.# -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
|
<commit_before># -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a
# dummy metaclass for one level of class instantiation that replaces
# itself with the actual metaclass.
class metaclass(type):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {})
<commit_msg>Revert "Port with_metaclass from flask"
This reverts commit db23ed0d62789ca995d2dceefd0a1468348c488b.<commit_after># -*- coding: utf8 -*-
# flake8: NOQA
import sys
PY2 = sys.version_info[0] == 2
if PY2:
unichr = unichr
text_type = unicode
string_types = (str, unicode)
integer_types = (int, long)
from urllib import urlretrieve
from cStringIO import StringIO as BytesIO
from StringIO import StringIO
import cPickle as pickle
import urlparse
def console_to_str(s):
return s.decode('utf_8')
exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
else:
unichr = chr
text_type = str
string_types = (str,)
integer_types = (int,)
from io import StringIO, BytesIO
import urllib.parse as urllib
import urllib.parse as urlparse
from urllib.request import urlretrieve
console_encoding = sys.__stdout__.encoding
def console_to_str(s):
""" From pypa/pip project, pip.backwardwardcompat. License MIT. """
try:
return s.decode(console_encoding)
except UnicodeDecodeError:
return s.decode('utf_8')
def reraise(tp, value, tb=None):
if value.__traceback__ is not tb:
raise (value.with_traceback(tb))
raise value
|
7ccc4567071edfa9bc35c38105061ef5a02c7875
|
vagrant/fabfile/hadoop.py
|
vagrant/fabfile/hadoop.py
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
# Make the user confirm because this is really dangerous
ans = raw_input('This will DELETE ALL DATA on HDFS, are you sure ? ([y|n]) ')
if ans != 'y':
return
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
Add safeguard against namenode formatting
|
[vagrant] Add safeguard against namenode formatting
|
Python
|
mit
|
terrai/rastercube,terrai/rastercube,terrai/rastercube
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
[vagrant] Add safeguard against namenode formatting
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
# Make the user confirm because this is really dangerous
ans = raw_input('This will DELETE ALL DATA on HDFS, are you sure ? ([y|n]) ')
if ans != 'y':
return
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
<commit_before>from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
<commit_msg>[vagrant] Add safeguard against namenode formatting<commit_after>
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
# Make the user confirm because this is really dangerous
ans = raw_input('This will DELETE ALL DATA on HDFS, are you sure ? ([y|n]) ')
if ans != 'y':
return
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
[vagrant] Add safeguard against namenode formattingfrom fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
# Make the user confirm because this is really dangerous
ans = raw_input('This will DELETE ALL DATA on HDFS, are you sure ? ([y|n]) ')
if ans != 'y':
return
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
<commit_before>from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
<commit_msg>[vagrant] Add safeguard against namenode formatting<commit_after>from fabric.api import *
from inventory import runs_on
@task
@runs_on('hadoop_master')
def start_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/start-dfs.sh')
@task
@runs_on('hadoop_master')
def stop_hdfs():
with cd('$HADOOP_HOME'):
run('sbin/stop-dfs.sh')
@task
@runs_on('hadoop_master')
def format_namenode():
# Make the user confirm because this is really dangerous
ans = raw_input('This will DELETE ALL DATA on HDFS, are you sure ? ([y|n]) ')
if ans != 'y':
return
with cd('$HADOOP_HOME'):
run('bin/hdfs namenode -format -nonInteractive -clusterId hdfs-terrai-cluster')
@task
@runs_on('hadoop_master')
def balance_datanodes():
with cd('$HADOOP_HOME'):
run('bin/hdfs balancer -policy datanode')
|
1d739dea9cbd91605319412637b32730a250014e
|
entropy/backends/base.py
|
entropy/backends/base.py
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
@abc.abstractmethod
def get_audits(self):
pass
@abc.abstractmethod
def get_repairs(self):
pass
@abc.abstractmethod
def audit_cfg_from_name(self, name):
pass
@abc.abstractmethod
def repair_cfg_from_name(self, name):
pass
@abc.abstractmethod
def get_script_cfg(self, script_type):
pass
@abc.abstractmethod
def check_script_exists(self, script_type, script_name):
pass
@abc.abstractmethod
def add_script(self, script_type, data):
pass
|
Add some abstract methods to backend
|
Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160
|
Python
|
apache-2.0
|
stackforge/entropy,stackforge/entropy,stackforge/entropy
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
@abc.abstractmethod
def get_audits(self):
pass
@abc.abstractmethod
def get_repairs(self):
pass
@abc.abstractmethod
def audit_cfg_from_name(self, name):
pass
@abc.abstractmethod
def repair_cfg_from_name(self, name):
pass
@abc.abstractmethod
def get_script_cfg(self, script_type):
pass
@abc.abstractmethod
def check_script_exists(self, script_type, script_name):
pass
@abc.abstractmethod
def add_script(self, script_type, data):
pass
|
<commit_before># Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
<commit_msg>Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160<commit_after>
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
@abc.abstractmethod
def get_audits(self):
pass
@abc.abstractmethod
def get_repairs(self):
pass
@abc.abstractmethod
def audit_cfg_from_name(self, name):
pass
@abc.abstractmethod
def repair_cfg_from_name(self, name):
pass
@abc.abstractmethod
def get_script_cfg(self, script_type):
pass
@abc.abstractmethod
def check_script_exists(self, script_type, script_name):
pass
@abc.abstractmethod
def add_script(self, script_type, data):
pass
|
# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160# Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
@abc.abstractmethod
def get_audits(self):
pass
@abc.abstractmethod
def get_repairs(self):
pass
@abc.abstractmethod
def audit_cfg_from_name(self, name):
pass
@abc.abstractmethod
def repair_cfg_from_name(self, name):
pass
@abc.abstractmethod
def get_script_cfg(self, script_type):
pass
@abc.abstractmethod
def check_script_exists(self, script_type, script_name):
pass
@abc.abstractmethod
def add_script(self, script_type, data):
pass
|
<commit_before># Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
<commit_msg>Add some abstract methods to backend
Added some methods in base.py that should probably be defined in
every backend
Change-Id: I6f99994b82c2f17083d83b4723f3b4d61fc80160<commit_after># Copyright (C) 2013 Yahoo! Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Backend(object):
"""Base class for persistence backends."""
def __init__(self, conf):
if not conf:
conf = {}
if not isinstance(conf, dict):
raise TypeError("Configuration dictionary expected not: %s"
% type(conf))
self._conf = conf
self._audit = 'audit'
self._repair = 'repair'
@abc.abstractmethod
def open(self):
pass
@abc.abstractmethod
def close(self):
"""Closes any resources this backend has open."""
pass
@abc.abstractmethod
def get_audits(self):
pass
@abc.abstractmethod
def get_repairs(self):
pass
@abc.abstractmethod
def audit_cfg_from_name(self, name):
pass
@abc.abstractmethod
def repair_cfg_from_name(self, name):
pass
@abc.abstractmethod
def get_script_cfg(self, script_type):
pass
@abc.abstractmethod
def check_script_exists(self, script_type, script_name):
pass
@abc.abstractmethod
def add_script(self, script_type, data):
pass
|
3136b2525ad0716c6b6f7fa60f78f5f6d776ee55
|
linter.py
|
linter.py
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
Remove vue from selectors and just use embedded html
|
Remove vue from selectors and just use embedded html
|
Python
|
mit
|
jackbrewer/SublimeLinter-contrib-stylint
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
Remove vue from selectors and just use embedded html
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
<commit_msg>Remove vue from selectors and just use embedded html<commit_after>
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
Remove vue from selectors and just use embedded html#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
<commit_before>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, text.html.vue, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
<commit_msg>Remove vue from selectors and just use embedded html<commit_after>#
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jack Brewer
# Copyright (c) 2015 Jack Brewer
#
# License: MIT
"""Exports the Stylint plugin class."""
from SublimeLinter.lint import NodeLinter, util
class Stylint(NodeLinter):
"""Provides an interface to stylint."""
cmd = 'stylint @ *'
defaults = {
'selector': 'source.stylus, source.stylus.embedded.html',
'--ignore=,': '',
'--warn=,': '',
'--error=,': ''
}
regex = r'''(?xi)
# Comments show example output for each line of a Stylint warning
# /path/to/file/example.styl
^.*$\s*
# 177:24 colors warning hexidecimal color should be a variable
# 177:24 warning hexidecimal color should be a variable colors
# 177 warning hexidecimal color should be a variable colors
^(?P<line>\d+):?(?P<col>\d+)?\s*(?P<rule>\w+)?\s*((?P<warning>warning)|(?P<error>error))\s*(?P<message>.+)$\s*
'''
multiline = True
error_stream = util.STREAM_STDOUT
tempfile_suffix = 'styl'
config_file = ('--config', '.stylintrc', '~')
|
0c71164f6c9a2229b8e99eb2dd38981407d8dfe7
|
measurement/migrations/0003_auto_20141013_1137.py
|
measurement/migrations/0003_auto_20141013_1137.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.IntegerField(choices=[(1, b'Activity'), (2, b'O2'), (3, b'Pulse'), (4, b'Temperature')]),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.CharField(max_length=1, choices=[(b'A', b'Activity'), (b'O', b'O2'), (b'P', b'Pulse'), (b'T', b'Temperature')]),
),
]
|
Patch a migration to work with postgres
|
Patch a migration to work with postgres
|
Python
|
mit
|
sigurdsa/angelika-api
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.IntegerField(choices=[(1, b'Activity'), (2, b'O2'), (3, b'Pulse'), (4, b'Temperature')]),
),
]
Patch a migration to work with postgres
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.CharField(max_length=1, choices=[(b'A', b'Activity'), (b'O', b'O2'), (b'P', b'Pulse'), (b'T', b'Temperature')]),
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.IntegerField(choices=[(1, b'Activity'), (2, b'O2'), (3, b'Pulse'), (4, b'Temperature')]),
),
]
<commit_msg>Patch a migration to work with postgres<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.CharField(max_length=1, choices=[(b'A', b'Activity'), (b'O', b'O2'), (b'P', b'Pulse'), (b'T', b'Temperature')]),
),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.IntegerField(choices=[(1, b'Activity'), (2, b'O2'), (3, b'Pulse'), (4, b'Temperature')]),
),
]
Patch a migration to work with postgres# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.CharField(max_length=1, choices=[(b'A', b'Activity'), (b'O', b'O2'), (b'P', b'Pulse'), (b'T', b'Temperature')]),
),
]
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.IntegerField(choices=[(1, b'Activity'), (2, b'O2'), (3, b'Pulse'), (4, b'Temperature')]),
),
]
<commit_msg>Patch a migration to work with postgres<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('measurement', '0002_auto_20141008_1605'),
]
operations = [
migrations.AlterField(
model_name='measurement',
name='type',
field=models.CharField(max_length=1, choices=[(b'A', b'Activity'), (b'O', b'O2'), (b'P', b'Pulse'), (b'T', b'Temperature')]),
),
]
|
6e0d583e0c3eea7ca9e7a37567cfc7535d8f406b
|
django_prices_openexchangerates/tasks.py
|
django_prices_openexchangerates/tasks.py
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
Make rates parsing more readable
|
Make rates parsing more readable
|
Python
|
bsd-3-clause
|
artursmet/django-prices-openexchangerates,mirumee/django-prices-openexchangerates
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
Make rates parsing more readable
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
<commit_before>from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
<commit_msg>Make rates parsing more readable<commit_after>
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
Make rates parsing more readablefrom __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
<commit_before>from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
class ExchangeRates(object):
def __init__(self, rates, default_currency=None):
self.rates = rates
self.default_currency = (
default_currency or settings.DEFAULT_CURRENCY)
def __getitem__(self, item):
rate = self.rates[item]
return rate / self.rates[self.default_currency]
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
exchange_data = response.json(parse_int=Decimal, parse_float=Decimal)
return ExchangeRates(rates=exchange_data['rates'])
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = exchange_rates[conversion_rate.to_currency]
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
<commit_msg>Make rates parsing more readable<commit_after>from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import requests
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from .models import ConversionRate
BASE_URL = r'http://openexchangerates.org/api'
ENDPOINT_LATEST = BASE_URL + r'/latest.json'
try:
API_KEY = settings.OPENEXCHANGERATES_API_KEY
except AttributeError:
raise ImproperlyConfigured('OPENEXCHANGERATES_API_KEY is required')
def extract_rate(rates, currency):
base_rate = rates[settings.DEFAULT_CURRENCY]
return rates[currency] / base_rate
def get_latest_exchange_rates():
response = requests.get(ENDPOINT_LATEST, params={'app_id': API_KEY})
response.raise_for_status()
return response.json(parse_int=Decimal, parse_float=Decimal)
def update_conversion_rates():
exchange_rates = get_latest_exchange_rates()
conversion_rates = ConversionRate.objects.all()
for conversion_rate in conversion_rates:
new_exchange_rate = extract_rate(exchange_rates,
conversion_rate.to_currency)
conversion_rate.rate = new_exchange_rate
conversion_rate.save(update_fields=['rate'])
return conversion_rates
|
60087afcf8f0130fb9cd6e154a9fb7290c0fde2e
|
tools/test.py
|
tools/test.py
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
Add third_party/android_tools/sdk/platform-tools to PATH if available
|
Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .
|
Python
|
bsd-3-clause
|
dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
<commit_msg>Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .<commit_after>
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
<commit_before>#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
<commit_msg>Add third_party/android_tools/sdk/platform-tools to PATH if available
R=whesse@google.com
Review URL: https://codereview.chromium.org/1938973002 .<commit_after>#!/usr/bin/env python
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
import os
import string
import subprocess
import sys
import utils
def Main():
args = sys.argv[1:]
tools_dir = os.path.dirname(os.path.realpath(__file__))
dart_script_name = 'test.dart'
dart_test_script = string.join([tools_dir, dart_script_name], os.sep)
command = [utils.CheckedInSdkExecutable(),
'--checked', dart_test_script] + args
# The testing script potentially needs the android platform tools in PATH so
# we do that in ./tools/test.py (a similar logic exists in ./tools/build.py).
android_platform_tools = os.path.normpath(os.path.join(
tools_dir,
'../third_party/android_tools/sdk/platform-tools'))
if os.path.isdir(android_platform_tools):
os.environ['PATH'] = '%s%s%s' % (
os.environ['PATH'], os.pathsep, android_platform_tools)
exit_code = subprocess.call(command)
utils.DiagnoseExitCode(exit_code, command)
return exit_code
if __name__ == '__main__':
sys.exit(Main())
|
6687d8bbfbda55110145d5398a07672e71735f7b
|
ecal_users.py
|
ecal_users.py
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
Use 8 characters for email address rather than 10.
|
Use 8 characters for email address rather than 10.
|
Python
|
mit
|
eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot,eentzel/myeventbot
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
Use 8 characters for email address rather than 10.
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
<commit_before>from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
<commit_msg>Use 8 characters for email address rather than 10.<commit_after>
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
Use 8 characters for email address rather than 10.from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
<commit_before>from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 10 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 10 = 3.62033331 x 10 ** 17
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(10) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
<commit_msg>Use 8 characters for email address rather than 10.<commit_after>from google.appengine.ext import db
import random
import string
def make_address():
"""
Returns a random alphanumeric string of 8 digits. Since there
are 57 choices per digit (we exclude '0', 'O', 'l', 'I' and '1'
for readability), this gives:
57 ** 8 = 1.11429157 x 10 ** 14
possible results. When there are a million accounts active,
we need:
10 ** 6 x 10 ** 6 = 10 ** 12
possible results to have a one-in-a-million chance of a
collision, so this seems like a safe number.
"""
chars = string.letters + string.digits
chars = chars.translate(string.maketrans('', ''), '0OlI1')
return ''.join([ random.choice(chars) for i in range(8) ])
class EmailUser(db.Model):
# the email address that the user sends events to:
email_address = db.StringProperty(default=make_address())
# the AuthSub token used to authenticate the user to gcal:
auth_token = db.StringProperty()
date_added = db.DateTimeProperty(auto_now_add=True)
last_action = db.DateTimeProperty(auto_now_add=True)
|
e466da4f26d8cbac45476e8c00e009e004cd4baa
|
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
|
fluent_blogs/templatetags/fluent_blogs_comments_tags.py
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
from django.contrib.comments.templatetags.comments import register
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
Support django-contrib-comments instead of django.contrib.comments for Django 1.8
|
Support django-contrib-comments instead of django.contrib.comments for Django 1.8
|
Python
|
apache-2.0
|
edoburu/django-fluent-blogs,edoburu/django-fluent-blogs
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
from django.contrib.comments.templatetags.comments import register
Support django-contrib-comments instead of django.contrib.comments for Django 1.8
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
<commit_before>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
from django.contrib.comments.templatetags.comments import register
<commit_msg>Support django-contrib-comments instead of django.contrib.comments for Django 1.8<commit_after>
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
from django.contrib.comments.templatetags.comments import register
Support django-contrib-comments instead of django.contrib.comments for Django 1.8"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
<commit_before>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
from django.contrib.comments.templatetags.comments import register
<commit_msg>Support django-contrib-comments instead of django.contrib.comments for Django 1.8<commit_after>"""
A simple wrapper library, that makes sure that the template
``fluent_blogs/entry_detail/comments.html`` can still be rendered
when ``django.contrib.comments`` is not included in the site.
This way, project authors can easily use an online commenting system
(such as DISQUS or Facebook comments) instead.
"""
from django.template import Library
from fluent_utils.django_compat import is_installed
# Expose the tag library in the site.
# If `django.contrib.comments` is not used, this library can provide stubs instead.
# Currently, the real tags are exposed as the template already checks for `object.comments_are_open`.
# When a custom template is used, authors likely choose the desired commenting library instead.
if is_installed('django.contrib.comments'):
from django.contrib.comments.templatetags.comments import register
elif is_installed('django_comments'):
from django_comments.templatetags.comments import register
else:
register = Library()
|
ecb1550f2cd02568e81b92ca360c0783df0e5bd7
|
zbzapp/extras/ocr/vars.py
|
zbzapp/extras/ocr/vars.py
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
Support currently removed for gifs because of bugs
|
Support currently removed for gifs because of bugs
|
Python
|
apache-2.0
|
bhavyanshu/zBzQuiz,bhavyanshu/zBzQuiz,bhavyanshu/zBzQuiz
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
Support currently removed for gifs because of bugs
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
<commit_before>#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
<commit_msg>Support currently removed for gifs because of bugs<commit_after>
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
Support currently removed for gifs because of bugs#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
<commit_before>#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", ["*.jpg", "*.jpeg", "*.gif"] ])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
<commit_msg>Support currently removed for gifs because of bugs<commit_after>#!/usr/bin/env python
'''
Author : Bhavyanshu Parasher
Email : bhavyanshu@codershangout.org
Description : This file contains all the main functions for the GUI.
'''
try:
from easygui import *
except ImportError:
raise ImportError,"The easygui module is required to run this program"
import sys
try:
import Image
from tesseract import image_to_string
except ImportError:
raise ImportError,"The Tesseract module is required to run this program"
def AskForFile():
fname = fileopenbox(msg='Filename: ', title='Please select the scanned document', default='*', filetypes= ["*.png", "*.jpg", "*.jpeg"])
content=image_to_string(Image.open(fname))
choices=['Copy to Clipboard','Wrong output? Try again!']
textbox(msg='The following text was extracted from the image', title='Text', text=content, codebox=0)
def help(): # create a function called Dump
msgbox("Author : Bhavyanshu Parasher (bhavyanshu@codershangout.org)","Help!")
def Post(): # create a function called Post
f = open(fname, "a"); # open the file defined in Ask.
message = enterbox(msg='Enter Message: ', title='Post', default=''); # Define message as the result of another enterbox.
f.write("\n"); # write a newline to the file.
f.write(message) # write your message to the file.
def Die(): # Define the function Die.
sys.exit() # Quit The Program.
|
ae3d8fd826647c8d853247b069726a26f4ae462d
|
exterminal.py
|
exterminal.py
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
Fix dangling default in kwargs 'shell_cmd'
|
Fix dangling default in kwargs 'shell_cmd'
|
Python
|
mit
|
jemc/SublimeExterminal,jemc/SublimeExterminal
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
Fix dangling default in kwargs 'shell_cmd'
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
<commit_before>import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
<commit_msg>Fix dangling default in kwargs 'shell_cmd'<commit_after>
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
Fix dangling default in kwargs 'shell_cmd'import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
<commit_before>import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd', '')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
<commit_msg>Fix dangling default in kwargs 'shell_cmd'<commit_after>import sublime, sublime_plugin
import os
def wrapped_exec(self, *args, **kwargs):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
if settings.get('enabled') and kwargs.get('use_exterminal', True):
wrapper = settings.get('exec_wrapper')
try:
shell_cmd = kwargs.get('shell_cmd')
shell_cmd = wrapper % shell_cmd.replace('"','\\"')
kwargs['shell_cmd'] = shell_cmd
except KeyError: pass
try:
cmd = ' '.join(kwargs.get('cmd'))
kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"')
except KeyError: pass
return self.run_cached_by_exterminal(*args, **kwargs)
def plugin_loaded():
exec_cls = [cls for cls in sublime_plugin.window_command_classes \
if cls.__qualname__=='ExecCommand'][0]
if hasattr(exec_cls(None), 'run_cached_by_exterminal'):
exec_cls.run = exec_cls.run_cached_by_exterminal
exec_cls.run_cached_by_exterminal = None
exec_cls.run_cached_by_exterminal = exec_cls.run
exec_cls.run = wrapped_exec
class StartExterminalCommand(sublime_plugin.WindowCommand):
def run(self, *args):
settings = sublime.load_settings("SublimeExterminal.sublime-settings")
cmd = settings.get('start_exterminal', '')
os.popen(cmd)
|
beb9528c4a1a8cba1b432c285135b7d1d18453dc
|
heltour/tournament/templatetags/tournament_extras.py
|
heltour/tournament/templatetags/tournament_extras.py
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
# If other_score is specified, assume the match may be incomplete and only display results that are clinched
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
Add comment to resultclass tag
|
Add comment to resultclass tag
|
Python
|
mit
|
cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
Add comment to resultclass tag
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
# If other_score is specified, assume the match may be incomplete and only display results that are clinched
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
<commit_before>from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
<commit_msg>Add comment to resultclass tag<commit_after>
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
# If other_score is specified, assume the match may be incomplete and only display results that are clinched
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
Add comment to resultclass tagfrom django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
# If other_score is specified, assume the match may be incomplete and only display results that are clinched
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
<commit_before>from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
<commit_msg>Add comment to resultclass tag<commit_after>from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.simple_tag
def leagueurl(name, league_tag=None, season_id=None, *args, **kwargs):
if season_id is not None and season_id != '':
name = "by_season:" + name
args = [season_id] + list(args)
if league_tag is not None and league_tag != '':
name = "by_league:" + name
args = [league_tag] + list(args)
return reverse(name, args=args, kwargs=kwargs)
@register.simple_tag
def resultclass(tie_score, my_score, other_score=None):
# If other_score is specified, assume the match may be incomplete and only display results that are clinched
if my_score is None:
return ''
elif my_score > tie_score:
return 'cell-win'
elif other_score is None and my_score < tie_score or other_score is not None and other_score > tie_score:
return 'cell-loss'
elif my_score == tie_score and (other_score is None or other_score == tie_score):
return 'cell-tie'
return ''
@register.filter
def format_result(result):
if result is None:
return ''
if result == '1/2-1/2':
return u'\u00BD-\u00BD'
return result
|
8748854969f8cab9f416a05b4565734b2632df77
|
statscache_plugins/releng/plugins/cloud_images_upload_base.py
|
statscache_plugins/releng/plugins/cloud_images_upload_base.py
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] == \
'org.fedoraproject.prod.fedimg.image.upload' and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod.fedimg.image.upload'
]
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] in self.topics and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
Move fedmsg topics listened to by a plugin to a class variable.
|
Move fedmsg topics listened to by a plugin to a class variable.
|
Python
|
lgpl-2.1
|
yazman/statscache_plugins
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] == \
'org.fedoraproject.prod.fedimg.image.upload' and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
Move fedmsg topics listened to by a plugin to a class variable.
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod.fedimg.image.upload'
]
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] in self.topics and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
<commit_before>import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] == \
'org.fedoraproject.prod.fedimg.image.upload' and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
<commit_msg>Move fedmsg topics listened to by a plugin to a class variable.<commit_after>
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod.fedimg.image.upload'
]
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] in self.topics and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] == \
'org.fedoraproject.prod.fedimg.image.upload' and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
Move fedmsg topics listened to by a plugin to a class variable.import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod.fedimg.image.upload'
]
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] in self.topics and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
<commit_before>import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] == \
'org.fedoraproject.prod.fedimg.image.upload' and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
<commit_msg>Move fedmsg topics listened to by a plugin to a class variable.<commit_after>import statscache.plugins
class Plugin(statscache.plugins.BasePlugin):
name = "releng, cloud images upload base"
summary = "Build logs for successful upload of cloud images"
description = """
Latest build logs for successful upload of cloud images
"""
topics = [
'org.fedoraproject.prod.fedimg.image.upload'
]
def handle(self, session, timestamp, messages):
rows = []
for message in messages:
if not (message['topic'] in self.topics and
message['msg'].get('status') == 'completed'):
continue
rows.append(
self.model(
timestamp=message['timestamp'],
message=json.dumps({
'name': message['msg']['image_name'],
'ami_name': '{name}, {region}'.format(
name=message['msg']['extra']['id'],
region=message['msg']['destination']),
'ami_link': (
"https://redirect.fedoraproject.org/console.aws."
"amazon.com/ec2/v2/home?region={region}"
"#LaunchInstanceWizard:ami={name}".format(
name=message['msg']['extra']['id'],
region=message['msg']['destination'])
)
}),
category='cloud_images_upload_base'
)
)
return rows
|
ec13c2591a18386f08ade69874a77ce8f561e8a1
|
application.py
|
application.py
|
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
|
import os
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8002))
debug = bool(os.environ.get('DEBUG', False))
application.run(host, port=port, debug=debug)
|
Read in some environment variables
|
Read in some environment variables
|
Python
|
mit
|
suminb/transporter,suminb/transporter
|
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
Read in some environment variables
|
import os
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8002))
debug = bool(os.environ.get('DEBUG', False))
application.run(host, port=port, debug=debug)
|
<commit_before>from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
<commit_msg>Read in some environment variables<commit_after>
|
import os
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8002))
debug = bool(os.environ.get('DEBUG', False))
application.run(host, port=port, debug=debug)
|
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
Read in some environment variablesimport os
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8002))
debug = bool(os.environ.get('DEBUG', False))
application.run(host, port=port, debug=debug)
|
<commit_before>from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
application.run(host='0.0.0.0', debug=True)
<commit_msg>Read in some environment variables<commit_after>import os
from transporter import create_app
application = create_app(__name__)
if __name__ == '__main__':
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 8002))
debug = bool(os.environ.get('DEBUG', False))
application.run(host, port=port, debug=debug)
|
6b603840b8abd0b63e13c8ccbffa40e8abc453b5
|
movies.py
|
movies.py
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', header=None, names=rnames, engine='python')
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::', header=None, names=rnames, engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table(directory + 'movies.dat', sep='::', header=None, names=mnames, engine='python')
print users[:5]
print ratings[:5]
print movies[:5]
|
Read and print all data files.
|
Read and print all data files.
|
Python
|
mit
|
m1key/data-science-sandbox
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', header=None, names=rnames, engine='python')
Read and print all data files.
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::', header=None, names=rnames, engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table(directory + 'movies.dat', sep='::', header=None, names=mnames, engine='python')
print users[:5]
print ratings[:5]
print movies[:5]
|
<commit_before>import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', header=None, names=rnames, engine='python')
<commit_msg>Read and print all data files.<commit_after>
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::', header=None, names=rnames, engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table(directory + 'movies.dat', sep='::', header=None, names=mnames, engine='python')
print users[:5]
print ratings[:5]
print movies[:5]
|
import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', header=None, names=rnames, engine='python')
Read and print all data files.import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::', header=None, names=rnames, engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table(directory + 'movies.dat', sep='::', header=None, names=mnames, engine='python')
print users[:5]
print ratings[:5]
print movies[:5]
|
<commit_before>import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'users.dat', sep='::', header=None, names=rnames, engine='python')
<commit_msg>Read and print all data files.<commit_after>import pandas as pd
directory = 'ml-1m/'
unames = ['user_id', 'gender', 'age', 'occupation', 'zip']
users = pd.read_table(directory + 'users.dat', sep='::', header=None, names=unames, engine='python')
rnames = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_table(directory + 'ratings.dat', sep='::', header=None, names=rnames, engine='python')
mnames = ['movie_id', 'title', 'genres']
movies = pd.read_table(directory + 'movies.dat', sep='::', header=None, names=mnames, engine='python')
print users[:5]
print ratings[:5]
print movies[:5]
|
4c2d33c50108aa1e2f5b8d12f6e45184d496fea2
|
apel/db/__init__.py
|
apel/db/__init__.py
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
Update cloud summary message header version num
|
Update cloud summary message header version num
|
Python
|
apache-2.0
|
stfc/apel,apel/apel,apel/apel,tofu-rocketry/apel,stfc/apel,tofu-rocketry/apel
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2'
from apel.db.apeldb import ApelDb, Query, ApelDbException
Update cloud summary message header version num
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
<commit_before>'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2'
from apel.db.apeldb import ApelDb, Query, ApelDbException
<commit_msg>Update cloud summary message header version num<commit_after>
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2'
from apel.db.apeldb import ApelDb, Query, ApelDbException
Update cloud summary message header version num'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
<commit_before>'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.2'
from apel.db.apeldb import ApelDb, Query, ApelDbException
<commit_msg>Update cloud summary message header version num<commit_after>'''
Copyright 2011 Will Rogers
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.
'''
LOGGER_ID = "apeldb"
JOB_MSG_HEADER = "APEL-individual-job-message: v0.3"
SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.2"
NORMALISED_SUMMARY_MSG_HEADER = "APEL-summary-job-message: v0.3"
SYNC_MSG_HEADER = "APEL-sync-message: v0.1"
CLOUD_MSG_HEADER = 'APEL-cloud-message: v0.4'
CLOUD_SUMMARY_MSG_HEADER = 'APEL-cloud-summary-message: v0.4'
from apel.db.apeldb import ApelDb, Query, ApelDbException
|
f3c04e95bc40d5a85fe2f560df68315384ef763e
|
picoCTF-web/daemons/cache_stats.py
|
picoCTF-web/daemons/cache_stats.py
|
#!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(api.stats.get_registration_count)
print("Caching the public scoreboard entries...")
cache(api.stats.get_all_team_scores)
cache(api.stats.get_all_team_scores, include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(api.stats.get_top_teams_score_progressions)
cache(api.stats.get_top_teams_score_progressions,
include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
# cache(
# api.stats.get_top_teams_score_progressions,
# gid=group['gid'])
cache(
api.stats.get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
cache(api.stats.get_group_scores, gid=group['gid'])
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(api.stats.get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
#!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(get_registration_count)
print("Caching the public scoreboard entries...")
get_all_team_scores()
get_all_team_scores(include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(get_top_teams_score_progressions)
cache(get_top_teams_score_progressions, include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
get_group_scores(gid=group['gid'])
cache(get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
Update stats daemon to update ZSets and memoization as necessary
|
Update stats daemon to update ZSets and memoization as necessary
|
Python
|
mit
|
royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF
|
#!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(api.stats.get_registration_count)
print("Caching the public scoreboard entries...")
cache(api.stats.get_all_team_scores)
cache(api.stats.get_all_team_scores, include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(api.stats.get_top_teams_score_progressions)
cache(api.stats.get_top_teams_score_progressions,
include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
# cache(
# api.stats.get_top_teams_score_progressions,
# gid=group['gid'])
cache(
api.stats.get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
cache(api.stats.get_group_scores, gid=group['gid'])
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(api.stats.get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
Update stats daemon to update ZSets and memoization as necessary
|
#!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(get_registration_count)
print("Caching the public scoreboard entries...")
get_all_team_scores()
get_all_team_scores(include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(get_top_teams_score_progressions)
cache(get_top_teams_score_progressions, include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
get_group_scores(gid=group['gid'])
cache(get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
<commit_before>#!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(api.stats.get_registration_count)
print("Caching the public scoreboard entries...")
cache(api.stats.get_all_team_scores)
cache(api.stats.get_all_team_scores, include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(api.stats.get_top_teams_score_progressions)
cache(api.stats.get_top_teams_score_progressions,
include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
# cache(
# api.stats.get_top_teams_score_progressions,
# gid=group['gid'])
cache(
api.stats.get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
cache(api.stats.get_group_scores, gid=group['gid'])
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(api.stats.get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
<commit_msg>Update stats daemon to update ZSets and memoization as necessary<commit_after>
|
#!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(get_registration_count)
print("Caching the public scoreboard entries...")
get_all_team_scores()
get_all_team_scores(include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(get_top_teams_score_progressions)
cache(get_top_teams_score_progressions, include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
get_group_scores(gid=group['gid'])
cache(get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
#!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(api.stats.get_registration_count)
print("Caching the public scoreboard entries...")
cache(api.stats.get_all_team_scores)
cache(api.stats.get_all_team_scores, include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(api.stats.get_top_teams_score_progressions)
cache(api.stats.get_top_teams_score_progressions,
include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
# cache(
# api.stats.get_top_teams_score_progressions,
# gid=group['gid'])
cache(
api.stats.get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
cache(api.stats.get_group_scores, gid=group['gid'])
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(api.stats.get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
Update stats daemon to update ZSets and memoization as necessary#!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(get_registration_count)
print("Caching the public scoreboard entries...")
get_all_team_scores()
get_all_team_scores(include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(get_top_teams_score_progressions)
cache(get_top_teams_score_progressions, include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
get_group_scores(gid=group['gid'])
cache(get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
<commit_before>#!/usr/bin/env python3
import api
import api.group
import api.stats
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(api.stats.get_registration_count)
print("Caching the public scoreboard entries...")
cache(api.stats.get_all_team_scores)
cache(api.stats.get_all_team_scores, include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(api.stats.get_top_teams_score_progressions)
cache(api.stats.get_top_teams_score_progressions,
include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
# cache(
# api.stats.get_top_teams_score_progressions,
# gid=group['gid'])
cache(
api.stats.get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
cache(api.stats.get_group_scores, gid=group['gid'])
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(api.stats.get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
<commit_msg>Update stats daemon to update ZSets and memoization as necessary<commit_after>#!/usr/bin/env python3
import api
import api.group
from api.stats import (get_all_team_scores, get_group_scores,
get_problem_solves, get_registration_count,
get_top_teams_score_progressions)
def run():
"""Run the stat caching daemon."""
with api.create_app().app_context():
def cache(f, *args, **kwargs):
result = f(reset_cache=True, *args, **kwargs)
return result
print("Caching registration stats.")
cache(get_registration_count)
print("Caching the public scoreboard entries...")
get_all_team_scores()
get_all_team_scores(include_ineligible=True)
print("Caching the public scoreboard graph...")
cache(get_top_teams_score_progressions)
cache(get_top_teams_score_progressions, include_ineligible=True)
print("Caching the scoreboard graph for each group...")
for group in api.group.get_all_groups():
get_group_scores(gid=group['gid'])
cache(get_top_teams_score_progressions,
gid=group['gid'],
include_ineligible=True)
print("Caching number of solves for each problem.")
for problem in api.problem.get_all_problems():
print(problem["name"],
cache(get_problem_solves, problem["pid"]))
if __name__ == '__main__':
run()
|
9406ed1d55151bb47760947c54c2bd29fcc1d3a3
|
knowledge_repo/converters/md.py
|
knowledge_repo/converters/md.py
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
Fix a lint required empty lines issue
|
Fix a lint required empty lines issue
|
Python
|
apache-2.0
|
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
Fix a lint required empty lines issue
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
<commit_before>from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
<commit_msg>Fix a lint required empty lines issue<commit_after>
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
Fix a lint required empty lines issuefrom ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
<commit_before>from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
<commit_msg>Fix a lint required empty lines issue<commit_after>from ..constants import MD
from ..converter import KnowledgePostConverter
from knowledge_repo.utils.files import read_text
class MdConverter(KnowledgePostConverter):
_registry_keys = [MD]
def from_file(self, filename):
self.kp_write(read_text(filename))
|
07cc3a2af6feb62a9ac07704d4468e875286f664
|
ibmcnx/doc/DataSources.py
|
ibmcnx/doc/DataSources.py
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
Create documentation of DataSource Settings
|
: Create documentation of DataSource Settings
Task-Url:
|
Python
|
apache-2.0
|
stoeps13/ibmcnx2,stoeps13/ibmcnx2
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ): Create documentation of DataSource Settings
Task-Url:
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )<commit_msg>: Create documentation of DataSource Settings
Task-Url: <commit_after>
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ): Create documentation of DataSource Settings
Task-Url: ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "'/Cell:" + AdminControl.getCell() + "/'"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )<commit_msg>: Create documentation of DataSource Settings
Task-Url: <commit_after>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
print AdminControl.getCell()
cell = "/Cell:" + AdminControl.getCell() + "/"
cellid = AdminConfig.getid( cell )
dbs = AdminConfig.list( 'DataSource', str(cellid) )
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 )
|
981b5f27bc819056a9bc888c29f21b4fd9a0bded
|
server/app.py
|
server/app.py
|
#!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App()
app.run(args.testname, args.database)
|
#!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(testname, database)
def run(self):
self.server.run()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App(args.testname, args.database)
app.run()
|
Add command line args to App
|
Add command line args to App
|
Python
|
mit
|
CaminsTECH/owncloud-test
|
#!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App()
app.run(args.testname, args.database)
Add command line args to App
|
#!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(testname, database)
def run(self):
self.server.run()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App(args.testname, args.database)
app.run()
|
<commit_before>#!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App()
app.run(args.testname, args.database)
<commit_msg>Add command line args to App<commit_after>
|
#!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(testname, database)
def run(self):
self.server.run()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App(args.testname, args.database)
app.run()
|
#!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App()
app.run(args.testname, args.database)
Add command line args to App#!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(testname, database)
def run(self):
self.server.run()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App(args.testname, args.database)
app.run()
|
<commit_before>#!/usr/bin/env python3
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
class App:
def run(self, testname, database):
server = ServerLoader.load(testname)
server.run(DatabaseSQLite(args.database))
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App()
app.run(args.testname, args.database)
<commit_msg>Add command line args to App<commit_after>#!/usr/bin/env python3
import argparse
import logging
from command import Command
from database import DatabaseSQLite
from client import Client
from server import Server
from serverLoader import ServerLoader
class App:
server = None
def __init__(self, testname, database):
self.server = ServerLoader().load(testname, database)
def run(self):
self.server.run()
def parseCommandLine():
parser = argparse.ArgumentParser()
parser.add_argument('--testname', required=True)
parser.add_argument('--database', required=True)
parser.add_argument('--loglevel', default='INFO')
parser.add_argument('--logfile', default=__name__ + '.log')
return parser.parse_args()
def configLogging(args):
level = getattr(logging, args.loglevel.upper(), None)
if not isinstance(level, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
format = '%(asctime)-15s %(message)s'
logging.basicConfig(format=format, filename=args.logfile, level=level)
if __name__ == '__main__':
args = parseCommandLine()
configLogging(args)
app = App(args.testname, args.database)
app.run()
|
15519437a0197582c4b321b9e55544320a759c28
|
src/lib/sd2/workspace.py
|
src/lib/sd2/workspace.py
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
hosts = [x for x in hosts if myhosts.is_enabled(x['name'])]
for host in hosts:
assert 'name' in host
return hosts
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
rr = [x for x in hosts if myhosts.is_enabled(x['name'])]
rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])])
for host in hosts:
assert 'name' in host
return hosts
|
Add containers in hosts so we can rsync into containers
|
Add containers in hosts so we can rsync into containers
|
Python
|
apache-2.0
|
gae123/sd2,gae123/sd2
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
hosts = [x for x in hosts if myhosts.is_enabled(x['name'])]
for host in hosts:
assert 'name' in host
return hosts
Add containers in hosts so we can rsync into containers
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
rr = [x for x in hosts if myhosts.is_enabled(x['name'])]
rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])])
for host in hosts:
assert 'name' in host
return hosts
|
<commit_before>#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
hosts = [x for x in hosts if myhosts.is_enabled(x['name'])]
for host in hosts:
assert 'name' in host
return hosts
<commit_msg>Add containers in hosts so we can rsync into containers<commit_after>
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
rr = [x for x in hosts if myhosts.is_enabled(x['name'])]
rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])])
for host in hosts:
assert 'name' in host
return hosts
|
#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
hosts = [x for x in hosts if myhosts.is_enabled(x['name'])]
for host in hosts:
assert 'name' in host
return hosts
Add containers in hosts so we can rsync into containers#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
rr = [x for x in hosts if myhosts.is_enabled(x['name'])]
rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])])
for host in hosts:
assert 'name' in host
return hosts
|
<commit_before>#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
hosts = [x for x in hosts if myhosts.is_enabled(x['name'])]
for host in hosts:
assert 'name' in host
return hosts
<commit_msg>Add containers in hosts so we can rsync into containers<commit_after>#!/usr/bin/env python
#############################################################################
# Copyright (c) 2017 SiteWare Corp. All right reserved
#############################################################################
from . import myhosts
class Workspace(object):
def __init__(self, node):
self._node = node
def get_targets(self):
hosts = self._node.get('targets', [])
rr = [x for x in hosts if myhosts.is_enabled(x['name'])]
rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])])
for host in hosts:
assert 'name' in host
return hosts
|
accca78e7d9dab841d4850f74795099d63854707
|
masters/master.client.v8.ports/master_site_config.py
|
masters/master.client.v8.ports/master_site_config.py
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
service_account_file = 'service-account-v8.json'
|
Add buildbucket integration to v8.ports
|
V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
service_account_file = 'service-account-v8.json'
|
<commit_before># Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
<commit_msg>V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98<commit_after>
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
service_account_file = 'service-account-v8.json'
|
# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98# Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
service_account_file = 'service-account-v8.json'
|
<commit_before># Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
<commit_msg>V8: Add buildbucket integration to v8.ports
BUG=595708
TBR=tandrii@chromium.org, kjellander@chromium.org
Review URL: https://codereview.chromium.org/1810113002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@299357 0039d316-1c4b-4281-b951-d872f2087c98<commit_after># Copyright 2016 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class V8Ports(Master.Master3):
base_app_url = 'https://v8-status.appspot.com'
tree_status_url = base_app_url + '/status'
store_revisions_url = base_app_url + '/revisions'
last_good_url = base_app_url + '/lkgr'
project_name = 'V8 Ports'
master_port_id = 17
project_url = 'https://developers.google.com/v8/'
buildbot_url = 'http://build.chromium.org/p/client.v8.ports/'
service_account_file = 'service-account-v8.json'
|
cd16b97f9e004d4b04fa06789a90fd560a1888be
|
libcrowds_data/view.py
|
libcrowds_data/view.py
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/data/index.html', projects=projects)
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/index.html', projects=projects)
|
Fix route for index page
|
Fix route for index page
|
Python
|
bsd-3-clause
|
LibCrowds/libcrowds-data,LibCrowds/libcrowds-data
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/data/index.html', projects=projects)
Fix route for index page
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/index.html', projects=projects)
|
<commit_before># -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/data/index.html', projects=projects)
<commit_msg>Fix route for index page<commit_after>
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/index.html', projects=projects)
|
# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/data/index.html', projects=projects)
Fix route for index page# -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/index.html', projects=projects)
|
<commit_before># -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/data/index.html', projects=projects)
<commit_msg>Fix route for index page<commit_after># -*- coding: utf8 -*-
"""Views modules for libcrowds-data."""
from flask import render_template
from pybossa.core import project_repo
@blueprint.route('/')
def index():
"""Return the Data page."""
projects = project_repo.get_all()
title = "Data"
description = """Download open datasets of all crowdsourced data produced
via LibCrowds."""
return render_template('/index.html', projects=projects)
|
85220f2830d355245803965ee57886e5c1268833
|
tests/unit/test_twitter.py
|
tests/unit/test_twitter.py
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
Update Twitter test to be more robust
|
Update Twitter test to be more robust
|
Python
|
apache-2.0
|
obsidianforensics/unfurl,obsidianforensics/unfurl
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()Update Twitter test to be more robust
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
<commit_before>from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()<commit_msg>Update Twitter test to be more robust<commit_after>
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()Update Twitter test to be more robustfrom unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
<commit_before>from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a tyipcal and a unique Discord url """
# unit test for a unique Discord url.
test = Unfurl()
test.add_to_queue(data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# test number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# is processing finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()<commit_msg>Update Twitter test to be more robust<commit_after>from unfurl import Unfurl
import unittest
class TestTwitter(unittest.TestCase):
def test_twitter(self):
""" Test a typical and a unique Twitter url """
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://twitter.com/_RyanBenson/status/1098230906194546688')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm that snowflake was detected
self.assertIn('Twitter Snowflakes', test.nodes[9].hover)
# embedded timestamp parses correctly
self.assertEqual('2019-02-20 14:40:26.837', test.nodes[13].value)
# make sure the queue finished empty
self.assertTrue(test.queue.empty())
self.assertEqual(len(test.edges), 0)
if __name__ == '__main__':
unittest.main()
|
db6d354d3fd877ef41cffc1fe909c8e89d5f9e79
|
invoke/parser/__init__.py
|
invoke/parser/__init__.py
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
for index, arg in enumerate(argv):
if context.has_arg(arg):
flag_index = index
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
return self.contexts
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
from ..util import debug
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
debug("Parsing argv %r" % (argv,))
debug("Starting with context %s" % context)
for index, arg in enumerate(argv):
debug("Testing string arg %r at index %r" % (arg, index))
if context.has_arg(arg):
flag_index = index
debug("Current context has this as a flag")
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
debug("Current context does not have this as a flag")
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
debug("That pevious flag needs no value")
return self.contexts
|
Make debug logging even more convenient.
|
Make debug logging even more convenient.
I'm sure we'll remove the globals() usage eventually.
|
Python
|
bsd-2-clause
|
pyinvoke/invoke,frol/invoke,mkusz/invoke,pfmoore/invoke,mattrobenolt/invoke,mattrobenolt/invoke,kejbaly2/invoke,kejbaly2/invoke,tyewang/invoke,mkusz/invoke,sophacles/invoke,singingwolfboy/invoke,pyinvoke/invoke,pfmoore/invoke,alex/invoke,frol/invoke
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
for index, arg in enumerate(argv):
if context.has_arg(arg):
flag_index = index
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
return self.contexts
Make debug logging even more convenient.
I'm sure we'll remove the globals() usage eventually.
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
from ..util import debug
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
debug("Parsing argv %r" % (argv,))
debug("Starting with context %s" % context)
for index, arg in enumerate(argv):
debug("Testing string arg %r at index %r" % (arg, index))
if context.has_arg(arg):
flag_index = index
debug("Current context has this as a flag")
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
debug("Current context does not have this as a flag")
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
debug("That pevious flag needs no value")
return self.contexts
|
<commit_before>from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
for index, arg in enumerate(argv):
if context.has_arg(arg):
flag_index = index
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
return self.contexts
<commit_msg>Make debug logging even more convenient.
I'm sure we'll remove the globals() usage eventually.<commit_after>
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
from ..util import debug
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
debug("Parsing argv %r" % (argv,))
debug("Starting with context %s" % context)
for index, arg in enumerate(argv):
debug("Testing string arg %r at index %r" % (arg, index))
if context.has_arg(arg):
flag_index = index
debug("Current context has this as a flag")
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
debug("Current context does not have this as a flag")
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
debug("That pevious flag needs no value")
return self.contexts
|
from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
for index, arg in enumerate(argv):
if context.has_arg(arg):
flag_index = index
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
return self.contexts
Make debug logging even more convenient.
I'm sure we'll remove the globals() usage eventually.from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
from ..util import debug
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
debug("Parsing argv %r" % (argv,))
debug("Starting with context %s" % context)
for index, arg in enumerate(argv):
debug("Testing string arg %r at index %r" % (arg, index))
if context.has_arg(arg):
flag_index = index
debug("Current context has this as a flag")
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
debug("Current context does not have this as a flag")
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
debug("That pevious flag needs no value")
return self.contexts
|
<commit_before>from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
for index, arg in enumerate(argv):
if context.has_arg(arg):
flag_index = index
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
return self.contexts
<commit_msg>Make debug logging even more convenient.
I'm sure we'll remove the globals() usage eventually.<commit_after>from .context import Context
from .argument import Argument # Mostly for importing via invoke.parser.<x>
from ..util import debug
class Parser(object):
def __init__(self, initial, contexts=()):
# TODO: what should contexts be? name-based dict?
self.initial = initial
self.contexts = contexts
def parse_argv(self, argv):
# Assumes any program name has already been stripped out.
context = self.initial
context_index = 0
flag_index = 0
debug("Parsing argv %r" % (argv,))
debug("Starting with context %s" % context)
for index, arg in enumerate(argv):
debug("Testing string arg %r at index %r" % (arg, index))
if context.has_arg(arg):
flag_index = index
debug("Current context has this as a flag")
# Otherwise, it's either a flag arg or a task name.
else:
flag = argv[flag_index]
debug("Current context does not have this as a flag")
# If previous flag takes an arg, this is the arg
if context.needs_value(flag):
context.set_value(flag, arg)
# If not, it's the first task name
else:
context = self.contexts[arg]
context_index = index
debug("That pevious flag needs no value")
return self.contexts
|
7ad2ecc4eea6ed143043d57867ce27bc47ea2c6e
|
cleanup.py
|
cleanup.py
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:v{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
Add version for removing image
|
Add version for removing image
|
Python
|
mit
|
dreipol/cleanup-deis-images,dreipol/cleanup-deis-images
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
Add version for removing image
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:v{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
<commit_before>#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
<commit_msg>Add version for removing image<commit_after>
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:v{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
Add version for removing image#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:v{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
<commit_before>#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
<commit_msg>Add version for removing image<commit_after>#!/usr/bin/env python
from collections import defaultdict
import subprocess
import os
KEEP_LAST_VERSIONS = os.environ.get('KEEP_LAST_VERSIONS', 4)
def find_obsolete_images(images):
for image_name, versions in images.items():
if len(versions) > KEEP_LAST_VERSIONS:
obsolete_versions = sorted(versions, reverse=True)[4:]
for version in obsolete_versions:
yield '{}:v{}'.format(image_name, version)
def parse_images(lines):
images = defaultdict(list)
for line in lines:
try:
image_name, version = line.split(' ')
version_num = int(version.replace('v', ''))
images[image_name].append(version_num)
except ValueError:
pass
return images
def remove_image(image_name):
subprocess.check_call(['docker', 'rm', image_name])
def all_images():
output = subprocess \
.check_output(['./docker_image_versions.sh'], shell=True) \
.decode('utf-8')
lines = output.split('\n')
return parse_images(lines)
if __name__ == '__main__':
images = all_images()
for image_name in find_obsolete_images(images):
remove_image(image_name)
|
9fe639db9cf671073057fc983a03c8d10b8752d3
|
genes/docker/main.py
|
genes/docker/main.py
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
Add todos and stubs for osx
|
Add todos and stubs for osx
|
Python
|
mit
|
hatchery/genepool,hatchery/Genepool2
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
Add todos and stubs for osx
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
<commit_before>from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
<commit_msg>Add todos and stubs for osx<commit_after>
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
Add todos and stubs for osxfrom genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
<commit_before>from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
else:
#FIXME: print failure case
pass
else:
#FIXME: print failure, handle osx/windows
pass
<commit_msg>Add todos and stubs for osx<commit_after>from genes import apt
import platform
class Config:
OS = platform.system()
(DIST, _, CODE) = platform.linux_distribution()
REPO = DIST.lower() + '-' + CODE
def main():
if Config.OS == 'Linux':
if Config.DIST == 'Ubuntu' or Config.DIST == 'Debian':
apt.recv_key('58118E89F3A912897C070ADBF76221572C52609D')
apt.add_repo('docker.list', 'https://apt.dockerproject.org/repo', Config.REPO, 'main')
apt.update()
apt.install('docker-engine')
#FIXME: add compose, machine, etc
else:
#FIXME: print failure case
pass
elif Config.OS = 'Darwin':
#brew_cask.install('dockertoolbox')
pass
else:
#FIXME: print failure, handle osx/windows
pass
|
2baab2e945af8c797d8b8804139fc56f366ea83d
|
ibmcnx/doc/DataSources.py
|
ibmcnx/doc/DataSources.py
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
# print db
print "AdminConfig.show( db ): "
AdminConfig.show( db )
print "AdminConfig.showall( db ): "
AdminConfig.showall( db )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print "AdminConfig.list( db ): "
AdminConfig.list ( db )
print "AdminConfig.showAttribute( db, 'name' ): "
AdminConfig.showAttribute( db, 'name' )
|
Create documentation of DataSource Settings
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
Python
|
apache-2.0
|
stoeps13/ibmcnx2,stoeps13/ibmcnx2
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
# print db
print "AdminConfig.show( db ): "
AdminConfig.show( db )
print "AdminConfig.showall( db ): "
AdminConfig.showall( db )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print "AdminConfig.list( db ): "
AdminConfig.list ( db )
print "AdminConfig.showAttribute( db, 'name' ): "
AdminConfig.showAttribute( db, 'name' )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
# print db
print "AdminConfig.show( db ): "
AdminConfig.show( db )
print "AdminConfig.showall( db ): "
AdminConfig.showall( db )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )<commit_msg>8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8<commit_after>
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print "AdminConfig.list( db ): "
AdminConfig.list ( db )
print "AdminConfig.showAttribute( db, 'name' ): "
AdminConfig.showAttribute( db, 'name' )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
# print db
print "AdminConfig.show( db ): "
AdminConfig.show( db )
print "AdminConfig.showall( db ): "
AdminConfig.showall( db )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print "AdminConfig.list( db ): "
AdminConfig.list ( db )
print "AdminConfig.showAttribute( db, 'name' ): "
AdminConfig.showAttribute( db, 'name' )
|
<commit_before>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
# print db
print "AdminConfig.show( db ): "
AdminConfig.show( db )
print "AdminConfig.showall( db ): "
AdminConfig.showall( db )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )<commit_msg>8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8<commit_after>######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
# remove unwanted databases
for db in dbs:
dbname = db.split('(')
n = 0
for i in dbname:
# i is only the name of the DataSource, db is DataSource ID!
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(db).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print "AdminConfig.list( db ): "
AdminConfig.list ( db )
print "AdminConfig.showAttribute( db, 'name' ): "
AdminConfig.showAttribute( db, 'name' )
|
ce703cbe3040770ee105fb0d953f85eebb92bdc9
|
us_ignite/sections/templatetags/sections_tags.py
|
us_ignite/sections/templatetags/sections_tags.py
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
template_context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, template_context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
Make sure the ``context`` is not overriden.
|
Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.
|
Python
|
bsd-3-clause
|
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
template_context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, template_context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
<commit_before>from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
<commit_msg>Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.<commit_after>
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
template_context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, template_context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
template_context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, template_context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
<commit_before>from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
<commit_msg>Bugfix: Make sure the ``context`` is not overriden.
The variable name for the string template context was removing
the actual ``context`` of the tempalte where the tag was
embeded.<commit_after>from django import template
from django.template.loader import render_to_string
from us_ignite.sections.models import Sponsor
register = template.Library()
class RenderingNode(template.Node):
def __init__(self, template_name):
self.template_name = template_name
def render(self, context):
template_name = self.template_name.resolve(context)
template_context = {
'object_list': Sponsor.objects.all()
}
return render_to_string(template_name, template_context)
def _render_sponsors(parser, token):
"""Tag to render the latest ``Articles``.
Usage:
{% render_sponsors "sections/sponsor_list.html" %}
Where the second argument is a template path.
"""
bits = token.split_contents()
if not len(bits) == 2:
raise template.TemplateSyntaxError(
"%r tag only accepts a template argument." % bits[0])
# Determine the template name (could be a variable or a string):
template_name = parser.compile_filter(bits[1])
return RenderingNode(template_name)
register.tag('render_sponsors', _render_sponsors)
|
f952a963dee28759e9ed4846eec5966d401c71e7
|
goodreads/scraper.py
|
goodreads/scraper.py
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class':'quoteText'})]
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes'
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class': 'quoteText'})]
return quotes
if __name__ == '__main__':
suffix = ''
print "Welcome! Choose the option to proceed"
choice = input("1. Popular\n2. Recently added")
if choice == 2:
suffix = 'recently_added'
url = 'https://www.goodreads.com/quotes/{}'.format(choice)
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
Allow user to get popular or new quotes
|
Allow user to get popular or new quotes
|
Python
|
mit
|
chankeypathak/goodreads-quotes
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class':'quoteText'})]
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes'
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
Allow user to get popular or new quotes
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class': 'quoteText'})]
return quotes
if __name__ == '__main__':
suffix = ''
print "Welcome! Choose the option to proceed"
choice = input("1. Popular\n2. Recently added")
if choice == 2:
suffix = 'recently_added'
url = 'https://www.goodreads.com/quotes/{}'.format(choice)
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
<commit_before>import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class':'quoteText'})]
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes'
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
<commit_msg>Allow user to get popular or new quotes<commit_after>
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class': 'quoteText'})]
return quotes
if __name__ == '__main__':
suffix = ''
print "Welcome! Choose the option to proceed"
choice = input("1. Popular\n2. Recently added")
if choice == 2:
suffix = 'recently_added'
url = 'https://www.goodreads.com/quotes/{}'.format(choice)
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class':'quoteText'})]
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes'
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
Allow user to get popular or new quotesimport requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class': 'quoteText'})]
return quotes
if __name__ == '__main__':
suffix = ''
print "Welcome! Choose the option to proceed"
choice = input("1. Popular\n2. Recently added")
if choice == 2:
suffix = 'recently_added'
url = 'https://www.goodreads.com/quotes/{}'.format(choice)
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
<commit_before>import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class':'quoteText'})]
return quotes
if __name__ == '__main__':
url = 'https://www.goodreads.com/quotes'
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
<commit_msg>Allow user to get popular or new quotes<commit_after>import requests
from bs4 import BeautifulSoup
class GoodReads(object):
def __init__(self):
print "Starting..."
def get_quotes(self, url):
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
quotes = [quote.text.strip().split("\n")[0] for quote in soup.findAll('div', {'class': 'quoteText'})]
return quotes
if __name__ == '__main__':
suffix = ''
print "Welcome! Choose the option to proceed"
choice = input("1. Popular\n2. Recently added")
if choice == 2:
suffix = 'recently_added'
url = 'https://www.goodreads.com/quotes/{}'.format(choice)
scraper = GoodReads()
for quote in scraper.get_quotes(url):
print quote
|
238427e684e6cb6f8c8cc6c80c8d24a51e908e24
|
bika/lims/upgrade/to3031.py
|
bika/lims/upgrade/to3031.py
|
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
from Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
Include catalog setup in 3031 upgrade
|
Include catalog setup in 3031 upgrade
|
Python
|
agpl-3.0
|
veroc/Bika-LIMS,anneline/Bika-LIMS,labsanmartin/Bika-LIMS,rockfruit/bika.lims,veroc/Bika-LIMS,anneline/Bika-LIMS,veroc/Bika-LIMS,anneline/Bika-LIMS,DeBortoliWines/Bika-LIMS,rockfruit/bika.lims,labsanmartin/Bika-LIMS,labsanmartin/Bika-LIMS,DeBortoliWines/Bika-LIMS,DeBortoliWines/Bika-LIMS
|
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
Include catalog setup in 3031 upgrade
|
from Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
<commit_before>from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
<commit_msg>Include catalog setup in 3031 upgrade<commit_after>
|
from Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
Include catalog setup in 3031 upgradefrom Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
<commit_before>from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
<commit_msg>Include catalog setup in 3031 upgrade<commit_after>from Acquisition import aq_parent, aq_inner
from Products.CMFCore.utils import getToolByName
from Products.CMFPlone.utils import _createObjectByType
from zExceptions import BadRequest
def upgrade(tool):
portal = aq_parent(aq_inner(tool))
at = getToolByName(portal, 'archetype_tool')
at.setCatalogsByType('SubGroup', ['bika_setup_catalog', ])
setup = portal.portal_setup
setup.runImportStepFromProfile('profile-bika.lims:default', 'controlpanel')
try:
_createObjectByType("SubGroups", portal.bika_setup, "bika_subgroups",
title="Sub-groups")
obj = portal.bika_setup.bika_subgroups
obj.unmarkCreationFlag()
obj.reindexObject()
except BadRequest:
# folder already exists
pass
return True
|
2e1516ee89fb0af69733bab259cbb38a3f8a614c
|
latexbuild/latex_parse.py
|
latexbuild/latex_parse.py
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one list
# (EXCEPT FOR ( "\" ), which is handled separately)
# escaping those which are special characters in
# PERL regular expressions
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
# For each latex escape character, create a regular expression
# that matches all of the following criteria
# 1) two characters
# 2) the first character is NOT a backslash ( "\" )
# 3) the second character is one of the latex escape characters
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
# Place escape characters in [] for "match any character" regex
ESCAPE_CHARS_OR = r'[{}\\]'.format(ESCAPE_CHARS)
# For the back slash, create a regular expression
# that matches all of the following criteria
# 1) three characters
# 2) the first character is not a backslash
# 3) the second characters is a backslash
# 4) the third character is none of the ESCAPE_CHARS,
# and is also not a backslash
REGEX_BACKSLASH = re.compile(r'(?!\\)\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
Update latex parser to better-handle edge cases
|
Update latex parser to better-handle edge cases
|
Python
|
mit
|
pappasam/latexbuild
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
Update latex parser to better-handle edge cases
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one list
# (EXCEPT FOR ( "\" ), which is handled separately)
# escaping those which are special characters in
# PERL regular expressions
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
# For each latex escape character, create a regular expression
# that matches all of the following criteria
# 1) two characters
# 2) the first character is NOT a backslash ( "\" )
# 3) the second character is one of the latex escape characters
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
# Place escape characters in [] for "match any character" regex
ESCAPE_CHARS_OR = r'[{}\\]'.format(ESCAPE_CHARS)
# For the back slash, create a regular expression
# that matches all of the following criteria
# 1) three characters
# 2) the first character is not a backslash
# 3) the second characters is a backslash
# 4) the third character is none of the ESCAPE_CHARS,
# and is also not a backslash
REGEX_BACKSLASH = re.compile(r'(?!\\)\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
<commit_before>"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
<commit_msg>Update latex parser to better-handle edge cases<commit_after>
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one list
# (EXCEPT FOR ( "\" ), which is handled separately)
# escaping those which are special characters in
# PERL regular expressions
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
# For each latex escape character, create a regular expression
# that matches all of the following criteria
# 1) two characters
# 2) the first character is NOT a backslash ( "\" )
# 3) the second character is one of the latex escape characters
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
# Place escape characters in [] for "match any character" regex
ESCAPE_CHARS_OR = r'[{}\\]'.format(ESCAPE_CHARS)
# For the back slash, create a regular expression
# that matches all of the following criteria
# 1) three characters
# 2) the first character is not a backslash
# 3) the second characters is a backslash
# 4) the third character is none of the ESCAPE_CHARS,
# and is also not a backslash
REGEX_BACKSLASH = re.compile(r'(?!\\)\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
Update latex parser to better-handle edge cases"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one list
# (EXCEPT FOR ( "\" ), which is handled separately)
# escaping those which are special characters in
# PERL regular expressions
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
# For each latex escape character, create a regular expression
# that matches all of the following criteria
# 1) two characters
# 2) the first character is NOT a backslash ( "\" )
# 3) the second character is one of the latex escape characters
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
# Place escape characters in [] for "match any character" regex
ESCAPE_CHARS_OR = r'[{}\\]'.format(ESCAPE_CHARS)
# For the back slash, create a regular expression
# that matches all of the following criteria
# 1) three characters
# 2) the first character is not a backslash
# 3) the second characters is a backslash
# 4) the third character is none of the ESCAPE_CHARS,
# and is also not a backslash
REGEX_BACKSLASH = re.compile(r'(?!\\)\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
<commit_before>"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
ESCAPE_CHARS_OR = '[{}]'.format('|'.join(ESCAPE_CHARS))
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
REGEX_BACKSLASH = re.compile(r'\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
<commit_msg>Update latex parser to better-handle edge cases<commit_after>"""Latex parsing functionality
This module provides functions to parse latex text
"""
import re
######################################################################
# Latex escape regex constants
######################################################################
# Organize all latex escape characters in one list
# (EXCEPT FOR ( "\" ), which is handled separately)
# escaping those which are special characters in
# PERL regular expressions
ESCAPE_CHARS = [r'\&', '%', r'\$', '#', '_', r'\{', r'\}', '~', r'\^', ]
# For each latex escape character, create a regular expression
# that matches all of the following criteria
# 1) two characters
# 2) the first character is NOT a backslash ( "\" )
# 3) the second character is one of the latex escape characters
REGEX_ESCAPE_CHARS = [
(re.compile(r"(?=[^\\])" + i), r"\\" + i.replace('\\', ''))
for i in ESCAPE_CHARS
]
# Place escape characters in [] for "match any character" regex
ESCAPE_CHARS_OR = r'[{}\\]'.format(ESCAPE_CHARS)
# For the back slash, create a regular expression
# that matches all of the following criteria
# 1) three characters
# 2) the first character is not a backslash
# 3) the second characters is a backslash
# 4) the third character is none of the ESCAPE_CHARS,
# and is also not a backslash
REGEX_BACKSLASH = re.compile(r'(?!\\)\\(?!{})'.format(ESCAPE_CHARS_OR))
######################################################################
# Declare module functions
######################################################################
def escape_latex_str(string_text):
'''Escape a latex string'''
for regex, replace_text in REGEX_ESCAPE_CHARS:
string_text = re.sub(regex, replace_text, string_text)
string_text = re.sub(REGEX_BACKSLASH, r'\\\\', string_text)
return string_text
|
f4b92c2212ce2533860764fccdb5ff05df8b8059
|
die_bag.py
|
die_bag.py
|
import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
eyes = int(raw_input('Number of eyes? '))
times = int(raw_input('Number of times? '))
#Call die
dieRoll = die_bag.die(self, eyes, times)
print dieRoll
d_class = die_bag()#Create a instance of die_bag
die_bag.take_input_die(d_class)#Call take_input_die
#Why does this not work?
die_bag.die(d_class, 20, 1)#Call die with parameters
|
import random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
|
Remove test functions and, clean code in preperation for posting a pull request
|
Remove test functions and, clean code in preperation for posting a pull request
|
Python
|
mit
|
Eanilsen/RPGHelper
|
import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
eyes = int(raw_input('Number of eyes? '))
times = int(raw_input('Number of times? '))
#Call die
dieRoll = die_bag.die(self, eyes, times)
print dieRoll
d_class = die_bag()#Create a instance of die_bag
die_bag.take_input_die(d_class)#Call take_input_die
#Why does this not work?
die_bag.die(d_class, 20, 1)#Call die with parametersRemove test functions and, clean code in preperation for posting a pull request
|
import random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
|
<commit_before>import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
eyes = int(raw_input('Number of eyes? '))
times = int(raw_input('Number of times? '))
#Call die
dieRoll = die_bag.die(self, eyes, times)
print dieRoll
d_class = die_bag()#Create a instance of die_bag
die_bag.take_input_die(d_class)#Call take_input_die
#Why does this not work?
die_bag.die(d_class, 20, 1)#Call die with parameters<commit_msg>Remove test functions and, clean code in preperation for posting a pull request<commit_after>
|
import random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
|
import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
eyes = int(raw_input('Number of eyes? '))
times = int(raw_input('Number of times? '))
#Call die
dieRoll = die_bag.die(self, eyes, times)
print dieRoll
d_class = die_bag()#Create a instance of die_bag
die_bag.take_input_die(d_class)#Call take_input_die
#Why does this not work?
die_bag.die(d_class, 20, 1)#Call die with parametersRemove test functions and, clean code in preperation for posting a pull requestimport random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
|
<commit_before>import random
class die_bag():#Class for rolling die/dices
def __init__(self):
self.data = []
def die(self, x, y = 1):#Roll a die and returns result
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
print result
def take_input_die(self):#Take input from user
eyes = int(raw_input('Number of eyes? '))
times = int(raw_input('Number of times? '))
#Call die
dieRoll = die_bag.die(self, eyes, times)
print dieRoll
d_class = die_bag()#Create a instance of die_bag
die_bag.take_input_die(d_class)#Call take_input_die
#Why does this not work?
die_bag.die(d_class, 20, 1)#Call die with parameters<commit_msg>Remove test functions and, clean code in preperation for posting a pull request<commit_after>import random
"""In this module, die or dices are rolled"""
def die(x, y = 1):
"""Function for rolling a die or several dice,
returns an array with results of dice rolls.
Parameter x is number of eyes on a die.
Parameter y = 1 is the times to a die is rolled.
"""
result = []
for i in range(y):
result.append(random.randint(1, x))
return result
|
fe9f2b7e76088afb6f4d905c0c4188df88b81516
|
pollirio/modules/__init__.py
|
pollirio/modules/__init__.py
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
from bts import *
from misc import *
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
#from bts import *
from misc import *
|
Disable bts plugin for general usage
|
Disable bts plugin for general usage
|
Python
|
mit
|
dpaleino/pollirio,dpaleino/pollirio
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
from bts import *
from misc import *
Disable bts plugin for general usage
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
#from bts import *
from misc import *
|
<commit_before># -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
from bts import *
from misc import *
<commit_msg>Disable bts plugin for general usage<commit_after>
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
#from bts import *
from misc import *
|
# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
from bts import *
from misc import *
Disable bts plugin for general usage# -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
#from bts import *
from misc import *
|
<commit_before># -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
from bts import *
from misc import *
<commit_msg>Disable bts plugin for general usage<commit_after># -*- coding: utf-8 -*-
from functools import wraps
from pollirio import commands
def old_expose(cmd):
def inner(fn):
def wrapped(*args, **kwargs):
commands[cmd] = fn
fn(*args)
return wraps(fn)(wrapped)
return inner
def expose(cmd, args=None):
def decorator(fn):
commands[cmd] = {"func":fn, "args":args}
return fn
return decorator
def plugin_run(name, *args):
if name in commands:
return commands.get(name)["func"](*args)
def check_args(name, bot, ievent):
if name in commands:
if commands.get(name)["args"]:
# TODO: check if we have all the arguments
print len(ievent.args), commands.get(name)["args"]
if len(ievent.args) < commands.get(name)["args"]:
bot.msg(ievent.channel, "%s: %s" % (ievent.nick, commands.get(name)["func"].__doc__))
return False
else:
return True
else:
return True
return False
from lart import *
from polygen import *
#from bts import *
from misc import *
|
7e823c7e46e21adb296decb45a0a2799ffc4fbe9
|
djconnectwise/__init__.py
|
djconnectwise/__init__.py
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 7, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 8, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
Change to 0.3.8, not alpha
|
Change to 0.3.8, not alpha
|
Python
|
mit
|
KerkhoffTechnologies/django-connectwise,KerkhoffTechnologies/django-connectwise
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 7, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
Change to 0.3.8, not alpha
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 8, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
<commit_before># -*- coding: utf-8 -*-
VERSION = (0, 3, 7, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
<commit_msg>Change to 0.3.8, not alpha<commit_after>
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 8, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
# -*- coding: utf-8 -*-
VERSION = (0, 3, 7, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
Change to 0.3.8, not alpha# -*- coding: utf-8 -*-
VERSION = (0, 3, 8, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
<commit_before># -*- coding: utf-8 -*-
VERSION = (0, 3, 7, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
<commit_msg>Change to 0.3.8, not alpha<commit_after># -*- coding: utf-8 -*-
VERSION = (0, 3, 8, 'final')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
default_app_config = 'djconnectwise.apps.DjangoConnectwiseConfig'
|
7c690e65fd1fe0a139eaca8df7799acf0f696ea5
|
mqtt/tests/test_client.py
|
mqtt/tests/test_client.py
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(TestMQTT, MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
Add more time to mqtt.test.client
|
Add more time to mqtt.test.client
|
Python
|
bsd-3-clause
|
EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(TestMQTT, MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
Add more time to mqtt.test.client
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
<commit_before>import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(TestMQTT, MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
<commit_msg>Add more time to mqtt.test.client<commit_after>
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(TestMQTT, MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
Add more time to mqtt.test.clientimport time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
<commit_before>import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(TestMQTT, MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
<commit_msg>Add more time to mqtt.test.client<commit_after>import time
from django.test import TestCase
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from io import BytesIO
import json
from login.models import Profile, AmbulancePermission, HospitalPermission
from login.serializers import ExtendedProfileSerializer
from ambulance.models import Ambulance, \
AmbulanceStatus, AmbulanceCapability
from ambulance.serializers import AmbulanceSerializer
from hospital.models import Hospital, \
Equipment, HospitalEquipment, EquipmentType
from hospital.serializers import EquipmentSerializer, \
HospitalSerializer, HospitalEquipmentSerializer
from django.test import Client
from .client import MQTTTestCase, MQTTTestClient
from ..client import MQTTException
from ..subscribe import SubscribeClient
class TestMQTTSeed(MQTTTestCase):
def test_mqttseed(self):
self.assertEqual(True, True)
|
fa108e8393632bad1a9dfc0e730bbd23fa6042c1
|
mysql_fuzzycount/admin.py
|
mysql_fuzzycount/admin.py
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def get_queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).get_queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
Update for newer versions of Django
|
Update for newer versions of Django
|
Python
|
mit
|
educreations/django-mysql-fuzzycount
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
Update for newer versions of Django
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def get_queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).get_queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
<commit_before>from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
<commit_msg>Update for newer versions of Django<commit_after>
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def get_queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).get_queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
Update for newer versions of Djangofrom django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def get_queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).get_queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
<commit_before>from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
<commit_msg>Update for newer versions of Django<commit_after>from django.contrib import admin
from mysql_fuzzycount.queryset import FuzzyCountQuerySet
class FuzzyCountModelAdminMixin(object):
def get_queryset(self, request):
qs = super(FuzzyCountModelAdminMixin, self).get_queryset(request)
return qs._clone(klass=FuzzyCountQuerySet)
class FuzzyCountModelAdmin(FuzzyCountModelAdminMixin, admin.ModelAdmin):
pass
|
3c60a46d9cb89dbf1e2e4a05766d91d837173089
|
encryptit/tests/openpgp_message/test_packet_location.py
|
encryptit/tests/openpgp_message/test_packet_location.py
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
Test for incorrect serialisation of PacketLocation
|
Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.
|
Python
|
agpl-3.0
|
paulfurley/encryptit,paulfurley/encryptit
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
<commit_before>import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
<commit_msg>Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.<commit_after>
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
<commit_before>import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_serialize():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION.serialize(), cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
<commit_msg>Test for incorrect serialisation of PacketLocation
Although the `serialize` method is returning the right thing, when we
serialize it with the `OpenPGPJsonEncoder`, it's being serialized as a
JSON array. Test to capture that behaviour.<commit_after>import json
from nose.tools import assert_equal
from encryptit.openpgp_message import PacketLocation
from encryptit.dump_json import OpenPGPJsonEncoder
PACKET_LOCATION = PacketLocation(
header_start=10,
body_start=12,
body_length=8)
def test_packet_location_header_length_field():
assert_equal(2, PACKET_LOCATION.header_length)
def test_packet_location_header_end_field():
assert_equal(12, PACKET_LOCATION.header_end)
def test_packet_location_body_end_field():
assert_equal(20, PACKET_LOCATION.body_end)
def test_packet_location_json_serializing():
# convert to JSON then back again in order to compare as python objects -
# less picky than comparing as strings.
as_json = json.dumps(PACKET_LOCATION, cls=OpenPGPJsonEncoder)
back_to_data = json.loads(as_json)
assert_equal(
{
'header_start': 10,
'header_length': 2,
'header_end': 12,
'body_start': 12,
'body_length': 8,
'body_end': 20,
},
back_to_data)
|
f165cb38e57315fcbe4049128a436c4ef743ef4b
|
lib/bx/misc/bgzf_tests.py
|
lib/bx/misc/bgzf_tests.py
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf()
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 "
|
Make BGZF test a real unittest
|
Make BGZF test a real unittest
|
Python
|
mit
|
bxlab/bx-python,bxlab/bx-python,bxlab/bx-python
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf()Make BGZF test a real unittest
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 "
|
<commit_before>import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf()<commit_msg>Make BGZF test a real unittest<commit_after>
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 "
|
import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf()Make BGZF test a real unittestimport bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 "
|
<commit_before>import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "../test_data/bgzf_tests/test.txt.gz" )
print f.read( 10 )
print f.seek( 0 )
print f.read( 10 )
test_bgzf()<commit_msg>Make BGZF test a real unittest<commit_after>import bx.misc.bgzf
def test_bgzf():
f = bx.misc.bgzf.BGZFFile( "test_data/bgzf_tests/test.txt.gz" )
assert f.read( 10 ) == "begin 644 "
print f.seek( 0 )
assert f.read( 10 ) == "begin 644 "
|
46fad55c9a707caeb28663d7560d93d5e4563b72
|
keteparaha/__init__.py
|
keteparaha/__init__.py
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
Add more detail to module docstring
|
Add more detail to module docstring
|
Python
|
mit
|
aychedee/keteparaha,tomdottom/keteparaha
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
Add more detail to module docstring
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
<commit_before># -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
<commit_msg>Add more detail to module docstring<commit_after>
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
Add more detail to module docstring# -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
<commit_before># -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply use:
pip install keteparaha
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
<commit_msg>Add more detail to module docstring<commit_after># -*- coding: utf-8 -*-
"""A collection of tools to help when functional testing
It contains utilities that assist with tasks like running a browser in a
headless environment, or checking that emails have been sent, or a file has
been uploaded to a server, or common testing flow control like retrying or
ignoring certain errors.
Installation
------------
Keteparaha is available on PyPi. To install the latest release simply run:
pip install keteparaha
Usage
-----
**BrowserTestCase** is a sub classed unittest.TestCase designed to make
working with Selenium Webdriver simpler. It can operate in headless mode to be
used with continuous integration.
**Page** and **Component** represent a web app's pages, or the components
that can be found on those pages.
License
-------
Keteparaha is released under the MIT license, see LICENSE in the software
repository for more details. Copyright 2015 by Hansel Dunlop.
"""
__version__ = '0.0.16'
from .email_client import GmailImapClient
from .page import Component, Page
from .browser import (
BrowserTestCase,
HeadlessBrowserTestCase,
snapshot_on_error
)
from .flow import ignore, retry
__version__ = '0.0.12'
__all__ = ['BrowserTestCase', 'Component', 'Page']
|
c705fcf1771466ac2445a8058334c27cd1040e81
|
docs/examples/compute/azure_arm/instantiate.py
|
docs/examples/compute/azure_arm/instantiate.py
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
|
Fix lint in example script
|
Fix lint in example script
|
Python
|
apache-2.0
|
Scalr/libcloud,illfelder/libcloud,pquentin/libcloud,apache/libcloud,pquentin/libcloud,andrewsomething/libcloud,samuelchong/libcloud,vongazman/libcloud,illfelder/libcloud,erjohnso/libcloud,SecurityCompass/libcloud,watermelo/libcloud,ByteInternet/libcloud,illfelder/libcloud,apache/libcloud,vongazman/libcloud,erjohnso/libcloud,mgogoulos/libcloud,techhat/libcloud,StackPointCloud/libcloud,ByteInternet/libcloud,samuelchong/libcloud,curoverse/libcloud,t-tran/libcloud,Scalr/libcloud,mistio/libcloud,StackPointCloud/libcloud,StackPointCloud/libcloud,t-tran/libcloud,pquentin/libcloud,Kami/libcloud,techhat/libcloud,andrewsomething/libcloud,SecurityCompass/libcloud,curoverse/libcloud,apache/libcloud,ZuluPro/libcloud,vongazman/libcloud,techhat/libcloud,t-tran/libcloud,mistio/libcloud,ByteInternet/libcloud,watermelo/libcloud,Scalr/libcloud,Kami/libcloud,ZuluPro/libcloud,watermelo/libcloud,samuelchong/libcloud,curoverse/libcloud,erjohnso/libcloud,mgogoulos/libcloud,mistio/libcloud,Kami/libcloud,andrewsomething/libcloud,SecurityCompass/libcloud,mgogoulos/libcloud,ZuluPro/libcloud
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
Fix lint in example script
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
|
<commit_before>from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
<commit_msg>Fix lint in example script<commit_after>
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
|
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
Fix lint in example scriptfrom libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
|
<commit_before>from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
<commit_msg>Fix lint in example script<commit_after>from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
|
cfb9838349a076e8fa3afe9a69db74581b13d296
|
labsys/auth/decorators.py
|
labsys/auth/decorators.py
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) and \
not current_app.config['TESTING'] == True:
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER) (f)
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
Remove test condition for permissions
|
:bug: Remove test condition for permissions
Otherwise I would not be able to test them properly
|
Python
|
mit
|
gems-uff/labsys,gems-uff/labsys,gems-uff/labsys
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) and \
not current_app.config['TESTING'] == True:
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER) (f)
:bug: Remove test condition for permissions
Otherwise I would not be able to test them properly
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
<commit_before>from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) and \
not current_app.config['TESTING'] == True:
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER) (f)
<commit_msg>:bug: Remove test condition for permissions
Otherwise I would not be able to test them properly<commit_after>
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) and \
not current_app.config['TESTING'] == True:
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER) (f)
:bug: Remove test condition for permissions
Otherwise I would not be able to test them properlyfrom functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
<commit_before>from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission) and \
not current_app.config['TESTING'] == True:
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER) (f)
<commit_msg>:bug: Remove test condition for permissions
Otherwise I would not be able to test them properly<commit_after>from functools import wraps
from flask import abort, current_app
from flask_login import current_user
from labsys.auth.models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if not current_user.can(permission):
abort(403)
return f(*args, **kwargs)
return decorated_function
return decorator
def admin_required(f):
return permission_required(Permission.ADMINISTER)(f)
|
e120aafad13138abb5d98bbad12c0d8bdc532b30
|
lglass/web/application.py
|
lglass/web/application.py
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
Replace static_file by open call
|
Replace static_file by open call
|
Python
|
mit
|
fritz0705/lglass
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
Replace static_file by open call
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
<commit_before># coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
<commit_msg>Replace static_file by open call<commit_after>
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
Replace static_file by open call# coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
<commit_before># coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return bottle.static_file(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
<commit_msg>Replace static_file by open call<commit_after># coding: utf-8
import bottle
from lglass.web.helpers import render_template, with_config
app = bottle.Bottle()
def index_handler():
return render_template("index.html")
@with_config
def robots_txt_handler(config):
if config["robots.txt"] is not None:
return open(config["robots.txt"])
bottle.abort(404, "File not found")
app.route("/", "GET", index_handler)
app.route("/robots.txt", "GET", robots_txt_handler)
import lglass.web.registry
app.route("/obj", "GET", lglass.web.registry.show_object_types)
app.route("/obj/<type>", "GET", lglass.web.registry.show_objects)
app.route("/obj/<type>/<primary_key>", "GET", lglass.web.registry.show_object)
app.route("/whois/<query>", "GET", lglass.web.registry.whois_query)
app.route("/whois", "POST", lglass.web.registry.whois_query)
app.route("/flush", "POST", lglass.web.registry.flush_cache)
|
3209c35a068a14c713175257ee26f7b2c61b9845
|
test_package/conanfile.py
|
test_package/conanfile.py
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-1@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-2@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
Update test_package version number to match the package
|
Update test_package version number to match the package
|
Python
|
mit
|
ohhi/conan-opencv,ohhi/conan-opencv
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-1@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
Update test_package version number to match the package
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-2@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
<commit_before>from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-1@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
<commit_msg>Update test_package version number to match the package<commit_after>
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-2@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-1@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
Update test_package version number to match the packagefrom conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-2@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
<commit_before>from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-1@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
<commit_msg>Update test_package version number to match the package<commit_after>from conans import ConanFile, CMake
import os
class MyTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "OpenCV/3.2.0-2@ohhi/stable"
generators = "cmake", "txt"
def imports(self):
self.copy("*.dll", dst="bin", src="bin")
def build(self):
cmake = CMake(self)
cmake.configure(source_dir=self.conanfile_directory, build_dir=".")
cmake.build(build_dir=".")
def test(self):
self.run(os.path.join(".","bin", "mytest"))
|
c32b1ac940aee449fb3a73fe9c04837618eb7ad1
|
python/servo/packages.py
|
python/servo/packages.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "8.0.1",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "9.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
Upgrade clang to 9.0 on Windows.
|
Upgrade clang to 9.0 on Windows.
|
Python
|
mpl-2.0
|
KiChjang/servo,splav/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,splav/servo,splav/servo,KiChjang/servo,splav/servo,splav/servo,splav/servo,splav/servo,KiChjang/servo,KiChjang/servo,KiChjang/servo,splav/servo,splav/servo,splav/servo
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "8.0.1",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
Upgrade clang to 9.0 on Windows.
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "9.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "8.0.1",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
<commit_msg>Upgrade clang to 9.0 on Windows.<commit_after>
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "9.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "8.0.1",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
Upgrade clang to 9.0 on Windows.# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "9.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
<commit_before># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "8.0.1",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
<commit_msg>Upgrade clang to 9.0 on Windows.<commit_after># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
WINDOWS_MSVC = {
"cmake": "3.14.3",
"llvm": "9.0.0",
"moztools": "3.2",
"ninja": "1.7.1",
"nuget": "08-08-2019",
"openssl": "111.3.0+1.1.1c-vs2017-2019-09-18",
"gstreamer-uwp": "1.16.0.5",
"openxr-loader-uwp": "1.0",
"xargo": "v0.3.17",
}
|
2b21871f3a06d296066b8409741212537b458fa3
|
tests/offline/__init__.py
|
tests/offline/__init__.py
|
# coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
def make_simple_text_mock(filename):
def mockreturn(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
return fd.read()
return mockreturn
@contextmanager
def assert_raises(exception_class, msg=None):
"""Check that an exception is raised and its message contains `msg`."""
with pytest.raises(exception_class) as exception:
yield
if msg is not None:
message = '%s' % exception
assert msg.lower() in message.lower()
|
# coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
class ContextualTest(object):
def __init__(self, monkeypatch, manager, action, service):
self.manager = manager
self.action = action
self.service = service
monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml'))
def close(self):
request = getattr(self.manager, self.service + '_request')
assert request_is_valid(request, self.action, self.service)
|
Use context manager for the offline tests
|
Use context manager for the offline tests
|
Python
|
mit
|
alexandriagroup/fnapy,alexandriagroup/fnapy
|
# coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
def make_simple_text_mock(filename):
def mockreturn(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
return fd.read()
return mockreturn
@contextmanager
def assert_raises(exception_class, msg=None):
"""Check that an exception is raised and its message contains `msg`."""
with pytest.raises(exception_class) as exception:
yield
if msg is not None:
message = '%s' % exception
assert msg.lower() in message.lower()
Use context manager for the offline tests
|
# coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
class ContextualTest(object):
def __init__(self, monkeypatch, manager, action, service):
self.manager = manager
self.action = action
self.service = service
monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml'))
def close(self):
request = getattr(self.manager, self.service + '_request')
assert request_is_valid(request, self.action, self.service)
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
def make_simple_text_mock(filename):
def mockreturn(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
return fd.read()
return mockreturn
@contextmanager
def assert_raises(exception_class, msg=None):
"""Check that an exception is raised and its message contains `msg`."""
with pytest.raises(exception_class) as exception:
yield
if msg is not None:
message = '%s' % exception
assert msg.lower() in message.lower()
<commit_msg>Use context manager for the offline tests<commit_after>
|
# coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
class ContextualTest(object):
def __init__(self, monkeypatch, manager, action, service):
self.manager = manager
self.action = action
self.service = service
monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml'))
def close(self):
request = getattr(self.manager, self.service + '_request')
assert request_is_valid(request, self.action, self.service)
|
# coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
def make_simple_text_mock(filename):
def mockreturn(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
return fd.read()
return mockreturn
@contextmanager
def assert_raises(exception_class, msg=None):
"""Check that an exception is raised and its message contains `msg`."""
with pytest.raises(exception_class) as exception:
yield
if msg is not None:
message = '%s' % exception
assert msg.lower() in message.lower()
Use context manager for the offline tests# coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
class ContextualTest(object):
def __init__(self, monkeypatch, manager, action, service):
self.manager = manager
self.action = action
self.service = service
monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml'))
def close(self):
request = getattr(self.manager, self.service + '_request')
assert request_is_valid(request, self.action, self.service)
|
<commit_before># coding: utf-8
from __future__ import unicode_literals, print_function
import os
import pytest
from codecs import open
from contextlib import contextmanager
from requests import Response
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
def make_simple_text_mock(filename):
def mockreturn(*args, **kwargs):
with open(os.path.join(os.path.dirname(__file__), 'assets', filename), 'r', 'utf-8') as fd:
return fd.read()
return mockreturn
@contextmanager
def assert_raises(exception_class, msg=None):
"""Check that an exception is raised and its message contains `msg`."""
with pytest.raises(exception_class) as exception:
yield
if msg is not None:
message = '%s' % exception
assert msg.lower() in message.lower()
<commit_msg>Use context manager for the offline tests<commit_after># coding: utf-8
# Python modules
from __future__ import unicode_literals, print_function
import os
from codecs import open
from contextlib import contextmanager
# Third-party modules
import pytest
# Project modules
from requests import Response
from tests import request_is_valid
def make_requests_get_mock(filename):
def mockreturn(*args, **kwargs):
response = Response()
with open(os.path.join(os.path.dirname(__file__), '../assets', filename), 'r', 'utf-8') as fd:
response._content = fd.read().encode('utf-8')
return response
return mockreturn
class ContextualTest(object):
def __init__(self, monkeypatch, manager, action, service):
self.manager = manager
self.action = action
self.service = service
monkeypatch.setattr('requests.post', make_requests_get_mock(self.action + '_response.xml'))
def close(self):
request = getattr(self.manager, self.service + '_request')
assert request_is_valid(request, self.action, self.service)
|
d64492c85182a992597729999f1e4483977b87d6
|
cisco_olt_client/command.py
|
cisco_olt_client/command.py
|
import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
import shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 means that the value string was either not properly
# quoted or is empty, in both cases we're not touching it
if len(_value) == 1:
value = _value[0]
return name, value
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status --onuID=23 --port=pon.7'
:param cmd: Full path to the command.
:type cmd: str
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
Add function for parsing cli arguments
|
Add function for parsing cli arguments
|
Python
|
mit
|
Vnet-as/cisco-olt-client
|
import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
Add function for parsing cli arguments
|
import shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 means that the value string was either not properly
# quoted or is empty, in both cases we're not touching it
if len(_value) == 1:
value = _value[0]
return name, value
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status --onuID=23 --port=pon.7'
:param cmd: Full path to the command.
:type cmd: str
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
<commit_before>import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
<commit_msg>Add function for parsing cli arguments<commit_after>
|
import shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 means that the value string was either not properly
# quoted or is empty, in both cases we're not touching it
if len(_value) == 1:
value = _value[0]
return name, value
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status --onuID=23 --port=pon.7'
:param cmd: Full path to the command.
:type cmd: str
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
Add function for parsing cli argumentsimport shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 means that the value string was either not properly
# quoted or is empty, in both cases we're not touching it
if len(_value) == 1:
value = _value[0]
return name, value
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status --onuID=23 --port=pon.7'
:param cmd: Full path to the command.
:type cmd: str
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
<commit_before>import collections
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status/show', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status/show --onuID=23 --port=pon.7'
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
<commit_msg>Add function for parsing cli arguments<commit_after>import shlex
import collections
def arg2tuple(arg):
'''
Parse command line argument into name, value tuple
'''
name, value = arg.split('=', 1)
if name.startswith('--'):
name = name[2:]
# try to normalize string that's quoted
_value = shlex.split(value)
# other length than 1 means that the value string was either not properly
# quoted or is empty, in both cases we're not touching it
if len(_value) == 1:
value = _value[0]
return name, value
class Command:
def __init__(self, cmd, args=None):
'''
Single command and it's output representation
>>> c = Command('/remote-eq/status', ['--onuID=23', '--port=pon.7'])
>>> c.compile()
'/remote-eq/status --onuID=23 --port=pon.7'
:param cmd: Full path to the command.
:type cmd: str
:param args: Additional command arguments. In python2, if you need to
preserve order of arguments use ordered dict or list of 2-tuples
:type args: list or dict
'''
self.cmd = cmd
self.args = args or {}
def _get_arg_strs(self):
if not isinstance(self.args, collections.Mapping):
if len(self.args) and isinstance(self.args[0], str):
return list(self.args)
return [
"--%s=%s" % (arg, value)
for arg, value in (
self.args.items()
if isinstance(self.args, collections.Mapping) else
self.args
)
]
def compile(self):
return " ".join([self.cmd] + self._get_arg_strs())
|
8d3e79d268ae16e9774c60332c47b11038407050
|
vagrant/roles/db/molecule/default/tests/test_default.py
|
vagrant/roles/db/molecule/default/tests/test_default.py
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
Add 'testinfra' test method 'test_mongo_host_port'
|
Add 'testinfra' test method 'test_mongo_host_port'
|
Python
|
mit
|
DmitriySh/infra,DmitriySh/infra,DmitriySh/infra
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
Add 'testinfra' test method 'test_mongo_host_port'
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
<commit_before>import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
<commit_msg>Add 'testinfra' test method 'test_mongo_host_port'<commit_after>
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
Add 'testinfra' test method 'test_mongo_host_port'import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
<commit_before>import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
<commit_msg>Add 'testinfra' test method 'test_mongo_host_port'<commit_after>import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
# check if MongoDB is listen concrete host and port
def test_mongo_host_port(host):
socket = host.socket("tcp://127.0.0.1:27017")
assert socket.is_listening
# check if MongoDB is enabled and running
def test_mongo_running_and_enabled(host):
mongo = host.service("mongod")
assert mongo.is_running
assert mongo.is_enabled
# check if configuration file contains the required line
def test_config_file(File):
config_file = File('/etc/mongod.conf')
assert config_file.contains('bindIp: 0.0.0.0')
assert config_file.is_file
|
8c1f303d4cc04c95170dea268ab836a23d626064
|
thezombies/management/commands/crawl_agency_datasets.py
|
thezombies/management/commands/crawl_agency_datasets.py
|
from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
|
from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
|
Add message for when command is not supplied any arguments.
|
Add message for when command is not supplied any arguments.
|
Python
|
bsd-3-clause
|
sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies,sunlightlabs/thezombies
|
from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
Add message for when command is not supplied any arguments.
|
from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
|
<commit_before>from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
<commit_msg>Add message for when command is not supplied any arguments.<commit_after>
|
from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
|
from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
Add message for when command is not supplied any arguments.from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
|
<commit_before>from django.core.management.base import BaseCommand
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
<commit_msg>Add message for when command is not supplied any arguments.<commit_after>from django.core.management.base import BaseCommand
from thezombies.models import Agency
from thezombies.tasks.main import crawl_agency_datasets
class Command(BaseCommand):
"""Start a task that crawl the datasets from an agency data catalog. This command will exit, but the task will run in the background"""
args = '<agency_id ...>'
def handle(self, *args, **options):
if len(args) > 0:
agency_id = args[0]
if agency_id:
task = crawl_agency_datasets.delay(agency_id)
self.stdout.write(u'Running task with id {0}'.format(task.id))
self.stdout.write(u'This can take many minutes...')
else:
self.stderr.write(u"Didn't get an agency_id!")
else:
self.stdout.write(u'Please provide an agency id:\n')
agency_list = u'\n'.join(['{0:2d}: {1}'.format(a.id, a.name) for a in Agency.objects.all()])
self.stdout.write(agency_list)
self.stdout.write(u'\n')
|
5ea20ad3bd4ca2a3384229e76559be9758b59ab1
|
tests/scan.py
|
tests/scan.py
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([2]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[2., 2.], [4., 4.], [8., 8.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([3]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[3., 3.], [6., 6.], [12., 12.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
Return different values for carry and output.
|
Return different values for carry and output.
|
Python
|
apache-2.0
|
google/objax,google/objax
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([2]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[2., 2.], [4., 4.], [8., 8.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
Return different values for carry and output.
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([3]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[3., 3.], [6., 6.], [12., 12.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
<commit_before># Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([2]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[2., 2.], [4., 4.], [8., 8.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
<commit_msg>Return different values for carry and output.<commit_after>
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([3]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[3., 3.], [6., 6.], [12., 12.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([2]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[2., 2.], [4., 4.], [8., 8.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
Return different values for carry and output.# Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([3]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[3., 3.], [6., 6.], [12., 12.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
<commit_before># Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([2]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[2., 2.], [4., 4.], [8., 8.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
<commit_msg>Return different values for carry and output.<commit_after># Copyright 2020 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.
"""Unittests for scan method."""
import unittest
import jax.numpy as jn
import objax
class TestScan(unittest.TestCase):
def test_scan(self):
def cell(carry, x):
return jn.array([2]) * carry * x, jn.array([3]) * carry * x
carry = jn.array([8., 8.])
output = jn.array([[3., 3.], [6., 6.], [12., 12.]])
test_carry, test_output = objax.functional.scan(cell, jn.ones((2,)), jn.ones((3,)))
self.assertTrue(jn.array_equal(carry, test_carry))
self.assertTrue(jn.array_equal(output, test_output))
|
22ef8a836a765b98fbc05bda5254ee9e5b6bf11b
|
udata/core/jobs/models.py
|
udata/core/jobs/models.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}'
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
class Crontab(BasePeriodicTask.Crontab):
def __unicode__(self):
return CRON.format(**self._data)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
interval = db.EmbeddedDocumentField(Interval)
crontab = db.EmbeddedDocumentField(Crontab)
|
Fix periodic tasks model display
|
Fix periodic tasks model display
|
Python
|
agpl-3.0
|
opendatateam/udata,davidbgk/udata,etalab/udata,opendatateam/udata,opendatateam/udata,etalab/udata,davidbgk/udata,etalab/udata,davidbgk/udata
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
Fix periodic tasks model display
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}'
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
class Crontab(BasePeriodicTask.Crontab):
def __unicode__(self):
return CRON.format(**self._data)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
interval = db.EmbeddedDocumentField(Interval)
crontab = db.EmbeddedDocumentField(Crontab)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
<commit_msg>Fix periodic tasks model display<commit_after>
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}'
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
class Crontab(BasePeriodicTask.Crontab):
def __unicode__(self):
return CRON.format(**self._data)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
interval = db.EmbeddedDocumentField(Interval)
crontab = db.EmbeddedDocumentField(Crontab)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
Fix periodic tasks model display# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}'
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
class Crontab(BasePeriodicTask.Crontab):
def __unicode__(self):
return CRON.format(**self._data)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
interval = db.EmbeddedDocumentField(Interval)
crontab = db.EmbeddedDocumentField(Crontab)
|
<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
<commit_msg>Fix periodic tasks model display<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from celerybeatmongo.models import PeriodicTask as BasePeriodicTask, PERIODS
from udata.i18n import lazy_gettext as _
from udata.models import db
__all__ = ('PeriodicTask', 'PERIODS')
CRON = '{minute} {hour} {day_of_month} {month_of_year} {day_of_week}'
class PeriodicTask(BasePeriodicTask):
last_run_id = db.StringField()
class Interval(BasePeriodicTask.Interval):
def __unicode__(self):
if self.every == 1:
return _('every {0.period_singular}').format(self)
return _('every {0.every} {0.period}').format(self)
class Crontab(BasePeriodicTask.Crontab):
def __unicode__(self):
return CRON.format(**self._data)
@property
def schedule_display(self):
if self.interval:
return str(self.interval)
elif self.crontab:
return str(self.crontab)
else:
raise Exception("must define internal or crontab schedule")
interval = db.EmbeddedDocumentField(Interval)
crontab = db.EmbeddedDocumentField(Crontab)
|
20699a38f8ab28fa605abbe110d0bfdb2b571662
|
workers/exec/examples/dummy_worker.py
|
workers/exec/examples/dummy_worker.py
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
print("Some error at {0}".format(i), file=sys.stderr)
time.sleep(0.1)
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
sys.stdout.flush()
print("Some error at {0}".format(i), file=sys.stderr)
sys.stderr.flush()
time.sleep(0.1)
|
Add flush for dummy exec worker
|
Add flush for dummy exec worker
|
Python
|
bsd-3-clause
|
timofey-barmin/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,timofey-barmin/mzbench,timofey-barmin/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench,machinezone/mzbench
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
print("Some error at {0}".format(i), file=sys.stderr)
time.sleep(0.1)
Add flush for dummy exec worker
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
sys.stdout.flush()
print("Some error at {0}".format(i), file=sys.stderr)
sys.stderr.flush()
time.sleep(0.1)
|
<commit_before>#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
print("Some error at {0}".format(i), file=sys.stderr)
time.sleep(0.1)
<commit_msg>Add flush for dummy exec worker<commit_after>
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
sys.stdout.flush()
print("Some error at {0}".format(i), file=sys.stderr)
sys.stderr.flush()
time.sleep(0.1)
|
#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
print("Some error at {0}".format(i), file=sys.stderr)
time.sleep(0.1)
Add flush for dummy exec worker#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
sys.stdout.flush()
print("Some error at {0}".format(i), file=sys.stderr)
sys.stderr.flush()
time.sleep(0.1)
|
<commit_before>#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
print("Some error at {0}".format(i), file=sys.stderr)
time.sleep(0.1)
<commit_msg>Add flush for dummy exec worker<commit_after>#!/usr/bin/env python
from __future__ import print_function
import socket
import time
import sys
DEFAULT_IP = '127.0.0.1'
DEFAULT_PORT = 8125
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for i in xrange(1, 3000):
s.sendto("dummy.counter1:{0}|c\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
s.sendto("dummy.gauge1:{0}|g\n".format(i), (DEFAULT_IP, DEFAULT_PORT))
print("Reporting {0}".format(i), file=sys.stdout)
sys.stdout.flush()
print("Some error at {0}".format(i), file=sys.stderr)
sys.stderr.flush()
time.sleep(0.1)
|
2ec5f71d04ae17a1c0a457fba1b82f8c8e8891ab
|
sc2reader/listeners/utils.py
|
sc2reader/listeners/utils.py
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass
|
Add a default ListenerBase.setup implementation.
|
Add a default ListenerBase.setup implementation.
|
Python
|
mit
|
StoicLoofah/sc2reader,vlaufer/sc2reader,vlaufer/sc2reader,GraylinKim/sc2reader,ggtracker/sc2reader,ggtracker/sc2reader,GraylinKim/sc2reader,StoicLoofah/sc2reader
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return trueAdd a default ListenerBase.setup implementation.
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass
|
<commit_before>from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true<commit_msg>Add a default ListenerBase.setup implementation.<commit_after>
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass
|
from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return trueAdd a default ListenerBase.setup implementation.from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass
|
<commit_before>from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true<commit_msg>Add a default ListenerBase.setup implementation.<commit_after>from sc2reader import log_utils
class ListenerBase(object):
def __init__(self):
self.logger = log_utils.get_logger(self.__class__)
def accepts(self, event):
return true
def setup(self, replay):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.